prompt
listlengths
1
1
compression_prompt
listlengths
1
1
target
stringlengths
1.03k
828k
[ { "content": "Return the code unaltered:\n```python\nimport os\nimport sys\nfrom sys import argv, exit\nfrom scipy.sparse.csgraph import dijkstra\n\nimport CPUtimer\n\nfrom data1 import instance_iteratorL, print_solution\n\ndef solve(instance_path):\n timer = CPUtimer.CPUTimer()\n for instance in instance...
[ { "content": "Return the code unaltered:\n<|memory_start|>```python\nimport os\nimport sys\nfrom sys import argv, exit\nfrom scipy.sparse.csgraph import dijkstra\n\nimport CPUtimer\n\nfrom data1 import instance_iteratorL, print_solution\n\ndef solve(instance_path):\n timer = CPUtimer.CPUTimer()\n for inst...
```python import os import sys from sys import argv, exit from scipy.sparse.csgraph import dijkstra import CPUtimer from data1 import instance_iteratorL, print_solution def solve(instance_path): timer = CPUtimer.CPUTimer() for instance in instance_iteratorL(instance_path): verticeInicial = 1 instance_name, numVertices, numArestas, listaAdjacencia = instance timer.reset() timer.start() for i in range(0, 2): distances, predecessors = dijkstra(listaAdjacencia, numVertices, verticeInicial) timer.lap() timer.stop() print_solution(verticeInicial, distances, predecessors, instance_name, '1a', timer) def dijkstra(listaAdjacencia, numVertices, verticeInicial): distancia = [99999 for x in range(numVertices+1)] predecessor = [99999 for x in range(numVertices+1)] distancia[verticeInicial] = 0 predecessor[verticeInicial] = 0 flaggedVertices = [False for x in range(numVertices+1)] flaggedVertices[0] = True menor = getVerticeMenorDistancia(distancia, flaggedVertices) while (menor != 99999): flaggedVertices[menor] = True if (len(listaAdjacencia[menor]) > 0): for i in range(len(listaAdjacencia[menor])): vertice = listaAdjacencia[menor][i][0] peso = listaAdjacencia[menor][i][1] if (distancia[vertice] > (distancia[menor] + peso)): distancia[vertice] = distancia[menor] + peso predecessor[vertice] = menor menor = getVerticeMenorDistancia(distancia, flaggedVertices) return distancia, predecessor def getVerticeMenorDistancia(distancia, flaggedVertices): verticesDistanciasNaoVisitados = [] vetorIntermediario = [] for i in range(len(flaggedVertices)): if (flaggedVertices[i] == False): vetorIntermediario.append(distancia[i]) vetorIntermediario.append(i) verticesDistanciasNaoVisitados.append(vetorIntermediario) vetorIntermediario = [] if (len(verticesDistanciasNaoVisitados)>0): menor = min(verticesDistanciasNaoVisitados) indiceMenor = menor[1] return indiceMenor else: return 99999 ```
[ { "content": "```python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Part of the PsychoPy library\n# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd.\n# Distributed under the terms of the GNU General Public License (GPL).\n\n\"\"\"Data useful for calibrations (Smith-Pokorny ...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Part of the PsychoPy library\n# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd.\n# Distributed under the terms of the GNU General Public License (GPL).\n\n\"\"\"Data useful for calibrations...
```python #!/usr/bin/env python # -*- coding: utf-8 -*- # Part of the PsychoPy library # Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). """Data useful for calibrations (Smith-Pokorny cone fundamentals etc...) """ from __future__ import absolute_import, print_function import numpy # 380 to 780 inclusive with 5nm steps wavelength_5nm = numpy.arange(380, 785, 5) juddVosXYZ1976_5nm = numpy.asarray([ [0.003, 0.005, 0.011, 0.021, 0.038, 0.063, 0.100, 0.158, 0.229, 0.281, 0.311, 0.331, 0.333, 0.317, 0.289, 0.260, 0.233, 0.210, 0.175, 0.133, 0.092, 0.057, 0.032, 0.015, 0.005, 0.002, 0.009, 0.029, 0.064, 0.111, 0.167, 0.228, 0.293, 0.362, 0.436, 0.515, 0.597, 0.681, 0.764, 0.844, 0.916, 0.977, 1.023, 1.051, 1.055, 1.036, 0.992, 0.929, 0.843, 0.740, 0.633, 0.534, 0.441, 0.355, 0.279, 0.215, 0.162, 0.118, 0.086, 0.063, 0.046, 0.032, 0.022, 0.016, 0.011, 0.008, 0.006, 0.004, 0.003, 0.002, 0.001, 0.001, 0.001, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.001, 0.002, 0.003, 0.005, 0.007, 0.012, 0.018, 0.023, 0.027, 0.033, 0.038, 0.042, 0.047, 0.052, 0.060, 0.073, 0.091, 0.113, 0.139, 0.170, 0.208, 0.258, 0.323, 0.405, 0.503, 0.608, 0.710, 0.795, 0.862, 0.915, 0.954, 0.980, 0.995, 1.000, 0.995, 0.979, 0.952, 0.916, 0.870, 0.816, 0.757, 0.695, 0.631, 0.567, 0.503, 0.442, 0.381, 0.321, 0.265, 0.217, 0.175, 0.138, 0.107, 0.082, 0.061, 0.044, 0.032, 0.023, 0.017, 0.012, 0.008, 0.006, 0.004, 0.003, 0.002, 0.001, 0.001, 0.001, 0.001, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.012, 0.024, 0.049, 0.095, 0.174, 0.290, 0.461, 0.732, 1.066, 1.315, 1.467, 1.580, 1.617, 1.568, 1.472, 1.374, 1.292, 1.236, 1.114, 0.942, 0.756, 0.586, 0.447, 0.341, 0.264, 0.206, 0.154, 0.109, 0.077, 0.056, 0.041, 0.029, 0.020, 0.013, 0.009, 0.006, 0.004, 0.003, 0.002, 0.002, 0.002, 0.002, 0.001, 0.001, 0.001, 0.001, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], ]) cones_SmithPokorny = numpy.asarray([ [0.000000, 0.000000, 0.000000, 0.000000, 0.002660, 0.004380, 0.006890, 0.010800, 0.015800, 0.020000, 0.023300, 0.026800, 0.030100, 0.032400, 0.034300, 0.036800, 0.041200, 0.050200, 0.062700, 0.079800, 0.102000, 0.128000, 0.162000, 0.206000, 0.263000, 0.337000, 0.423000, 0.520000, 0.617000, 0.700000, 0.773000, 0.834000, 0.883000, 0.923000, 0.954000, 0.977000, 0.993000, 1.000000, 0.997000, 0.986000, 0.965000, 0.934000, 0.894000, 0.848000, 0.795000, 0.735000, 0.670000, 0.602000, 0.530000, 0.454000, 0.380000, 0.315000, 0.256000, 0.204000, 0.159000, 0.122000, 0.091400, 0.067000, 0.048200, 0.035000, 0.025700, 0.018000, 0.012400, 0.008660, 0.006210, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 0.000000, 0.000000, 0.002820, 0.004750, 0.007670, 0.012400, 0.018900, 0.025400, 0.031700, 0.039500, 0.047700, 0.055500, 0.063500, 0.073100, 0.086000, 0.107000, 0.130000, 0.157000, 0.189000, 0.224000, 0.267000, 0.324000, 0.396000, 0.491000, 0.595000, 0.706000, 0.808000, 0.884000, 0.941000, 0.978000, 0.997000, 0.999000, 0.987000, 0.961000, 0.922000, 0.870000, 0.806000, 0.732000, 0.651000, 0.564000, 0.477000, 0.393000, 0.318000, 0.250000, 0.193000, 0.147000, 0.110000, 0.080800, 0.058300, 0.041800, 0.029600, 0.020700, 0.014400, 0.010100, 0.006990, 0.004850, 0.003330, 0.002330, 0.001640, 0.001110, 0.000750, 0.000517, 0.000368, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 0.000000, 0.000000, 0.108000, 0.179000, 0.285000, 0.453000, 0.659000, 0.813000, 0.908000, 0.977000, 1.000000, 0.970000, 0.910000, 0.850000, 0.799000, 0.775000, 0.689000, 0.582000, 0.468000, 0.362000, 0.276000, 0.212000, 0.164000, 0.128000, 0.095600, 0.067600, 0.047400, 0.034700, 0.025600, 0.018200, 0.012400, 0.008260, 0.005450, 0.003650, 0.002530, 0.001840, 0.001440, 0.001260, 0.001160, 0.001000, 0.000812, 0.000741, 0.000610, 0.000479, 0.000312, 0.000240, 0.000198, 0.000132, 0.000090, 0.000068, 0.000053, 0.000038, 0.000025, 0.000019, 0.000014, 0.000010, 0.000008, 0.000005, 0.000004, 0.000003, 0.000002, 0.000001, 0.000001, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000], ]) ```
[ { "content": "```python\nfrom datetime import timedelta\n\nimport pytest\nfrom furl import furl\n\nfrom osf_tests.factories import (\n AuthUserFactory,\n PreprintFactory,\n PreprintProviderFactory,\n)\nfrom reviews.permissions import GroupHelper\nfrom reviews_tests.factories import ReviewLogFactory\nfr...
[ { "content": "<|memory_start|>```python\nfrom datetime import timedelta\n\nimport pytest\nfrom furl import furl\n\nfrom osf_tests.factories import (\n AuthUserFactory,\n PreprintFactory,\n PreprintProviderFactory,\n)\nfrom reviews.permissions import GroupHelper\nfrom reviews_tests.factories import Revi...
```python from datetime import timedelta import pytest from furl import furl from osf_tests.factories import ( AuthUserFactory, PreprintFactory, PreprintProviderFactory, ) from reviews.permissions import GroupHelper from reviews_tests.factories import ReviewLogFactory from website.util import permissions as osf_permissions @pytest.mark.django_db class ReviewLogCommentSettingsMixin(object): @pytest.fixture() def url(self): raise NotImplementedError @pytest.fixture() def provider(self): return PreprintProviderFactory() @pytest.fixture() def preprint(self, provider): return PreprintFactory(provider=provider) @pytest.fixture() def logs(self, preprint): return [ReviewLogFactory(reviewable=preprint) for _ in range(5)] @pytest.fixture() def provider_admin(self, provider): user = AuthUserFactory() user.groups.add(GroupHelper(provider).get_group('admin')) return user @pytest.fixture() def provider_moderator(self, provider): user = AuthUserFactory() user.groups.add(GroupHelper(provider).get_group('moderator')) return user @pytest.fixture() def node_admin(self, preprint): user = AuthUserFactory() preprint.node.add_contributor(user, permissions=[osf_permissions.READ, osf_permissions.WRITE, osf_permissions.ADMIN]) return user def test_comment_settings(self, app, url, provider, logs, provider_admin, provider_moderator, node_admin): expected_ids = set([l._id for l in logs]) for anonymous in [True, False]: for private in [True, False]: provider.reviews_comments_anonymous = anonymous provider.reviews_comments_private = private provider.save() # admin always sees comment/creator res = app.get(url, auth=provider_admin.auth) self.__assert_fields(res, expected_ids, False, False) # moderator always sees comment/creator res = app.get(url, auth=provider_moderator.auth) self.__assert_fields(res, expected_ids, False, False) # node admin sees what the settings allow res = app.get(url, auth=node_admin.auth) self.__assert_fields(res, expected_ids, anonymous, private) def __assert_fields(self, res, expected_ids, hidden_creator, hidden_comment): data = res.json['data'] actual_ids = set([l['id'] for l in data]) if expected_ids != actual_ids: raise Exception((expected_ids, actual_ids)) assert expected_ids == actual_ids for log in data: if hidden_creator: assert 'creator' not in log['relationships'] else: assert 'creator' in log['relationships'] if hidden_comment: assert 'comment' not in log['attributes'] else: assert 'comment' in log['attributes'] ```
[ { "content": "Here is some code:\n```python\n# Copyright 2015-2017 Cisco Systems, Inc.\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# ...
[ { "content": "Here is some code:\n<|memory_start|>```python\n# Copyright 2015-2017 Cisco Systems, Inc.\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License...
```python # Copyright 2015-2017 Cisco Systems, Inc. # 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. from __future__ import print_function from libbgp.bgp.message import Message update_msg_dict = { 'type': 2, 'msg': { 'attr': { 1: 2, 2: [(2, [701, 71])], 3: '219.158.1.204', 5: 100, 6: 0, 7: [71, '16.96.243.103'], 9: '219.158.1.204', 10: ['219.158.1.209', '0.0.0.30'] }, 'nlri': ['192.168.1.1/32', '172.16.1.1/32'], 'withdraw': [] } } update_msg = Message.pack(update_msg_dict) print(update_msg.hex_value) # >>> from __future__ import print_function # >>> # >>> from libbgp.bgp.message import Message # >>> # >>> # >>> update_msg_dict = { # ... 'type': 2, # ... 'msg': { # ... 'attr': { # ... 1: 2, # ... 2: [(2, [701, 71])], # ... 3: '219.158.1.204', # ... 5: 100, # ... 6: 0, # ... 7: [71, '16.96.243.103'], # ... 9: '219.158.1.204', # ... 10: ['219.158.1.209', '0.0.0.30'] # ... }, # ... 'nlri': ['192.168.1.1/32', '172.16.1.1/32'], # ... 'withdraw': [] # ... } # ... } # >>> # >>> update_msg = Message.pack(update_msg_dict) # >>> update_msg.value # {'attr': {1: 2, 2: [(2, [701, 71])], 3: '219.158.1.204', 5: 100, 6: 0, 7: [71, '16.96.243.103'], # 9: '219.158.1.204', 10: ['219.158.1.209', '0.0.0.30']}, 'withdraw': [], 'nlri': ['192.168.1.1/32', '172.16.1.1/32']} # >>> update_msg.hex_value # '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00[\x02\x00\x00 # \x00:@\x01\x01\x02@\x02\x06\x02\x02\x02\xbd\x00G@\x03\x04\xdb\x9e\x01\xcc@\x05\x04 # \x00\x00\x00d@\x06\x01\x00\xc0\x07\x06\x00G\x10`\xf3g\x80\t\x04\xdb\x9e\x01\xcc\x80 # \n\x08\xdb\x9e\x01\xd1\x00\x00\x00\x1e \xc0\xa8\x01\x01 \xac\x10\x01\x01' # >>> Message.unpack(update_msg.hex_value).value # {'nlri': ['192.168.1.1/32', '172.16.1.1/32'], 'withdraw': [], 'attr': {1: 2, 2: [(2, [701, 71])], # 3: '219.158.1.204', 5: 100, 6: 0, 7: [71, '16.96.243.103'], 9: '219.158.1.204', 10: ['219.158.1.209', '0.0.0.30']}} # >>> Message.unpack(update_msg.hex_value).value == update_msg.value # True # >>> ```
[ { "content": "Here is the code content:\n```python\nfrom flask import render_template, url_for, Response\n\nfrom common.config import read_config\nfrom common.utils import concat_url_path\nfrom web.content import content\n\n\n@content.route('/jquery', methods=['GET'])\ndef get_jquery():\n \"\"\" Returns the ...
[ { "content": "Here is the code content:\n<|memory_start|>```python\nfrom flask import render_template, url_for, Response\n\nfrom common.config import read_config\nfrom common.utils import concat_url_path\nfrom web.content import content\n\n\n@content.route('/jquery', methods=['GET'])\ndef get_jquery():\n \"\...
```python from flask import render_template, url_for, Response from common.config import read_config from common.utils import concat_url_path from web.content import content @content.route('/jquery', methods=['GET']) def get_jquery(): """ Returns the jQuery.js file """ return render_template('javascript/jquery.js') @content.route('/prune', methods=['GET']) def get_prune(): """ Returns the prune.js file """ return render_template('javascript/prune.js') @content.route('/js', methods=['GET']) def get_javascript(): """ The view that returns the actual javascript shell to the client. It takes in consideration configuration from the `config.json` file. It also appends the dependencies which are `jQuery` and `JSON.prune`. """ config = read_config() url = config.get('URL', '//') shell_javascript = render_template( 'javascript/shell.js', post_back_url=concat_url_path(url, url_for('api.post_back')), poll_url=concat_url_path(url, url_for('api.poll_new_commands')), register_url=concat_url_path(url, url_for('api.register')) ) script_content = '\n\n'.join([ render_template('javascript/jquery.js'), 'var JJ = $.noConflict(true);;', render_template('javascript/prune.js'), shell_javascript ]) return Response(script_content, mimetype='application/javascript') ```
[ { "content": "```python\nimport os\nfrom gdcdatamodel import models as m\nfrom graphviz import Digraph\n\n\ndef build_visualization():\n print('Building schema documentation...')\n\n # Load directory tree info\n bin_dir = os.path.dirname(os.path.realpath(__file__))\n root_dir = os.path.join(os.path....
[ { "content": "<|memory_start|>```python\nimport os\nfrom gdcdatamodel import models as m\nfrom graphviz import Digraph\n\n\ndef build_visualization():\n print('Building schema documentation...')\n\n # Load directory tree info\n bin_dir = os.path.dirname(os.path.realpath(__file__))\n root_dir = os.pa...
```python import os from gdcdatamodel import models as m from graphviz import Digraph def build_visualization(): print('Building schema documentation...') # Load directory tree info bin_dir = os.path.dirname(os.path.realpath(__file__)) root_dir = os.path.join(os.path.abspath( os.path.join(bin_dir, os.pardir, os.pardir))) # Create graph dot = Digraph( comment="High level graph representation of GDC data model", format='pdf') dot.graph_attr['rankdir'] = 'RL' dot.node_attr['fillcolor'] = 'lightblue' dot.node_attr['style'] = 'filled' # Add nodes for node in m.Node.get_subclasses(): label = node.get_label() print label dot.node(label, label) # Add edges for edge in m.Edge.get_subclasses(): if edge.__dst_class__ == 'Case' and edge.label == 'relates_to': # Skip case cache edges continue src = m.Node.get_subclass_named(edge.__src_class__) dst = m.Node.get_subclass_named(edge.__dst_class__) dot.edge(src.get_label(), dst.get_label(), edge.get_label()) gv_path = os.path.join(root_dir, 'docs', 'viz', 'gdc_data_model.gv') dot.render(gv_path) print('graphviz output to {}'.format(gv_path)) if __name__ == '__main__': build_visualization() ```
[ { "content": "Return the code unaltered:\n```python\n# Copyright (c) 2012, 2013 Rich Porter - see LICENSE for further details\n\nimport re\n\nimport coverage\nimport database\nimport mdb\nimport message\n\n################################################################################\n\n# ids can be given in ...
[ { "content": "Return the code unaltered:\n<|memory_start|>```python\n# Copyright (c) 2012, 2013 Rich Porter - see LICENSE for further details\n\nimport re\n\nimport coverage\nimport database\nimport mdb\nimport message\n\n################################################################################\n\n# ids ...
```python # Copyright (c) 2012, 2013 Rich Porter - see LICENSE for further details import re import coverage import database import mdb import message ################################################################################ # ids can be given in the form range-or-id,+ # where range-or-id is [0-9]+(..[0-9]+) parser = message.reportOptionParser() parser.add_option('', '--order', help='order sequence '+str(database.optimize.options.keys()), default=[], action='append', choices=database.optimize.options.keys()) parser.add_option('-r', '--regression', default=[], help='Regression root id', action='append') parser.add_option('', '--robust', default=False, help='Attempt to make test set robust', action='store_true') parser.add_option('-t', '--test', default=[], help='Test id', action='append') parser.add_option('', '--threshold', default=0, help='Coverage threshold for "incr" order') parser.add_option('-x', '--xml', help='xml out', default='optimize_%d.xml') options, values = parser.parse_args() ################################################################################ mdb.db.connection.set_default_db(db='../db/mdb.db') mdb_conn=mdb.mdb('optimize', activity='optimizing') ################################################################################ # generate lists def to_list(args, values=[]) : def ignoring(arg) : message.warning('Ignoring %(arg)s', arg=arg) def cast(x) : try : return int(x) except : ignoring(x) return None if isinstance(args, list) : return to_list(args[1:], to_list(args[0], values)) if args else values _args = args.split(',') if len(_args) > 1 : return to_list(_args, values) _match = re.match('(?P<from>\d+)\.{2,3}(?P<to>\d+)', args) if _match : _to, _from = cast(_match.group('to')), cast(_match.group('from')) if _from > _to : _to, _from = _from, _to if _to is not None and _from is not None : return range(_from, _to + 1) + values ignoring(args) return values if cast(args) : return [cast(args), ] + values return values ################################################################################ if not options.order : options.order = ['cvg', ] if options.regression is None : # presume leftover args are ids options.regression = values regressions = to_list(options.regression) tests = to_list(options.test) if not regressions and not tests : message.fatal('No invocations provided') message.information('optimizing begins') ################################################################################ coverage.messages.hush_creation() optimize_opts = {'threshold' : options.threshold, 'robust' : options.robust} def iteration(ordering, iter_cnt=1, xml=None) : # use current optimization group if this is not first iteration order = ordering[0] message.note('Iteration %(iter_cnt)d uses "%(order)s"', **locals()) if xml : opt = database.optimize.options[order](xml=xml, **optimize_opts) else : opt = database.optimize.options[order](regressions, tests, **optimize_opts) run = opt.run() optimize_opts['previous'] = opt if len(ordering) > 1 : return iteration(ordering[1:], iter_cnt+1, run) # always return last optimization run return opt, run opt, xml = iteration(options.order) # annotate optimized coverage result to this invocation opt.insert(mdb_conn.log_id) ################################################################################ if options.xml : try : outfile = options.xml % (regressions[0] if regressions else tests[0]) except : outfile = options.xml message.information('dumping optimize to ' + outfile) with open(outfile, 'w') as desc : xml.write(desc) message.success('optimizing ends') mdb.finalize_all() ```
[ { "content": "Here is the source code:\n```python\n# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n DemTools\n A QGIS plugin\n A suite of tools for doing neat things with DEMs\n ----------...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n DemTools\n A QGIS plugin\n A suite of tools for doing neat things with DEMs\n ...
```python # -*- coding: utf-8 -*- """ /*************************************************************************** DemTools A QGIS plugin A suite of tools for doing neat things with DEMs ------------------- begin : 2014-05-15 copyright : (C) 2014 by Kris Hammerberg email : kris.hammerberg@gmail.com ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ """ # Import the PyQt and QGIS libraries from PyQt4.QtCore import * from PyQt4.QtGui import * from qgis.core import * # Initialize Qt resources from file resources.py import resources_rc # Import the code for the dialog import os.path import sys from shaDEM import shaDEM from svf import svf from solaraccess import SolarAccess class DemTools: def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # save reference to tool interfaces self.shaDEM = shaDEM(iface) self.svf = svf(iface) self.SolarAccess = SolarAccess(iface) # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value("locale/userLocale")[0:2] localePath = os.path.join(self.plugin_dir, 'i18n', 'demtools_{}.qm'.format(locale)) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) #check necessary libraries try: import numpy import numexpr except ImportError: QMessageBox.critical( self.iface.mainWindow(),"ImportError", "Plugin requires Numpy & Numexpr libraries.\n\See http://www.numpy.org & https://code.google.com/p/numexpr/" ) try: import Pysolar as solar except ImportError: try: import solar except ImportError: QMessageBox.critical( self.iface.mainWindow(),"ImportError", "Plugin requires Pysolar libraries.\n\See http://pysolar.org/" ) def initGui(self): # Create action that will start plugin configuration self.shaDEMact = QAction( QIcon(":/plugins/demtools/shaDEM.png"), u"ShaDEM", self.iface.mainWindow()) self.SVFact = QAction( QIcon(":/plugins/demtools/SVF.png"), u"SVF", self.iface.mainWindow()) self.solaract = QAction( QIcon(":/plugins/demtools/solaraccess.png"), u"SolarAccess", self.iface.mainWindow()) # connect the actions to the run methods self.shaDEMact.triggered.connect(self.shaDEM.start) self.SVFact.triggered.connect(self.svf.start) self.solaract.triggered.connect(self.SolarAccess.start) # Add toolbar buttons and menu items self.iface.addToolBarIcon(self.shaDEMact) self.iface.addPluginToRasterMenu(u"&DEM Tools", self.shaDEMact) self.iface.addToolBarIcon(self.SVFact) self.iface.addPluginToRasterMenu(u"&DEM Tools", self.SVFact) self.iface.addToolBarIcon(self.solaract) self.iface.addPluginToRasterMenu(u"&DEM Tools", self.solaract) def unload(self): # Remove the plugin menu items and icons self.iface.removePluginRasterMenu(u"&DEM Tools", self.shaDEMact) self.iface.removeToolBarIcon(self.shaDEMact) self.iface.removePluginRasterMenu(u"&DEM Tools", self.SVFact) self.iface.removeToolBarIcon(self.SVFact) self.iface.removePluginRasterMenu(u"&DEM Tools", self.solaract) self.iface.removeToolBarIcon(self.solaract) ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\n# -*- coding:utf-8 -*-\n#--\n# Copyright (c) 2012-2014 Net-ng.\n# All rights reserved.\n#\n# This software is licensed under the BSD License, as described in\n# the file LICENSE.txt, which you should have received as p...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\n# -*- coding:utf-8 -*-\n#--\n# Copyright (c) 2012-2014 Net-ng.\n# All rights reserved.\n#\n# This software is licensed under the BSD License, as described in\n# the file LICENSE.txt, which you should ha...
```python # -*- coding:utf-8 -*- #-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- from nagare import security from peak.rules import when from nagare.security import common from kansha.card import Card from kansha.cardextension import CardExtension from kansha.board import VOTES_PUBLIC, VOTES_MEMBERS from .models import DataVote class Votes(CardExtension): '''Vote component''' LOAD_PRIORITY = 70 @property def allowed(self): return self.configurator.votes_allowed def count_votes(self): '''Returns number of votes for a card''' return DataVote.count_votes(self.card.data) def toggle(self): '''Add a vote to the current card. Remove vote if user has already voted ''' security.check_permissions('vote', self) user = security.get_user() if self.has_voted(): DataVote.get_vote(self.card.data, user.data).delete() else: DataVote(card=self.card.data, user=user.data) def has_voted(self): '''Check if the current user already vote for this card''' user = security.get_user() return DataVote.has_voted(self.card.data, user.data) def delete(self): DataVote.purge(self.card.data) # FIXME: redesign security from scratch @when(common.Rules.has_permission, "user and perm == 'vote' and isinstance(subject, Votes)") def has_permission_Card_vote(self, user, perm, votes): return ((security.has_permissions('edit', votes.card) and votes.allowed == VOTES_MEMBERS) or (votes.allowed == VOTES_PUBLIC and user)) ```
[ { "content": "Reconstruct the code exactly:\n```python\n# -*- coding: UTF-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF ...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n# -*- coding: UTF-8 -*-\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright owne...
```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. r"""Project dashboard for Apache(TM) Bloodhound WikiMacros and WikiProcessors related to dashboard system. """ from ast import literal_eval from genshi.builder import tag from trac.web.chrome import Chrome from trac.wiki.api import parse_args from trac.wiki.macros import WikiMacroBase from bhdashboard.web_ui import DashboardChrome, DashboardModule GUIDE_NAME = 'Guide' RENAME_MAP = {'TracGuide': GUIDE_NAME + '/Index',} def new_name(name, force=False): if name.startswith('Trac'): return RENAME_MAP.get(name, GUIDE_NAME + '/' + name[4:]) else: return name class WidgetMacro(WikiMacroBase): """Embed Bloodhound widgets using WikiFormatting. """ #: A gettext domain to translate the macro description _domain = None #: A macro description _description = """Embed Bloodhound widgets using WikiFormatting.""" def expand_macro(self, formatter, name, content): """Render widget contents by re-using wiki markup implementation """ if self.env[DashboardModule] is None: return DashboardModule(self.env).alert_disabled() largs, kwargs = parse_args(content, strict=True) try: (widget_name ,) = largs except ValueError: template = 'widget_alert.html' data = { 'msgtype' : 'error', 'msglabel' : 'Error', 'msgbody' : tag('Expected ', tag.code(1), ' positional argument (i.e. widget name), but got ', tag.code(len(largs)), ' instead'), 'msgdetails' : [ ('Macro name', tag.code('WidgetMacro')), ('Arguments', ', '.join(largs) if largs \ else tag.span('None', class_='label')), ], } else: widget_name = widget_name.strip() wopts = {} ; wargs = {} def parse_literal(value): try: return literal_eval(value) except (SyntaxError, ValueError): return value for argnm, value in kwargs.iteritems(): if argnm.startswith('wo_'): wopts[argnm[3:]] = value else : wargs[argnm] = parse_literal(value) template = 'widget.html' data = { 'args' : wargs, 'bhdb' : DashboardChrome(self.env), 'id' : None, 'opts' : wopts, 'widget' : widget_name } return Chrome(self.env).render_template( formatter.req, template, data, fragment=True) ```
[ { "content": "```python\nfrom dopamine.environments import TestEnvironment\nfrom dopamine.environments import DiscreteCartPoleEnvironment, CartPoleRenderer\n\nfrom dopamine.agents import QAgent, SARSAAgent\nfrom dopamine.experiments import Experiment\nfrom dopamine.adapters import EpsilonGreedyExplorer, VQState...
[ { "content": "<|memory_start|>```python\nfrom dopamine.environments import TestEnvironment\nfrom dopamine.environments import DiscreteCartPoleEnvironment, CartPoleRenderer\n\nfrom dopamine.agents import QAgent, SARSAAgent\nfrom dopamine.experiments import Experiment\nfrom dopamine.adapters import EpsilonGreedyE...
```python from dopamine.environments import TestEnvironment from dopamine.environments import DiscreteCartPoleEnvironment, CartPoleRenderer from dopamine.agents import QAgent, SARSAAgent from dopamine.experiments import Experiment from dopamine.adapters import EpsilonGreedyExplorer, VQStateDiscretizationAdapter from matplotlib import pyplot as plt from numpy import * import time # create agent, environment, renderer, experiment agent = SARSAAgent() environment = DiscreteCartPoleEnvironment() experiment = Experiment(environment, agent) # add discretization adapter discretizer = VQStateDiscretizationAdapter(30) experiment.addAdapter(discretizer) # add e-greedy exploration explorer = EpsilonGreedyExplorer(0.3, episodeCount=1000) experiment.addAdapter(explorer) # force experiment setup now experiment.setup() for i in range(len(discretizer.stateVectors)): plt.text(discretizer.stateVectors[i,0], discretizer.stateVectors[i,1], "%i"%i, bbox=dict(facecolor='green', alpha=0.5)) plt.xlim(-2.5, 2.5) plt.ylim(-10, 10) plt.show() agent.forget() explorer.epsilon = 0.3 # renderer = CartPoleRenderer() # environment.renderer = renderer # renderer.start() # run experiment for i in range(1000): experiment.runEpisode(reset=True) discretizer.adaptClusters() agent.learn() print "sum rewards:", sum(agent.episode.rewards) print "exploration:", explorer.epsilon ```
[ { "content": "Here is the source code:\n```python\n#!python\n\nimport random, time\n\nclass RandomGenerator:\n def __init__(self):\n random.seed(time.clock())\n \n def generate_uniform(self, min_v, max_v):\n return random.uniform(min_v, max_v)\n \n def generate_int(self, min...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n#!python\n\nimport random, time\n\nclass RandomGenerator:\n def __init__(self):\n random.seed(time.clock())\n \n def generate_uniform(self, min_v, max_v):\n return random.uniform(min_v, max_v)\n \n def genera...
```python #!python import random, time class RandomGenerator: def __init__(self): random.seed(time.clock()) def generate_uniform(self, min_v, max_v): return random.uniform(min_v, max_v) def generate_int(self, min_v, max_v): return random.randint(min_v, max_v) def generate_int_sequence_no_repetitions(self, length, min_v, max_v): ret = set() if length > max_v - min_v + 1: raise ValueError("Requested a length of " + str(length) + " for an interval of " + str(max_v - min_v + 1)) while len(ret) < length: val = ret.add(self.generate_int(min_v, max_v)) return sorted(ret) def generate_int_sequence(self, length, min_v, max_v): ret = list() while len(ret) < length: ret.append(self.generate_int(min_v, max_v)) return ret class RandomGeneratorDeterministic(RandomGenerator): def __init__(self): random.seed(0) def generate_uniform(self, min_v, max_v): return (max_v - min_v) /2 def generate_int(self, min_v, max_v): return 42 ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\nfrom __future__ import absolute_import\nfrom .nixbase import NixBase\nimport numpy as np\n\n\nclass WeightStack(NixBase):\n\n def __init__(self, nix_object):\n super(WeightStack, self).__init__(nix_object)\n ...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\nfrom __future__ import absolute_import\nfrom .nixbase import NixBase\nimport numpy as np\n\n\nclass WeightStack(NixBase):\n\n def __init__(self, nix_object):\n super(WeightStack, self).__init_...
```python from __future__ import absolute_import from .nixbase import NixBase import numpy as np class WeightStack(NixBase): def __init__(self, nix_object): super(WeightStack, self).__init__(nix_object) self._sources = [] self._targets = [] @property def data(self): return self._nix_object.data @property def data_type(self): return self._nix_object.data_type @property def dimensions(self): return self._nix_object.dimensions def append_snapshot(self, snapshot, time): self.data.append(snapshot) # extend time dimension if len(self._nix_object.dimensions) == 0: self.build_dimensions([time], self._sources, self._targets) else: dim = self._nix_object.dimensions[0] dim.ticks = np.array(list(dim.ticks) + [time]) def build_dimensions(self, times, sources, targets): """ Builds dimensions according to the given values. :param times: ticks for time domain (in 'ms') :param sources: list of NEST IDs of sources :param targets: list of NEST IDs of targets :return: """ for dim in (times, sources, targets): assert(len(dim) > 0) nix_array = self._nix_object nix_array.append_range_dimension(times) nix_array.append_range_dimension(sorted(sources)) nix_array.append_range_dimension(sorted(targets)) nix_array.dimensions[0].unit = 'ms' nix_array.dimensions[0].label = 'time' nix_array.dimensions[1].label = 'source' nix_array.dimensions[2].label = 'target' @staticmethod def create_weight_stack(where, name, weights, sources, targets, times=()): """ Creates a Stack with connection weights evolution in time. :param name: name of the weight stack (str) :param where: block where to create Node (nix::Block) :param weights: 3D array with connection weights. Dimensions: - time (1) - source (2) - target (3) :return: instance of WeightStack """ assert(hasattr(weights, 'dtype')) assert(len(weights.shape) == 3) for dim in (sources, targets): assert(len(dim) > 0) params = name, 'weightstack', weights.dtype, weights.shape ws = where.create_data_array(*params) ws.data.append(weights) weightstack = WeightStack(ws) if len(times) > 0: weightstack.build_dimensions(sources, targets, times) else: # need to temporary store these because 'time' should be first weightstack._sources = sources weightstack._targets = targets return weightstack ```
[ { "content": "Reconstruct the code exactly:\n```python\n\"\"\"GPU-based interactive Mandelbrot fractal example.\"\"\"\nfrom galry import *\nimport numpy as np\nimport numpy.random as rdn\n\nFSH = \"\"\"\n// take a position and a number of iterations, and\n// returns the first iteration where the system escapes ...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n\"\"\"GPU-based interactive Mandelbrot fractal example.\"\"\"\nfrom galry import *\nimport numpy as np\nimport numpy.random as rdn\n\nFSH = \"\"\"\n// take a position and a number of iterations, and\n// returns the first iteration where the...
```python """GPU-based interactive Mandelbrot fractal example.""" from galry import * import numpy as np import numpy.random as rdn FSH = """ // take a position and a number of iterations, and // returns the first iteration where the system escapes a box of size N. int mandelbrot_escape(vec2 pos, int iterations) { vec2 z = vec2(0., 0.); int n = 0; int N = 10; int N2 = N * N; float r2 = 0.; for (int i = 0; i < iterations; i++) { float zx = z.x * z.x - z.y * z.y + pos.x; float zy = 2 * z.x * z.y + pos.y; r2 = zx * zx + zy * zy; if (r2 > N2) { n = i; break; } z = vec2(zx, zy); } return n; } """ FS = """ // this vector contains the coordinates of the current pixel // varying_tex_coords contains a position in [0,1]^2 vec2 pos = vec2(-2.0 + 3. * varying_tex_coords.x, -1.5 + 3. * varying_tex_coords.y); // run mandelbrot system int n = mandelbrot_escape(pos, iterations); float c = log(float(n)) / log(float(iterations)); // compute the red value as a function of n out_color = vec4(c, 0., 0., 1.); """ def get_iterations(zoom=1): return int(500 * np.log(1 + zoom)) class MandelbrotVisual(TextureVisual): def initialize_fragment(self): self.add_fragment_header(FSH) self.add_fragment_main(FS) def base_mandelbrot(self, iterations=None): if iterations is None: iterations = get_iterations() self.add_uniform("iterations", vartype="int", ndim=1, data=iterations) def initialize(self, *args, **kwargs): iterations = kwargs.pop('iterations', None) super(MandelbrotVisual, self).initialize(*args, **kwargs) self.base_mandelbrot(iterations) def update(figure, parameter): zoom = figure.get_processor('navigation').sx figure.set_data(iterations=get_iterations(zoom)) figure(constrain_ratio=True, constrain_navigation=True,) visual(MandelbrotVisual) # event('Pan', pan) event('Zoom', update) show() ```
[ { "content": "Provide an exact copy of the source code:\n```python\n# Copyright 2015 Google Inc. 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# h...
[ { "content": "Provide an exact copy of the source code:\n<|memory_start|>```python\n# Copyright 2015 Google Inc. 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 Licens...
```python # Copyright 2015 Google Inc. 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. # ============================================================================== """Functional tests for shape inference helper classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.framework import test_util from tensorflow.python.platform import googletest class DimensionTest(test_util.TensorFlowTestCase): def testDimension(self): dim = tensor_shape.Dimension(12) self.assertEqual(12, dim.value) self.assertEqual(12, int(dim)) self.assertEqual(dim, tensor_shape.Dimension(12)) self.assertEqual(tensor_shape.Dimension(15), dim + tensor_shape.Dimension(3)) self.assertEqual(tensor_shape.Dimension(15), dim + 3) self.assertEqual(tensor_shape.Dimension(24), dim * tensor_shape.Dimension(2)) self.assertEqual(tensor_shape.Dimension(24), dim * 2) self.assertEqual( tensor_shape.Dimension(6), dim // tensor_shape.Dimension(2)) self.assertEqual(tensor_shape.Dimension(6), dim // 2) self.assertEqual(tensor_shape.Dimension(12), dim.merge_with(tensor_shape.Dimension(12))) self.assertEqual(tensor_shape.Dimension(12), dim.merge_with(12)) self.assertLess(tensor_shape.Dimension(12), tensor_shape.Dimension(13)) self.assertGreater(tensor_shape.Dimension(13), tensor_shape.Dimension(12)) self.assertLessEqual(tensor_shape.Dimension(12), tensor_shape.Dimension(12)) self.assertLessEqual(tensor_shape.Dimension(12), tensor_shape.Dimension(13)) self.assertGreater(tensor_shape.Dimension(13), tensor_shape.Dimension(12)) self.assertGreaterEqual(tensor_shape.Dimension(12), tensor_shape.Dimension(12)) self.assertGreaterEqual(tensor_shape.Dimension(13), tensor_shape.Dimension(12)) with self.assertRaises(ValueError): dim.merge_with(tensor_shape.Dimension(13)) def testUnknownDimension(self): dim = tensor_shape.Dimension(None) self.assertIs(None, dim.value) self.assertEqual(dim.value, tensor_shape.Dimension(None).value) self.assertEqual(tensor_shape.Dimension(None).value, (dim + tensor_shape.Dimension(None)).value) self.assertEqual(tensor_shape.Dimension(None).value, (dim * tensor_shape.Dimension(None)).value) self.assertEqual( tensor_shape.Dimension(None).value, (dim // tensor_shape.Dimension(None)).value) self.assertEqual(tensor_shape.Dimension(None).value, dim.merge_with(tensor_shape.Dimension(None)).value) self.assertIs(None, tensor_shape.Dimension(None) < tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(None) <= tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(None) > tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(None) >= tensor_shape.Dimension(None)) def testKnownAndUnknownDimensions(self): known = tensor_shape.Dimension(12) unknown = tensor_shape.Dimension(None) self.assertEqual( tensor_shape.Dimension(None).value, (known + unknown).value) self.assertEqual( tensor_shape.Dimension(None).value, (unknown + known).value) self.assertEqual( tensor_shape.Dimension(None).value, (known * unknown).value) self.assertEqual( tensor_shape.Dimension(None).value, (unknown * known).value) self.assertEqual( tensor_shape.Dimension(None).value, (known // unknown).value) self.assertEqual( tensor_shape.Dimension(None).value, (unknown // known).value) self.assertEqual( tensor_shape.Dimension(12), known.merge_with(unknown)) self.assertEqual( tensor_shape.Dimension(12), unknown.merge_with(known)) self.assertIs(None, tensor_shape.Dimension(12) < tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(12) <= tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(12) > tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(12) >= tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(None) < tensor_shape.Dimension(12)) self.assertIs(None, tensor_shape.Dimension(None) <= tensor_shape.Dimension(12)) self.assertIs(None, tensor_shape.Dimension(None) > tensor_shape.Dimension(12)) self.assertIs(None, tensor_shape.Dimension(None) >= tensor_shape.Dimension(12)) def testAsDimension(self): self.assertEqual(tensor_shape.Dimension(12), tensor_shape.as_dimension(tensor_shape.Dimension(12))) self.assertEqual(tensor_shape.Dimension(12), tensor_shape.as_dimension(12)) self.assertEqual( tensor_shape.Dimension(None).value, tensor_shape.as_dimension(tensor_shape.Dimension(None)).value) self.assertEqual(tensor_shape.Dimension(None).value, tensor_shape.as_dimension(None).value) def testEquality(self): self.assertTrue(tensor_shape.Dimension(12) == tensor_shape.Dimension(12)) self.assertFalse(tensor_shape.Dimension(12) == tensor_shape.Dimension(13)) self.assertIs(None, tensor_shape.Dimension(12) == tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(None) == tensor_shape.Dimension(12)) self.assertIs(None, tensor_shape.Dimension(None) == tensor_shape.Dimension(None)) def testInequality(self): self.assertTrue(tensor_shape.Dimension(12) != tensor_shape.Dimension(13)) self.assertFalse(tensor_shape.Dimension(12) != tensor_shape.Dimension(12)) self.assertIs(None, tensor_shape.Dimension(12) != tensor_shape.Dimension(None)) self.assertIs(None, tensor_shape.Dimension(None) != tensor_shape.Dimension(12)) self.assertIs(None, tensor_shape.Dimension(None) != tensor_shape.Dimension(None)) class ShapeTest(test_util.TensorFlowTestCase): def testUnknownShape(self): s = tensor_shape.TensorShape(None) with self.assertRaises(ValueError): s.assert_is_fully_defined() self.assertIs(None, s.ndims) with self.assertRaises(ValueError): len(s) self.assertFalse(s) self.assertIs(None, s.dims) def testFullyDefinedShape(self): s = tensor_shape.TensorShape([tensor_shape.Dimension(3), tensor_shape.Dimension(4), tensor_shape.Dimension(7)]) s.assert_is_fully_defined() self.assertEqual(3, s.ndims) self.assertEqual(3, len(s)) self.assertTrue(s) s.assert_has_rank(3) self.assertEqual([tensor_shape.Dimension(3), tensor_shape.Dimension(4), tensor_shape.Dimension(7)], s.dims) self.assertEqual(tensor_shape.Dimension(3), s[0]) self.assertEqual(tensor_shape.Dimension(4), s[1]) self.assertEqual(tensor_shape.Dimension(7), s[2]) self.assertEqual([3, 4, 7], s.as_list()) s.assert_is_compatible_with([3, 4, 7]) s.assert_same_rank([6, 3, 7]) def testPartiallyDefinedShape(self): s = tensor_shape.TensorShape([tensor_shape.Dimension(3), tensor_shape.Dimension(None), tensor_shape.Dimension(7)]) with self.assertRaises(ValueError): s.assert_is_fully_defined() self.assertEqual(3, s.ndims) self.assertEqual(3, len(s)) self.assertTrue(s) s.assert_has_rank(3) self.assertEqual(tensor_shape.Dimension(3), s[0]) self.assertEqual(tensor_shape.Dimension(None).value, s[1].value) self.assertEqual(tensor_shape.Dimension(7), s[2]) s.assert_same_rank([6, 3, 7]) def testMergeFullShapes(self): self.assertEqual([3, 4, 7], tensor_shape.TensorShape([3, 4, 7]).merge_with( tensor_shape.TensorShape([3, 4, 7])).as_list()) with self.assertRaises(ValueError): tensor_shape.TensorShape([3, 4, 7]).merge_with( tensor_shape.TensorShape([6, 3, 7])) def testMergePartialShapes(self): s1 = tensor_shape.TensorShape([tensor_shape.Dimension(3), tensor_shape.Dimension(None), tensor_shape.Dimension(7)]) s2 = tensor_shape.TensorShape([tensor_shape.Dimension(None), tensor_shape.Dimension(4), tensor_shape.Dimension(7)]) self.assertEqual([3, 4, 7], s1.merge_with(s2).as_list()) def testMergeFullAndUnknownShape(self): self.assertEqual([3, 4, 7], tensor_shape.TensorShape([3, 4, 7]).merge_with( tensor_shape.TensorShape(None)).as_list()) def testSlice(self): known = tensor_shape.TensorShape([0, 1, 2, 3, 4]) self.assertEqual(tensor_shape.Dimension(2), known[2]) tensor_shape.TensorShape([1, 2, 3]).assert_is_compatible_with(known[1:4]) unknown = tensor_shape.TensorShape(None) self.assertEqual(tensor_shape.Dimension(None).value, unknown[2].value) tensor_shape.TensorShape( [None, None, None]).assert_is_compatible_with(unknown[1:4]) def testConcatenate(self): tensor_shape.TensorShape([1, 2, 3, 4]).assert_is_compatible_with( tensor_shape.TensorShape([1, 2]).concatenate( tensor_shape.TensorShape([3, 4]))) tensor_shape.TensorShape([1, 2, 3, 4]).assert_is_compatible_with( tensor_shape.TensorShape([1, 2]).concatenate( tensor_shape.TensorShape(None))) tensor_shape.TensorShape([1, 2, 3, 4]).assert_is_compatible_with( tensor_shape.TensorShape(None).concatenate( tensor_shape.TensorShape([3, 4]))) tensor_shape.TensorShape([1, 2, 3, 4]).assert_is_compatible_with( tensor_shape.TensorShape(None).concatenate( tensor_shape.TensorShape(None))) tensor_shape.TensorShape([1, 2, 3]).assert_is_compatible_with( tensor_shape.TensorShape([1, 2]).concatenate( tensor_shape.Dimension(3))) def testHelpers(self): tensor_shape.TensorShape([]).assert_is_compatible_with( tensor_shape.scalar()) tensor_shape.TensorShape([37]).assert_is_compatible_with( tensor_shape.vector(37)) tensor_shape.TensorShape( [94, 43]).assert_is_compatible_with(tensor_shape.matrix(94, 43)) def testTruedivFails(self): unknown = tensor_shape.Dimension(None) self.assertEqual((unknown // unknown).value, None) with self.assertRaisesRegexp(TypeError, r"unsupported operand type"): unknown / unknown # pylint: disable=pointless-statement def testConvertFromProto(self): proto = tensor_util.make_tensor_shape_proto([]) self.assertEqual(tensor_shape.TensorShape([]), tensor_shape.TensorShape(proto)) self.assertEqual(tensor_shape.TensorShape([]), tensor_shape.as_shape(proto)) proto = tensor_util.make_tensor_shape_proto([1, 37, 42]) self.assertEqual(tensor_shape.TensorShape([1, 37, 42]), tensor_shape.TensorShape(proto)) self.assertEqual(tensor_shape.TensorShape([1, 37, 42]), tensor_shape.as_shape(proto)) partial_proto_shape = tensor_shape.as_shape( tensor_util.make_tensor_shape_proto([-1, 37, 42])) partial_shape = tensor_shape.TensorShape([None, 37, 42]) self.assertNotEqual(partial_proto_shape, partial_shape) self.assertEqual(partial_proto_shape[0].value, None) self.assertEqual(partial_proto_shape[1].value, 37) self.assertEqual(partial_proto_shape[2].value, 42) self.assertTrue(partial_shape.is_compatible_with(partial_proto_shape)) def testStr(self): self.assertEqual("<unknown>", str(tensor_shape.unknown_shape())) self.assertEqual("(?,)", str(tensor_shape.unknown_shape(ndims=1))) self.assertEqual("(?, ?)", str(tensor_shape.unknown_shape(ndims=2))) self.assertEqual("(?, ?, ?)", str(tensor_shape.unknown_shape(ndims=3))) self.assertEqual("()", str(tensor_shape.scalar())) self.assertEqual("(7,)", str(tensor_shape.vector(7))) self.assertEqual("(3, 8)", str(tensor_shape.matrix(3, 8))) self.assertEqual("(4, 5, 2)", str(tensor_shape.TensorShape([4, 5, 2]))) self.assertEqual("(32, ?, 1, 9)", str(tensor_shape.TensorShape([32, None, 1, 9]))) if __name__ == "__main__": googletest.main() ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\nfrom django.db import models\n\nfrom sigma_chat.models.chat_member import ChatMember\nfrom sigma_chat.models.chat import Chat\n\n\ndef chat_directory_path(instance, filename):\n # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>\n return 'uploads/c...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\nfrom django.db import models\n\nfrom sigma_chat.models.chat_member import ChatMember\nfrom sigma_chat.models.chat import Chat\n\n\ndef chat_directory_path(instance, filename):\n # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>\n r...
```python # -*- coding: utf-8 -*- from django.db import models from sigma_chat.models.chat_member import ChatMember from sigma_chat.models.chat import Chat def chat_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'uploads/chats/{0}/{1}'.format(instance.chat_id.id, filename) class Message(models.Model): text = models.TextField(blank=True) chatmember_id = models.ForeignKey(ChatMember, related_name='chatmember_message') chat_id = models.ForeignKey(Chat, related_name='message') date = models.DateTimeField(auto_now=True) attachment = models.FileField(upload_to=chat_directory_path, blank=True) ################################################################ # PERMISSIONS # ################################################################ @staticmethod def has_read_permission(request): return True def has_object_read_permission(self, request): return request.user.is_member(self.chat) @staticmethod def has_write_permission(request): return True def has_object_write_permission(self, request): return request.user == self.chatmember.user and self.chatmember.is_member ```
[ { "content": "```python\n\"\"\"\nPlatform-specific code lives here.\n\nThis is its own module to abstract away what would otherwise be distracting\nlogic-flow interruptions.\n\"\"\"\n\nfrom contextlib import contextmanager\nimport select\nimport sys\n\n# TODO: move in here? They're currently platform-agnostic.....
[ { "content": "<|memory_start|>```python\n\"\"\"\nPlatform-specific code lives here.\n\nThis is its own module to abstract away what would otherwise be distracting\nlogic-flow interruptions.\n\"\"\"\n\nfrom contextlib import contextmanager\nimport select\nimport sys\n\n# TODO: move in here? They're currently pla...
```python """ Platform-specific code lives here. This is its own module to abstract away what would otherwise be distracting logic-flow interruptions. """ from contextlib import contextmanager import select import sys # TODO: move in here? They're currently platform-agnostic... from .util import has_fileno, isatty WINDOWS = (sys.platform == 'win32') """ Whether or not the current platform appears to be Windows in nature. Note that Cygwin's Python is actually close enough to "real" UNIXes that it doesn't need (or want!) to use PyWin32 -- so we only test for literal Win32 setups (vanilla Python, ActiveState etc) here. """ if WINDOWS: import msvcrt from ctypes import Structure, c_ushort, windll, POINTER, byref from ctypes.wintypes import HANDLE, _COORD, _SMALL_RECT else: import fcntl import struct import termios import tty def pty_size(): """ Determine current local pseudoterminal dimensions. :returns: A ``(num_cols, num_rows)`` two-tuple describing PTY size. Defaults to ``(80, 24)`` if unable to get a sensible result dynamically. """ cols, rows = _pty_size() if not WINDOWS else _win_pty_size() # TODO: make defaults configurable? return ((cols or 80), (rows or 24)) def _pty_size(): """ Suitable for most POSIX platforms. """ # Sentinel values to be replaced w/ defaults by caller size = (None, None) # We want two short unsigned integers (rows, cols) fmt = 'HH' # Create an empty (zeroed) buffer for ioctl to map onto. Yay for C! buf = struct.pack(fmt, 0, 0) # Call TIOCGWINSZ to get window size of stdout, returns our filled # buffer try: result = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, buf) # Unpack buffer back into Python data types # NOTE: this unpack gives us rows x cols, but we return the # inverse. rows, cols = struct.unpack(fmt, result) return (cols, rows) # Fallback to emptyish return value in various failure cases: # * sys.stdout being monkeypatched, such as in testing, and lacking .fileno # * sys.stdout having a .fileno but not actually being attached to a TTY # * termios not having a TIOCGWINSZ attribute (happens sometimes...) # * other situations where ioctl doesn't explode but the result isn't # something unpack can deal with except (struct.error, TypeError, IOError, AttributeError): pass return size def _win_pty_size(): class CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [ ('dwSize', _COORD), ('dwCursorPosition', _COORD), ('wAttributes', c_ushort), ('srWindow', _SMALL_RECT), ('dwMaximumWindowSize', _COORD) ] GetStdHandle = windll.kernel32.GetStdHandle GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo GetStdHandle.restype = HANDLE GetConsoleScreenBufferInfo.argtypes = [ HANDLE, POINTER(CONSOLE_SCREEN_BUFFER_INFO) ] hstd = GetStdHandle(-11) # STD_OUTPUT_HANDLE = -11 csbi = CONSOLE_SCREEN_BUFFER_INFO() ret = GetConsoleScreenBufferInfo(hstd, byref(csbi)) if ret: sizex = csbi.srWindow.Right - csbi.srWindow.Left + 1 sizey = csbi.srWindow.Bottom - csbi.srWindow.Top + 1 return sizex, sizey else: return (None, None) @contextmanager def character_buffered(stream): """ Force local terminal ``stream`` be character, not line, buffered. Only applies to Unix-based systems; on Windows this is a no-op. """ if WINDOWS or not isatty(stream): yield else: old_settings = termios.tcgetattr(stream) tty.setcbreak(stream) try: yield finally: termios.tcsetattr(stream, termios.TCSADRAIN, old_settings) def ready_for_reading(input_): """ Test ``input_`` to determine whether a read action will succeed. :param input_: Input stream object (file-like). :returns: ``True`` if a read should succeed, ``False`` otherwise. """ # A "real" terminal stdin needs select/kbhit to tell us when it's ready for # a nonblocking read(). # Otherwise, assume a "safer" file-like object that can be read from in a # nonblocking fashion (e.g. a StringIO or regular file). if not has_fileno(input_): return True if WINDOWS: return msvcrt.kbhit() else: reads, _, _ = select.select([input_], [], [], 0.0) return bool(reads and reads[0] is input_) def read_byte(input_): """ Read 1 byte from stdin stream ``input_``. :param input_: Input stream object (file-like). :returns: The read byte (a ``str`` or ``bytes`` depending on Python version.) """ # NOTE: there may be dragons here re: what exactly input_ is and what mode # it has been opened in. # NOTE: used to use msvcrt.getch() on Win which is why it's in platform.py. # NOTE: msvcrt.getch was unequivocally wrong - it ignores the argument # input_, and its behaviour isn't even what we want if input_ is # the console. It returns a byte, which is not what input_.read() does # (in spite of the function name!) when input_is opened in text mode # like sys.stdin. And when the user presses a special key like F1 (or even # just a non-ASCII international character) it returns the first byte of # a control sequence that isn't even valid encoded Unicode. return input_.read(1) ```
[ { "content": "Repeat the code precisely:\n```python\nfrom Tkinter import *\r\n\r\nfrom idlelib import SearchEngine\r\nfrom idlelib.SearchDialogBase import SearchDialogBase\r\nimport re\r\n\r\n\r\ndef replace(text):\r\n root = text._root()\r\n engine = SearchEngine.get(root)\r\n if not hasattr(engine, \...
[ { "content": "Repeat the code precisely:\n<|memory_start|>```python\nfrom Tkinter import *\r\n\r\nfrom idlelib import SearchEngine\r\nfrom idlelib.SearchDialogBase import SearchDialogBase\r\nimport re\r\n\r\n\r\ndef replace(text):\r\n root = text._root()\r\n engine = SearchEngine.get(root)\r\n if not h...
```python from Tkinter import * from idlelib import SearchEngine from idlelib.SearchDialogBase import SearchDialogBase import re def replace(text): root = text._root() engine = SearchEngine.get(root) if not hasattr(engine, "_replacedialog"): engine._replacedialog = ReplaceDialog(root, engine) dialog = engine._replacedialog dialog.open(text) class ReplaceDialog(SearchDialogBase): title = "Replace Dialog" icon = "Replace" def __init__(self, root, engine): SearchDialogBase.__init__(self, root, engine) self.replvar = StringVar(root) def open(self, text): SearchDialogBase.open(self, text) try: first = text.index("sel.first") except TclError: first = None try: last = text.index("sel.last") except TclError: last = None first = first or text.index("insert") last = last or first self.show_hit(first, last) self.ok = 1 def create_entries(self): SearchDialogBase.create_entries(self) self.replent = self.make_entry("Replace with:", self.replvar) def create_command_buttons(self): SearchDialogBase.create_command_buttons(self) self.make_button("Find", self.find_it) self.make_button("Replace", self.replace_it) self.make_button("Replace+Find", self.default_command, 1) self.make_button("Replace All", self.replace_all) def find_it(self, event=None): self.do_find(0) def replace_it(self, event=None): if self.do_find(self.ok): self.do_replace() def default_command(self, event=None): if self.do_find(self.ok): if self.do_replace(): # Only find next match if replace succeeded. # A bad re can cause a it to fail. self.do_find(0) def _replace_expand(self, m, repl): """ Helper function for expanding a regular expression in the replace field, if needed. """ if self.engine.isre(): try: new = m.expand(repl) except re.error: self.engine.report_error(repl, 'Invalid Replace Expression') new = None else: new = repl return new def replace_all(self, event=None): prog = self.engine.getprog() if not prog: return repl = self.replvar.get() text = self.text res = self.engine.search_text(text, prog) if not res: text.bell() return text.tag_remove("sel", "1.0", "end") text.tag_remove("hit", "1.0", "end") line = res[0] col = res[1].start() if self.engine.iswrap(): line = 1 col = 0 ok = 1 first = last = None # XXX ought to replace circular instead of top-to-bottom when wrapping text.undo_block_start() while 1: res = self.engine.search_forward(text, prog, line, col, 0, ok) if not res: break line, m = res chars = text.get("%d.0" % line, "%d.0" % (line+1)) orig = m.group() new = self._replace_expand(m, repl) if new is None: break i, j = m.span() first = "%d.%d" % (line, i) last = "%d.%d" % (line, j) if new == orig: text.mark_set("insert", last) else: text.mark_set("insert", first) if first != last: text.delete(first, last) if new: text.insert(first, new) col = i + len(new) ok = 0 text.undo_block_stop() if first and last: self.show_hit(first, last) self.close() def do_find(self, ok=0): if not self.engine.getprog(): return False text = self.text res = self.engine.search_text(text, None, ok) if not res: text.bell() return False line, m = res i, j = m.span() first = "%d.%d" % (line, i) last = "%d.%d" % (line, j) self.show_hit(first, last) self.ok = 1 return True def do_replace(self): prog = self.engine.getprog() if not prog: return False text = self.text try: first = pos = text.index("sel.first") last = text.index("sel.last") except TclError: pos = None if not pos: first = last = pos = text.index("insert") line, col = SearchEngine.get_line_col(pos) chars = text.get("%d.0" % line, "%d.0" % (line+1)) m = prog.match(chars, col) if not prog: return False new = self._replace_expand(m, self.replvar.get()) if new is None: return False text.mark_set("insert", first) text.undo_block_start() if m.group(): text.delete(first, last) if new: text.insert(first, new) text.undo_block_stop() self.show_hit(first, text.index("insert")) self.ok = 0 return True def show_hit(self, first, last): text = self.text text.mark_set("insert", first) text.tag_remove("sel", "1.0", "end") text.tag_add("sel", first, last) text.tag_remove("hit", "1.0", "end") if first == last: text.tag_add("hit", first) else: text.tag_add("hit", first, last) text.see("insert") text.update_idletasks() def close(self, event=None): SearchDialogBase.close(self, event) self.text.tag_remove("hit", "1.0", "end") ```
[ { "content": "```python\n#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2012 emijrp\n# Copyright (C) 2015 Matt Hazinski <matt@hazinski.net>\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 F...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\n# Copyright (C) 2012 emijrp\n# Copyright (C) 2015 Matt Hazinski <matt@hazinski.net>\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 publi...
```python #!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (C) 2012 emijrp # Copyright (C) 2015 Matt Hazinski <matt@hazinski.net> # 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/>. """ Instructions: 1) Create a subdirectory "download" and add a videostodo.txt file with YouTube links. 2) In the current directory, create a keys.txt file with your IA S3 keys. Accesskey and secretkey in two separated lines. 3) Install youtube-dl 4) Modify preferences if desired (see below). 5) Run this script: python youtube2internetarchive.py [english|spanish] [cc|all] [collectionname] (where param 1 is language for the video dates, param 2 is a filter to upload only Creative Commons or all param 3 is the collection name in Internet Archive) """ # Keys: http://archive.org/account/s3.php # Documentation: http://archive.org/help/abouts3.txt # https://wiki.archive.org/twiki/bin/view/Main/IAS3BulkUploader import json import os import glob import re import subprocess import sys import time import unicodedata import urllib import internetarchive num2month = { 'spanish': {'01':'enero', '02': 'febrero', '03':'marzo', '04':'abril', '05':'mayo', '06':'junio', '07':'julio', '08':'agosto','09':'septiembre','10':'octubre', '11':'noviembre', '12':'diciembre'}, 'english': {'01':'january', '02': 'february', '03':'march', '04':'april', '05':'may', '06':'june', '07':'july', '08':'august','09':'september','10':'october', '11':'november', '12':'december'}, } # Start preferences sizelimit = 0 # file size, if you want to skip those videos greater than this size, 10000*1024*1024 for 10GB. Set to 0 to never skip. if len(sys.argv) < 4: print 'python youtube2internetarchive.py [english|spanish] [cc|all] [collectionname]' sys.exit() language = sys.argv[1] if language not in num2month.keys(): print 'Bad language parameter' sys.exit() cc = sys.argv[2].lower() if cc == 'cc': cc = True else: cc = False collection = sys.argv[3] encoder = 'ffmpeg' # valid options are: 'ffmpeg', 'avconv', 'none' # youtube-dl muxes bestvideo+bestaudio with # ffmpeg/avconv, else just does 'best' quality. subject_contains_collection = False id_contains_collection = False # End preferences accesskey = open('keys.txt', 'r').readlines()[0].strip() secretkey = open('keys.txt', 'r').readlines()[1].strip() videotodourls = [l.strip() for l in open('download/videostodo.txt', 'r').readlines()] def quote(t): return re.sub(ur"'", ur"\'", t) def removeoddchars(s): #http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string s = ''.join((c for c in unicodedata.normalize('NFD', u'%s' % s) if unicodedata.category(c) != 'Mn')) s = re.sub(ur"(?im)[^a-z0-9_\.-]", ur"", s) # greek chars and others cause errors in item name if not removed return s def updatetodo(l): f = open('videostodo.txt', 'w') f.write('\n'.join(l)) f.close() while len(videotodourls) > 0: os.chdir('download') videotodourl = videotodourls[0] videohtml = unicode(urllib.urlopen(videotodourl).read(), 'utf-8') videoid = videotodourl.split('watch?v=')[1] #check if it is on IA searchurl = 'http://archive.org/search.php?query=%s' % (re.sub(ur"(?im)^-+", ur"", videoid)) rawsearch = unicode(urllib.urlopen(searchurl).read(), 'utf-8', errors='replace') print searchurl while not re.search(ur"\d+ through \d+", rawsearch): #error in IA search engine? retry.... print 'Error while searching in IA... waiting some seconds and retrying' time.sleep(15) rawsearch = unicode(urllib.urlopen(searchurl).read(), 'utf-8') if not re.search(ur"1 through 0 of <b>0</b>", rawsearch): print "It is on Internet Archive http://archive.org/search.php?query=%s" % videoid videotodourls.remove(videotodourl) updatetodo(videotodourls) os.chdir('..') continue #verify license in youtube if cc and not re.search(ur"(?i)/t/creative_commons", videohtml): print "It is not Creative Commons", videotodourl videotodourls.remove(videotodourl) updatetodo(videotodourls) os.chdir('..') continue #get tags tags = re.findall(ur"search=tag\">([^<]+)</a>", videohtml) tags = [quote(tag) for tag in tags] if encoder == 'avconv': os.system('youtube-dl --title --continue --retries 4 --write-info-json --write-description --write-thumbnail --write-annotations --all-subs --ignore-errors --format bestvideo+bestaudio/best %s' % (videotodourl)) elif encoder == 'ffmpeg': os.system('youtube-dl --title --continue --retries 4 --write-info-json --write-description --write-thumbnail --write-annotations --all-subs --ignore-errors --prefer-ffmpeg --format bestvideo+bestaudio/best %s' % (videotodourl)) else: os.system('youtube-dl --title --continue --retries 4 --write-info-json --write-description --write-thumbnail --write-annotations --all-subs --ignore-errors --format best %s' % (videotodourl)) #mp4 (18) videofilename = '' jsonfilename = '' for dirname, dirnames, filenames in os.walk('.'): if dirname == '.': for f in filenames: if f.endswith('%s.mp4' % videoid): videofilename = unicode(f, 'utf-8') break #stop searching, do not explore subdirectories if videofilename: videobasename = os.path.splitext(videofilename)[0] jsonfilename = '%s.info.json' % (videobasename) if sizelimit > 0: if os.path.getsize(videofilename) > sizelimit: print 'Video is greater than', sizelimit, 'bytes' print 'Skiping...' videotodourls.remove(videotodourl) updatetodo(videotodourls) os.chdir('..') continue else: print 'No video downloaded, an error occurred' videotodourls.remove(videotodourl) updatetodo(videotodourls) os.chdir('..') continue json_ = json.loads(unicode(open(jsonfilename, 'r').read(), 'utf-8')) upload_date = json_['upload_date'][:4] + '-' + json_['upload_date'][4:6] + '-' + json_['upload_date'][6:8] upload_year = json_['upload_date'][:4] upload_month = num2month[language][json_['upload_date'][4:6]] description = json_['description'] uploader = json_['uploader'] title = re.sub(u"%", u"/", json_['title']) # 6%7 if id_contains_collection: itemname = removeoddchars('%s-%s' % (collection, videofilename.split(videoid)[0][:-1])) # [:-1] to remove the - else: itemname = removeoddchars(videofilename.split(videoid)[0][:-1]) # [:-1] to remove the - itemname = itemname[:88] + '-' + videoid videofilename_ = removeoddchars(videofilename) if not re.search(ur"Item cannot be found", unicode(urllib.urlopen('http://archive.org/details/%s' % (itemname)).read(), 'utf-8')): print 'That item exists at Internet Archive', 'http://archive.org/details/%s' % (itemname) videotodourls.remove(videotodourl) updatetodo(videotodourls) os.chdir('..') continue if subject_contains_collection: subject = (u'; '.join([collection, upload_month, upload_year] + tags)) else: subject = (u'; '.join([upload_month, upload_year] + tags)) item = internetarchive.get_item(itemname) md = dict(mediatype='movies', creator=uploader, language=language, collection=collection, title=title, description=u'{0} <br/><br/>Source: <a href="{1}">{2}</a><br/>Uploader: <a href="http://www.youtube.com/user/{3}">{4}</a><br/>Upload date: {5}'.format(description, videotodourl, videotodourl, uploader, uploader, upload_date), date=upload_date, year=upload_year, subject=subject, originalurl=videotodourl, licenseurl=(cc and 'http://creativecommons.org/licenses/by/3.0/' or '')) item.upload(glob.glob(videobasename + '*'), metadata=md, access_key=accesskey, secret_key=secretkey) print 'You can browse it in http://archive.org/details/%s' % (itemname) videotodourls.remove(videotodourl) updatetodo(videotodourls) os.remove(videofilename) os.remove(jsonfilename) os.chdir('..') ```
[ { "content": "Here is a code snippet:\n```python\nimport unittest\n\n\nclass Solution:\n def restoreIpAddresses(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n result = []\n slen = len(s)\n # [0,p1) [p1,p2) [p2,p3) [p3,slen)\n for p1 in...
[ { "content": "Here is a code snippet:\n<|memory_start|>```python\nimport unittest\n\n\nclass Solution:\n def restoreIpAddresses(self, s):\n \"\"\"\n :type s: str\n :rtype: List[str]\n \"\"\"\n result = []\n slen = len(s)\n # [0,p1) [p1,p2) [p2,p3) [p3,slen)\n ...
```python import unittest class Solution: def restoreIpAddresses(self, s): """ :type s: str :rtype: List[str] """ result = [] slen = len(s) # [0,p1) [p1,p2) [p2,p3) [p3,slen) for p1 in range(1, 4): for p2 in range(p1 + 1, p1 + 4): for p3 in range(p2 + 1, p2 + 4): l4 = slen - p3 if l4 < 1 or l4 > 3: continue if p1 > 1 and s[0] == '0': continue l2 = p2 - p1 if l2 > 1 and s[p1] == '0': continue l3 = p3 - p2 if l3 > 1 and s[p2] == '0': continue if l4 > 1 and s[p3] == '0': continue s1 = s[0:p1] b1 = int(s1) if b1 > 255: continue s2 = s[p1:p2] b2 = int(s2) if b2 > 255: continue s3 = s[p2:p3] b3 = int(s3) if b3 > 255: continue s4 = s[p3:slen] b4 = int(s4) if b4 > 255: continue result.append(s1 + '.' + s2 + '.' + s3 + '.' + s4) return result class Test(unittest.TestCase): def test(self): self._test('25525511135', [ '255.255.11.135', '255.255.111.35', ]) self._test('10999', [ '10.9.9.9', '1.0.99.9', '1.0.9.99', # Should not contain 1.9.9.9 ]) def _test(self, s, expected): actual = Solution().restoreIpAddresses(s) self.assertCountEqual(expected, actual) if __name__ == '__main__': unittest.main() ```
[ { "content": "```python\n\"\"\" smashlib.plugins.env_command\n\"\"\"\nimport os\nfrom smashlib import get_smash\nfrom smashlib.plugins import Plugin\nfrom smashlib.patches.base import PatchMagic\nfrom smashlib.completion import smash_env_complete\n\nenv_completer = lambda himself, event: smash_env_complete(even...
[ { "content": "<|memory_start|>```python\n\"\"\" smashlib.plugins.env_command\n\"\"\"\nimport os\nfrom smashlib import get_smash\nfrom smashlib.plugins import Plugin\nfrom smashlib.patches.base import PatchMagic\nfrom smashlib.completion import smash_env_complete\n\nenv_completer = lambda himself, event: smash_e...
```python """ smashlib.plugins.env_command """ import os from smashlib import get_smash from smashlib.plugins import Plugin from smashlib.patches.base import PatchMagic from smashlib.completion import smash_env_complete env_completer = lambda himself, event: smash_env_complete(event.symbol) env_regex = r'env [A-Za-z0-9_]+$' class PatchEnv(PatchMagic): """ Patches builtin "env" command to add support for wildcard queries. Example: smash$ env XTERM* { 'XTERM_LOCALE': 'en_US.UTF-8', 'XTERM_SHELL': '/bin/bash', 'XTERM_VERSION': 'XTerm(297)' } """ name = 'env' def __call__(self, parameter_s=''): split = '=' if '=' in parameter_s else ' ' bits = parameter_s.split(split) if len(bits) == 1 and bits[0]: varname = bits[0] if varname[-1].endswith('*'): return dict([[k, v] for k, v in os.environ.items() if k.startswith(varname[:-1])]) return self.original(parameter_s) class EnvCommand(Plugin): verbose = True def init(self): self.contribute_patch(PatchEnv) self.contribute_completer( env_regex, env_completer) def load_ipython_extension(ip): """ called by %load_ext magic""" return EnvCommand(get_ipython()).install() ```
[ { "content": "Reconstruct the code exactly:\n```python\n\"\"\"\n``fitscheck`` is a command line script based on pyfits for verifying and\nupdating the CHECKSUM and DATASUM keywords of .fits files. ``fitscheck`` can\nalso detect and often fix other FITS standards violations. ``fitscheck``\nfacilitates re-writi...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n\"\"\"\n``fitscheck`` is a command line script based on pyfits for verifying and\nupdating the CHECKSUM and DATASUM keywords of .fits files. ``fitscheck`` can\nalso detect and often fix other FITS standards violations. ``fitscheck``\nfaci...
```python """ ``fitscheck`` is a command line script based on pyfits for verifying and updating the CHECKSUM and DATASUM keywords of .fits files. ``fitscheck`` can also detect and often fix other FITS standards violations. ``fitscheck`` facilitates re-writing the non-standard checksums originally generated by pyfits with standard checksums which will interoperate with CFITSIO. ``fitscheck`` will refuse to write new checksums if the checksum keywords are missing or their values are bad. Use ``--force`` to write new checksums regardless of whether or not they currently exist or pass. Use ``--ignore-missing`` to tolerate missing checksum keywords without comment. Example uses of fitscheck: 1. Verify and update checksums, tolerating non-standard checksums, updating to standard checksum:: $ fitscheck --checksum either --write *.fits 2. Write new checksums, even if existing checksums are bad or missing:: $ fitscheck --write --force *.fits 3. Verify standard checksums and FITS compliance without changing the files:: $ fitscheck --compliance *.fits 4. Verify original nonstandard checksums only:: $ fitscheck --checksum nonstandard *.fits 5. Only check and fix compliance problems, ignoring checksums:: $ fitscheck --checksum none --compliance --write *.fits 6. Verify standard interoperable checksums:: $ fitscheck *.fits 7. Delete checksum keywords:: $ fitscheck --checksum none --write *.fits """ import logging import optparse import sys import textwrap import warnings import pyfits log = logging.getLogger('fitscheck') warnings.filterwarnings('error', message='Checksum verification failed') warnings.filterwarnings('error', message='Datasum verification failed') warnings.filterwarnings('ignore', message='Overwriting existing file') def handle_options(args): if not len(args): args = ['-h'] parser = optparse.OptionParser(usage=textwrap.dedent(""" fitscheck [options] <.fits files...> .e.g. fitscheck example.fits Verifies and optionally re-writes the CHECKSUM and DATASUM keywords for a .fits file. Optionally detects and fixes FITS standard compliance problems. """.strip())) parser.add_option( '-k', '--checksum', dest='checksum_kind', type='choice', choices=['standard', 'nonstandard', 'either', 'none'], help='Choose FITS checksum mode or none. Defaults standard.', default='standard', metavar='[standard | nonstandard | either | none]') parser.add_option( '-w', '--write', dest='write_file', help='Write out file checksums and/or FITS compliance fixes.', default=False, action='store_true') parser.add_option( '-f', '--force', dest='force', help='Do file update even if original checksum was bad.', default=False, action='store_true') parser.add_option( '-c', '--compliance', dest='compliance', help='Do FITS compliance checking; fix if possible.', default=False, action='store_true') parser.add_option( '-i', '--ignore-missing', dest='ignore_missing', help='Ignore missing checksums.', default=False, action='store_true') parser.add_option( '-v', '--verbose', dest='verbose', help='Generate extra output.', default=False, action='store_true') global OPTIONS OPTIONS, fits_files = parser.parse_args(args) if OPTIONS.checksum_kind == 'none': OPTIONS.checksum_kind = False return fits_files def setup_logging(): if OPTIONS.verbose: log.setLevel(logging.INFO) else: log.setLevel(logging.WARNING) handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('%(message)s')) log.addHandler(handler) def verify_checksums(filename): """ Prints a message if any HDU in `filename` has a bad checksum or datasum. """ errors = 0 try: hdulist = pyfits.open(filename, checksum=OPTIONS.checksum_kind) except UserWarning, w: remainder = '.. ' + ' '.join(str(w).split(' ')[1:]).strip() # if "Checksum" in str(w) or "Datasum" in str(w): log.warn('BAD %r %s' % (filename, remainder)) return 1 if not OPTIONS.ignore_missing: for i, hdu in enumerate(hdulist): if not hdu._checksum: log.warn('MISSING %r .. Checksum not found in HDU #%d' % (filename, i)) return 1 if not hdu._datasum: log.warn('MISSING %r .. Datasum not found in HDU #%d' % (filename, i)) return 1 if not errors: log.info('OK %r' % filename) return errors def verify_compliance(filename): """Check for FITS standard compliance.""" hdulist = pyfits.open(filename) try: hdulist.verify('exception') except pyfits.VerifyError: exc = sys.exc_info()[1] log.warn('NONCOMPLIANT %r .. %s' % (filename), str(exc).replace('\n', ' ')) return 1 return 0 def update(filename): """ Sets the ``CHECKSUM`` and ``DATASUM`` keywords for each HDU of `filename`. Also updates fixes standards violations if possible and requested. """ hdulist = pyfits.open(filename) try: output_verify = 'silentfix' if OPTIONS.compliance else 'ignore' hdulist.writeto(filename, checksum=OPTIONS.checksum_kind, clobber=True, output_verify=output_verify) except pyfits.VerifyError: pass # unfixable errors already noted during verification phase finally: hdulist.close() def process_file(filename): """ Handle a single .fits file, returning the count of checksum and compliance errors. """ try: checksum_errors = verify_checksums(filename) if OPTIONS.compliance: compliance_errors = verify_compliance(filename) else: compliance_errors = 0 if OPTIONS.write_file and checksum_errors == 0 or OPTIONS.force: update(filename) return checksum_errors + compliance_errors except Exception: exc = sys.exc_info()[1] log.error('EXCEPTION %r .. %s' % (filename, exc)) return 1 def main(): """ Processes command line parameters into options and files, then checks or update FITS DATASUM and CHECKSUM keywords for the specified files. """ errors = 0 fits_files = handle_options(sys.argv[1:]) setup_logging() for filename in fits_files: errors += process_file(filename) if errors: log.warn('%d errors' % errors) return int(bool(errors)) ```
[ { "content": "```python\nimport cv2\nimport numpy\n\nimport Tool\n\nclass HueEqualiser(Tool.Tool):\n def on_init(self):\n self.id = \"hueequaliser\"\n self.name = \"Hue Equaliser\"\n self.icon_path = \"ui/PF2_Icons/HueEqualiser.png\"\n self.properties = [\n Tool.Propert...
[ { "content": "<|memory_start|>```python\nimport cv2\nimport numpy\n\nimport Tool\n\nclass HueEqualiser(Tool.Tool):\n def on_init(self):\n self.id = \"hueequaliser\"\n self.name = \"Hue Equaliser\"\n self.icon_path = \"ui/PF2_Icons/HueEqualiser.png\"\n self.properties = [\n ...
```python import cv2 import numpy import Tool class HueEqualiser(Tool.Tool): def on_init(self): self.id = "hueequaliser" self.name = "Hue Equaliser" self.icon_path = "ui/PF2_Icons/HueEqualiser.png" self.properties = [ Tool.Property("header", "Hue Equaliser", "Header", None, has_toggle=False, has_button=False), Tool.Property("bleed", "Hue Bleed", "Slider", 0.5, max=2.0, min=0.01), Tool.Property("neighbour_bleed", "Neighbour Bleed", "Slider", 0.25, max=2.0, min=0.0), # Red Tool.Property("header_red", "Red", "Header", None, has_toggle=False, has_button=False), Tool.Property("red_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("red_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Yellow Tool.Property("header_yellow", "Yellow", "Header", None, has_toggle=False, has_button=False), Tool.Property("yellow_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("yellow_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Green Tool.Property("header_green", "Green", "Header", None, has_toggle=False, has_button=False), Tool.Property("green_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("green_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Cyan Tool.Property("header_cyan", "Cyan", "Header", None, has_toggle=False, has_button=False), Tool.Property("cyan_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("cyan_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Blue Tool.Property("header_blue", "Blue", "Header", None, has_toggle=False, has_button=False), Tool.Property("blue_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("blue_saturation", "Saturation", "Slider", 0, max=50, min=-50), # Violet Tool.Property("header_violet", "Violet", "Header", None, has_toggle=False, has_button=False), Tool.Property("violet_value", "Value", "Slider", 0, max=50, min=-50), Tool.Property("violet_saturation", "Saturation", "Slider", 0, max=50, min=-50), ] def on_update(self, image): hues = { "red": 0, "yellow": 60, "green": 120, "cyan": 180, "blue": 240, "violet": 300, "_red": 360, } out = image if(not self.is_default()): bleed = self.props["bleed"].get_value() neighbour_bleed = self.props["neighbour_bleed"].get_value() out = out.astype(numpy.float32) # Convert to HSV colorspace out = cv2.cvtColor(out, cv2.COLOR_BGR2HSV) # Bits per pixel bpp = float(str(image.dtype).replace("uint", "").replace("float", "")) # Pixel value range np = float(2 ** bpp - 1) imhue = out[0:, 0:, 0] imsat = out[0:, 0:, 1] imval = out[0:, 0:, 2] for hue in hues: hsat = self.props["%s_saturation" % hue.replace('_', '')].get_value() hval = self.props["%s_value" % hue.replace('_', '')].get_value() isHue = self._is_hue(imhue, hues[hue], (3.5/bleed)) isHue = self._neighbour_bleed(isHue, neighbour_bleed) imsat = imsat + ((hsat / 10000) * 255) * isHue imval = imval + ((hval / 1000) * np) * isHue # Clip any values out of bounds imval[imval < 0.0] = 0.0 imval[imval > np] = np imsat[imsat < 0.0] = 0.0 imsat[imsat > 1.0] = 1.0 out[0:, 0:, 1] = imsat out[0:, 0:, 2] = imval # Convert back to BGR colorspace out = cv2.cvtColor(out, cv2.COLOR_HSV2BGR) out = out.astype(image.dtype) return out def _is_hue(self, image, hue_value, bleed_value = 3.5): mif = hue_value - 30 mir = hue_value + 30 if (mir > 360): mir = 360 if (mif < 0): mif = 0 bleed = float(360 / bleed_value) icopy = image.copy() print(bleed, mif, mir) if(mif != 0): icopy[icopy < mif - bleed] = 0.0 icopy[icopy > mir + bleed] = 0.0 icopy[(icopy < mif) * (icopy != 0.0)] = (((mif - (icopy[(icopy < mif) * (icopy != 0.0)]))/360.0) / (bleed/360.0)) * -1 + 1 icopy[(icopy > mir) * (icopy != 0.0)] = ((((icopy[(icopy > mir) * (icopy != 0.0)]) - mir)/360.0) / (bleed/360.0)) * -1 + 1 icopy[(icopy >= mif) * (icopy <= mir)] = 1.0 if(mif == 0): icopy[icopy > mir + bleed] = 0.0 icopy[(icopy > mir) * (icopy != 0.0)] = ((((icopy[(icopy > mir) * (icopy != 0.0)]) - mir) / 360.0) / (bleed/360.0)) * -1 + 1 return icopy def _neighbour_bleed(self, map, bleed): strength = bleed*30 if (strength > 0): height, width = map.shape[:2] size = (height * width) mul = numpy.math.sqrt(size) / 1064.416 # numpy.math.sqrt(1132982.0) map = map*255 blur_size = abs(2 * round((round(strength * mul) + 1) / 2) - 1) im = cv2.blur(map, (int(blur_size), int(blur_size))) return im/255.0 return map ```
[ { "content": "```python\n#!/usr/bin/python\n# Copyright: (c) 2018, Ondrej Famera <ondrej-xa2iel8u@famera.cz>\n# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)\n# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)\n\nf...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/python\n# Copyright: (c) 2018, Ondrej Famera <ondrej-xa2iel8u@famera.cz>\n# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)\n# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/L...
```python #!/usr/bin/python # Copyright: (c) 2018, Ondrej Famera <ondrej-xa2iel8u@famera.cz> # GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = ''' --- author: "Ondrej Famera (@OndrejHome)" module: pcs_resource short_description: "wrapper module for 'pcs resource' " description: - "Module for creating, deleting and updating clusters resources using 'pcs' utility." - "This module should be executed for same resorce only on one of the nodes in cluster at a time." version_added: "2.4" options: state: description: - "'present' - ensure that cluster resource exists" - "'absent' - ensure cluster resource doesn't exist" required: false default: present choices: ['present', 'absent'] name: description: - "name of cluster resource - cluster resource identifier" required: true resource_class: description: - class of cluster resource required: true default: 'ocf' choices: ['ocf', 'systemd', 'stonith'] resource_type: description: - cluster resource type required: false options: description: - "additional options passed to 'pcs' command" required: false force_resource_update: description: - "skip checking for cluster changes when updating existing resource configuration - use 'scope=resources' when pushing the change to cluster. Useful in busy clusters, dangerous when there are concurent updates as they can be lost." required: false default: no type: bool cib_file: description: - "Apply changes to specified file containing cluster CIB instead of running cluster." - "This module requires the file to already contain cluster configuration." required: false notes: - tested on CentOS 6.8, 7.3 - module can create and delete clones, groups and master resources indirectly - resource can specify --clone, --group, --master option which will cause them to create or become part of clone/group/master ''' EXAMPLES = ''' - name: ensure Dummy('ocf:pacemaker:Dummy') resource with name 'test' is present pcs_resource: name: 'test' resource_type: 'ocf:pacemaker:Dummy' - name: ensure that resource with name 'vip' is not present pcs_resource: name: 'vip' state: 'absent' - name: ensure resource 'test2' of IPaddr2('ocf:heartbeat:IPaddr2') type exists an has 5 second monitor interval pcs_resource: name: 'test2' resource_type: 'ocf:heartbeat:IPaddr2' options: 'ip=192.168.1.2 op monitor interval=5' - name: create resource in group 'testgrp' pcs_resource: name: 'test3' resource_type: 'ocf:pacemaker:Dummy' options: '--group testgrp' - name: create complex Master/Slave resource 'test-master' of 'ocf:pacemaker:Dummy' type pcs_resource: name: 'test' resource_type: 'ocf:pacemaker:Dummy' options: > fake=some_value --master meta master-max=1 master-node-max=1 clone-max=2 clone-node-max=1 notify=true op monitor interval=60s meta resource-stickiness=100 ''' # TODO if group exists and is not part of group, then specifying group won't put it into group # same problem is with clone and master - it might be better to make this functionality into separate module import sys import os.path import xml.etree.ElementTree as ET import tempfile from distutils.spawn import find_executable from ansible.module_utils.basic import AnsibleModule # determine if we have 'to_native' function that we can use for 'ansible --diff' output to_native_support = False try: from ansible.module_utils._text import to_native to_native_support = True except ImportError: pass def replace_element(elem, replacement): elem.clear() elem.text = replacement.text elem.tail = replacement.tail elem.tag = replacement.tag elem.attrib = replacement.attrib elem[:] = replacement[:] def compare_resources(module, res1, res2): # we now have 2 nodes that we can compare, so lets dump them into files for comparring n1_file_fd, n1_tmp_path = tempfile.mkstemp() n2_file_fd, n2_tmp_path = tempfile.mkstemp() n1_file = open(n1_tmp_path, 'w') n2_file = open(n2_tmp_path, 'w') # dump the XML resource definitions into temporary files sys.stdout = n1_file ET.dump(res1) sys.stdout = n2_file ET.dump(res2) sys.stdout = sys.__stdout__ # close files n1_file.close() n2_file.close() # normalize the files and store results in new files - this also removes some unimportant spaces and stuff n3_file_fd, n3_tmp_path = tempfile.mkstemp() n4_file_fd, n4_tmp_path = tempfile.mkstemp() rc, out, err = module.run_command('xmllint --format --output ' + n3_tmp_path + ' ' + n1_tmp_path) rc, out, err = module.run_command('xmllint --format --output ' + n4_tmp_path + ' ' + n2_tmp_path) # add files that should be cleaned up module.add_cleanup_file(n1_tmp_path) module.add_cleanup_file(n2_tmp_path) module.add_cleanup_file(n3_tmp_path) module.add_cleanup_file(n4_tmp_path) # now compare files diff = '' rc, out, err = module.run_command('diff ' + n3_tmp_path + ' ' + n4_tmp_path) if rc != 0: # if there was difference then show the diff n3_file = open(n3_tmp_path, 'r+') n4_file = open(n4_tmp_path, 'r+') if to_native_support: # produce diff only where we have to_native function which give sensible output # without 'to_native' whole text is wrapped as single line and not diffed # seems that to_native was added in ansible-2.2 (commit 57701d7) diff = { 'before_header': '', 'before': to_native(b''.join(n3_file.readlines())), 'after_header': '', 'after': to_native(b''.join(n4_file.readlines())), } return rc, diff def find_resource(cib, resource_id): my_resource = None tags = ['group', 'clone', 'master', 'primitive'] for elem in list(cib): if elem.attrib.get('id') == resource_id: return elem elif elem.tag in tags: my_resource = find_resource(elem, resource_id) if my_resource is not None: break return my_resource def run_module(): module = AnsibleModule( argument_spec=dict( state=dict(default="present", choices=['present', 'absent']), name=dict(required=True), resource_class=dict(default="ocf", choices=['ocf', 'systemd', 'stonith', 'master']), resource_type=dict(required=False), options=dict(default="", required=False), force_resource_update=dict(default=False, type='bool', required=False), cib_file=dict(required=False), ), supports_check_mode=True ) state = module.params['state'] resource_name = module.params['name'] resource_class = module.params['resource_class'] cib_file = module.params['cib_file'] if state == 'present' and (not module.params['resource_type']): module.fail_json(msg='When creating cluster resource you must specify the resource_type') result = {} if find_executable('pcs') is None: module.fail_json(msg="'pcs' executable not found. Install 'pcs'.") module.params['cib_file_param'] = '' if cib_file is not None: # use cib_file if specified if os.path.isfile(cib_file): try: current_cib = ET.parse(cib_file) except Exception as e: module.fail_json(msg="Error encountered parsing the cib_file - %s" % (e)) current_cib_root = current_cib.getroot() module.params['cib_file_param'] = '-f ' + cib_file else: module.fail_json(msg="%(cib_file)s is not a file or doesn't exists" % module.params) else: # get running cluster configuration rc, out, err = module.run_command('pcs cluster cib') if rc == 0: current_cib_root = ET.fromstring(out) else: module.fail_json(msg='Failed to load cluster configuration', out=out, error=err) # try to find the resource that we seek resource = None cib_resources = current_cib_root.find('./configuration/resources') resource = find_resource(cib_resources, resource_name) if state == 'present' and resource is None: # resource should be present, but we don't see it in configuration - lets create it result['changed'] = True if not module.check_mode: if resource_class == 'stonith': cmd = 'pcs %(cib_file_param)s stonith create %(name)s %(resource_type)s %(options)s' % module.params elif resource_class == 'master': cmd = 'pcs %(cib_file_param)s resource master %(name)s %(resource_type)s %(options)s' % module.params else: cmd = 'pcs %(cib_file_param)s resource create %(name)s %(resource_type)s %(options)s' % module.params rc, out, err = module.run_command(cmd) if rc != 0 and "Call cib_replace failed (-62): Timer expired" in err: # EL6: special retry when we failed to create resource because of timer waiting on cib expired rc, out, err = module.run_command(cmd) if rc == 0: module.exit_json(changed=True) else: module.fail_json(msg="Failed to create resource using command '" + cmd + "'", output=out, error=err) elif state == 'present' and resource is not None and resource_class == 'master': # modify the master resource params directly cmd = 'pcs resource meta %(name)s %(options)s' % module.params rc, out, err = module.run_command(cmd) if rc == 0: module.exit_json(changed=True) else: module.fail_json(msg="Failed to modify resource using command '" + cmd + "'", output=out, error=err) elif state == 'present' and resource is not None: # resource should be present and we have find resource with such ID - lets compare it with definition if it needs a change # lets simulate how the resource would look like if it was created using command we have clean_cib_fd, clean_cib_path = tempfile.mkstemp() module.add_cleanup_file(clean_cib_path) module.do_cleanup_files() # we must be sure that clean_cib_path is empty if resource_class == 'stonith': cmd = 'pcs -f ' + clean_cib_path + ' stonith create %(name)s %(resource_type)s %(options)s' % module.params else: cmd = 'pcs -f ' + clean_cib_path + ' resource create %(name)s %(resource_type)s %(options)s' % module.params rc, out, err = module.run_command(cmd) if rc == 0: # we have a comparable resource created in clean cluster, so lets select it and compare it clean_cib = ET.parse(clean_cib_path) clean_cib_root = clean_cib.getroot() clean_resource = None cib_clean_resources = clean_cib_root.find('./configuration/resources') clean_resource = find_resource(cib_clean_resources, resource_name) if clean_resource is not None: # remove the meta_attribute element from original cluster cib when empty to make comparison clean - Issue #10 for elem in list(resource): if elem.tag == 'meta_attributes' and len(list(elem)) == 0: resource.remove(elem) rc, diff = compare_resources(module, resource, clean_resource) if rc == 0: # if no differnces were find there is no need to update the resource module.exit_json(changed=False) else: # otherwise lets replace the resource with new one result['changed'] = True result['diff'] = diff if not module.check_mode: replace_element(resource, clean_resource) # when we use cib_file then we can dump the changed CIB directly into file if cib_file is not None: try: current_cib.write(cib_file) # FIXME add try/catch for writing into file except Exception as e: module.fail_json(msg="Error encountered writing result to cib_file - %s" % (e)) module.exit_json(changed=True) # when not using cib_file then we continue preparing changes for cib-push into running cluster new_cib = ET.ElementTree(current_cib_root) new_cib_fd, new_cib_path = tempfile.mkstemp() module.add_cleanup_file(new_cib_path) new_cib.write(new_cib_path) push_scope = 'scope=resources' if module.params['force_resource_update'] else '' push_cmd = 'pcs cluster cib-push ' + push_scope + ' ' + new_cib_path rc, out, err = module.run_command(push_cmd) if rc == 0: module.exit_json(changed=True) else: module.fail_json(msg="Failed to push updated configuration to cluster using command '" + push_cmd + "'", output=out, error=err) else: module.fail_json(msg="Unable to find simulated resource, This is most probably a bug.") else: module.fail_json(msg="Unable to simulate resource with given definition using command '" + cmd + "'", output=out, error=err) elif state == 'absent' and resource is not None: # resource should not be present but we have found something - lets remove that result['changed'] = True if not module.check_mode: if resource_class == 'stonith': cmd = 'pcs %(cib_file_param)s stonith delete %(name)s' % module.params else: cmd = 'pcs %(cib_file_param)s resource delete %(name)s' % module.params rc, out, err = module.run_command(cmd) if rc == 0: module.exit_json(changed=True) else: module.fail_json(msg="Failed to delete resource using command '" + cmd + "'", output=out, error=err) else: # resource should not be present and is nto there, nothing to do result['changed'] = False # END of module module.exit_json(**result) def main(): run_module() if __name__ == '__main__': main() ```
[ { "content": "Repeat the code precisely:\n```python\n#-------------------------------------------------------------------------------\n\n# ServiceManager.py\n#\n# Purpose: Creates, updates, deletes services in ArcGIS Online\n#\n#\n# Prerequisites/Inputs:\n# TokenManager: authentication token for NPS...
[ { "content": "Repeat the code precisely:\n<|memory_start|>```python\n#-------------------------------------------------------------------------------\n\n# ServiceManager.py\n#\n# Purpose: Creates, updates, deletes services in ArcGIS Online\n#\n#\n# Prerequisites/Inputs:\n# TokenManager: authenticati...
```python #------------------------------------------------------------------------------- # ServiceManager.py # # Purpose: Creates, updates, deletes services in ArcGIS Online # # # Prerequisites/Inputs: # TokenManager: authentication token for NPS ArcGIS Online # ServiceConfiguration: service configuration structure # ServiceSource: service content # # XML metadata template in known subfolder (<somewhere>/Templates/Metadata) # Working Folder/Workspace # # Outputs: # Create: feature service in ArcGIS Online repository # Manage: updated feature service in ArcGIS Online repository # Delete: log of deleted service(s) # # Created by: NPS Inventory and Monitoring Division Staff # Update date: 20161019 # # # #------------------------------------------------------------------------------- import urllib import urllib2 import arcrest #import TokenManager from TokenManager import TokenManager import ServiceConfiguration from ServiceConfiguration import ServiceConfiguration #import ServiceSource from ServiceSource import ServiceSource class ServiceManager(object): ''' INFO ---- Object to manage ArcGIS Online feature services ''' token = None admin = None def __init__(self): if self.token == None: tm = TokenManager("Portal", "https://nps.maps.arcgis.com", "IMDGISTeam", "G3010g!c2016", "https://irma.nps.gov") tm.getToken() self.token = tm.token if self.admin == None: self.admin = tm.admin def getConfiguration(self, itype, title, description, url=None, tags=None, snippet=None, accessInformation=None, metadata=None): sc = ServiceConfiguration(itype=itype, title=title , description=description , url=url , tags=tags , snippet=snippet , accessInformation=accessInformation , metadata=metadata) return sc.itemParams if __name__=='__main__': sm = ServiceManager() serviceToken = sm.token admin = sm.admin print serviceToken content = admin.content userInfo = content.users.user() ss = ServiceSource() # Data Store/ServCat example ss.sourceFilter = ss.dsscConnection("GRI", "GeospatialDataset") ss.sourceList = ss.getDSSCSources("http://irmaservices.nps.gov/datastore/v4/rest/AdvancedSearch/Composite?top=2000&format=json") # ArcGIS Server example #ss.agsConnection("https://inp2300fcvhafo1", "arcgis_admin", "admin2016...") #ss.sourceList = ss.getAGSSources(ss.agsServer, "Inventory_Geology") # Metadata: may work if convert this to an XML object: , metadata="https://irma.nps.gov/DataStore/DownloadFile/544273" for i in range(1, len(ss.sourceList['serviceName'])): itemParameters = sm.getConfiguration(itype="Map Service" , title=ss.sourceList['serviceName'][i] , description=ss.sourceList['description'][i] , url=ss.sourceList['serviceURL'][i].replace('http','https') #, url=urllib.urlencode(ss.sourceList['serviceURL'][i]) , tags="National Park Service (NPS) Geologic Resources Inventory (GRI), Geology" , snippet="Digital Data, Digital Geologic Map, NPS Geologic Resources Inventory" , accessInformation="National Park Service (NPS) Geologic Resources Inventory (GRI) program, National Park Service (NPS) Inventory and Monitoring Division") print ss.sourceList['serviceURL'][i] #print str(itemParameters) # This request works although the overwrite and folder params are ignored item = userInfo.addItem(itemParameters=itemParameters, overwrite=True) print item.title ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n# Copyright(c) 2017, Dimitar Venkov\n# @5devene, dimitar.ven@gmail.com\n# www.badmonkeys.net\n\n#inspired by Troy Gates https://forums.autodesk.com/t5/revit-api/revit-api-selected-element-set-order/td-p/5597203\n\nimport c...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n# Copyright(c) 2017, Dimitar Venkov\n# @5devene, dimitar.ven@gmail.com\n# www.badmonkeys.net\n\n#inspired by Troy Gates https://forums.autodesk.com/t5/revit-api/revit-api-selected-element-set-order/td-p/559...
```python # Copyright(c) 2017, Dimitar Venkov # @5devene, dimitar.ven@gmail.com # www.badmonkeys.net #inspired by Troy Gates https://forums.autodesk.com/t5/revit-api/revit-api-selected-element-set-order/td-p/5597203 import clr clr.AddReference("RevitAPIUI") from Autodesk.Revit.UI import * clr.AddReference("RevitAPI") from Autodesk.Revit.DB import RevitLinkInstance clr.AddReference("RevitServices") import RevitServices from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument clr.AddReference("RevitNodes") import Revit clr.ImportExtensions(Revit.Elements) clr.ImportExtensions(Revit.GeometryConversion) sel1 = uidoc.Selection obt1 = Selection.ObjectType.Element obt2 = Selection.ObjectType.LinkedElement picked = [] if IN[0]: TaskDialog.Show("Spring Nodes", "First select a link instance. Then pick elements from that instance in the desired order. Hit ESC to stop picking.") msg1 = 'Pick elements in the desired order, hit ESC to stop picking.' li_ref = sel1.PickObject(obt1, "Select a link instance first.") link1 = doc.GetElement(li_ref.ElementId) if isinstance(link1, RevitLinkInstance): linkDoc = link1.GetLinkDocument() flag = True while flag: try: el1 = sel1.PickObject(obt2, msg1).LinkedElementId if el1.IntegerValue != -1: picked.append(el1) except : flag = False elems = [] for p in picked: el1 = linkDoc.GetElement(p) if el1 is not None: elems.append(el1.ToDSType(True) ) tf1 = link1.GetTotalTransform().ToCoordinateSystem(True) OUT = elems, tf1 else: OUT = 'Failed to pick a link instance', None ```
[ { "content": "Write the code verbatim:\n```python\nfrom itertools import chain\n\nfrom collections import (\n defaultdict,\n Iterable,\n)\n\nfrom django.http import HttpResponseNotAllowed\n\n\n__version__ = '0.1.1'\n\n\nclass Handler(object):\n \"\"\"Container for views.\n\n :param decorators: (opti...
[ { "content": "Write the code verbatim:\n<|memory_start|>```python\nfrom itertools import chain\n\nfrom collections import (\n defaultdict,\n Iterable,\n)\n\nfrom django.http import HttpResponseNotAllowed\n\n\n__version__ = '0.1.1'\n\n\nclass Handler(object):\n \"\"\"Container for views.\n\n :param d...
```python from itertools import chain from collections import ( defaultdict, Iterable, ) from django.http import HttpResponseNotAllowed __version__ = '0.1.1' class Handler(object): """Container for views. :param decorators: (optional) list of decorators that will be applied to each endpoint. """ def __init__(self, decorators=None): self._decorators = decorators or [] self._views = defaultdict(dict) self._pre_hooks = defaultdict(list) self._post_hooks = defaultdict(list) self._invalid_endpoint_names = dir(self) def add_view(self, method, endpoint_name, view): """Adds a view to handler. :param method: HTTP method to be handled by the view :param endpoint_name: name of endpoint to associate the view with :param view: function to be used for requests handling """ self._ensure_endpoint_exists(endpoint_name) self._views[endpoint_name][method.upper()] = view def _ensure_endpoint_exists(self, endpoint_name): self._validate_endpoint_name(endpoint_name) if endpoint_name not in self._views: self._add_endpoint(endpoint_name) def _validate_endpoint_name(self, endpoint_name): if endpoint_name in self._invalid_endpoint_names: raise ValueError('Invalid endpoint name {}'.format(endpoint_name)) def _add_endpoint(self, endpoint_name): def endpoint(request, *args, **kwargs): for hook in self._get_pre_hooks(endpoint_name): hook(request, *args, **kwargs) try: view = self._views[endpoint_name][request.method] except KeyError: allowed_methods = self._views[endpoint_name].keys() response = HttpResponseNotAllowed(allowed_methods) else: response = view(request, *args, **kwargs) for hook in self._get_post_hooks(endpoint_name): hook(request, *args, **kwargs) return response for decorator in reversed(self._decorators): endpoint = decorator(endpoint) setattr(self, endpoint_name, endpoint) def _get_pre_hooks(self, endpoint_name): return chain(self._pre_hooks[None], self._pre_hooks[endpoint_name]) def _get_post_hooks(self, endpoint_name): return chain(self._post_hooks[None], self._post_hooks[endpoint_name]) def _register(self, method, endpoint_name): def decorator(view): self.add_view(method, endpoint_name, view) return view return decorator def get(self, endpoint_name): """Decorates a view to use it for handling of GET requests. :param endpoint_name: name of endpoint for given view. """ return self._register('GET', endpoint_name) def head(self, endpoint_name): """Decorates a view to use it for handling of HEAD requests. :param endpoint_name: name of endpoint for given view. """ return self._register('HEAD', endpoint_name) def options(self, endpoint_name): """Decorates a view to use it for handling of OPTIONS requests. :param endpoint_name: name of endpoint for given view. """ return self._register('OPTIONS', endpoint_name) def post(self, endpoint_name): """Decorates a view to use it for handling of POST requests. :param endpoint_name: name of endpoint`. """ return self._register('POST', endpoint_name) def put(self, endpoint_name): """Decorates a view to use it for handling of PUT requests. :param endpoint_name: name of endpoint. """ return self._register('PUT', endpoint_name) def patch(self, endpoint_name): """Decorates a view to use it for handling of PATCH requests. :param endpoint_name: name of endpoint. """ return self._register('PATCH', endpoint_name) def delete(self, endpoint_name): """Decorates a view to use it for handling of DELETE requests. :param endpoint_name: name of endpoint. """ return self._register('DELETE', endpoint_name) def before(self, target): """Decorates a function to call it before views. :param target: (optional) name of endpoint. Without it the hook will be added for all endpoints. """ if callable(target): endpoint_name = None else: endpoint_name = target def decorator(view): self.add_pre_hook(endpoint_name, view) return view if endpoint_name is None: return decorator(target) return decorator def add_pre_hook(self, endpoint_name, hook): """Adds a function to call it before endpoint's views. :param endpoint_name: name of handler endpoint :param hook: function that should be called after endpoint's views """ self._pre_hooks[endpoint_name].append(hook) def after(self, target): """Decorates a function to call it after views. :param target: (optional) name of endpoint. Without it the hook will be added for all endpoints. """ if callable(target): endpoint_name = None else: endpoint_name = target def decorator(view): self.add_post_hook(endpoint_name, view) return view if endpoint_name is None: return decorator(target) return decorator def add_post_hook(self, endpoint_name, hook): """Adds a function to call it after endpoint's views. :param endpoint_name: name of handler endpoint :param hook: function that should be called after endpoint's views """ self._post_hooks[endpoint_name].append(hook) def decorate(self, endpoint_name, decorator): """Decorates an endpoint. :param endpoint_name: an endpoint to decorate. :param decorator: one decorator or iterable with decorators. """ endpoint = getattr(self, endpoint_name) if isinstance(decorator, Iterable): for dec in reversed(decorator): endpoint = dec(endpoint) else: endpoint = decorator(endpoint) setattr(self, endpoint_name, endpoint) ```
[ { "content": "Here is the script:\n```python\n# =============================================================================\n# Copyright (C) 2010 Diego Duclos\n#\n# This file is part of pyfa.\n#\n# pyfa is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public Lic...
[ { "content": "Here is the script:\n<|memory_start|>```python\n# =============================================================================\n# Copyright (C) 2010 Diego Duclos\n#\n# This file is part of pyfa.\n#\n# pyfa is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Ge...
```python # ============================================================================= # Copyright (C) 2010 Diego Duclos # # This file is part of pyfa. # # pyfa 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. # # pyfa 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 pyfa. If not, see <http://www.gnu.org/licenses/>. # ============================================================================= # noinspection PyPackageRequirements import wx from gui.statsView import StatsView from gui.bitmap_loader import BitmapLoader from gui.utils.numberFormatter import formatAmount, roundToPrec class CapacitorViewFull(StatsView): name = "capacitorViewFull" def __init__(self, parent): StatsView.__init__(self) self.parent = parent def getHeaderText(self, fit): return "Capacitor" def getTextExtentW(self, text): width, height = self.parent.GetTextExtent(text) return width def populatePanel(self, contentPanel, headerPanel): contentSizer = contentPanel.GetSizer() parent = self.panel = contentPanel self.headerPanel = headerPanel panel = "full" sizerCapacitor = wx.GridSizer(1, 2, 0, 0) contentSizer.Add(sizerCapacitor, 0, wx.EXPAND, 0) # Capacitor capacity and time baseBox = wx.BoxSizer(wx.HORIZONTAL) sizerCapacitor.Add(baseBox, 0, wx.ALIGN_LEFT) bitmap = BitmapLoader.getStaticBitmap("capacitorInfo_big", parent, "gui") tooltip = wx.ToolTip("Capacitor stability") bitmap.SetToolTip(tooltip) baseBox.Add(bitmap, 0, wx.ALIGN_CENTER) box = wx.BoxSizer(wx.VERTICAL) baseBox.Add(box, 0, wx.ALIGN_LEFT) hbox = wx.BoxSizer(wx.HORIZONTAL) box.Add(hbox, 0, wx.ALIGN_LEFT) hbox.Add(wx.StaticText(parent, wx.ID_ANY, "Total: "), 0, wx.ALIGN_LEFT | wx.LEFT, 3) lbl = wx.StaticText(parent, wx.ID_ANY, "0.0") setattr(self, "label%sCapacitorCapacity" % panel.capitalize(), lbl) hbox.Add(lbl, 0, wx.ALIGN_LEFT) hbox.Add(wx.StaticText(parent, wx.ID_ANY, " GJ"), 0, wx.ALIGN_LEFT) hbox = wx.BoxSizer(wx.HORIZONTAL) box.Add(hbox, 0, wx.ALIGN_LEFT) lbl = wx.StaticText(parent, wx.ID_ANY, "Lasts ") hbox.Add(lbl, 0, wx.ALIGN_LEFT | wx.LEFT, 3) setattr(self, "label%sCapacitorState" % panel.capitalize(), lbl) lbl = wx.StaticText(parent, wx.ID_ANY, "0s") setattr(self, "label%sCapacitorTime" % panel.capitalize(), lbl) hbox.Add(lbl, 0, wx.ALIGN_LEFT) # Capacitor balance baseBox = wx.BoxSizer(wx.HORIZONTAL) sizerCapacitor.Add(baseBox, 0, wx.ALIGN_CENTER_HORIZONTAL) tooltip = wx.ToolTip("Extra stats") bitmap = BitmapLoader.getStaticBitmap("capacitorRecharge_big", parent, "gui") bitmap.SetToolTip(tooltip) baseBox.Add(bitmap, 0, wx.ALIGN_CENTER) # Delta chargeSizer = wx.BoxSizer(wx.VERTICAL) baseBox.Add(chargeSizer, 0, wx.ALIGN_CENTER) lbl = wx.StaticText(parent, wx.ID_ANY, "0 GJ/s") setattr(self, "label%sCapacitorDelta" % panel.capitalize(), lbl) chargeSizer.Add(lbl, 0, wx.ALIGN_CENTER) # Resists lbl = wx.StaticText(parent, wx.ID_ANY, "0%") setattr(self, "label%sCapacitorResist" % panel.capitalize(), lbl) chargeSizer.Add(lbl, 0, wx.ALIGN_CENTER) def refreshPanel(self, fit): # If we did anything intresting, we'd update our labels to reflect the new fit's stats here stats = ( ("label%sCapacitorCapacity", lambda: fit.ship.getModifiedItemAttr("capacitorCapacity"), 3, 0, 9, False, ''), ("label%sCapacitorDelta", lambda: fit.capDelta, 3, 0, 0, True, ' GJ/s'), ("label%sCapacitorResist", lambda: (1 - fit.ship.getModifiedItemAttr("energyWarfareResistance", 1)) * 100, 3, 0, 0, False, '%'), ) if fit is not None: cap_amount = fit.ship.getModifiedItemAttr("capacitorCapacity") cap_recharge = fit.capRecharge cap_use = fit.capUsed neut_res = fit.ship.getModifiedItemAttr("energyWarfareResistance", 1) else: cap_amount = 0 cap_recharge = 0 cap_use = 0 neut_res = 1 panel = "Full" for labelName, value, prec, lowest, highest, forceSign, unit in stats: label = getattr(self, labelName % panel) value = value() if fit is not None else 0 value = value if value is not None else 0 if isinstance(value, str): label.SetLabel(value) label.SetToolTip(wx.ToolTip(value)) else: label.SetLabel('{}{}'.format(formatAmount(value, prec, lowest, highest, forceSign=forceSign), unit)) label.SetToolTip(wx.ToolTip("%.1f" % value)) if labelName == 'label%sCapacitorDelta' and (cap_recharge or cap_use): lines = [] lines.append('Capacitor delta:') lines.append(' +{} GJ/s'.format(formatAmount(cap_recharge, 3, 0, 3))) lines.append(' -{} GJ/s'.format(formatAmount(cap_use, 3, 0, 3))) delta = round(cap_recharge - cap_use, 3) if delta > 0 and 0 < round(neut_res, 4) < 1: lines.append('') lines.append('Effective excessive gain:') lines.append(' +{} GJ/s'.format(formatAmount(delta / neut_res, 3, 0, 3))) label.SetToolTip(wx.ToolTip('\n'.join(lines))) if labelName == 'label%sCapacitorResist': texts = ['Neutralizer resistance'] if cap_amount > 0 and 0 < round(neut_res, 4) < 1: texts.append('Effective capacity: {} GJ'.format(formatAmount(cap_amount / neut_res, 3, 0, 9))) label.SetToolTip(wx.ToolTip('\n'.join(texts))) capState = fit.capState if fit is not None else 0 capStable = fit.capStable if fit is not None else False lblNameTime = "label%sCapacitorTime" lblNameState = "label%sCapacitorState" if isinstance(capState, tuple) and len(capState) >= 2: t = ("{0}%-{1}%", capState[0], capState[1]) s = "" else: if capStable: t = "%.1f%%" % capState else: if capState > 60: t = "%dm%ds" % divmod(capState, 60) else: t = "%ds" % capState s = "Stable: " if capStable else "Lasts " getattr(self, lblNameTime % panel).SetLabel(t) getattr(self, lblNameState % panel).SetLabel(s) self.panel.Layout() self.headerPanel.Layout() CapacitorViewFull.register() ```
[ { "content": "```python\nimport base64\nimport csv\nimport sys\n\nFIELDS = (\"summary\", \"detail\")\n\n\ndef extract_doc(stream):\n\n targets = dict()\n target = None\n\n for line in stream:\n\n # only comment lines\n if not line.startswith(\"#\"):\n continue\n\n # stri...
[ { "content": "<|memory_start|>```python\nimport base64\nimport csv\nimport sys\n\nFIELDS = (\"summary\", \"detail\")\n\n\ndef extract_doc(stream):\n\n targets = dict()\n target = None\n\n for line in stream:\n\n # only comment lines\n if not line.startswith(\"#\"):\n continue\n...
```python import base64 import csv import sys FIELDS = ("summary", "detail") def extract_doc(stream): targets = dict() target = None for line in stream: # only comment lines if not line.startswith("#"): continue # strip off the comment, trailing whitespace, and a single leading # space - this gives the raw line line = line[1:].rstrip() if line.startswith(" "): line = line[1:] # end of section marker is a line consisting only of "#" if target is not None and line and not line.replace("#", ""): if target is not None: for field in FIELDS: targets[target][field] = \ "\n".join(targets[target][field]).strip().encode() target = None continue # target marker if line.startswith("Target:"): target = line.split()[1] targets[target] = dict(zip(FIELDS, ([], []))) field = "summary" continue if target is not None: if field == "summary" and not line: continue targets[target][field].append(line) field = "detail" writer = csv.writer(sys.stdout) for target in sorted(targets.keys()): writer.writerow((target, base64.b64encode(targets[target]["summary"]).decode(), base64.b64encode(targets[target]["detail"]).decode())) if __name__ == "__main__": extract_doc(sys.stdin) ```
[ { "content": "Return the code exactly, with no changes:\n```python\nimport pygame\n\nBLACK = ( 0, 0, 0)\nWHITE = ( 255, 255, 255)\nBLUE = ( 0, 0, 255)\nRED = ( 255, 0, 0)\nGREEN = ( 0, 255, 0)\n\nsize = (800, 600)\n\nclass Player(pygame.sprite.Sprite):\n\n\tchange_x = 0\n\tchange_y = 0\n\n\tlevel = None\n\t\n\t...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\nimport pygame\n\nBLACK = ( 0, 0, 0)\nWHITE = ( 255, 255, 255)\nBLUE = ( 0, 0, 255)\nRED = ( 255, 0, 0)\nGREEN = ( 0, 255, 0)\n\nsize = (800, 600)\n\nclass Player(pygame.sprite.Sprite):\n\n\tchange_x = 0\n\tchange_y = 0\n\n\tleve...
```python import pygame BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) BLUE = ( 0, 0, 255) RED = ( 255, 0, 0) GREEN = ( 0, 255, 0) size = (800, 600) class Player(pygame.sprite.Sprite): change_x = 0 change_y = 0 level = None def __init__(self): pygame.sprite.Sprite.__init__(self) #The player. take an image, but now a shit self.image = pygame.Surface([40,60]) self.image.fill(RED) self.rect = self.image.get_rect() def update(self): #Move #Gravity self.calc_grav() #Move l/r self.rect.x += self.change_x #Check collissions blocks_hit = pygame.sprite.spritecollide(self,\ self.level.platform_list, False) for block in blocks_hit: if self.change_x > 0: self.rect.right = block.rect.left elif self.change_x < 0: self.rect.left = block.rect.right #Move u/d self.rect.y += self.change_y #Check collissions blocks_hit = pygame.sprite.spritecollide(self,\ self.level.platform_list, False) for block in blocks_hit: if self.change_y > 0: self.rect.bottom = block.rect.top elif self.change_y < 0: self.rect.top = block.rect.bottom self.change_y = 0 def calc_grav(self): if self.change_y == 0: self.change_y = 1 else: self.change_y += .35 if self.rect.y >= size[1] - self.rect.height and self.change_y >= 0: self.change_y = 0 self.rect.y = size[1] - self.rect.height def jump(self): #Saltar #Movemos dos pixeles, vemos si haf colision, y si la hay, se salta self.rect.y += 2 platform_hit = pygame.sprite.spritecollide(self, \ self.level.platform_list, False) self.rect.y -= 2 if len(platform_hit) > 0 or self.rect.bottom >= size[1]: self.change_y = -10 def go_left(self): self.change_x = -6 def go_right(self): self.change_x = 6 def stop(self): self.change_x = 0 class Platform(pygame.sprite.Sprite): def __init__(self, w, h): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([w,h]) self.image.fill(GREEN) self.rect = self.image.get_rect() class Level(object): #Super class platform_list = None enemy_list = None background = None def __init__(self, player): self.platform_list = pygame.sprite.Group() self.enemy_list = pygame.sprite.Group() self.player = player def update(self): self.platform_list.update() self.enemy_list.update() def draw(self, screen): screen.fill(BLUE) self.platform_list.draw(screen) self.enemy_list.draw(screen) class Level01(Level): def __init__(self, player): Level.__init__(self, player) level = [[210, 70, 500, 500], [210, 70, 200, 400], [210, 70, 600, 300],] for plat in level: block = Platform(plat[0], plat[1]) block.rect.x = plat[2] block.rect.y = plat[3] block.player = self.player self.platform_list.add(block) def main(): pygame.init() screen = pygame.display.set_mode(size) pygame.display.set_caption('jumper') pygame.mouse.set_visible(False) player = Player() lvl_list = [] lvl_list.append(Level01(player)) current_lvl_no = 0 current_lvl = lvl_list[current_lvl_no] active_sprite_list = pygame.sprite.Group() player.level = current_lvl player.rect.x = 340 player.rect.y = size[1] - player.rect.height active_sprite_list.add(player) done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.go_left() if event.key == pygame.K_RIGHT: player.go_right() if event.key == pygame.K_UP: player.jump() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and player.change_x < 0: player.stop() if event.key == pygame.K_RIGHT and player.change_x > 0: player.stop() active_sprite_list.update() current_lvl.update() if player.rect.right > size[0]: player.rect.right = size[0] if player.rect.left < 0: player.rect.left = 0 current_lvl.draw(screen) active_sprite_list.draw(screen) pygame.display.flip() clock.tick(60) pygame.quit() if __name__ == '__main__': main() ```
[ { "content": "Here is the script:\n```python\n# -*- encoding: utf-8 -*-\n# #############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).\n#\n# This program is free software: you can r...
[ { "content": "Here is the script:\n<|memory_start|>```python\n# -*- encoding: utf-8 -*-\n# #############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).\n#\n# This program is free sof...
```python # -*- encoding: utf-8 -*- # ############################################################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) import base64 import sys, os class doctor_hc_report_inherit(osv.osv): _inherit = "doctor.list_report" _columns = { 'attentions_psychology_ids': fields.one2many('doctor.psicologia', 'list_report_print_spicologia_id', 'Attentions'), } doctor_hc_report_inherit() ```
[ { "content": "```python\n# Samba-specific bits for optparse\n# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007\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 ...
[ { "content": "<|memory_start|>```python\n# Samba-specific bits for optparse\n# Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007\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;...
```python # Samba-specific bits for optparse # Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007 # # 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/>. # """Support for parsing Samba-related command-line options.""" from __future__ import absolute_import from __future__ import print_function __docformat__ = "restructuredText" import optparse import os from samba.credentials import ( Credentials, AUTO_USE_KERBEROS, DONT_USE_KERBEROS, MUST_USE_KERBEROS, ) from samba.hostconfig import Hostconfig import sys class SambaOptions(optparse.OptionGroup): """General Samba-related command line options.""" def __init__(self, parser): from samba.param import LoadParm optparse.OptionGroup.__init__(self, parser, "Samba Common Options") self.add_option("-s", "--configfile", action="callback", type=str, metavar="FILE", help="Configuration file", callback=self._load_configfile) self.add_option("-d", "--debuglevel", action="callback", type=int, metavar="DEBUGLEVEL", help="debug level", callback=self._set_debuglevel) self.add_option("--option", action="callback", type=str, metavar="OPTION", help="set smb.conf option from command line", callback=self._set_option) self.add_option("--realm", action="callback", type=str, metavar="REALM", help="set the realm name", callback=self._set_realm) self._configfile = None self._lp = LoadParm() self.realm = None def get_loadparm_path(self): """Return path to the smb.conf file specified on the command line.""" return self._configfile def _load_configfile(self, option, opt_str, arg, parser): self._configfile = arg def _set_debuglevel(self, option, opt_str, arg, parser): if arg < 0: raise optparse.OptionValueError("invalid %s option value: %s" % (opt_str, arg)) self._lp.set('debug level', str(arg)) def _set_realm(self, option, opt_str, arg, parser): self._lp.set('realm', arg) self.realm = arg def _set_option(self, option, opt_str, arg, parser): if arg.find('=') == -1: raise optparse.OptionValueError( "--option option takes a 'a=b' argument") a = arg.split('=') try: self._lp.set(a[0], a[1]) except Exception as e: raise optparse.OptionValueError( "invalid --option option value %r: %s" % (arg, e)) def get_loadparm(self): """Return loadparm object with data specified on the command line.""" if self._configfile is not None: self._lp.load(self._configfile) elif os.getenv("SMB_CONF_PATH") is not None: self._lp.load(os.getenv("SMB_CONF_PATH")) else: self._lp.load_default() return self._lp def get_hostconfig(self): return Hostconfig(self.get_loadparm()) class VersionOptions(optparse.OptionGroup): """Command line option for printing Samba version.""" def __init__(self, parser): optparse.OptionGroup.__init__(self, parser, "Version Options") self.add_option("-V", "--version", action="callback", callback=self._display_version, help="Display version number") def _display_version(self, option, opt_str, arg, parser): import samba print(samba.version) sys.exit(0) def parse_kerberos_arg(arg, opt_str): if arg.lower() in ["yes", 'true', '1']: return MUST_USE_KERBEROS elif arg.lower() in ["no", 'false', '0']: return DONT_USE_KERBEROS elif arg.lower() in ["auto"]: return AUTO_USE_KERBEROS else: raise optparse.OptionValueError("invalid %s option value: %s" % (opt_str, arg)) class CredentialsOptions(optparse.OptionGroup): """Command line options for specifying credentials.""" def __init__(self, parser, special_name=None): self.special_name = special_name if special_name is not None: self.section = "Credentials Options (%s)" % special_name else: self.section = "Credentials Options" self.ask_for_password = True self.ipaddress = None self.machine_pass = False optparse.OptionGroup.__init__(self, parser, self.section) self._add_option("--simple-bind-dn", metavar="DN", action="callback", callback=self._set_simple_bind_dn, type=str, help="DN to use for a simple bind") self._add_option("--password", metavar="PASSWORD", action="callback", help="Password", type=str, callback=self._set_password) self._add_option("-U", "--username", metavar="USERNAME", action="callback", type=str, help="Username", callback=self._parse_username) self._add_option("-W", "--workgroup", metavar="WORKGROUP", action="callback", type=str, help="Workgroup", callback=self._parse_workgroup) self._add_option("-N", "--no-pass", action="callback", help="Don't ask for a password", callback=self._set_no_password) self._add_option("-k", "--kerberos", metavar="KERBEROS", action="callback", type=str, help="Use Kerberos", callback=self._set_kerberos) self._add_option("", "--ipaddress", metavar="IPADDRESS", action="callback", type=str, help="IP address of server", callback=self._set_ipaddress) self._add_option("-P", "--machine-pass", action="callback", help="Use stored machine account password", callback=self._set_machine_pass) self.creds = Credentials() def _add_option(self, *args1, **kwargs): if self.special_name is None: return self.add_option(*args1, **kwargs) args2 = () for a in args1: if not a.startswith("--"): continue args2 += (a.replace("--", "--%s-" % self.special_name),) self.add_option(*args2, **kwargs) def _parse_username(self, option, opt_str, arg, parser): self.creds.parse_string(arg) self.machine_pass = False def _parse_workgroup(self, option, opt_str, arg, parser): self.creds.set_domain(arg) def _set_password(self, option, opt_str, arg, parser): self.creds.set_password(arg) self.ask_for_password = False self.machine_pass = False def _set_no_password(self, option, opt_str, arg, parser): self.ask_for_password = False def _set_machine_pass(self, option, opt_str, arg, parser): self.machine_pass = True def _set_ipaddress(self, option, opt_str, arg, parser): self.ipaddress = arg def _set_kerberos(self, option, opt_str, arg, parser): self.creds.set_kerberos_state(parse_kerberos_arg(arg, opt_str)) def _set_simple_bind_dn(self, option, opt_str, arg, parser): self.creds.set_bind_dn(arg) def get_credentials(self, lp, fallback_machine=False): """Obtain the credentials set on the command-line. :param lp: Loadparm object to use. :return: Credentials object """ self.creds.guess(lp) if self.machine_pass: self.creds.set_machine_account(lp) elif self.ask_for_password: self.creds.set_cmdline_callbacks() # possibly fallback to using the machine account, if we have # access to the secrets db if fallback_machine and not self.creds.authentication_requested(): try: self.creds.set_machine_account(lp) except Exception: pass return self.creds class CredentialsOptionsDouble(CredentialsOptions): """Command line options for specifying credentials of two servers.""" def __init__(self, parser): CredentialsOptions.__init__(self, parser) self.no_pass2 = True self.add_option("--simple-bind-dn2", metavar="DN2", action="callback", callback=self._set_simple_bind_dn2, type=str, help="DN to use for a simple bind") self.add_option("--password2", metavar="PASSWORD2", action="callback", help="Password", type=str, callback=self._set_password2) self.add_option("--username2", metavar="USERNAME2", action="callback", type=str, help="Username for second server", callback=self._parse_username2) self.add_option("--workgroup2", metavar="WORKGROUP2", action="callback", type=str, help="Workgroup for second server", callback=self._parse_workgroup2) self.add_option("--no-pass2", action="store_true", help="Don't ask for a password for the second server") self.add_option("--kerberos2", metavar="KERBEROS2", action="callback", type=str, help="Use Kerberos", callback=self._set_kerberos2) self.creds2 = Credentials() def _parse_username2(self, option, opt_str, arg, parser): self.creds2.parse_string(arg) def _parse_workgroup2(self, option, opt_str, arg, parser): self.creds2.set_domain(arg) def _set_password2(self, option, opt_str, arg, parser): self.creds2.set_password(arg) self.no_pass2 = False def _set_kerberos2(self, option, opt_str, arg, parser): self.creds2.set_kerberos_state(parse_kerberos_arg(arg, opt_str)) def _set_simple_bind_dn2(self, option, opt_str, arg, parser): self.creds2.set_bind_dn(arg) def get_credentials2(self, lp, guess=True): """Obtain the credentials set on the command-line. :param lp: Loadparm object to use. :param guess: Try guess Credentials from environment :return: Credentials object """ if guess: self.creds2.guess(lp) elif not self.creds2.get_username(): self.creds2.set_anonymous() if self.no_pass2: self.creds2.set_cmdline_callbacks() return self.creds2 ```
[ { "content": "Provide an exact copy of the source code:\n```python\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# All Rights Reserved.\n# Copyright 2011 - 2012, Red Hat, Inc...
[ { "content": "Provide an exact copy of the source code:\n<|memory_start|>```python\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2010 United States Government as represented by the\n# Administrator of the National Aeronautics and Space Administration.\n# All Rights Reserved.\n# Copyright 2011 - 20...
```python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright 2011 - 2012, Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Shared code between AMQP based openstack.common.rpc implementations. The code in this module is shared between the rpc implemenations based on AMQP. Specifically, this includes impl_kombu and impl_qpid. impl_carrot also uses AMQP, but is deprecated and predates this code. """ import inspect import logging import sys import uuid from eventlet import greenpool from eventlet import pools from eventlet import semaphore from nova.openstack.common import cfg from nova.openstack.common import excutils from nova.openstack.common.gettextutils import _ from nova.openstack.common import local from nova.openstack.common.rpc import common as rpc_common LOG = logging.getLogger(__name__) class Pool(pools.Pool): """Class that implements a Pool of Connections.""" def __init__(self, conf, connection_cls, *args, **kwargs): self.connection_cls = connection_cls self.conf = conf kwargs.setdefault("max_size", self.conf.rpc_conn_pool_size) kwargs.setdefault("order_as_stack", True) super(Pool, self).__init__(*args, **kwargs) # TODO(comstud): Timeout connections not used in a while def create(self): LOG.debug('Pool creating new connection') return self.connection_cls(self.conf) def empty(self): while self.free_items: self.get().close() _pool_create_sem = semaphore.Semaphore() def get_connection_pool(conf, connection_cls): with _pool_create_sem: # Make sure only one thread tries to create the connection pool. if not connection_cls.pool: connection_cls.pool = Pool(conf, connection_cls) return connection_cls.pool class ConnectionContext(rpc_common.Connection): """The class that is actually returned to the caller of create_connection(). This is essentially a wrapper around Connection that supports 'with'. It can also return a new Connection, or one from a pool. The function will also catch when an instance of this class is to be deleted. With that we can return Connections to the pool on exceptions and so forth without making the caller be responsible for catching them. If possible the function makes sure to return a connection to the pool. """ def __init__(self, conf, connection_pool, pooled=True, server_params=None): """Create a new connection, or get one from the pool""" self.connection = None self.conf = conf self.connection_pool = connection_pool if pooled: self.connection = connection_pool.get() else: self.connection = connection_pool.connection_cls( conf, server_params=server_params) self.pooled = pooled def __enter__(self): """When with ConnectionContext() is used, return self""" return self def _done(self): """If the connection came from a pool, clean it up and put it back. If it did not come from a pool, close it. """ if self.connection: if self.pooled: # Reset the connection so it's ready for the next caller # to grab from the pool self.connection.reset() self.connection_pool.put(self.connection) else: try: self.connection.close() except Exception: pass self.connection = None def __exit__(self, exc_type, exc_value, tb): """End of 'with' statement. We're done here.""" self._done() def __del__(self): """Caller is done with this connection. Make sure we cleaned up.""" self._done() def close(self): """Caller is done with this connection.""" self._done() def create_consumer(self, topic, proxy, fanout=False): self.connection.create_consumer(topic, proxy, fanout) def create_worker(self, topic, proxy, pool_name): self.connection.create_worker(topic, proxy, pool_name) def consume_in_thread(self): self.connection.consume_in_thread() def __getattr__(self, key): """Proxy all other calls to the Connection instance""" if self.connection: return getattr(self.connection, key) else: raise rpc_common.InvalidRPCConnectionReuse() def msg_reply(conf, msg_id, connection_pool, reply=None, failure=None, ending=False): """Sends a reply or an error on the channel signified by msg_id. Failure should be a sys.exc_info() tuple. """ with ConnectionContext(conf, connection_pool) as conn: if failure: failure = rpc_common.serialize_remote_exception(failure) try: msg = {'result': reply, 'failure': failure} except TypeError: msg = {'result': dict((k, repr(v)) for k, v in reply.__dict__.iteritems()), 'failure': failure} if ending: msg['ending'] = True conn.direct_send(msg_id, msg) class RpcContext(rpc_common.CommonRpcContext): """Context that supports replying to a rpc.call""" def __init__(self, **kwargs): self.msg_id = kwargs.pop('msg_id', None) self.conf = kwargs.pop('conf') super(RpcContext, self).__init__(**kwargs) def deepcopy(self): values = self.to_dict() values['conf'] = self.conf values['msg_id'] = self.msg_id return self.__class__(**values) def reply(self, reply=None, failure=None, ending=False, connection_pool=None): if self.msg_id: msg_reply(self.conf, self.msg_id, connection_pool, reply, failure, ending) if ending: self.msg_id = None def unpack_context(conf, msg): """Unpack context from msg.""" context_dict = {} for key in list(msg.keys()): # NOTE(vish): Some versions of python don't like unicode keys # in kwargs. key = str(key) if key.startswith('_context_'): value = msg.pop(key) context_dict[key[9:]] = value context_dict['msg_id'] = msg.pop('_msg_id', None) context_dict['conf'] = conf ctx = RpcContext.from_dict(context_dict) rpc_common._safe_log(LOG.debug, _('unpacked context: %s'), ctx.to_dict()) return ctx def pack_context(msg, context): """Pack context into msg. Values for message keys need to be less than 255 chars, so we pull context out into a bunch of separate keys. If we want to support more arguments in rabbit messages, we may want to do the same for args at some point. """ context_d = dict([('_context_%s' % key, value) for (key, value) in context.to_dict().iteritems()]) msg.update(context_d) class ProxyCallback(object): """Calls methods on a proxy object based on method and args.""" def __init__(self, conf, proxy, connection_pool): self.proxy = proxy self.pool = greenpool.GreenPool(conf.rpc_thread_pool_size) self.connection_pool = connection_pool self.conf = conf def __call__(self, message_data): """Consumer callback to call a method on a proxy object. Parses the message for validity and fires off a thread to call the proxy object method. Message data should be a dictionary with two keys: method: string representing the method to call args: dictionary of arg: value Example: {'method': 'echo', 'args': {'value': 42}} """ # It is important to clear the context here, because at this point # the previous context is stored in local.store.context if hasattr(local.store, 'context'): del local.store.context rpc_common._safe_log(LOG.debug, _('received %s'), message_data) ctxt = unpack_context(self.conf, message_data) method = message_data.get('method') args = message_data.get('args', {}) version = message_data.get('version', None) if not method: LOG.warn(_('no method for message: %s') % message_data) ctxt.reply(_('No method for message: %s') % message_data, connection_pool=self.connection_pool) return self.pool.spawn_n(self._process_data, ctxt, version, method, args) def _process_data(self, ctxt, version, method, args): """Process a message in a new thread. If the proxy object we have has a dispatch method (see rpc.dispatcher.RpcDispatcher), pass it the version, method, and args and let it dispatch as appropriate. If not, use the old behavior of magically calling the specified method on the proxy we have here. """ ctxt.update_store() try: rval = self.proxy.dispatch(ctxt, version, method, **args) # Check if the result was a generator if inspect.isgenerator(rval): for x in rval: ctxt.reply(x, None, connection_pool=self.connection_pool) else: ctxt.reply(rval, None, connection_pool=self.connection_pool) # This final None tells multicall that it is done. ctxt.reply(ending=True, connection_pool=self.connection_pool) except Exception as e: LOG.exception('Exception during message handling') ctxt.reply(None, sys.exc_info(), connection_pool=self.connection_pool) class MulticallWaiter(object): def __init__(self, conf, connection, timeout): self._connection = connection self._iterator = connection.iterconsume(timeout=timeout or conf.rpc_response_timeout) self._result = None self._done = False self._got_ending = False self._conf = conf def done(self): if self._done: return self._done = True self._iterator.close() self._iterator = None self._connection.close() def __call__(self, data): """The consume() callback will call this. Store the result.""" if data['failure']: failure = data['failure'] self._result = rpc_common.deserialize_remote_exception(self._conf, failure) elif data.get('ending', False): self._got_ending = True else: self._result = data['result'] def __iter__(self): """Return a result until we get a 'None' response from consumer""" if self._done: raise StopIteration while True: try: self._iterator.next() except Exception: with excutils.save_and_reraise_exception(): self.done() if self._got_ending: self.done() raise StopIteration result = self._result if isinstance(result, Exception): self.done() raise result yield result def create_connection(conf, new, connection_pool): """Create a connection""" return ConnectionContext(conf, connection_pool, pooled=not new) def multicall(conf, context, topic, msg, timeout, connection_pool): """Make a call that returns multiple times.""" # Can't use 'with' for multicall, as it returns an iterator # that will continue to use the connection. When it's done, # connection.close() will get called which will put it back into # the pool LOG.debug(_('Making asynchronous call on %s ...'), topic) msg_id = uuid.uuid4().hex msg.update({'_msg_id': msg_id}) LOG.debug(_('MSG_ID is %s') % (msg_id)) pack_context(msg, context) conn = ConnectionContext(conf, connection_pool) wait_msg = MulticallWaiter(conf, conn, timeout) conn.declare_direct_consumer(msg_id, wait_msg) conn.topic_send(topic, msg) return wait_msg def call(conf, context, topic, msg, timeout, connection_pool): """Sends a message on a topic and wait for a response.""" rv = multicall(conf, context, topic, msg, timeout, connection_pool) # NOTE(vish): return the last result from the multicall rv = list(rv) if not rv: return return rv[-1] def cast(conf, context, topic, msg, connection_pool): """Sends a message on a topic without waiting for a response.""" LOG.debug(_('Making asynchronous cast on %s...'), topic) pack_context(msg, context) with ConnectionContext(conf, connection_pool) as conn: conn.topic_send(topic, msg) def fanout_cast(conf, context, topic, msg, connection_pool): """Sends a message on a fanout exchange without waiting for a response.""" LOG.debug(_('Making asynchronous fanout cast...')) pack_context(msg, context) with ConnectionContext(conf, connection_pool) as conn: conn.fanout_send(topic, msg) def cast_to_server(conf, context, server_params, topic, msg, connection_pool): """Sends a message on a topic to a specific server.""" pack_context(msg, context) with ConnectionContext(conf, connection_pool, pooled=False, server_params=server_params) as conn: conn.topic_send(topic, msg) def fanout_cast_to_server(conf, context, server_params, topic, msg, connection_pool): """Sends a message on a fanout exchange to a specific server.""" pack_context(msg, context) with ConnectionContext(conf, connection_pool, pooled=False, server_params=server_params) as conn: conn.fanout_send(topic, msg) def notify(conf, context, topic, msg, connection_pool): """Sends a notification event on a topic.""" event_type = msg.get('event_type') LOG.debug(_('Sending %(event_type)s on %(topic)s'), locals()) pack_context(msg, context) with ConnectionContext(conf, connection_pool) as conn: conn.notify_send(topic, msg) def cleanup(connection_pool): if connection_pool: connection_pool.empty() def get_control_exchange(conf): try: return conf.control_exchange except cfg.NoSuchOptError: return 'openstack' ```
[ { "content": "Here is the script:\n```python\n# char encode:\n# the value can be: utf-8, ascii, windows-1252, ...\nchar_encode = 'ascii'\n\nimport os\nimport os_base\nimport codecs\n\n#\nmat_data = []\nftxt = \"materials_data.txt\"\nm3d_ex = \"_export.m3d\"\n\n#\nname_list = ['sinon']\nname_list += ['pepper']\n...
[ { "content": "Here is the script:\n<|memory_start|>```python\n# char encode:\n# the value can be: utf-8, ascii, windows-1252, ...\nchar_encode = 'ascii'\n\nimport os\nimport os_base\nimport codecs\n\n#\nmat_data = []\nftxt = \"materials_data.txt\"\nm3d_ex = \"_export.m3d\"\n\n#\nname_list = ['sinon']\nname_list...
```python # char encode: # the value can be: utf-8, ascii, windows-1252, ... char_encode = 'ascii' import os import os_base import codecs # mat_data = [] ftxt = "materials_data.txt" m3d_ex = "_export.m3d" # name_list = ['sinon'] name_list += ['pepper'] name_list += ['nino'] name_list += ['black_warrior'] # mat_start = {} mat_start['sinon'] = 0 mat_start['pepper'] = 11 mat_start['nino'] = 22 mat_start['black_warrior'] = 43 # m3d_start = {} m3d_start['sinon'] = 0 m3d_start['pepper'] = 0 m3d_start['nino'] = 0 m3d_start['black_warrior'] = 8 # m3d_end = {} m3d_end['sinon'] = 0 m3d_end['pepper'] = 0 m3d_end['nino'] = 0 m3d_end['black_warrior'] = 27 # str_replace def str_replace(fm3d_in, mat_start_in, m3d_start_in, m3d_end_in): f = codecs.open(fm3d_in, encoding = char_encode) fw = codecs.open(fm3d_in+'t','w', encoding = char_encode) lines = f.readlines() # for i in range(m3d_start_in, m3d_end_in): lines[i] = mat_data[mat_start_in+(i-m3d_start_in)] for line in lines: fw.writelines(line) f.close() fw.close() # os.remove(fm3d_in) os.rename(fm3d_in+'t', fm3d_in) print(fm3d_in, "replace OK") # main assert(os.path.isfile(ftxt)) fd = codecs.open(ftxt, encoding = char_encode) mat_data = fd.readlines() fd.close() for i in range(0, len(name_list)): fm3d = name_list[i]+m3d_ex; if (os.path.isfile(fm3d)): str_replace(fm3d, mat_start[name_list[i]], m3d_start[name_list[i]], m3d_end[name_list[i]]) print("- Program End -") #exit = input('>') ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: pogoprotos/networking/platform/responses/plat_eight_response.proto\n\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))\nfrom google.prot...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: pogoprotos/networking/platform/responses/plat_eight_response.proto\n\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))\n...
```python # Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/networking/platform/responses/plat_eight_response.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='pogoprotos/networking/platform/responses/plat_eight_response.proto', package='pogoprotos.networking.platform.responses', syntax='proto3', serialized_pb=_b('\nBpogoprotos/networking/platform/responses/plat_eight_response.proto\x12(pogoprotos.networking.platform.responses\"$\n\x11PlatEightResponse\x12\x0f\n\x07message\x18\x02 \x01(\tb\x06proto3') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _PLATEIGHTRESPONSE = _descriptor.Descriptor( name='PlatEightResponse', full_name='pogoprotos.networking.platform.responses.PlatEightResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='message', full_name='pogoprotos.networking.platform.responses.PlatEightResponse.message', index=0, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=112, serialized_end=148, ) DESCRIPTOR.message_types_by_name['PlatEightResponse'] = _PLATEIGHTRESPONSE PlatEightResponse = _reflection.GeneratedProtocolMessageType('PlatEightResponse', (_message.Message,), dict( DESCRIPTOR = _PLATEIGHTRESPONSE, __module__ = 'pogoprotos.networking.platform.responses.plat_eight_response_pb2' # @@protoc_insertion_point(class_scope:pogoprotos.networking.platform.responses.PlatEightResponse) )) _sym_db.RegisterMessage(PlatEightResponse) # @@protoc_insertion_point(module_scope) ```
[ { "content": "Produce an exact reconstruction of the code:\n```python\nimport os\nfrom flask import Flask, request, jsonify\nfrom mongoengine import *\nimport datetime\n\napp = Flask(__name__)\n\nmongodb_uri = os.environ.get('MONGODB_URI', 'localhost:27017')\n\nconnect(\"pokerstats\", host=mongodb_uri)\n\nclass...
[ { "content": "Produce an exact reconstruction of the code:\n<|memory_start|>```python\nimport os\nfrom flask import Flask, request, jsonify\nfrom mongoengine import *\nimport datetime\n\napp = Flask(__name__)\n\nmongodb_uri = os.environ.get('MONGODB_URI', 'localhost:27017')\n\nconnect(\"pokerstats\", host=mongo...
```python import os from flask import Flask, request, jsonify from mongoengine import * import datetime app = Flask(__name__) mongodb_uri = os.environ.get('MONGODB_URI', 'localhost:27017') connect("pokerstats", host=mongodb_uri) class Player(Document): name = StringField(required=True, unique=True, max_length=200) class Record(Document): player = ReferenceField("Player", required=True) game = ReferenceField("Game", required=True) cash_in = FloatField() good_all_in = ListField(field=DateTimeField) bad_all_in = ListField(field=DateTimeField) cash_out = FloatField() class Game(Document): name = StringField(max_length=200) date = DateTimeField() cash = FloatField() @app.route('/', methods=['GET']) @app.route('/players', methods=['GET']) def get_players(): return Player.objects.to_json() @app.route('/players/<player_id>', methods=['GET']) def get_player(player_id): p = Player.objects(id=player_id) return p.to_json(), 200 @app.route('/players', methods=['POST']) def create_player(): # TODO: add check for is json json_data = request.get_json() p = Player(**json_data) try: p.save() except NotUniqueError as e: return jsonify({'error' : e.message}), 200 return p.to_json(), 201 @app.route('/players/<player_id>', methods=['DELETE']) def delete_player(player_id): Player.objects(id=player_id).delete() return jsonify({}), 200 @app.route('/players/<player_id>', methods=['PUT']) def update_player(player_id): # TODO: add check for is json json_data = request.get_json() p = Player.objects(id=player_id) p.update(**json_data) return p.to_json(), 200 @app.route('/games', methods=['GET']) def get_games(): return Game.objects.to_json() @app.route('/games/<game_id>', methods=['GET']) def get_game(game_id): p = Game.objects(id=game_id) return p.to_json(), 200 @app.route('/games', methods=['POST']) def create_game(): # TODO: add check for is json json_data = request.get_json() p = Game(**json_data) try: p.save() except NotUniqueError as e: return jsonify({'error' : e.message}), 200 return p.to_json(), 201 @app.route('/games/<game_id>', methods=['DELETE']) def delete_game(game_id): Game.objects(id=game_id).delete() return jsonify({}), 200 @app.route('/games/<game_id>', methods=['PUT']) def update_game(game_id): # TODO: add check for is json json_data = request.get_json() p = Game.objects(id=game_id) p.update(**json_data) return p.to_json(), 200 @app.route('/records', methods=['GET']) def get_records(): return Record.objects.to_json() @app.route('/records/<record_id>', methods=['GET']) def get_record(record_id): p = Record.objects(id=record_id) return p.to_json(), 200 @app.route('/records', methods=['POST']) def create_record(): # TODO: add check for is json json_data = request.get_json() p = Record(**json_data) try: p.save() except NotUniqueError as e: return jsonify({'error' : e.message}), 200 return p.to_json(), 201 @app.route('/records/<record_id>', methods=['DELETE']) def delete_record(record_id): Record.objects(id=record_id).delete() return jsonify({}), 200 @app.route('/records/<record_id>', methods=['PUT']) def update_record(record_id): # TODO: add check for is json json_data = request.get_json() p = Record.objects(id=record_id) p.update(**json_data) return p.to_json(), 200 if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) # connect to the mongodb database ```
[ { "content": "Here is a code file:\n```python\nfrom elemental_core.util import process_uuids_value\n\nfrom ._resource_type import ResourceType\nfrom ._resource_reference import ResourceReference\nfrom ._property_changed_hook import PropertyChangedHook\n\n\nclass FilterType(ResourceType):\n \"\"\"\n Repres...
[ { "content": "Here is a code file:\n<|memory_start|>```python\nfrom elemental_core.util import process_uuids_value\n\nfrom ._resource_type import ResourceType\nfrom ._resource_reference import ResourceReference\nfrom ._property_changed_hook import PropertyChangedHook\n\n\nclass FilterType(ResourceType):\n \"...
```python from elemental_core.util import process_uuids_value from ._resource_type import ResourceType from ._resource_reference import ResourceReference from ._property_changed_hook import PropertyChangedHook class FilterType(ResourceType): """ Represents a collection of AttributeIds that should be filtered together. Content Instances of various types will have different Attribute Types that may represent the same high-level property, such as a name. FilterType's role is to represent this high-level association in order to easily filter different types of Content Instances using a single dimension. """ @property def attribute_type_ids(self): return self._attribute_type_ids @attribute_type_ids.setter def attribute_type_ids(self, value): try: value = process_uuids_value(value) except (TypeError, ValueError): msg = ( 'Failed to set attribute type ids: ' 'Value contains invalid UUID values - {0}' ) msg = msg.format(value) raise ValueError(msg) original_value = self._attribute_type_ids if value != original_value: self._attribute_type_ids = value self._attribute_type_ids_changed(self, original_value, value) @property def attribute_type_ids_changed(self): return self._attribute_type_ids_changed @ResourceReference def attribute_types(self): return self._attribute_type_ids def __init__(self, id=None, name=None, attribute_type_ids=None): super(FilterType, self).__init__(id=id, name=name) self._attribute_type_ids = [] self._attribute_type_ids_changed = PropertyChangedHook() self.attribute_type_ids = attribute_type_ids ```
[ { "content": "```python\nimport itertools\n\nfrom utils.utils import range_union\n\n# adapted from ips-util for python 3.2 (https://pypi.org/project/ips-util/)\nclass IPS_Patch(object):\n def __init__(self, patchDict=None):\n self.records = []\n self.truncate_length = None\n self.max_siz...
[ { "content": "<|memory_start|>```python\nimport itertools\n\nfrom utils.utils import range_union\n\n# adapted from ips-util for python 3.2 (https://pypi.org/project/ips-util/)\nclass IPS_Patch(object):\n def __init__(self, patchDict=None):\n self.records = []\n self.truncate_length = None\n ...
```python import itertools from utils.utils import range_union # adapted from ips-util for python 3.2 (https://pypi.org/project/ips-util/) class IPS_Patch(object): def __init__(self, patchDict=None): self.records = [] self.truncate_length = None self.max_size = 0 if patchDict is not None: for addr, data in patchDict.items(): byteData = bytearray(data) self.add_record(addr, byteData) def toDict(self): ret = {} for record in self.records: if 'rle_count' in record: ret[record['address']] = [int.from_bytes(record['data'],'little')]*record['rle_count'] else: ret[record['address']] = [int(b) for b in record['data']] return ret @staticmethod def load(filename): loaded_patch = IPS_Patch() with open(filename, 'rb') as file: header = file.read(5) if header != b'PATCH': raise Exception('Not a valid IPS patch file!') while True: address_bytes = file.read(3) if address_bytes == b'EOF': break address = int.from_bytes(address_bytes, byteorder='big') length = int.from_bytes(file.read(2), byteorder='big') rle_count = 0 if length == 0: rle_count = int.from_bytes(file.read(2), byteorder='big') length = 1 data = file.read(length) if rle_count > 0: loaded_patch.add_rle_record(address, data, rle_count) else: loaded_patch.add_record(address, data) truncate_bytes = file.read(3) if len(truncate_bytes) == 3: loaded_patch.set_truncate_length(int.from_bytes(truncate_bytes, byteorder='big')) return loaded_patch @staticmethod def create(original_data, patched_data): # The heuristics for optimizing a patch were chosen with reference to # the source code of Flips: https://github.com/Alcaro/Flips patch = IPS_Patch() run_in_progress = False current_run_start = 0 current_run_data = bytearray() runs = [] if len(original_data) > len(patched_data): patch.set_truncate_length(len(patched_data)) original_data = original_data[:len(patched_data)] elif len(original_data) < len(patched_data): original_data += bytes([0] * (len(patched_data) - len(original_data))) if original_data[-1] == 0 and patched_data[-1] == 0: patch.add_record(len(patched_data) - 1, bytes([0])) for index, (original, patched) in enumerate(zip(original_data, patched_data)): if not run_in_progress: if original != patched: run_in_progress = True current_run_start = index current_run_data = bytearray([patched]) else: if original == patched: runs.append((current_run_start, current_run_data)) run_in_progress = False else: current_run_data.append(patched) if run_in_progress: runs.append((current_run_start, current_run_data)) for start, data in runs: if start == int.from_bytes(b'EOF', byteorder='big'): start -= 1 data = bytes([patched_data[start - 1]]) + data grouped_byte_data = list([ {'val': key, 'count': sum(1 for _ in group), 'is_last': False} for key,group in itertools.groupby(data) ]) grouped_byte_data[-1]['is_last'] = True record_in_progress = bytearray() pos = start for group in grouped_byte_data: if len(record_in_progress) > 0: # We don't want to interrupt a record in progress with a new header unless # this group is longer than two complete headers. if group['count'] > 13: patch.add_record(pos, record_in_progress) pos += len(record_in_progress) record_in_progress = bytearray() patch.add_rle_record(pos, bytes([group['val']]), group['count']) pos += group['count'] else: record_in_progress += bytes([group['val']] * group['count']) elif (group['count'] > 3 and group['is_last']) or group['count'] > 8: # We benefit from making this an RLE record if the length is at least 8, # or the length is at least 3 and we know it to be the last part of this diff. # Make sure not to overflow the maximum length. Split it up if necessary. remaining_length = group['count'] while remaining_length > 0xffff: patch.add_rle_record(pos, bytes([group['val']]), 0xffff) remaining_length -= 0xffff pos += 0xffff patch.add_rle_record(pos, bytes([group['val']]), remaining_length) pos += remaining_length else: # Just begin a new standard record. record_in_progress += bytes([group['val']] * group['count']) if len(record_in_progress) > 0xffff: patch.add_record(pos, record_in_progress[:0xffff]) record_in_progress = record_in_progress[0xffff:] pos += 0xffff # Finalize any record still in progress. if len(record_in_progress) > 0: patch.add_record(pos, record_in_progress) return patch def add_record(self, address, data): if address == int.from_bytes(b'EOF', byteorder='big'): raise RuntimeError('Start address {0:x} is invalid in the IPS format. Please shift your starting address back by one byte to avoid it.'.format(address)) if address > 0xffffff: raise RuntimeError('Start address {0:x} is too large for the IPS format. Addresses must fit into 3 bytes.'.format(address)) if len(data) > 0xffff: raise RuntimeError('Record with length {0} is too large for the IPS format. Records must be less than 65536 bytes.'.format(len(data))) if len(data) == 0: # ignore empty records return record = {'address': address, 'data': data, 'size':len(data)} self.appendRecord(record) def add_rle_record(self, address, data, count): if address == int.from_bytes(b'EOF', byteorder='big'): raise RuntimeError('Start address {0:x} is invalid in the IPS format. Please shift your starting address back by one byte to avoid it.'.format(address)) if address > 0xffffff: raise RuntimeError('Start address {0:x} is too large for the IPS format. Addresses must fit into 3 bytes.'.format(address)) if count > 0xffff: raise RuntimeError('RLE record with length {0} is too large for the IPS format. RLE records must be less than 65536 bytes.'.format(count)) if len(data) != 1: raise RuntimeError('Data for RLE record must be exactly one byte! Received {0}.'.format(data)) record = {'address': address, 'data': data, 'rle_count': count, 'size': count} self.appendRecord(record) def appendRecord(self, record): sz = record['address'] + record['size'] if sz > self.max_size: self.max_size = sz self.records.append(record) def set_truncate_length(self, truncate_length): self.truncate_length = truncate_length def encode(self): encoded_bytes = bytearray() encoded_bytes += 'PATCH'.encode('ascii') for record in self.records: encoded_bytes += record['address'].to_bytes(3, byteorder='big') if 'rle_count' in record: encoded_bytes += (0).to_bytes(2, byteorder='big') encoded_bytes += record['rle_count'].to_bytes(2, byteorder='big') else: encoded_bytes += len(record['data']).to_bytes(2, byteorder='big') encoded_bytes += record['data'] encoded_bytes += 'EOF'.encode('ascii') if self.truncate_length is not None: encoded_bytes += self.truncate_length.to_bytes(3, byteorder='big') return encoded_bytes # save patch into IPS file def save(self, path): with open(path, 'wb') as ipsFile: ipsFile.write(self.encode()) # applies patch on an existing bytearray def apply(self, in_data): out_data = bytearray(in_data) for record in self.records: if record['address'] >= len(out_data): out_data += bytes([0] * (record['address'] - len(out_data) + 1)) if 'rle_count' in record: out_data[record['address'] : record['address'] + record['rle_count']] = b''.join([record['data']] * record['rle_count']) else: out_data[record['address'] : record['address'] + len(record['data'])] = record['data'] if self.truncate_length is not None: out_data = out_data[:self.truncate_length] return out_data # applies patch on an opened file def applyFile(self, handle): for record in self.records: handle.seek(record['address']) if 'rle_count' in record: handle.write(bytearray(b'').join([record['data']]) * record['rle_count']) else: handle.write(record['data']) # appends an IPS_Patch on top of this one def append(self, patch): if patch.truncate_length is not None and (self.truncate_length is None or patch.truncate_length > self.truncate_length): self.set_truncate_length(patch.truncate_length) for record in patch.records: if record['size'] > 0: # ignore empty records self.appendRecord(record) # gets address ranges written to by this patch def getRanges(self): def getRange(record): return range(record['address'], record['address']+record['size']) return range_union([getRange(record) for record in self.records]) ```
[ { "content": "Output the full code verbatim (no extra comments):\n```python\n# -*- coding: utf-8 -*-\n\n# Copyright 2013 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy...
[ { "content": "Output the full code verbatim (no extra comments):\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n# Copyright 2013 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obt...
```python # -*- coding: utf-8 -*- # Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import simplejson as json import urllib2 from nailgun.errors import errors from nailgun.logger import logger class ZabbixManager(object): @classmethod def _make_zabbix_request(cls, url, method, params, auth=None): header = {'Content-type': 'application/json'} data = {'jsonrpc': '2.0', 'id': '1', 'method': method, 'params': params} if auth: data['auth'] = auth logger.debug("Zabbix request: %s", data) request = urllib2.Request(url, json.dumps(data), header) try: response = urllib2.urlopen(request) except urllib2.URLError as e: raise errors.CannotMakeZabbixRequest( "Can't make a request to Zabbix: {0}".format(e) ) result = json.loads(response.read()) logger.debug("Zabbix response: %s", result) if 'error' in result: code = result['error']['code'] msg = result['error']['message'] data = result['error'].get('data', '') raise errors.ZabbixRequestError( "Zabbix returned error code {0}, {1}: {2}".format( code, msg, data ) ) return result['result'] @classmethod def _zabbix_auth(cls, url, user, password): method = 'user.authenticate' params = {'user': user, 'password': password} auth_hash = cls._make_zabbix_request(url, method, params) return auth_hash @classmethod def _get_zabbix_hostid(cls, url, auth, name): method = 'host.get' params = {'filter': {'host': name}} result = cls._make_zabbix_request(url, method, params, auth=auth) if len(result) == 0: logger.info("Host %s does not exist in zabbix, skipping", name) return None return result[0]['hostid'] @classmethod def remove_from_zabbix(cls, zabbix, nodes): url = zabbix['url'] user = zabbix['user'] password = zabbix['password'] auth = cls._zabbix_auth(url, user, password) hostids = [] method = "host.delete" for node in nodes: name = node['slave_name'] hostid = cls._get_zabbix_hostid(url, auth, name) if hostid: hostids.append(hostid) if hostids: cls._make_zabbix_request(url, method, hostids, auth=auth) @classmethod def get_zabbix_node(cls, cluster): zabbix_nodes = filter( lambda node: filter( lambda role: role.name == 'zabbix-server', node.role_list ), cluster.nodes ) if not zabbix_nodes: return None return zabbix_nodes[0] @classmethod def get_zabbix_credentials(cls, cluster): creds = {} zabbix_node = cls.get_zabbix_node(cluster) attributes = cluster.attributes zabbix_attrs = attributes.editable['zabbix'] creds['user'] = zabbix_attrs['username']['value'] creds['password'] = zabbix_attrs['password']['value'] creds['url'] = "http://{0}/zabbix/api_jsonrpc.php".format( zabbix_node.ip ) return creds ```
[ { "content": "```python\n# Copyright 2015-2016 Yelp Inc.\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 requir...
[ { "content": "<|memory_start|>```python\n# Copyright 2015-2016 Yelp Inc.\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#\...
```python # Copyright 2015-2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from behave import given from behave import then from behave import when from path import Path from paasta_tools.utils import _run @given("a simple service to test") def given_simple_service(context): context.fake_service_name = "fake_simple_service" assert os.path.isfile(os.path.join(context.fake_service_name, "Dockerfile")) assert os.path.isfile(os.path.join(context.fake_service_name, "Makefile")) @when( "we run paasta local-run on a Marathon service in non-interactive mode " 'with environment variable "{var}" set to "{val}"' ) def non_interactive_local_run(context, var, val): with Path("fake_simple_service"): # The local-run invocation here is designed to run and return a sentinel # exit code that we can look out for. It also sleeps a few seconds # because the local-run code currently crashes when the docker # container dies before it gets a chance to lookup the containerid # (which causes jenkins flakes) The sleep can be removed once local-run # understands that containers can die quickly. localrun_cmd = ( "paasta local-run " "--yelpsoa-config-root ../fake_soa_configs_local_run/ " "--service fake_simple_service " "--cluster test-cluster " "--instance main " "--build " """--cmd '/bin/sh -c "echo \\"%s=$%s\\" && sleep 2s && exit 42"' """ % (var, var) ) context.return_code, context.output = _run(command=localrun_cmd, timeout=90) @then( 'we should see the environment variable "{var}" with the value "{val}" in the output' ) def env_var_in_output(context, var, val): assert f"{var}={val}" in context.output @when("we run paasta local-run on an interactive job") def local_run_on_adhoc_job(context): with Path("fake_simple_service"): local_run_cmd = ( "paasta local-run " "--yelpsoa-config-root ../fake_soa_configs_local_run/ " "--service fake_simple_service " "--cluster test-cluster " "--instance sample_adhoc_job " "--build " ) context.return_code, context.output = _run(command=local_run_cmd, timeout=90) @when("we run paasta local-run on a tron action") def local_run_on_tron_action(context): with Path("fake_simple_service"): local_run_cmd = ( "paasta local-run " "--yelpsoa-config-root ../fake_soa_configs_local_run/ " "--service fake_simple_service " "--cluster test-cluster " "--instance sample_tron_job.action1 " "--build " ) context.return_code, context.output = _run(command=local_run_cmd, timeout=90) ```
[ { "content": "Here is the code block:\n```python\n# Copyright 2017 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....
[ { "content": "Here is the code block:\n<|memory_start|>```python\n# Copyright 2017 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/lic...
```python # Copyright 2017 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. from google.api_core import client_info def test_constructor_defaults(): info = client_info.ClientInfo() assert info.python_version is not None assert info.grpc_version is not None assert info.api_core_version is not None assert info.gapic_version is None assert info.client_library_version is None assert info.rest_version is None def test_constructor_options(): info = client_info.ClientInfo( python_version="1", grpc_version="2", api_core_version="3", gapic_version="4", client_library_version="5", user_agent="6", rest_version="7", ) assert info.python_version == "1" assert info.grpc_version == "2" assert info.api_core_version == "3" assert info.gapic_version == "4" assert info.client_library_version == "5" assert info.user_agent == "6" assert info.rest_version == "7" def test_to_user_agent_minimal(): info = client_info.ClientInfo( python_version="1", api_core_version="2", grpc_version=None ) user_agent = info.to_user_agent() assert user_agent == "gl-python/1 gax/2" def test_to_user_agent_full(): info = client_info.ClientInfo( python_version="1", grpc_version="2", api_core_version="3", gapic_version="4", client_library_version="5", user_agent="app-name/1.0", ) user_agent = info.to_user_agent() assert user_agent == "app-name/1.0 gl-python/1 grpc/2 gax/3 gapic/4 gccl/5" def test_to_user_agent_rest(): info = client_info.ClientInfo( python_version="1", grpc_version=None, rest_version="2", api_core_version="3", gapic_version="4", client_library_version="5", user_agent="app-name/1.0", ) user_agent = info.to_user_agent() assert user_agent == "app-name/1.0 gl-python/1 rest/2 gax/3 gapic/4 gccl/5" ```
[ { "content": "Here is the snippet:\n```python\n#!/usr/bin/env python\n\nimport unittest\nfrom day22 import Node, make_nodes, viable_nodes\n\n\nclass TestMakingNodes(unittest.TestCase):\n\n def test_makes_nodes_from_input(self):\n df = \"\"\"\n /dev/grid/node-x0-y0 87T 71T 16T 81%\n ...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n#!/usr/bin/env python\n\nimport unittest\nfrom day22 import Node, make_nodes, viable_nodes\n\n\nclass TestMakingNodes(unittest.TestCase):\n\n def test_makes_nodes_from_input(self):\n df = \"\"\"\n /dev/grid/node-x0-y0 87T 71T ...
```python #!/usr/bin/env python import unittest from day22 import Node, make_nodes, viable_nodes class TestMakingNodes(unittest.TestCase): def test_makes_nodes_from_input(self): df = """ /dev/grid/node-x0-y0 87T 71T 16T 81% /dev/grid/node-x0-y1 93T 72T 21T 77% /dev/grid/node-x1-y0 86T 66T 20T 76% /dev/grid/node-x1-y1 93T 64T 29T 68% """ nodes = make_nodes(df) self.assertEqual(nodes, [ [Node(name='node-x0-y0', size=87, used=71, avail=16), Node(name='node-x1-y0', size=86, used=66, avail=20)], [Node(name='node-x0-y1', size=93, used=72, avail=21), Node(name='node-x1-y1', size=93, used=64, avail=29)]]) class TestFindingViableNodes(unittest.TestCase): grid = [ [Node(name='A', size=100, used=1, avail=99), Node(name='B', size=100, used=50, avail=50)], [Node(name='C', size=100, used=0, avail=100), Node(name='D', size=100, used=100, avail=0)], [Node(name='E', size=50, used=10, avail=40), Node(name='F', size=100, used=60, avail=40)]] def test_finds_viable_nodes(self): grid = self.grid nodes = viable_nodes(grid) self.assertEqual(nodes, { (grid[0][0], grid[0][1]), (grid[0][0], grid[1][0]), (grid[0][0], grid[2][0]), (grid[0][0], grid[2][1]), (grid[0][1], grid[0][0]), (grid[0][1], grid[1][0]), (grid[1][1], grid[1][0]), (grid[2][0], grid[0][0]), (grid[2][0], grid[0][1]), (grid[2][0], grid[1][0]), (grid[2][0], grid[2][1]), (grid[2][1], grid[0][0]), (grid[2][1], grid[1][0])}) if __name__ == '__main__': unittest.main() ```
[ { "content": "```python\n\"\"\" Test the API for Gyms \"\"\"\nfrom datetime import datetime, timedelta\nfrom app.models.gym import Gym\nfrom app.models.gym_item import GymItem\nfrom app.models.raid_item import RaidItem\nfrom app.tests.api.personalised.gym_collection.gym_common import \\\n GymAPICommonCase\ni...
[ { "content": "<|memory_start|>```python\n\"\"\" Test the API for Gyms \"\"\"\nfrom datetime import datetime, timedelta\nfrom app.models.gym import Gym\nfrom app.models.gym_item import GymItem\nfrom app.models.raid_item import RaidItem\nfrom app.tests.api.personalised.gym_collection.gym_common import \\\n Gym...
```python """ Test the API for Gyms """ from datetime import datetime, timedelta from app.models.gym import Gym from app.models.gym_item import GymItem from app.models.raid_item import RaidItem from app.tests.api.personalised.gym_collection.gym_common import \ GymAPICommonCase import pytz class TestGymCollectionModelData(GymAPICommonCase): """ Test the API methods for the Gym """ def test_gym_list(self): """ Test that a list of Gyms is returned """ gym = Gym.objects.create( name='Test Gym 2', location='666,1337', image_url='image.jpg' ) self.profile.tracked_gyms.add(gym) resp = self.api.get('/api/v1/gyms/') results = resp.data.get('results') self.assertEqual(len(results), 2) def test_active_raid(self): """ Test that active raid data is returned if a Gym has an active raid on it """ raid_time = datetime.now(tz=pytz.UTC) + timedelta(hours=1) RaidItem.objects.create( gym=self.gym, pokemon='Test Pokemon', level=5, end_date=raid_time ) resp = self.api.get('/api/v1/gyms/') results = resp.data.get('results')[0] self.assertEqual(results.get('raid').get('pokemon'), 'Test Pokemon') self.assertEqual(results.get('raid').get('level'), 5) self.assertTrue('0:59:' in results.get('raid').get('time_left')) def test_visited_gym(self): """ Test that if a gym has been visited the gym_visit_date is returned """ visit_date = datetime(1988, 1, 12, 6, 0, 0, tzinfo=pytz.UTC) GymItem.objects.create( gym=self.gym, profile=self.profile, gym_visit_date=visit_date ) resp = self.api.get('/api/v1/gyms/') results = resp.data.get('results')[0] self.assertEqual(results.get('gym_visit_date'), visit_date) def test_gym_name(self): """ Test that gym name is returned """ resp = self.api.get('/api/v1/gyms/') result = resp.data.get('results')[0] self.assertEqual(result.get('name'), self.gym.name) def test_gym_image(self): """ Test that gym image is returned """ resp = self.api.get('/api/v1/gyms/') result = resp.data.get('results')[0] self.assertEqual(result.get('image_url'), self.gym.image_url) def test_gym_location(self): """ Test that the location of the gym is returned """ resp = self.api.get('/api/v1/gyms/') result = resp.data.get('results')[0] self.assertEqual(result.get('location'), self.gym.location) def test_gym_id(self): """ Test that the location of the gym is returned """ resp = self.api.get('/api/v1/gyms/') result = resp.data.get('results')[0] self.assertEqual(result.get('id'), self.gym.id) ```
[ { "content": "Here is the source code:\n```python\n# -*- coding: utf-8 -*-\nimport hashlib\nimport libtorrent as lt\nimport logging\nfrom threading import Timer, Event\nimport os\nimport time\nfrom p2c.exceptions import SessionNotBindedException, TorrentHasNotMetadataYet\nimport settings\nfrom torrent.movie imp...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nimport hashlib\nimport libtorrent as lt\nimport logging\nfrom threading import Timer, Event\nimport os\nimport time\nfrom p2c.exceptions import SessionNotBindedException, TorrentHasNotMetadataYet\nimport settings\nfrom t...
```python # -*- coding: utf-8 -*- import hashlib import libtorrent as lt import logging from threading import Timer, Event import os import time from p2c.exceptions import SessionNotBindedException, TorrentHasNotMetadataYet import settings from torrent.movie import Movie SOURCE_TYPES = ("MAGNET", "TORRENT") logger = logging.getLogger(__name__) class Torrent(object): def __init__(self, source_type, source, name): """ :type source: str magnet or torrent file path :type name: str :type source_type: str """ if not source_type in SOURCE_TYPES: raise Exception( "source_type must be one of {0}".format(SOURCE_TYPES)) self.name = name self.source_type = source_type self.source = source self.torrent_handler = None self._torrent_info = None # dict where key is path and value is Movie instance # this is files which are downloading or downloaded self.files = None # piece_length in this torrent self.piece_length = None # amount of pieces which made up DOWNLOAD_PIECE_SIZE self._jump = None # if first prioritizing task was run once self._prioritized = False self.priority_interval = settings.PRIORITY_INTERVAL self._priority_thread_stop = Event() self._priority_timer = None # currently downloading Movie self._downloading = None def __del__(self): self._stop_torrent_threads() def __str__(self): return self.name def set_source(self, source, session): self.source = source if self.source: self.bind_session(session) def bind_session(self, session): """ Creates torrent handler based on source_type """ add_data = {} if self.source_type == "TORRENT": add_data['ti'] = lt.torrent_info(self.source) elif self.source_type == "MAGNET": add_data['url'] = self.source add_data['save_path'] = self._get_download_dir() add_data['storage_mode'] = lt.storage_mode_t(1) self.torrent_handler = session.add_torrent(add_data) self._prioritize_to_none() def get_filelist(self): info = self.get_torrent_info(wait=True) return [file.path for file in info.files()] def get_movies_filelist(self): if self.files is None: self._create_movies() return list(self.files.keys()) def get_movies(self): if self.files is None: self._create_movies() return list(self.files.values()) def download_file(self, filename:str): if not filename in self.get_movies_filelist(): raise Exception("filename not found in torrent") self._prioritize_to_none() self._downloading = self.files[filename] self._run_torrent_threads() def pause_download(self): self._stop_torrent_threads() self.torrent_handler.pause() self._downloading = None def has_torrent_info(self): """ Checks if torrent has downloaded metadata """ try: self.get_torrent_info() return True except (TorrentHasNotMetadataYet, SessionNotBindedException): return False def get_torrent_info(self, wait=False): """ Gets torrent's metadata """ if self._torrent_info != None: return self._torrent_info if self.torrent_handler is None: if wait: while not self.torrent_handler is None: time.sleep(0.1) else: raise SessionNotBindedException if not self.torrent_handler.has_metadata(): if wait: while not self.torrent_handler.has_metadata(): time.sleep(0.1) else: raise TorrentHasNotMetadataYet self._torrent_info = self.torrent_handler.get_torrent_info() return self._torrent_info def get_status(self): """ Gets torrent's status with field like download rate, peers number, state and progress level """ status = self.torrent_handler.status() state_str = ['queued', 'checking', 'downloading metadata', 'downloading', 'finished', 'seeding', 'allocating', 'checking fastresume'] data = { 'download_rate': status.download_rate, 'download_payload_rate': status.download_payload_rate, 'num_peers': status.num_peers, 'state': state_str[status.state], 'progress': status.progress } return data def get_seconds_to_buffer(self): rate = self.get_status()['download_rate'] if(rate > 100 * 1024): # round to 100 kbs, 200 kbs, 300 kbs rate = int(rate / (100 * 1024)) * 100 * 1024 movie = self.get_downloading_movie() # minimum rate if movie and rate > 30 * 1024: return int(movie.pieces_to_play * movie.piece_length / rate) def get_downloading_movie(self): return self._downloading def _create_movies(self): info = self.get_torrent_info() files = info.files() self.piece_length = info.piece_length() self.priority_interval = settings.PRIORITY_INTERVAL * self.piece_length / ( 1024 ** 2) self._jump = int(settings.DOWNLOAD_PIECE_SIZE / self.piece_length) + 1 self.files = {} for file in files: ext = os.path.splitext(file.path)[1] if ext and ext[1:].lower() in settings.SUPPORTED_MOVIE_EXTENSIONS: first_piece = int(file.offset / self.piece_length) last_piece = int((file.size + file.offset) / self.piece_length) self.files[file.path] = Movie(path=file.path, size=file.size, first_piece=first_piece, last_piece=last_piece, piece_length=self.piece_length, download_dir=self._get_download_dir()) def _update_movies_progress(self): """ Updates movie progress based on number of downloaded pieces """ p_downloaded = self.torrent_handler.status().pieces movie = self.get_downloading_movie() first_piece, last_piece = movie.first_piece, movie.last_piece # logger.debug("first_piece: {}".format(first_piece)) # logger.debug("last_piece: {}".format(last_piece )) counter = 0 for item in p_downloaded[first_piece:last_piece]: if item == True: counter += 1 else: break # logger.debug("download_pieces inside thread is: {}".format(counter)) movie.downloaded_pieces = counter def _manage_pieces_priority(self): """ Sets priority blocks. First pieces should be downloaded first swo its have the highest priority. """ p_downloaded = self.torrent_handler.status().pieces movie = self.get_downloading_movie() if not movie: return first_piece, last_piece = movie.cur_first_piece, movie.cur_last_piece if not False in p_downloaded[first_piece:first_piece + self._jump + 1]: # all block downloaded first_piece += self._jump movie.cur_first_piece = first_piece # prioritezing # [7, 7, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...] if first_piece + self._jump + self._jump <= last_piece: for piece in range(first_piece + 4 * self._jump, last_piece + 1): # logger.debug("the lowest priority for: {}".format(piece)) self.torrent_handler.piece_priority(piece, 0) if first_piece + self._jump <= last_piece: for piece in range(first_piece + 2 * self._jump, min(last_piece + 1, first_piece + 4 * self._jump)): # logger.debug("low priority for: {}".format(piece)) self.torrent_handler.piece_priority(piece, 2) if first_piece <= last_piece: for piece in range(first_piece, min(last_piece + 1, first_piece + 2 * self._jump)): # logger.debug("the highest priority for: {}".format(piece)) self.torrent_handler.piece_priority(piece, 7) # for mp4 get 512KB end of file # TODO: bug below # for piece in range( # last_piece - int(self.piece_length / 512 * 1024) + 1, # last_piece): # logger.debug("the highest priority for (512KB end of file): {}".format(piece)) # self.torrent_handler.piece_priority(piece, 7) self._update_movies_progress() if not self._priority_thread_stop.is_set(): if self._priority_timer: self._priority_timer.cancel() self._priority_timer = None self._run_torrent_threads() def _run_torrent_threads(self): # logger.debug("run threads for {}".format(self.priority_interval)) if not self._priority_thread_stop.is_set(): if not self._priority_timer: self._priority_timer = Timer(self.priority_interval, self._manage_pieces_priority) self._priority_timer.start() def _stop_torrent_threads(self): self._priority_thread_stop.set() if self._priority_timer: self._priority_timer.cancel() def _prioritize_to_none(self): if not self._prioritized and self.has_torrent_info(): self._prioritized = True info = self.get_torrent_info() for piece in range(0, info.num_pieces()): self.torrent_handler.piece_priority(piece, 0) def _get_download_dir(self): path = os.path.join(settings.DOWNLOAD_DIR, hashlib.md5(self.name.encode()).hexdigest()) try: os.makedirs(path) except OSError: pass return path ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\nimport networkx as nx\nfrom load_data import *\nfrom compute_metrics_multiplex import *\n\ndef numNodes(g):\n return g.number_of_nodes()\n \ndef numEdges(g):\n return g.number_of_edges()\n \ndef avgDeg(g):\n ...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\nimport networkx as nx\nfrom load_data import *\nfrom compute_metrics_multiplex import *\n\ndef numNodes(g):\n return g.number_of_nodes()\n \ndef numEdges(g):\n return g.number_of_edges()\n \ndef...
```python import networkx as nx from load_data import * from compute_metrics_multiplex import * def numNodes(g): return g.number_of_nodes() def numEdges(g): return g.number_of_edges() def avgDeg(g): return g.number_of_edges()*1.0/g.number_of_nodes() def getGiantComponent(g): return g.subgraph(max([key for key in nx.strongly_connected_components(g)],key=len)) def diameter(g): return nx.diameter(getGiantComponent(g)) def avgPathLen(g): return nx.average_shortest_path_length(getGiantComponent(g)) def nodesInGiantComponent(g): return getGiantComponent(g).number_of_nodes() def edgesInGiantComponent(g): return getGiantComponent(g).number_of_edges() def assortativity(g): return nx.degree_assortativity_coefficient(g,x="in",y="in") stats = { "# nodes":numNodes, "# edges":numEdges, "Avg. degree":avgDeg , "Diameter":diameter,"Avg. path length":avgPathLen,\ "# Nodes in GC":nodesInGiantComponent,"# Edges in GC":edgesInGiantComponent,\ "Assortativity":assortativity} def getHeader(): res = "\t" for stat in stats: res += ","+stat return res def getStatsForGraph(g): res = g.graph["title"][4:] for stat in stats: res += ","+str(stats[stat](g)) return res def getGlobalStatsFromAttribute(graphs,graph_combinations=[],metrics=[]): res = graphs[0].graph["title"][:3] for metric in metrics: res += ","+metric for i,k in graph_combinations: gi,gk = graphs[i],graphs[k] if i == k: res += "\n"+gi.graph["title"][4:] else: res += "\n"+gi.graph["title"][4:]+"->"+gk.graph["title"][4:] for metric in metrics: attribute_name = "Global "+getMetricString(metric,gi,gk) res += ",{0:.3f}".format(gi.graph[attribute_name]) return res def getStatsDistributionFromAttribute(graphs,graph_combinations=[],metrics=[]): res = graphs[0].graph["title"][:3]+"\n" for i,k in graph_combinations: g = graphs[i] res += "\n"+g.graph["title"][4:]+"\nid" for metric in metrics: res += ","+metric res += ",#out_edges,#in_edges\n" for node in range(g.number_of_nodes()): res += str(node)+"," for metric in metrics: attribute_name = getMetricString(metric,g,g) value = g.graph[attribute_name][node] res += '{0:.3f}'.format(value)+"," res += str(len(g.out_edges(node)))+","+str(len(g.in_edges(node)))+"\n" return res def getStasForDataset(dataset="wan"): graphs,node_mapping = load_4_layers(dataset) #metrics = metrics_dict_multiplex.copy() #del metrics["Overlapping Index"] metrics = {"Reciprocity":reciprocity,"tp1":tp1,"tp2":tp2,\ "tc1":tc1,"tc2":tc2} temp = [(i,i) for i in range(len(graphs))] addMetricsAsAttributesMultiplex(graphs,temp,metrics) res = getGlobalStatsFromAttribute(graphs,temp,metrics) res += "\n" res += "\n" #res += "Multiplex" #res += "\n" #res += "\n" #metrics = metrics_dict_multiplex.copy() #temp = graph_combinations+[(k,i) for i,k in graph_combinations] #addMetricsAsAttributesMultiplex(graphs,temp,metrics) #res += getGlobalStatsFromAttribute(graphs,temp,metrics) return res def getSingleStatsForDataset(dataset="wan"): graphs,node_mapping = load_4_layers(dataset) temp = [(i,i) for i in range(len(graphs))] metrics = {"Reciprocity":reciprocity,"tp1":tp1,"tp2":tp2,\ "tc1":tc1,"tc2":tc2} addMetricsAsAttributesMultiplex(graphs,temp,metrics) res = getStatsDistributionFromAttribute(graphs,temp,metrics) return res from csv_to_latex_table import * def main(): with open("wan_table_56.csv","w") as pout: pout.write(get56TablesForDataset("wan")) with open("bms_table_56.csv","w") as pout: pout.write(get56TablesForDataset("bms")) table_from_csv("wan_table_56.txt","wan_table_56.csv") table_from_csv("bms_table_56.txt","bms_table_56.csv") if __name__ == "__main__": main() ```
[ { "content": "Here is a code snippet:\n```python\n# encoding: utf-8\nfrom south.v2 import DataMigration\nfrom django.contrib.gis.maps.google.overlays import GPolygon\n\nclass Migration(DataMigration):\n class NewGPolygon(GPolygon):\n def latlng_from_coords(self, coords):\n \"Generates a Jav...
[ { "content": "Here is a code snippet:\n<|memory_start|>```python\n# encoding: utf-8\nfrom south.v2 import DataMigration\nfrom django.contrib.gis.maps.google.overlays import GPolygon\n\nclass Migration(DataMigration):\n class NewGPolygon(GPolygon):\n def latlng_from_coords(self, coords):\n \...
```python # encoding: utf-8 from south.v2 import DataMigration from django.contrib.gis.maps.google.overlays import GPolygon class Migration(DataMigration): class NewGPolygon(GPolygon): def latlng_from_coords(self, coords): "Generates a JavaScript array of GLatLng objects for the given coordinates." return '[%s]' % ','.join(['new google.maps.LatLng(%s,%s)' % (y, x) for x, y in coords]) def forwards(self, orm): for worldborder in orm.WorldBorder.objects.all(): worldborder.google_border = '[%s]' % ','.join(unicode(self.NewGPolygon(subregion).points) for subregion in worldborder.mpoly) worldborder.save() def backwards(self, orm): for worldborder in orm.WorldBorder.objects.all(): worldborder.google_border = '' worldborder.save() models = { 'world.worldborder': { 'Meta': {'object_name': 'WorldBorder'}, 'area': ('django.db.models.fields.IntegerField', [], {}), 'fips': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'google_border': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'iso2': ('django.db.models.fields.CharField', [], {'max_length': '2'}), 'iso3': ('django.db.models.fields.CharField', [], {'max_length': '3'}), 'lat': ('django.db.models.fields.FloatField', [], {}), 'lon': ('django.db.models.fields.FloatField', [], {}), 'mpoly': ('django.contrib.gis.db.models.fields.MultiPolygonField', [], {}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'pop2005': ('django.db.models.fields.IntegerField', [], {}), 'region': ('django.db.models.fields.IntegerField', [], {}), 'subregion': ('django.db.models.fields.IntegerField', [], {}), 'un': ('django.db.models.fields.IntegerField', [], {}) } } complete_apps = ['world'] ```
[ { "content": "```python\n#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n#----------------------------------------------------------------------------\n\"\"\"HTTP content negotiation application.\"\"\"\n__author__ = ('Lance Finn Helsten',)\n__version__ = '0.0'\n__copyright__ = \"\"\"Copyright (C) 2014 Lance Fi...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n#----------------------------------------------------------------------------\n\"\"\"HTTP content negotiation application.\"\"\"\n__author__ = ('Lance Finn Helsten',)\n__version__ = '0.0'\n__copyright__ = \"\"\"Copyright (...
```python #!/usr/bin/env python3 # -*- coding: UTF-8 -*- #---------------------------------------------------------------------------- """HTTP content negotiation application.""" __author__ = ('Lance Finn Helsten',) __version__ = '0.0' __copyright__ = """Copyright (C) 2014 Lance Finn Helsten""" __license__ = """ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import sys import os import setuptools setuptools.setup( name = "viperaccept", version = __version__, author = 'Lance Finn Helsten', author_email = 'lanhel@flyingtitans.com', description = __doc__, long_description = open('README.rst').read(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: HTTP Servers', 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', ], packages = [ 'viperaccept' ], # scripts = [ # ], ) ```
[ { "content": "Here is the code block:\n```python\n\"\"\"\r\nSTDM Import/Export module\r\n\"\"\"\r\n__author__ = 'John Gitau'\r\n__license__ = 'GNU Lesser General Public License (LGPL)'\r\n__url__ = 'http://www.unhabitat.org'\r\n\r\nfrom stdm.settings import QGISRegistryConfig\r\nfrom .exceptions import Translat...
[ { "content": "Here is the code block:\n<|memory_start|>```python\n\"\"\"\r\nSTDM Import/Export module\r\n\"\"\"\r\n__author__ = 'John Gitau'\r\n__license__ = 'GNU Lesser General Public License (LGPL)'\r\n__url__ = 'http://www.unhabitat.org'\r\n\r\nfrom stdm.settings import QGISRegistryConfig\r\nfrom .exceptions...
```python """ STDM Import/Export module """ __author__ = 'John Gitau' __license__ = 'GNU Lesser General Public License (LGPL)' __url__ = 'http://www.unhabitat.org' from stdm.settings import QGISRegistryConfig from .exceptions import TranslatorException from .reader import OGRReader from .writer import OGRWriter from .value_translators import ( MultipleEnumerationTranslator, SourceValueTranslator, ValueTranslatorManager, RelatedTableTranslator ) _UIGroup = "UI" _lastVectorDirKey = "lastVectorFileFilterDir" def vectorFileDir(): """ Returns the directory of the last vector file accessed by QGIS. """ qgisReg = QGISRegistryConfig(_UIGroup) regValues = qgisReg.read([_lastVectorDirKey]) if len(regValues) == 0: return "" else: return regValues[_lastVectorDirKey] def setVectorFileDir(dir): """ Update the last vector file directory. """ qgisReg = QGISRegistryConfig(_UIGroup) qgisReg.write({_lastVectorDirKey:dir}) ```
[ { "content": "```python\n# coding=utf-8\n# Copyright 2021 The Google Research Authors.\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/L...
[ { "content": "<|memory_start|>```python\n# coding=utf-8\n# Copyright 2021 The Google Research Authors.\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.apach...
```python # coding=utf-8 # Copyright 2021 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Keypoint profile class and utility functions.""" import abc import enum import six import tensorflow as tf from poem.core import keypoint_utils class LeftRightType(enum.Enum): """Keypoint/segment left/right type.""" UNKNOWN = 0 CENTRAL = 1 LEFT = 2 RIGHT = 3 def infer_keypoint_left_right_type(left_right_types, indices): """Infers keypoint left/right type. The inferred left/right type is decided as follows: 1. If either type is UNKNOWN, returns UNKNOWN. 2. If both types are the same, returns this type. 3. If one type is CENTRAL, and the other type is LEFT or RIGHT, returns the other type. 4. If one type is LEFT and the other type is RIGHT, returns CENTRAL. Args: left_right_types: A list of LeftRightType enum values for all keypoints. indices: A list of integers for keypoint indices. Returns: A LeftRightType enum value for inferred type. Raises: ValueError: If any index is out of range. """ if not indices: return LeftRightType.UNKNOWN def lookup(i): if i < 0 or i >= len(left_right_types): raise ValueError('Left/right type index is out of range: %d.' % i) return left_right_types[i] if len(indices) == 1: return lookup(indices[0]) output_type = LeftRightType.CENTRAL for i in indices: current_type = lookup(i) if current_type == LeftRightType.UNKNOWN: return LeftRightType.UNKNOWN if output_type == LeftRightType.CENTRAL: output_type = current_type elif current_type != LeftRightType.CENTRAL and current_type != output_type: output_type = LeftRightType.CENTRAL return output_type def infer_segment_left_right_type(left_right_types, start_indices, end_indices): """Infers segment left/right type. The inferred left/right type is decided as follows: 1. If either type is UNKNOWN, returns UNKNOWN. 2. If both types are the same, returns this type. 3. If one type is CENTRAL, and the other type is LEFT or RIGHT, returns the other type. 4. If one type is LEFT and the other type is RIGHT, returns CENTRAL. Args: left_right_types: A list of LeftRightType enum values for all keypoints. start_indices: A list of integers for LHS keypoint indices. end_indices: A list of integers for RHS keypoint indices. Returns: A LeftRightType enum value for inferred type. """ lhs_type = infer_keypoint_left_right_type(left_right_types, start_indices) rhs_type = infer_keypoint_left_right_type(left_right_types, end_indices) if lhs_type == LeftRightType.UNKNOWN or rhs_type == LeftRightType.UNKNOWN: return LeftRightType.UNKNOWN if lhs_type == LeftRightType.CENTRAL: return rhs_type if rhs_type == LeftRightType.CENTRAL: return lhs_type return lhs_type if lhs_type == rhs_type else LeftRightType.CENTRAL class KeypointProfile(six.with_metaclass(abc.ABCMeta, object)): """Keypoint profile base class.""" def __init__(self, name, keypoint_names, offset_keypoint_names, scale_keypoint_name_pairs, scale_distance_reduction_fn, scale_unit, segment_name_pairs, head_keypoint_name=None, neck_keypoint_name=None, left_shoulder_keypoint_name=None, right_shoulder_keypoint_name=None, left_elbow_keypoint_name=None, right_elbow_keypoint_name=None, left_wrist_keypoint_name=None, right_wrist_keypoint_name=None, spine_keypoint_name=None, pelvis_keypoint_name=None, left_hip_keypoint_name=None, right_hip_keypoint_name=None, left_knee_keypoint_name=None, right_knee_keypoint_name=None, left_ankle_keypoint_name=None, right_ankle_keypoint_name=None): """Initializer.""" self._name = name self._keypoint_names = [name for name, _ in keypoint_names] self._keypoint_left_right_types = [ left_right_type for _, left_right_type in keypoint_names ] self._offset_keypoint_index = [ self._keypoint_names.index(keypoint_name) for keypoint_name in offset_keypoint_names ] self._scale_keypoint_index_pairs = [] for start_names, end_names in scale_keypoint_name_pairs: self._scale_keypoint_index_pairs.append( ([self._keypoint_names.index(name) for name in start_names], [self._keypoint_names.index(name) for name in end_names])) self._scale_distance_reduction_fn = scale_distance_reduction_fn self._scale_unit = scale_unit self._segment_index_pairs = [] for start_names, end_names in segment_name_pairs: self._segment_index_pairs.append( ([self._keypoint_names.index(name) for name in start_names], [self._keypoint_names.index(name) for name in end_names])) self._head_keypoint_name = head_keypoint_name self._neck_keypoint_name = neck_keypoint_name self._left_shoulder_keypoint_name = left_shoulder_keypoint_name self._right_shoulder_keypoint_name = right_shoulder_keypoint_name self._left_elbow_keypoint_name = left_elbow_keypoint_name self._right_elbow_keypoint_name = right_elbow_keypoint_name self._left_wrist_keypoint_name = left_wrist_keypoint_name self._right_wrist_keypoint_name = right_wrist_keypoint_name self._spine_keypoint_name = spine_keypoint_name self._pelvis_keypoint_name = pelvis_keypoint_name self._left_hip_keypoint_name = left_hip_keypoint_name self._right_hip_keypoint_name = right_hip_keypoint_name self._left_knee_keypoint_name = left_knee_keypoint_name self._right_knee_keypoint_name = right_knee_keypoint_name self._left_ankle_keypoint_name = left_ankle_keypoint_name self._right_ankle_keypoint_name = right_ankle_keypoint_name @property def name(self): """Gets keypoint profile name.""" return self._name @property def keypoint_names(self): """Gets keypoint names.""" return self._keypoint_names @property @abc.abstractmethod def keypoint_dim(self): """Gets keypoint dimensionality.""" raise NotImplementedError @property def keypoint_num(self): """Gets number of keypoints.""" return len(self._keypoint_names) def keypoint_left_right_type(self, keypoint_index): """Gets keypoint left/right type given index.""" if isinstance(keypoint_index, int): keypoint_index = [keypoint_index] return infer_keypoint_left_right_type(self._keypoint_left_right_types, keypoint_index) def segment_left_right_type(self, start_index, end_index): """Gets segment left/right type given index.""" if isinstance(start_index, int): start_index = [start_index] if isinstance(end_index, int): end_index = [end_index] return infer_segment_left_right_type(self._keypoint_left_right_types, start_index, end_index) @property def offset_keypoint_index(self): """Gets offset keypoint index.""" return self._offset_keypoint_index @property def scale_keypoint_index_pairs(self): """Gets scale keypoint index pairs.""" return self._scale_keypoint_index_pairs @property def scale_unit(self): """Gets scale unit.""" return self._scale_unit @property def segment_index_pairs(self): """Gets segment index pairs.""" return self._segment_index_pairs @property def keypoint_affinity_matrix(self): """Gets keypoint affinity matrix. If a segment has multi-point end, all pairs of relevant points are considered as in affinity. Returns: matrix: A double list of floats for the keypoint affinity matrix. Raises: ValueError: If affinity matrix has any isolated node. """ matrix = [[0.0 for _ in range(self.keypoint_num)] for _ in range(self.keypoint_num)] # Self-affinity. for i in range(self.keypoint_num): matrix[i][i] = 1.0 for lhs_index, rhs_index in self._segment_index_pairs: for i in lhs_index: for j in lhs_index: matrix[i][j] = 1.0 matrix[j][i] = 1.0 for i in rhs_index: for j in rhs_index: matrix[i][j] = 1.0 matrix[j][i] = 1.0 for i in lhs_index: for j in rhs_index: matrix[i][j] = 1.0 matrix[j][i] = 1.0 # Check if the affinity matrix is valid, i.e., each node must have degree # greater than 1 (no isolated node). for row in matrix: if sum(row) <= 1.0: raise ValueError( 'Affinity matrix has a node with degree less than 2: %s.' % str(matrix)) return matrix def keypoint_index(self, keypoint_name, raise_error_if_not_found=False): """Gets keypoint index given name. If `raise_error_if_not_found` is True, raises ValueError if keypoint does not exist. Otherwise, returns -1 if keypoint does not exist. Args: keypoint_name: A string for keypoint name to find index of. raise_error_if_not_found: A boolean for whether to raise ValueError if keypoint does not exist. Returns: An integer for keypoint index. Raises: ValueError: If keypoint does not exist and `raise_error_if_not_found` is True. """ if keypoint_name in self._keypoint_names: return self._keypoint_names.index(keypoint_name) if raise_error_if_not_found: raise ValueError('Failed to find keypoint: `%s`.' % str(keypoint_name)) return -1 @property def head_keypoint_index(self): """Gets head keypoint index.""" if not self._head_keypoint_name: raise ValueError('Head keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._head_keypoint_name ] @property def neck_keypoint_index(self): """Gets neck keypoint index.""" if not self._neck_keypoint_name: raise ValueError('Neck keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._neck_keypoint_name ] @property def left_shoulder_keypoint_index(self): """Gets left shoulder keypoint index.""" if not self._left_shoulder_keypoint_name: raise ValueError('Left shoulder keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._left_shoulder_keypoint_name ] @property def right_shoulder_keypoint_index(self): """Gets right shoulder keypoint index.""" if not self._right_shoulder_keypoint_name: raise ValueError('Right shoulder keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._right_shoulder_keypoint_name ] @property def left_elbow_keypoint_index(self): """Gets left elbow keypoint index.""" if not self._left_elbow_keypoint_name: raise ValueError('Left elbow keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._left_elbow_keypoint_name ] @property def right_elbow_keypoint_index(self): """Gets right elbow keypoint index.""" if not self._right_elbow_keypoint_name: raise ValueError('Right elbow keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._right_elbow_keypoint_name ] @property def left_wrist_keypoint_index(self): """Gets left wrist keypoint index.""" if not self._left_wrist_keypoint_name: raise ValueError('Left wrist keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._left_wrist_keypoint_name ] @property def right_wrist_keypoint_index(self): """Gets right wrist keypoint index.""" if not self._right_wrist_keypoint_name: raise ValueError('Right wrist keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._right_wrist_keypoint_name ] @property def spine_keypoint_index(self): """Gets spine keypoint index.""" if not self._spine_keypoint_name: raise ValueError('Spine keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._spine_keypoint_name ] @property def pelvis_keypoint_index(self): """Gets pelvis keypoint index.""" if not self._pelvis_keypoint_name: raise ValueError('Pelvis keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._pelvis_keypoint_name ] @property def left_hip_keypoint_index(self): """Gets left hip keypoint index.""" if not self._left_hip_keypoint_name: raise ValueError('Left hip keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._left_hip_keypoint_name ] @property def right_hip_keypoint_index(self): """Gets right hip keypoint index.""" if not self._right_hip_keypoint_name: raise ValueError('Right hip keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._right_hip_keypoint_name ] @property def left_knee_keypoint_index(self): """Gets left knee keypoint index.""" if not self._left_knee_keypoint_name: raise ValueError('Left knee keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._left_knee_keypoint_name ] @property def right_knee_keypoint_index(self): """Gets right knee keypoint index.""" if not self._right_knee_keypoint_name: raise ValueError('Right knee keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._right_knee_keypoint_name ] @property def left_ankle_keypoint_index(self): """Gets left ankle keypoint index.""" if not self._left_ankle_keypoint_name: raise ValueError('Left ankle keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._left_ankle_keypoint_name ] @property def right_ankle_keypoint_index(self): """Gets right ankle keypoint index.""" if not self._right_ankle_keypoint_name: raise ValueError('Right ankle keypoint is not specified.') return [ self.keypoint_index(name, raise_error_if_not_found=True) for name in self._right_ankle_keypoint_name ] @property def standard_part_names(self): """Gets all standard part names.""" return [ 'HEAD', 'NECK', 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_ELBOW', 'RIGHT_ELBOW', 'LEFT_WRIST', 'RIGHT_WRIST', 'SPINE', 'PELVIS', 'LEFT_HIP', 'RIGHT_HIP', 'LEFT_KNEE', 'RIGHT_KNEE', 'LEFT_ANKLE', 'RIGHT_ANKLE' ] def get_standard_part_index(self, part_name): """Gets part index by standardized name.""" if part_name.upper() == 'HEAD': return self.head_keypoint_index if part_name.upper() == 'NECK': return self.neck_keypoint_index if part_name.upper() == 'LEFT_SHOULDER': return self.left_shoulder_keypoint_index if part_name.upper() == 'RIGHT_SHOULDER': return self.right_shoulder_keypoint_index if part_name.upper() == 'LEFT_ELBOW': return self.left_elbow_keypoint_index if part_name.upper() == 'RIGHT_ELBOW': return self.right_elbow_keypoint_index if part_name.upper() == 'LEFT_WRIST': return self.left_wrist_keypoint_index if part_name.upper() == 'RIGHT_WRIST': return self.right_wrist_keypoint_index if part_name.upper() == 'SPINE': return self.spine_keypoint_index if part_name.upper() == 'PELVIS': return self.pelvis_keypoint_index if part_name.upper() == 'LEFT_HIP': return self.left_hip_keypoint_index if part_name.upper() == 'RIGHT_HIP': return self.right_hip_keypoint_index if part_name.upper() == 'LEFT_KNEE': return self.left_knee_keypoint_index if part_name.upper() == 'RIGHT_KNEE': return self.right_knee_keypoint_index if part_name.upper() == 'LEFT_ANKLE': return self.left_ankle_keypoint_index if part_name.upper() == 'RIGHT_ANKLE': return self.right_ankle_keypoint_index raise ValueError('Unsupported part name: `%s`.' % part_name) def normalize(self, keypoints, keypoint_masks=None): """Normalizes keypoints.""" del keypoint_masks return keypoint_utils.normalize_points( keypoints, offset_point_indices=self._offset_keypoint_index, scale_distance_point_index_pairs=self._scale_keypoint_index_pairs, scale_distance_reduction_fn=self._scale_distance_reduction_fn, scale_unit=self._scale_unit) def denormalize(self, normalized_keypoints, offset_points, scale_distances, keypoint_masks=None): """Denormalizes keypoints.""" del keypoint_masks return (normalized_keypoints / self._scale_unit * scale_distances + offset_points) class KeypointProfile3D(KeypointProfile): """3D keypoint profile base class.""" def __init__(self, name, keypoint_names, offset_keypoint_names, scale_keypoint_name_pairs, segment_name_pairs, scale_distance_reduction_fn=tf.math.reduce_sum, scale_unit=1.0, head_keypoint_name=None, neck_keypoint_name=None, left_shoulder_keypoint_name=None, right_shoulder_keypoint_name=None, left_elbow_keypoint_name=None, right_elbow_keypoint_name=None, left_wrist_keypoint_name=None, right_wrist_keypoint_name=None, spine_keypoint_name=None, pelvis_keypoint_name=None, left_hip_keypoint_name=None, right_hip_keypoint_name=None, left_knee_keypoint_name=None, right_knee_keypoint_name=None, left_ankle_keypoint_name=None, right_ankle_keypoint_name=None): """Initializer.""" super(KeypointProfile3D, self).__init__( name=name, keypoint_names=keypoint_names, offset_keypoint_names=offset_keypoint_names, scale_keypoint_name_pairs=scale_keypoint_name_pairs, scale_distance_reduction_fn=scale_distance_reduction_fn, scale_unit=scale_unit, segment_name_pairs=segment_name_pairs, head_keypoint_name=head_keypoint_name, neck_keypoint_name=neck_keypoint_name, left_shoulder_keypoint_name=left_shoulder_keypoint_name, right_shoulder_keypoint_name=right_shoulder_keypoint_name, left_elbow_keypoint_name=left_elbow_keypoint_name, right_elbow_keypoint_name=right_elbow_keypoint_name, left_wrist_keypoint_name=left_wrist_keypoint_name, right_wrist_keypoint_name=right_wrist_keypoint_name, spine_keypoint_name=spine_keypoint_name, pelvis_keypoint_name=pelvis_keypoint_name, left_hip_keypoint_name=left_hip_keypoint_name, right_hip_keypoint_name=right_hip_keypoint_name, left_knee_keypoint_name=left_knee_keypoint_name, right_knee_keypoint_name=right_knee_keypoint_name, left_ankle_keypoint_name=left_ankle_keypoint_name, right_ankle_keypoint_name=right_ankle_keypoint_name) @property def keypoint_dim(self): """Gets keypoint dimensionality.""" return 3 class KeypointProfile2D(KeypointProfile): """2D keypoint profile base class.""" def __init__(self, name, keypoint_names, offset_keypoint_names, scale_keypoint_name_pairs, segment_name_pairs, compatible_keypoint_name_dict=None, scale_distance_reduction_fn=tf.math.reduce_max, scale_unit=0.5, head_keypoint_name=None, neck_keypoint_name=None, left_shoulder_keypoint_name=None, right_shoulder_keypoint_name=None, left_elbow_keypoint_name=None, right_elbow_keypoint_name=None, left_wrist_keypoint_name=None, right_wrist_keypoint_name=None, spine_keypoint_name=None, pelvis_keypoint_name=None, left_hip_keypoint_name=None, right_hip_keypoint_name=None, left_knee_keypoint_name=None, right_knee_keypoint_name=None, left_ankle_keypoint_name=None, right_ankle_keypoint_name=None): """Initializer.""" super(KeypointProfile2D, self).__init__( name=name, keypoint_names=keypoint_names, offset_keypoint_names=offset_keypoint_names, scale_keypoint_name_pairs=scale_keypoint_name_pairs, scale_distance_reduction_fn=scale_distance_reduction_fn, scale_unit=scale_unit, segment_name_pairs=segment_name_pairs, head_keypoint_name=head_keypoint_name, neck_keypoint_name=neck_keypoint_name, left_shoulder_keypoint_name=left_shoulder_keypoint_name, right_shoulder_keypoint_name=right_shoulder_keypoint_name, left_elbow_keypoint_name=left_elbow_keypoint_name, right_elbow_keypoint_name=right_elbow_keypoint_name, left_wrist_keypoint_name=left_wrist_keypoint_name, right_wrist_keypoint_name=right_wrist_keypoint_name, spine_keypoint_name=spine_keypoint_name, pelvis_keypoint_name=pelvis_keypoint_name, left_hip_keypoint_name=left_hip_keypoint_name, right_hip_keypoint_name=right_hip_keypoint_name, left_knee_keypoint_name=left_knee_keypoint_name, right_knee_keypoint_name=right_knee_keypoint_name, left_ankle_keypoint_name=left_ankle_keypoint_name, right_ankle_keypoint_name=right_ankle_keypoint_name) self._compatible_keypoint_name_dict = {} if compatible_keypoint_name_dict is not None: for _, compatible_keypoint_names in compatible_keypoint_name_dict.items(): if len(compatible_keypoint_names) != len(self._keypoint_names): raise ValueError('Compatible keypoint names must be of the same size ' 'as keypoint names.') self._compatible_keypoint_name_dict = compatible_keypoint_name_dict @property def keypoint_dim(self): """Gets keypoint dimensionality.""" return 2 @property def compatible_keypoint_name_dict(self): """Gets compatible keypoint name dictionary.""" return self._compatible_keypoint_name_dict class Std16KeypointProfile3D(KeypointProfile3D): """Standard 3D 16-keypoint profile.""" def __init__(self): """Initializer.""" super(Std16KeypointProfile3D, self).__init__( name='3DSTD16', keypoint_names=[('HEAD', LeftRightType.CENTRAL), ('NECK', LeftRightType.CENTRAL), ('LEFT_SHOULDER', LeftRightType.LEFT), ('RIGHT_SHOULDER', LeftRightType.RIGHT), ('LEFT_ELBOW', LeftRightType.LEFT), ('RIGHT_ELBOW', LeftRightType.RIGHT), ('LEFT_WRIST', LeftRightType.LEFT), ('RIGHT_WRIST', LeftRightType.RIGHT), ('SPINE', LeftRightType.CENTRAL), ('PELVIS', LeftRightType.CENTRAL), ('LEFT_HIP', LeftRightType.LEFT), ('RIGHT_HIP', LeftRightType.RIGHT), ('LEFT_KNEE', LeftRightType.LEFT), ('RIGHT_KNEE', LeftRightType.RIGHT), ('LEFT_ANKLE', LeftRightType.LEFT), ('RIGHT_ANKLE', LeftRightType.RIGHT)], offset_keypoint_names=['PELVIS'], scale_keypoint_name_pairs=[(['NECK'], ['SPINE']), (['SPINE'], ['PELVIS'])], segment_name_pairs=[(['HEAD'], ['NECK']), (['NECK'], ['LEFT_SHOULDER']), (['NECK'], ['RIGHT_SHOULDER']), (['NECK'], ['SPINE']), (['LEFT_SHOULDER'], ['LEFT_ELBOW']), (['RIGHT_SHOULDER'], ['RIGHT_ELBOW']), (['LEFT_ELBOW'], ['LEFT_WRIST']), (['RIGHT_ELBOW'], ['RIGHT_WRIST']), (['SPINE'], ['PELVIS']), (['PELVIS'], ['LEFT_HIP']), (['PELVIS'], ['RIGHT_HIP']), (['LEFT_HIP'], ['LEFT_KNEE']), (['RIGHT_HIP'], ['RIGHT_KNEE']), (['LEFT_KNEE'], ['LEFT_ANKLE']), (['RIGHT_KNEE'], ['RIGHT_ANKLE'])], head_keypoint_name=['HEAD'], neck_keypoint_name=['NECK'], left_shoulder_keypoint_name=['LEFT_SHOULDER'], right_shoulder_keypoint_name=['RIGHT_SHOULDER'], left_elbow_keypoint_name=['LEFT_ELBOW'], right_elbow_keypoint_name=['RIGHT_ELBOW'], left_wrist_keypoint_name=['LEFT_WRIST'], right_wrist_keypoint_name=['RIGHT_WRIST'], spine_keypoint_name=['SPINE'], pelvis_keypoint_name=['PELVIS'], left_hip_keypoint_name=['LEFT_HIP'], right_hip_keypoint_name=['RIGHT_HIP'], left_knee_keypoint_name=['LEFT_KNEE'], right_knee_keypoint_name=['RIGHT_KNEE'], left_ankle_keypoint_name=['LEFT_ANKLE'], right_ankle_keypoint_name=['RIGHT_ANKLE']) class Std13KeypointProfile3D(KeypointProfile3D): """Standard 3D 13-keypoint profile.""" def __init__(self): """Initializer.""" super(Std13KeypointProfile3D, self).__init__( name='3DSTD13', keypoint_names=[('HEAD', LeftRightType.CENTRAL), ('LEFT_SHOULDER', LeftRightType.LEFT), ('RIGHT_SHOULDER', LeftRightType.RIGHT), ('LEFT_ELBOW', LeftRightType.LEFT), ('RIGHT_ELBOW', LeftRightType.RIGHT), ('LEFT_WRIST', LeftRightType.LEFT), ('RIGHT_WRIST', LeftRightType.RIGHT), ('LEFT_HIP', LeftRightType.LEFT), ('RIGHT_HIP', LeftRightType.RIGHT), ('LEFT_KNEE', LeftRightType.LEFT), ('RIGHT_KNEE', LeftRightType.RIGHT), ('LEFT_ANKLE', LeftRightType.LEFT), ('RIGHT_ANKLE', LeftRightType.RIGHT)], offset_keypoint_names=['LEFT_HIP', 'RIGHT_HIP'], scale_keypoint_name_pairs=[(['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['LEFT_HIP', 'RIGHT_HIP'])], segment_name_pairs=[ (['HEAD'], ['LEFT_SHOULDER', 'RIGHT_SHOULDER']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['LEFT_SHOULDER']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['RIGHT_SHOULDER']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER'], ['LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_HIP', 'RIGHT_HIP']), (['LEFT_SHOULDER'], ['LEFT_ELBOW']), (['RIGHT_SHOULDER'], ['RIGHT_ELBOW']), (['LEFT_ELBOW'], ['LEFT_WRIST']), (['RIGHT_ELBOW'], ['RIGHT_WRIST']), (['LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_HIP', 'RIGHT_HIP'], ['LEFT_HIP', 'RIGHT_HIP']), (['LEFT_HIP', 'RIGHT_HIP'], ['LEFT_HIP']), (['LEFT_HIP', 'RIGHT_HIP'], ['RIGHT_HIP']), (['LEFT_HIP'], ['LEFT_KNEE']), (['RIGHT_HIP'], ['RIGHT_KNEE']), (['LEFT_KNEE'], ['LEFT_ANKLE']), (['RIGHT_KNEE'], ['RIGHT_ANKLE']) ], head_keypoint_name=['HEAD'], neck_keypoint_name=['LEFT_SHOULDER', 'RIGHT_SHOULDER'], left_shoulder_keypoint_name=['LEFT_SHOULDER'], right_shoulder_keypoint_name=['RIGHT_SHOULDER'], left_elbow_keypoint_name=['LEFT_ELBOW'], right_elbow_keypoint_name=['RIGHT_ELBOW'], left_wrist_keypoint_name=['LEFT_WRIST'], right_wrist_keypoint_name=['RIGHT_WRIST'], spine_keypoint_name=[ 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_HIP', 'RIGHT_HIP' ], pelvis_keypoint_name=['LEFT_HIP', 'RIGHT_HIP'], left_hip_keypoint_name=['LEFT_HIP'], right_hip_keypoint_name=['RIGHT_HIP'], left_knee_keypoint_name=['LEFT_KNEE'], right_knee_keypoint_name=['RIGHT_KNEE'], left_ankle_keypoint_name=['LEFT_ANKLE'], right_ankle_keypoint_name=['RIGHT_ANKLE']) class LegacyH36m17KeypointProfile3D(KeypointProfile3D): """Legacy Human3.6M 3D 17-keypoint profile.""" def __init__(self): """Initializer.""" super(LegacyH36m17KeypointProfile3D, self).__init__( name='LEGACY_3DH36M17', keypoint_names=[('Hip', LeftRightType.CENTRAL), ('Head', LeftRightType.CENTRAL), ('Neck/Nose', LeftRightType.CENTRAL), ('Thorax', LeftRightType.CENTRAL), ('LShoulder', LeftRightType.LEFT), ('RShoulder', LeftRightType.RIGHT), ('LElbow', LeftRightType.LEFT), ('RElbow', LeftRightType.RIGHT), ('LWrist', LeftRightType.LEFT), ('RWrist', LeftRightType.RIGHT), ('Spine', LeftRightType.CENTRAL), ('LHip', LeftRightType.LEFT), ('RHip', LeftRightType.RIGHT), ('LKnee', LeftRightType.LEFT), ('RKnee', LeftRightType.RIGHT), ('LFoot', LeftRightType.LEFT), ('RFoot', LeftRightType.RIGHT)], offset_keypoint_names=['Hip'], scale_keypoint_name_pairs=[(['Hip'], ['Spine']), (['Spine'], ['Thorax'])], segment_name_pairs=[(['Hip'], ['Spine']), (['Hip'], ['LHip']), (['Hip'], ['RHip']), (['Spine'], ['Thorax']), (['LHip'], ['LKnee']), (['RHip'], ['RKnee']), (['LKnee'], ['LFoot']), (['RKnee'], ['RFoot']), (['Thorax'], ['Neck/Nose']), (['Thorax'], ['LShoulder']), (['Thorax'], ['RShoulder']), (['Neck/Nose'], ['Head']), (['LShoulder'], ['LElbow']), (['RShoulder'], ['RElbow']), (['LElbow'], ['LWrist']), (['RElbow'], ['RWrist'])], head_keypoint_name=['Head'], neck_keypoint_name=['Thorax'], left_shoulder_keypoint_name=['LShoulder'], right_shoulder_keypoint_name=['RShoulder'], left_elbow_keypoint_name=['LElbow'], right_elbow_keypoint_name=['RElbow'], left_wrist_keypoint_name=['LWrist'], right_wrist_keypoint_name=['RWrist'], spine_keypoint_name=['Spine'], pelvis_keypoint_name=['Hip'], left_hip_keypoint_name=['LHip'], right_hip_keypoint_name=['RHip'], left_knee_keypoint_name=['LKnee'], right_knee_keypoint_name=['RKnee'], left_ankle_keypoint_name=['LFoot'], right_ankle_keypoint_name=['RFoot']) class LegacyH36m13KeypointProfile3D(KeypointProfile3D): """Legacy Human3.6M 3D 13-keypoint profile.""" def __init__(self): """Initializer.""" super(LegacyH36m13KeypointProfile3D, self).__init__( name='LEGACY_3DH36M13', keypoint_names=[('Head', LeftRightType.CENTRAL), ('LShoulder', LeftRightType.LEFT), ('RShoulder', LeftRightType.RIGHT), ('LElbow', LeftRightType.LEFT), ('RElbow', LeftRightType.RIGHT), ('LWrist', LeftRightType.LEFT), ('RWrist', LeftRightType.RIGHT), ('LHip', LeftRightType.LEFT), ('RHip', LeftRightType.RIGHT), ('LKnee', LeftRightType.LEFT), ('RKnee', LeftRightType.RIGHT), ('LFoot', LeftRightType.LEFT), ('RFoot', LeftRightType.RIGHT)], offset_keypoint_names=['LHip'], scale_keypoint_name_pairs=[ (['LHip', 'RHip'], ['LShoulder', 'RShoulder']), ], segment_name_pairs=[(['LHip', 'RHip'], ['LShoulder', 'RShoulder']), (['LHip', 'RHip'], ['LHip']), (['LHip', 'RHip'], ['RHip']), (['LHip'], ['LKnee']), (['RHip'], ['RKnee']), (['LKnee'], ['LFoot']), (['RKnee'], ['RFoot']), (['LShoulder', 'RShoulder'], ['Head']), (['LShoulder', 'RShoulder'], ['LShoulder']), (['LShoulder', 'RShoulder'], ['RShoulder']), (['LShoulder'], ['LElbow']), (['RShoulder'], ['RElbow']), (['LElbow'], ['LWrist']), (['RElbow'], ['RWrist'])], head_keypoint_name=['Head'], neck_keypoint_name=['LShoulder', 'RShoulder'], left_shoulder_keypoint_name=['LShoulder'], right_shoulder_keypoint_name=['RShoulder'], left_elbow_keypoint_name=['LElbow'], right_elbow_keypoint_name=['RElbow'], left_wrist_keypoint_name=['LWrist'], right_wrist_keypoint_name=['RWrist'], spine_keypoint_name=['LShoulder', 'RShoulder', 'LHip', 'RHip'], pelvis_keypoint_name=['LHip', 'RHip'], left_hip_keypoint_name=['LHip'], right_hip_keypoint_name=['RHip'], left_knee_keypoint_name=['LKnee'], right_knee_keypoint_name=['RKnee'], left_ankle_keypoint_name=['LFoot'], right_ankle_keypoint_name=['RFoot']) class LegacyMpii3dhp17KeypointProfile3D(KeypointProfile3D): """Legacy MPII-3DHP 3D 17-keypoint profile.""" def __init__(self): """Initializer.""" super(LegacyMpii3dhp17KeypointProfile3D, self).__init__( name='LEGACY_3DMPII3DHP17', keypoint_names=[('pelvis', LeftRightType.CENTRAL), ('head', LeftRightType.CENTRAL), ('neck', LeftRightType.CENTRAL), ('head_top', LeftRightType.CENTRAL), ('left_shoulder', LeftRightType.LEFT), ('right_shoulder', LeftRightType.RIGHT), ('left_elbow', LeftRightType.LEFT), ('right_elbow', LeftRightType.RIGHT), ('left_wrist', LeftRightType.LEFT), ('right_wrist', LeftRightType.RIGHT), ('spine', LeftRightType.CENTRAL), ('left_hip', LeftRightType.LEFT), ('right_hip', LeftRightType.RIGHT), ('left_knee', LeftRightType.LEFT), ('right_knee', LeftRightType.RIGHT), ('left_ankle', LeftRightType.LEFT), ('right_ankle', LeftRightType.RIGHT)], offset_keypoint_names=['pelvis'], scale_keypoint_name_pairs=[(['pelvis'], ['spine']), (['spine'], ['neck'])], segment_name_pairs=[(['pelvis'], ['spine']), (['pelvis'], ['left_hip']), (['pelvis'], ['right_hip']), (['spine'], ['neck']), (['left_hip'], ['left_knee']), (['right_hip'], ['right_knee']), (['left_knee'], ['left_ankle']), (['right_knee'], ['right_ankle']), (['neck'], ['head']), (['neck'], ['left_shoulder']), (['neck'], ['right_shoulder']), (['head'], ['head_top']), (['left_shoulder'], ['left_elbow']), (['right_shoulder'], ['right_elbow']), (['left_elbow'], ['left_wrist']), (['right_elbow'], ['right_wrist'])], head_keypoint_name=['head'], neck_keypoint_name=['neck'], left_shoulder_keypoint_name=['left_shoulder'], right_shoulder_keypoint_name=['right_shoulder'], left_elbow_keypoint_name=['left_elbow'], right_elbow_keypoint_name=['right_elbow'], left_wrist_keypoint_name=['left_wrist'], right_wrist_keypoint_name=['right_wrist'], spine_keypoint_name=['spine'], pelvis_keypoint_name=['pelvis'], left_hip_keypoint_name=['left_hip'], right_hip_keypoint_name=['right_hip'], left_knee_keypoint_name=['left_knee'], right_knee_keypoint_name=['right_knee'], left_ankle_keypoint_name=['left_ankle'], right_ankle_keypoint_name=['right_ankle']) class Std13KeypointProfile2D(KeypointProfile2D): """Standard 2D 13-keypoint profile.""" def __init__(self): """Initializer.""" super(Std13KeypointProfile2D, self).__init__( name='2DSTD13', keypoint_names=[('NOSE_TIP', LeftRightType.CENTRAL), ('LEFT_SHOULDER', LeftRightType.LEFT), ('RIGHT_SHOULDER', LeftRightType.RIGHT), ('LEFT_ELBOW', LeftRightType.LEFT), ('RIGHT_ELBOW', LeftRightType.RIGHT), ('LEFT_WRIST', LeftRightType.LEFT), ('RIGHT_WRIST', LeftRightType.RIGHT), ('LEFT_HIP', LeftRightType.LEFT), ('RIGHT_HIP', LeftRightType.RIGHT), ('LEFT_KNEE', LeftRightType.LEFT), ('RIGHT_KNEE', LeftRightType.RIGHT), ('LEFT_ANKLE', LeftRightType.LEFT), ('RIGHT_ANKLE', LeftRightType.RIGHT)], offset_keypoint_names=['LEFT_HIP', 'RIGHT_HIP'], scale_keypoint_name_pairs=[(['LEFT_SHOULDER'], ['RIGHT_SHOULDER']), (['LEFT_SHOULDER'], ['LEFT_HIP']), (['LEFT_SHOULDER'], ['RIGHT_HIP']), (['RIGHT_SHOULDER'], ['LEFT_HIP']), (['RIGHT_SHOULDER'], ['RIGHT_HIP']), (['LEFT_HIP'], ['RIGHT_HIP'])], segment_name_pairs=[(['NOSE_TIP'], ['LEFT_SHOULDER']), (['NOSE_TIP'], ['RIGHT_SHOULDER']), (['LEFT_SHOULDER'], ['RIGHT_SHOULDER']), (['LEFT_SHOULDER'], ['LEFT_ELBOW']), (['RIGHT_SHOULDER'], ['RIGHT_ELBOW']), (['LEFT_ELBOW'], ['LEFT_WRIST']), (['RIGHT_ELBOW'], ['RIGHT_WRIST']), (['LEFT_SHOULDER'], ['LEFT_HIP']), (['RIGHT_SHOULDER'], ['RIGHT_HIP']), (['LEFT_HIP'], ['RIGHT_HIP']), (['LEFT_HIP'], ['LEFT_KNEE']), (['RIGHT_HIP'], ['RIGHT_KNEE']), (['LEFT_KNEE'], ['LEFT_ANKLE']), (['RIGHT_KNEE'], ['RIGHT_ANKLE'])], compatible_keypoint_name_dict={ '3DSTD16': [ 'HEAD', 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_ELBOW', 'RIGHT_ELBOW', 'LEFT_WRIST', 'RIGHT_WRIST', 'LEFT_HIP', 'RIGHT_HIP', 'LEFT_KNEE', 'RIGHT_KNEE', 'LEFT_ANKLE', 'RIGHT_ANKLE' ], '3DSTD13': [ 'HEAD', 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_ELBOW', 'RIGHT_ELBOW', 'LEFT_WRIST', 'RIGHT_WRIST', 'LEFT_HIP', 'RIGHT_HIP', 'LEFT_KNEE', 'RIGHT_KNEE', 'LEFT_ANKLE', 'RIGHT_ANKLE' ], 'LEGACY_3DH36M17': [ 'Head', 'LShoulder', 'RShoulder', 'LElbow', 'RElbow', 'LWrist', 'RWrist', 'LHip', 'RHip', 'LKnee', 'RKnee', 'LFoot', 'RFoot' ], 'LEGACY_3DMPII3DHP17': [ 'head', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle' ], }, head_keypoint_name=['NOSE_TIP'], neck_keypoint_name=['LEFT_SHOULDER', 'RIGHT_SHOULDER'], left_shoulder_keypoint_name=['LEFT_SHOULDER'], right_shoulder_keypoint_name=['RIGHT_SHOULDER'], left_elbow_keypoint_name=['LEFT_ELBOW'], right_elbow_keypoint_name=['RIGHT_ELBOW'], left_wrist_keypoint_name=['LEFT_WRIST'], right_wrist_keypoint_name=['RIGHT_WRIST'], spine_keypoint_name=[ 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_HIP', 'RIGHT_HIP' ], pelvis_keypoint_name=['LEFT_HIP', 'RIGHT_HIP'], left_hip_keypoint_name=['LEFT_HIP'], right_hip_keypoint_name=['RIGHT_HIP'], left_knee_keypoint_name=['LEFT_KNEE'], right_knee_keypoint_name=['RIGHT_KNEE'], left_ankle_keypoint_name=['LEFT_ANKLE'], right_ankle_keypoint_name=['RIGHT_ANKLE']) class LegacyCoco13KeypointProfile2D(Std13KeypointProfile2D): """Legacy COCO 2D 13-keypoint profile. This profile is the same as the `2DSTD13` profil, except the name. """ def __init__(self): """Initializer.""" super(LegacyCoco13KeypointProfile2D, self).__init__() self._name = 'LEGACY_2DCOCO13' class LegacyH36m13KeypointProfile2D(KeypointProfile2D): """Legacy Human3.6M 2D 13-keypoint profile.""" def __init__(self): """Initializer.""" super(LegacyH36m13KeypointProfile2D, self).__init__( name='LEGACY_2DH36M13', keypoint_names=[('Head', LeftRightType.CENTRAL), ('LShoulder', LeftRightType.LEFT), ('RShoulder', LeftRightType.RIGHT), ('LElbow', LeftRightType.LEFT), ('RElbow', LeftRightType.RIGHT), ('LWrist', LeftRightType.LEFT), ('RWrist', LeftRightType.RIGHT), ('LHip', LeftRightType.LEFT), ('RHip', LeftRightType.RIGHT), ('LKnee', LeftRightType.LEFT), ('RKnee', LeftRightType.RIGHT), ('LFoot', LeftRightType.LEFT), ('RFoot', LeftRightType.RIGHT)], offset_keypoint_names=['LHip', 'RHip'], scale_keypoint_name_pairs=[(['LShoulder'], ['RShoulder']), (['LShoulder'], ['LHip']), (['LShoulder'], ['RHip']), (['RShoulder'], ['LHip']), (['RShoulder'], ['RHip']), (['LHip'], ['RHip'])], segment_name_pairs=[(['Head'], ['LShoulder']), (['Head'], ['RShoulder']), (['LShoulder'], ['LElbow']), (['LElbow'], ['LWrist']), (['RShoulder'], ['RElbow']), (['RElbow'], ['RWrist']), (['LShoulder'], ['LHip']), (['RShoulder'], ['RHip']), (['LHip'], ['LKnee']), (['LKnee'], ['LFoot']), (['RHip'], ['RKnee']), (['RKnee'], ['RFoot']), (['LShoulder'], ['RShoulder']), (['LHip'], ['RHip'])], compatible_keypoint_name_dict={ '3DSTD16': [ 'HEAD', 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_ELBOW', 'RIGHT_ELBOW', 'LEFT_WRIST', 'RIGHT_WRIST', 'LEFT_HIP', 'RIGHT_HIP', 'LEFT_KNEE', 'RIGHT_KNEE', 'LEFT_ANKLE', 'RIGHT_ANKLE' ], '3DSTD13': [ 'HEAD', 'LEFT_SHOULDER', 'RIGHT_SHOULDER', 'LEFT_ELBOW', 'RIGHT_ELBOW', 'LEFT_WRIST', 'RIGHT_WRIST', 'LEFT_HIP', 'RIGHT_HIP', 'LEFT_KNEE', 'RIGHT_KNEE', 'LEFT_ANKLE', 'RIGHT_ANKLE' ], 'LEGACY_3DH36M17': [ 'Head', 'LShoulder', 'RShoulder', 'LElbow', 'RElbow', 'LWrist', 'RWrist', 'LHip', 'RHip', 'LKnee', 'RKnee', 'LFoot', 'RFoot' ], 'LEGACY_3DMPII3DHP17': [ 'head', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle' ], }, head_keypoint_name=['Head'], neck_keypoint_name=['LShoulder', 'RShoulder'], left_shoulder_keypoint_name=['LShoulder'], right_shoulder_keypoint_name=['RShoulder'], left_elbow_keypoint_name=['LElbow'], right_elbow_keypoint_name=['RElbow'], left_wrist_keypoint_name=['LWrist'], right_wrist_keypoint_name=['RWrist'], spine_keypoint_name=['LShoulder', 'RShoulder', 'LHip', 'RHip'], pelvis_keypoint_name=['LHip', 'RHip'], left_hip_keypoint_name=['LHip'], right_hip_keypoint_name=['RHip'], left_knee_keypoint_name=['LKnee'], right_knee_keypoint_name=['RKnee'], left_ankle_keypoint_name=['LFoot'], right_ankle_keypoint_name=['RFoot']) def create_keypoint_profile_or_die(keypoint_profile_name): """Creates keypoint profile based on name. Args: keypoint_profile_name: A string for keypoint profile name. Returns: A keypint profile class object. Raises: ValueError: If keypoint profile name is unsupported. """ if keypoint_profile_name == '3DSTD16': return Std16KeypointProfile3D() if keypoint_profile_name == '3DSTD13': return Std13KeypointProfile3D() if keypoint_profile_name == 'LEGACY_3DH36M17': return LegacyH36m17KeypointProfile3D() if keypoint_profile_name == 'LEGACY_3DH36M13': return LegacyH36m13KeypointProfile3D() if keypoint_profile_name == 'LEGACY_3DMPII3DHP17': return LegacyMpii3dhp17KeypointProfile3D() if keypoint_profile_name == '2DSTD13': return Std13KeypointProfile2D() if keypoint_profile_name == 'LEGACY_2DCOCO13': return LegacyCoco13KeypointProfile2D() if keypoint_profile_name == 'LEGACY_2DH36M13': return LegacyH36m13KeypointProfile2D() raise ValueError('Unsupported keypoint profile name: `%s`.' % str(keypoint_profile_name)) ```
[ { "content": "Replicate the source code:\n```python\nimport types\nimport platform\n\n_PYTHON_VERSION = platform.python_version()\n_IS_PYTHON_3 = _PYTHON_VERSION >= '3'\n_IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'\n\ndef get_underlying_function(f):\n if _IS_BELOW_PYTHON_2_7 and (isinstance(f, classmethod)...
[ { "content": "Replicate the source code:\n<|memory_start|>```python\nimport types\nimport platform\n\n_PYTHON_VERSION = platform.python_version()\n_IS_PYTHON_3 = _PYTHON_VERSION >= '3'\n_IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7'\n\ndef get_underlying_function(f):\n if _IS_BELOW_PYTHON_2_7 and (isinstance...
```python import types import platform _PYTHON_VERSION = platform.python_version() _IS_PYTHON_3 = _PYTHON_VERSION >= '3' _IS_BELOW_PYTHON_2_7 = _PYTHON_VERSION < '2.7' def get_underlying_function(f): if _IS_BELOW_PYTHON_2_7 and (isinstance(f, classmethod) or isinstance(f, staticmethod)): return _get_underlying_classmethod_function(f) return f.__func__ def _get_underlying_classmethod_function(f): """Hack for older python versions...""" class TemporaryClass(object): func = f if isinstance(f, staticmethod): return TemporaryClass.func return TemporaryClass.func.im_func from six.moves import xrange from six import iteritems from six import itervalues if _IS_PYTHON_3: create_bound_method = types.MethodType else: def create_bound_method(func, self): return types.MethodType(func, self, type(self)) if _IS_PYTHON_3: basestring = str else: from __builtin__ import basestring if _IS_BELOW_PYTHON_2_7: from ordereddict import OrderedDict else: from collections import OrderedDict ```
[ { "content": "```python\nimport datetime\n\nfrom django.core import signing\nfrom django.test import SimpleTestCase\nfrom django.test.utils import freeze_time\nfrom django.utils.crypto import InvalidAlgorithm\n\n\nclass TestSigner(SimpleTestCase):\n\n def test_signature(self):\n \"signature() method s...
[ { "content": "<|memory_start|>```python\nimport datetime\n\nfrom django.core import signing\nfrom django.test import SimpleTestCase\nfrom django.test.utils import freeze_time\nfrom django.utils.crypto import InvalidAlgorithm\n\n\nclass TestSigner(SimpleTestCase):\n\n def test_signature(self):\n \"sign...
```python import datetime from django.core import signing from django.test import SimpleTestCase from django.test.utils import freeze_time from django.utils.crypto import InvalidAlgorithm class TestSigner(SimpleTestCase): def test_signature(self): "signature() method should generate a signature" signer = signing.Signer('predictable-secret') signer2 = signing.Signer('predictable-secret2') for s in ( b'hello', b'3098247:529:087:', '\u2019'.encode(), ): self.assertEqual( signer.signature(s), signing.base64_hmac( signer.salt + 'signer', s, 'predictable-secret', algorithm=signer.algorithm, ) ) self.assertNotEqual(signer.signature(s), signer2.signature(s)) def test_signature_with_salt(self): "signature(value, salt=...) should work" signer = signing.Signer('predictable-secret', salt='extra-salt') self.assertEqual( signer.signature('hello'), signing.base64_hmac( 'extra-salt' + 'signer', 'hello', 'predictable-secret', algorithm=signer.algorithm, ) ) self.assertNotEqual( signing.Signer('predictable-secret', salt='one').signature('hello'), signing.Signer('predictable-secret', salt='two').signature('hello')) def test_custom_algorithm(self): signer = signing.Signer('predictable-secret', algorithm='sha512') self.assertEqual( signer.signature('hello'), 'Usf3uVQOZ9m6uPfVonKR-EBXjPe7bjMbp3_Fq8MfsptgkkM1ojidN0BxYaT5HAEN1' 'VzO9_jVu7R-VkqknHYNvw', ) def test_invalid_algorithm(self): signer = signing.Signer('predictable-secret', algorithm='whatever') msg = "'whatever' is not an algorithm accepted by the hashlib module." with self.assertRaisesMessage(InvalidAlgorithm, msg): signer.sign('hello') def test_legacy_signature(self): # RemovedInDjango40Warning: pre-Django 3.1 signatures won't be # supported. signer = signing.Signer() sha1_sig = 'foo:l-EMM5FtewpcHMbKFeQodt3X9z8' self.assertNotEqual(signer.sign('foo'), sha1_sig) self.assertEqual(signer.unsign(sha1_sig), 'foo') def test_sign_unsign(self): "sign/unsign should be reversible" signer = signing.Signer('predictable-secret') examples = [ 'q;wjmbk;wkmb', '3098247529087', '3098247:529:087:', 'jkw osanteuh ,rcuh nthu aou oauh ,ud du', '\u2019', ] for example in examples: signed = signer.sign(example) self.assertIsInstance(signed, str) self.assertNotEqual(example, signed) self.assertEqual(example, signer.unsign(signed)) def test_sign_unsign_non_string(self): signer = signing.Signer('predictable-secret') values = [ 123, 1.23, True, datetime.date.today(), ] for value in values: with self.subTest(value): signed = signer.sign(value) self.assertIsInstance(signed, str) self.assertNotEqual(signed, value) self.assertEqual(signer.unsign(signed), str(value)) def test_unsign_detects_tampering(self): "unsign should raise an exception if the value has been tampered with" signer = signing.Signer('predictable-secret') value = 'Another string' signed_value = signer.sign(value) transforms = ( lambda s: s.upper(), lambda s: s + 'a', lambda s: 'a' + s[1:], lambda s: s.replace(':', ''), ) self.assertEqual(value, signer.unsign(signed_value)) for transform in transforms: with self.assertRaises(signing.BadSignature): signer.unsign(transform(signed_value)) def test_dumps_loads(self): "dumps and loads be reversible for any JSON serializable object" objects = [ ['a', 'list'], 'a string \u2019', {'a': 'dictionary'}, ] for o in objects: self.assertNotEqual(o, signing.dumps(o)) self.assertEqual(o, signing.loads(signing.dumps(o))) self.assertNotEqual(o, signing.dumps(o, compress=True)) self.assertEqual(o, signing.loads(signing.dumps(o, compress=True))) def test_decode_detects_tampering(self): "loads should raise exception for tampered objects" transforms = ( lambda s: s.upper(), lambda s: s + 'a', lambda s: 'a' + s[1:], lambda s: s.replace(':', ''), ) value = { 'foo': 'bar', 'baz': 1, } encoded = signing.dumps(value) self.assertEqual(value, signing.loads(encoded)) for transform in transforms: with self.assertRaises(signing.BadSignature): signing.loads(transform(encoded)) def test_works_with_non_ascii_keys(self): binary_key = b'\xe7' # Set some binary (non-ASCII key) s = signing.Signer(binary_key) self.assertEqual( 'foo:EE4qGC5MEKyQG5msxYA0sBohAxLC0BJf8uRhemh0BGU', s.sign('foo'), ) def test_valid_sep(self): separators = ['/', '*sep*', ','] for sep in separators: signer = signing.Signer('predictable-secret', sep=sep) self.assertEqual( 'foo%sjZQoX_FtSO70jX9HLRGg2A_2s4kdDBxz1QoO_OpEQb0' % sep, signer.sign('foo'), ) def test_invalid_sep(self): """should warn on invalid separator""" msg = 'Unsafe Signer separator: %r (cannot be empty or consist of only A-z0-9-_=)' separators = ['', '-', 'abc'] for sep in separators: with self.assertRaisesMessage(ValueError, msg % sep): signing.Signer(sep=sep) class TestTimestampSigner(SimpleTestCase): def test_timestamp_signer(self): value = 'hello' with freeze_time(123456789): signer = signing.TimestampSigner('predictable-key') ts = signer.sign(value) self.assertNotEqual(ts, signing.Signer('predictable-key').sign(value)) self.assertEqual(signer.unsign(ts), value) with freeze_time(123456800): self.assertEqual(signer.unsign(ts, max_age=12), value) # max_age parameter can also accept a datetime.timedelta object self.assertEqual(signer.unsign(ts, max_age=datetime.timedelta(seconds=11)), value) with self.assertRaises(signing.SignatureExpired): signer.unsign(ts, max_age=10) ```
[ { "content": "```python\n# Copyright 2013 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# ...
[ { "content": "<|memory_start|>```python\n# Copyright 2013 Hewlett-Packard Development Company, L.P.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License...
```python # Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from trove.common import cfg CONF = cfg.CONF url_ref = { "type": "string", "minLength": 8, "pattern": 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]' '|(?:%[0-9a-fA-F][0-9a-fA-F]))+' } boolean_string = { "type": "integer", "minimum": 0, "maximum": 1 } non_empty_string = { "type": "string", "minLength": 1, "maxLength": 255, "pattern": "^.*[0-9a-zA-Z]+.*$" } configuration_data_types = { "type": "string", "minLength": 1, "pattern": "integer|string" } configuration_integer_size = { "type": "string", "maxLength": 40, "pattern": "[0-9]+" } configuration_positive_integer = { "type": "string", "maxLength": 40, "minLength": 1, "pattern": "^[0-9]+$" } configuration_non_empty_string = { "type": "string", "minLength": 1, "maxLength": 128, "pattern": "^.*[0-9a-zA-Z]+.*$" } flavorref = { 'oneOf': [ non_empty_string, { "type": "integer" }] } volume_size = { "oneOf": [ { "type": "integer", "minimum": 0 }, configuration_positive_integer] } host_string = { "type": "string", "minLength": 1, "pattern": "^[%]?[\w(-).]*[%]?$" } name_string = { "type": "string", "minLength": 1, "pattern": "^.*[0-9a-zA-Z]+.*$" } uuid = { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}" "-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}$" } backup_id = { "type": "string", "minLength": 1, "maxLength": 64, "pattern": "^(([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}" "-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}|last)$" } volume = { "type": "object", "required": ["size"], "properties": { "size": volume_size, "required": True } } nics = { "type": "array", "items": { "type": "object", } } databases_ref_list = { "type": "array", "minItems": 0, "uniqueItems": True, "items": { "type": "object", "required": ["name"], "additionalProperties": True, "properties": { "name": non_empty_string } } } databases_ref_list_required = { "type": "array", "minItems": 0, "uniqueItems": True, "items": { "type": "object", "required": ["name"], "additionalProperties": True, "properties": { "name": non_empty_string } } } databases_ref = { "type": "object", "required": ["databases"], "additionalProperties": True, "properties": { "databases": databases_ref_list_required } } databases_def = { "type": "array", "minItems": 0, "items": { "type": "object", "required": ["name"], "additionalProperties": True, "properties": { "name": non_empty_string, "character_set": non_empty_string, "collate": non_empty_string } } } user_attributes = { "type": "object", "additionalProperties": True, "minProperties": 1, "properties": { "name": name_string, "password": non_empty_string, "host": host_string } } users_list = { "type": "array", "minItems": 0, "items": { "type": "object", "required": ["name", "password"], "additionalProperties": True, "properties": { "name": name_string, "password": non_empty_string, "host": host_string, "databases": databases_ref_list } } } null_configuration_id = { "type": "null" } configuration_id = { 'oneOf': [ uuid, null_configuration_id ] } module_list = { "type": "array", "minItems": 0, "items": { "type": "object", "required": ["id"], "additionalProperties": True, "properties": { "id": uuid, } } } cluster = { "create": { "type": "object", "required": ["cluster"], "additionalProperties": True, "properties": { "cluster": { "type": "object", "required": ["name", "datastore", "instances"], "additionalProperties": True, "properties": { "name": non_empty_string, "datastore": { "type": "object", "required": ["type", "version"], "additionalProperties": True, "properties": { "type": non_empty_string, "version": non_empty_string } }, "instances": { "type": "array", "items": { "type": "object", "required": ["flavorRef"], "additionalProperties": True, "properties": { "flavorRef": flavorref, "volume": volume, "nics": nics, "availability_zone": non_empty_string, "modules": module_list, "region_name": non_empty_string } } }, "locality": non_empty_string } } } }, "add_shard": { "type": "object", "required": ["add_shard"], "additionalProperties": True, "properties": { "add_shard": { "type": "object" } } }, "grow": { "type": "object", "required": ["grow"], "additionalProperties": True, "properties": { "grow": { "type": "array", "items": { "type": "object", "required": ["flavorRef"], "additionalProperties": True, "properties": { "name": non_empty_string, "flavorRef": flavorref, "volume": volume, "nics": nics, "availability_zone": non_empty_string, "modules": module_list, "related_to": non_empty_string, "type": non_empty_string, "region_name": non_empty_string } } } } }, "shrink": { "type": "object", "required": ["shrink"], "additionalProperties": True, "properties": { "shrink": { "type": "array", "items": { "type": "object", "required": ["id"], "additionalProperties": True, "properties": { "id": uuid } } } } } } instance = { "create": { "type": "object", "required": ["instance"], "additionalProperties": True, "properties": { "instance": { "type": "object", "required": ["name", "flavorRef"], "additionalProperties": True, "properties": { "name": non_empty_string, "configuration_id": configuration_id, "flavorRef": flavorref, "volume": volume, "databases": databases_def, "users": users_list, "restorePoint": { "type": "object", "required": ["backupRef"], "additionalProperties": True, "properties": { "backupRef": uuid } }, "availability_zone": non_empty_string, "datastore": { "type": "object", "additionalProperties": True, "properties": { "type": non_empty_string, "version": non_empty_string } }, "nics": nics, "modules": module_list, "region_name": non_empty_string, "locality": non_empty_string } } } }, "edit": { "name": "instance:edit", "type": "object", "required": ["instance"], "properties": { "instance": { "type": "object", "required": [], "additionalProperties": False, "properties": { "slave_of": {}, "replica_of": {}, "name": non_empty_string, "configuration": configuration_id, "datastore_version": non_empty_string, } } } }, "action": { "resize": { "volume": { "type": "object", "required": ["resize"], "additionalProperties": True, "properties": { "resize": { "type": "object", "required": ["volume"], "additionalProperties": True, "properties": { "volume": volume } } } }, 'flavorRef': { "type": "object", "required": ["resize"], "additionalProperties": True, "properties": { "resize": { "type": "object", "required": ["flavorRef"], "additionalProperties": True, "properties": { "flavorRef": flavorref } } } } }, "restart": { "type": "object", "required": ["restart"], "additionalProperties": True, "properties": { "restart": { "type": "object" } } } } } mgmt_cluster = { "action": { 'reset-task': { "type": "object", "required": ["reset-task"], "additionalProperties": True, "properties": { "reset-task": { "type": "object" } } } } } mgmt_instance = { "action": { 'migrate': { "type": "object", "required": ["migrate"], "additionalProperties": True, "properties": { "migrate": { "type": "object" } } }, "reboot": { "type": "object", "required": ["reboot"], "additionalProperties": True, "properties": { "reboot": { "type": "object" } } }, "stop": { "type": "object", "required": ["stop"], "additionalProperties": True, "properties": { "stop": { "type": "object" } } } } } user = { "create": { "name": "users:create", "type": "object", "required": ["users"], "properties": { "users": users_list } }, "update_all": { "users": { "type": "object", "required": ["users"], "additionalProperties": True, "properties": { "users": users_list } }, "databases": databases_ref }, "update": { "type": "object", "required": ["user"], "additionalProperties": True, "properties": { "user": user_attributes } } } dbschema = { "create": { "type": "object", "required": ["databases"], "additionalProperties": True, "properties": { "databases": databases_def } } } backup = { "create": { "name": "backup:create", "type": "object", "required": ["backup"], "properties": { "backup": { "type": "object", "required": ["instance", "name"], "properties": { "description": non_empty_string, "instance": uuid, "name": non_empty_string, "parent_id": backup_id } } } } } guest_log = { "action": { "name": "guest_log:action", "type": "object", "required": ["name"], "properties": { "name": non_empty_string, "enable": boolean_string, "disable": boolean_string, "publish": boolean_string, "discard": boolean_string } } } module_contents = { "type": "string", "minLength": 1, "maxLength": 4294967295, "pattern": "^.*.+.*$" } module = { "create": { "name": "module:create", "type": "object", "required": ["module"], "properties": { "module": { "type": "object", "required": ["name", "module_type", "contents"], "additionalProperties": True, "properties": { "name": non_empty_string, "module_type": non_empty_string, "contents": module_contents, "description": non_empty_string, "datastore": { "type": "object", "properties": { "type": non_empty_string, "version": non_empty_string } }, "auto_apply": boolean_string, "all_tenants": boolean_string, "visible": boolean_string, "live_update": boolean_string, } } } }, "update": { "name": "module:update", "type": "object", "required": ["module"], "properties": { "module": { "type": "object", "required": [], "additionalProperties": True, "properties": { "name": non_empty_string, "type": non_empty_string, "contents": module_contents, "description": non_empty_string, "datastore": { "type": "object", "additionalProperties": True, "properties": { "type": non_empty_string, "version": non_empty_string } }, "auto_apply": boolean_string, "all_tenants": boolean_string, "visible": boolean_string, "live_update": boolean_string, } } } }, "apply": { "name": "module:apply", "type": "object", "required": ["modules"], "properties": { "modules": module_list, } }, "list": { "name": "module:list", "type": "object", "required": [], "properties": { "module": uuid, "from_guest": boolean_string, "include_contents": boolean_string } }, } configuration = { "create": { "name": "configuration:create", "type": "object", "required": ["configuration"], "properties": { "configuration": { "type": "object", "required": ["values", "name"], "properties": { "description": non_empty_string, "values": { "type": "object", }, "name": non_empty_string, "datastore": { "type": "object", "additionalProperties": True, "properties": { "type": non_empty_string, "version": non_empty_string } } } } } }, "update": { "name": "configuration:update", "type": "object", "required": ["configuration"], "properties": { "configuration": { "type": "object", "required": [], "properties": { "description": non_empty_string, "values": { "type": "object", }, "name": non_empty_string } } } }, "edit": { "name": "configuration:edit", "type": "object", "required": ["configuration"], "properties": { "configuration": { "type": "object", "required": [], "properties": { "values": { "type": "object", } } } } } } mgmt_configuration = { "create": { "name": "configuration_parameter:create", "type": "object", "required": ["configuration-parameter"], "properties": { "configuration-parameter": { "type": "object", "required": ["name", "restart_required", "data_type"], "properties": { "name": configuration_non_empty_string, "data_type": configuration_data_types, "restart_required": boolean_string, "max": configuration_integer_size, "min": configuration_integer_size, } } } }, "update": { "name": "configuration_parameter:update", "type": "object", "required": ["configuration-parameter"], "properties": { "configuration-parameter": { "type": "object", "required": ["name", "restart_required", "data_type"], "properties": { "name": configuration_non_empty_string, "data_type": configuration_data_types, "restart_required": boolean_string, "max": configuration_integer_size, "min": configuration_integer_size, } } } }, } account = { 'create': { "type": "object", "name": "users", "required": ["users"], "additionalProperties": True, "properties": { "users": users_list } } } upgrade = { "create": { "type": "object", "required": ["upgrade"], "additionalProperties": True, "properties": { "upgrade": { "type": "object", "required": [], "additionalProperties": True, "properties": { "instance_version": non_empty_string, "location": non_empty_string, "metadata": {} } } } } } package_list = { "type": "array", "minItems": 0, "uniqueItems": True, "items": { "type": "string", "minLength": 1, "maxLength": 255, "pattern": "^.*[0-9a-zA-Z]+.*$" } } mgmt_datastore_version = { "create": { "name": "mgmt_datastore_version:create", "type": "object", "required": ["version"], "properties": { "version": { "type": "object", "required": ["name", "datastore_name", "image", "active"], "additionalProperties": True, "properties": { "name": non_empty_string, "datastore_name": non_empty_string, "datastore_manager": non_empty_string, "packages": package_list, "image": uuid, "active": {"enum": [True, False]}, "default": {"enum": [True, False]} } } } }, "edit": { "name": "mgmt_datastore_version:edit", "type": "object", "required": [], "additionalProperties": True, "properties": { "datastore_manager": non_empty_string, "packages": package_list, "image": uuid, "active": {"enum": [True, False]}, "default": {"enum": [True, False]}, } } } ```
[ { "content": "Return the code exactly, with no changes:\n```python\nimport tensorflow as tf #Tensorflow사용을 위한 import\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# Dataset loading\nmnist = input_data.read_data_sets(\"./samples/MNIST_data/\", one_hot=True)\n\n# Set up model\nx = tf.placeh...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\nimport tensorflow as tf #Tensorflow사용을 위한 import\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# Dataset loading\nmnist = input_data.read_data_sets(\"./samples/MNIST_data/\", one_hot=True)\n\n# Set up mode...
```python import tensorflow as tf #Tensorflow사용을 위한 import from tensorflow.examples.tutorials.mnist import input_data # Dataset loading mnist = input_data.read_data_sets("./samples/MNIST_data/", one_hot=True) # Set up model x = tf.placeholder(tf.float32, [None, 784]) #심볼릭 변수들을 사용하여 상호작용하는 작업들을 기술 W = tf.Variable(tf.zeros([784, 10])) #tf.Variable를 사용한 예제 b = tf.Variable(tf.zeros([10])) #tf.Variable를 사용한 예제 y = tf.nn.softmax(tf.matmul(x, W) + b) #9번줄과 10번줄을 이용한 모델 구현 y_ = tf.placeholder(tf.float32, [None, 10]) #정답을 입력하기 위한 새 placeholder를 추가 cross_entropy = -tf.reduce_sum(y_*tf.log(y)) #교차 엔트로피 −∑y′log(y) 를 구현 train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) #비용 최소화에 어떤 변수가 얼마나 영향을 주는지를 계산 # Session init = tf.initialize_all_variables() #만든 변수들을 초기화하는 작업 sess = tf.Session() #세션에서 모델을 시작하고 변수들을 초기화 sess.run(init) #실행 # Learning for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # Validation correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) #특정한 축을 따라 가장 큰 원소의 색인을 알려준다 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #얼마나 많은 비율로 맞았는지 확인 # Result should be approximately 91%. print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) #테스트 데이터를 대상으로 정확도 ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).\n# Co...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2009 Tiny SPRL (<http://tin...
```python # -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2011 SYLEAM (<http://syleam.fr/>) # Copyright (C) 2013 Julius Network Solutions SARL <contact@julius.fr> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time import urllib from openerp.osv import fields, orm from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) try: from SOAPpy import WSDL except : _logger.warning("ERROR IMPORTING SOAPpy, if not installed, please install it:" " e.g.: apt-get install python-soappy") class partner_sms_send(orm.Model): _name = "partner.sms.send" def _default_get_mobile(self, cr, uid, fields, context=None): if context is None: context = {} partner_pool = self.pool.get('res.partner') active_ids = fields.get('active_ids') res = {} i = 0 for partner in partner_pool.browse(cr, uid, active_ids, context=context): i += 1 res = partner.mobile if i > 1: raise orm.except_orm(_('Error'), _('You can only select one partner')) return res def _default_get_gateway(self, cr, uid, fields, context=None): if context is None: context = {} sms_obj = self.pool.get('sms.smsclient') gateway_ids = sms_obj.search(cr, uid, [], limit=1, context=context) return gateway_ids and gateway_ids[0] or False def onchange_gateway(self, cr, uid, ids, gateway_id, context=None): if context is None: context = {} sms_obj = self.pool.get('sms.smsclient') if not gateway_id: return {} gateway = sms_obj.browse(cr, uid, gateway_id, context=context) return { 'value': { 'validity': gateway.validity, 'classes': gateway.classes, 'deferred': gateway.deferred, 'priority': gateway.priority, 'coding': gateway.coding, 'tag': gateway.tag, 'nostop': gateway.nostop, } } _columns = { 'mobile_to': fields.char('To', size=256, required=True), 'app_id': fields.char('API ID', size=256), 'user': fields.char('Login', size=256), 'password': fields.char('Password', size=256), 'text': fields.text('SMS Message', required=True), 'gateway': fields.many2one('sms.smsclient', 'SMS Gateway', required=True), 'validity': fields.integer('Validity', help='the maximum time -in minute(s)- before the message is dropped'), 'classes': fields.selection([ ('0', 'Flash'), ('1', 'Phone display'), ('2', 'SIM'), ('3', 'Toolkit') ], 'Class', help='the sms class: flash(0), phone display(1), SIM(2), toolkit(3)'), 'deferred': fields.integer('Deferred', help='the time -in minute(s)- to wait before sending the message'), 'priority': fields.selection([ ('0','0'), ('1','1'), ('2','2'), ('3','3') ], 'Priority', help='The priority of the message'), 'coding': fields.selection([ ('1', '7 bit'), ('2', 'Unicode') ], 'Coding', help='The SMS coding: 1 for 7 bit or 2 for unicode'), 'tag': fields.char('Tag', size=256, help='an optional tag'), 'nostop': fields.boolean('NoStop', help='Do not display STOP clause in the message, this requires that this is not an advertising message'), } _defaults = { 'mobile_to': _default_get_mobile, 'gateway': _default_get_gateway, } def sms_send(self, cr, uid, ids, context=None): if context is None: context = {} client_obj = self.pool.get('sms.smsclient') for data in self.browse(cr, uid, ids, context=context): if not data.gateway: raise orm.except_orm(_('Error'), _('No Gateway Found')) else: client_obj._send_message(cr, uid, data, context=context) return {} class SMSClient(orm.Model): _name = 'sms.smsclient' _description = 'SMS Client' _columns = { 'name': fields.char('Gateway Name', size=256, required=True), 'url': fields.char('Gateway URL', size=256, required=True, help='Base url for message'), 'property_ids': fields.one2many('sms.smsclient.parms', 'gateway_id', 'Parameters'), 'history_line': fields.one2many('sms.smsclient.history', 'gateway_id', 'History'), 'method': fields.selection([ ('http', 'HTTP Method'), ('smpp', 'SMPP Method') ], 'API Method', select=True), 'state': fields.selection([ ('new', 'Not Verified'), ('waiting', 'Waiting for Verification'), ('confirm', 'Verified'), ], 'Gateway Status', select=True, readonly=True), 'users_id': fields.many2many('res.users', 'res_smsserver_group_rel', 'sid', 'uid', 'Users Allowed'), 'code': fields.char('Verification Code', size=256), 'body': fields.text('Message', help="The message text that will be send along with the email which is send through this server"), 'validity': fields.integer('Validity', help='The maximum time -in minute(s)- before the message is dropped'), 'classes': fields.selection([ ('0', 'Flash'), ('1', 'Phone display'), ('2', 'SIM'), ('3', 'Toolkit') ], 'Class', help='The SMS class: flash(0),phone display(1),SIM(2),toolkit(3)'), 'deferred': fields.integer('Deferred', help='The time -in minute(s)- to wait before sending the message'), 'priority': fields.selection([ ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3') ], 'Priority', help='The priority of the message '), 'coding': fields.selection([ ('1', '7 bit'), ('2', 'Unicode') ],'Coding', help='The SMS coding: 1 for 7 bit or 2 for unicode'), 'tag': fields.char('Tag', size=256, help='an optional tag'), 'nostop': fields.boolean('NoStop', help='Do not display STOP clause in the message, this requires that this is not an advertising message'), 'char_limit' : fields.boolean('Character Limit'), } _defaults = { 'state': 'new', 'method': 'http', 'validity': 10, 'classes': '1', 'deferred': 0, 'priority': '3', 'coding': '1', 'nostop': True, 'char_limit' : True, } def _check_permissions(self, cr, uid, id, context=None): cr.execute('select * from res_smsserver_group_rel where sid=%s and uid=%s' % (id, uid)) data = cr.fetchall() if len(data) <= 0: return False return True def _prepare_smsclient_queue(self, cr, uid, data, name, context=None): return { 'name': name, 'gateway_id': data.gateway.id, 'state': 'draft', 'mobile': data.mobile_to, 'msg': data.text, 'validity': data.validity, 'classes': data.classes, 'deffered': data.deferred, 'priorirty': data.priority, 'coding': data.coding, 'tag': data.tag, 'nostop': data.nostop, } def _send_message(self, cr, uid, data, context=None): if context is None: context = {} gateway = data.gateway if gateway: if not self._check_permissions(cr, uid, gateway.id, context=context): raise orm.except_orm(_('Permission Error!'), _('You have no permission to access %s ') % (gateway.name,)) url = gateway.url name = url if gateway.method == 'http': prms = {} for p in data.gateway.property_ids: if p.type == 'user': prms[p.name] = p.value elif p.type == 'password': prms[p.name] = p.value elif p.type == 'to': prms[p.name] = data.mobile_to elif p.type == 'sms': prms[p.name] = data.text elif p.type == 'extra': prms[p.name] = p.value params = urllib.urlencode(prms) name = url + "?" + params queue_obj = self.pool.get('sms.smsclient.queue') vals = self._prepare_smsclient_queue(cr, uid, data, name, context=context) queue_obj.create(cr, uid, vals, context=context) return True def _check_queue(self, cr, uid, context=None): if context is None: context = {} queue_obj = self.pool.get('sms.smsclient.queue') history_obj = self.pool.get('sms.smsclient.history') sids = queue_obj.search(cr, uid, [ ('state', '!=', 'send'), ('state', '!=', 'sending') ], limit=30, context=context) queue_obj.write(cr, uid, sids, {'state': 'sending'}, context=context) error_ids = [] sent_ids = [] for sms in queue_obj.browse(cr, uid, sids, context=context): if sms.gateway_id.char_limit: if len(sms.msg) > 160: error_ids.append(sms.id) continue if sms.gateway_id.method == 'http': try: urllib.urlopen(sms.name) except Exception as e: raise orm.except_orm('Error', e) ### New Send Process OVH Dedicated ### ## Parameter Fetch ## if sms.gateway_id.method == 'smpp': for p in sms.gateway_id.property_ids: if p.type == 'user': login = p.value elif p.type == 'password': pwd = p.value elif p.type == 'sender': sender = p.value elif p.type == 'sms': account = p.value try: soap = WSDL.Proxy(sms.gateway_id.url) message = '' if sms.coding == '2': message = str(sms.msg).decode('iso-8859-1').encode('utf8') if sms.coding == '1': message = str(sms.msg) result = soap.telephonySmsUserSend(str(login), str(pwd), str(account), str(sender), str(sms.mobile), message, int(sms.validity), int(sms.classes), int(sms.deferred), int(sms.priority), int(sms.coding),str(sms.gateway_id.tag), int(sms.gateway_id.nostop)) ### End of the new process ### except Exception as e: raise orm.except_orm('Error', e) history_obj.create(cr, uid, { 'name': _('SMS Sent'), 'gateway_id': sms.gateway_id.id, 'sms': sms.msg, 'to': sms.mobile, }, context=context) sent_ids.append(sms.id) queue_obj.write(cr, uid, sent_ids, {'state': 'send'}, context=context) queue_obj.write(cr, uid, error_ids, { 'state': 'error', 'error': 'Size of SMS should not be more then 160 char' }, context=context) return True class SMSQueue(orm.Model): _name = 'sms.smsclient.queue' _description = 'SMS Queue' _columns = { 'name': fields.text('SMS Request', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'msg': fields.text('SMS Text', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'mobile': fields.char('Mobile No', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'gateway_id': fields.many2one('sms.smsclient', 'SMS Gateway', readonly=True, states={'draft': [('readonly', False)]}), 'state': fields.selection([ ('draft', 'Queued'), ('sending', 'Waiting'), ('send', 'Sent'), ('error', 'Error'), ], 'Message Status', select=True, readonly=True), 'error': fields.text('Last Error', size=256, readonly=True, states={'draft': [('readonly', False)]}), 'date_create': fields.datetime('Date', readonly=True), 'validity': fields.integer('Validity', help='The maximum time -in minute(s)- before the message is dropped'), 'classes': fields.selection([ ('0', 'Flash'), ('1', 'Phone display'), ('2', 'SIM'), ('3', 'Toolkit') ], 'Class', help='The sms class: flash(0), phone display(1), SIM(2), toolkit(3)'), 'deferred': fields.integer('Deferred', help='The time -in minute(s)- to wait before sending the message'), 'priority': fields.selection([ ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3') ], 'Priority', help='The priority of the message '), 'coding': fields.selection([ ('1', '7 bit'), ('2', 'Unicode') ], 'Coding', help='The sms coding: 1 for 7 bit or 2 for unicode'), 'tag': fields.char('Tag', size=256, help='An optional tag'), 'nostop': fields.boolean('NoStop', help='Do not display STOP clause in the message, this requires that this is not an advertising message'), } _defaults = { 'date_create': fields.datetime.now, 'state': 'draft', } class Properties(orm.Model): _name = 'sms.smsclient.parms' _description = 'SMS Client Properties' _columns = { 'name': fields.char('Property name', size=256, help='Name of the property whom appear on the URL'), 'value': fields.char('Property value', size=256, help='Value associate on the property for the URL'), 'gateway_id': fields.many2one('sms.smsclient', 'SMS Gateway'), 'type': fields.selection([ ('user', 'User'), ('password', 'Password'), ('sender', 'Sender Name'), ('to', 'Recipient No'), ('sms', 'SMS Message'), ('extra', 'Extra Info') ], 'API Method', select=True, help='If parameter concern a value to substitute, indicate it'), } class HistoryLine(orm.Model): _name = 'sms.smsclient.history' _description = 'SMS Client History' _columns = { 'name': fields.char('Description', size=160, required=True, readonly=True), 'date_create': fields.datetime('Date', readonly=True), 'user_id': fields.many2one('res.users', 'Username', readonly=True, select=True), 'gateway_id': fields.many2one('sms.smsclient', 'SMS Gateway', ondelete='set null', required=True), 'to': fields.char('Mobile No', size=15, readonly=True), 'sms': fields.text('SMS', size=160, readonly=True), } _defaults = { 'date_create': fields.datetime.now, 'user_id': lambda obj, cr, uid, context: uid, } def create(self, cr, uid, vals, context=None): if context is None: context = {} super(HistoryLine, self).create(cr, uid, vals, context=context) cr.commit() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: ```
[ { "content": "```python\nimport qrcode\n\nfrom PyQt5.QtGui import QColor, QPen\nimport PyQt5.QtGui as QtGui\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (\n QApplication, QVBoxLayout, QTextEdit, QHBoxLayout, QPushButton, QWidget,\n QFileDialog,\n)\n\nfrom electrum_ltc.i18n import _\nfrom elec...
[ { "content": "<|memory_start|>```python\nimport qrcode\n\nfrom PyQt5.QtGui import QColor, QPen\nimport PyQt5.QtGui as QtGui\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import (\n QApplication, QVBoxLayout, QTextEdit, QHBoxLayout, QPushButton, QWidget,\n QFileDialog,\n)\n\nfrom electrum_ltc.i18n imp...
```python import qrcode from PyQt5.QtGui import QColor, QPen import PyQt5.QtGui as QtGui from PyQt5.QtCore import Qt from PyQt5.QtWidgets import ( QApplication, QVBoxLayout, QTextEdit, QHBoxLayout, QPushButton, QWidget, QFileDialog, ) from electrum_ltc.i18n import _ from electrum_ltc.simple_config import SimpleConfig from .util import WindowModalDialog, WWLabel, getSaveFileName class QRCodeWidget(QWidget): def __init__(self, data = None, fixedSize=False): QWidget.__init__(self) self.data = None self.qr = None self.fixedSize=fixedSize if fixedSize: self.setFixedSize(fixedSize, fixedSize) self.setData(data) def setData(self, data): if self.data != data: self.data = data if self.data: self.qr = qrcode.QRCode( error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=0, ) self.qr.add_data(self.data) if not self.fixedSize: k = len(self.qr.get_matrix()) self.setMinimumSize(k*5,k*5) else: self.qr = None self.update() def paintEvent(self, e): if not self.data: return black = QColor(0, 0, 0, 255) white = QColor(255, 255, 255, 255) black_pen = QPen(black) black_pen.setJoinStyle(Qt.MiterJoin) if not self.qr: qp = QtGui.QPainter() qp.begin(self) qp.setBrush(white) qp.setPen(white) r = qp.viewport() qp.drawRect(0, 0, r.width(), r.height()) qp.end() return matrix = self.qr.get_matrix() k = len(matrix) qp = QtGui.QPainter() qp.begin(self) r = qp.viewport() margin = 10 framesize = min(r.width(), r.height()) boxsize = int((framesize - 2*margin)/k) size = k*boxsize left = (framesize - size)/2 top = (framesize - size)/2 # Draw white background with margin qp.setBrush(white) qp.setPen(white) qp.drawRect(0, 0, framesize, framesize) # Draw qr code qp.setBrush(black) qp.setPen(black_pen) for r in range(k): for c in range(k): if matrix[r][c]: qp.drawRect(int(left+c*boxsize), int(top+r*boxsize), boxsize - 1, boxsize - 1) qp.end() class QRDialog(WindowModalDialog): def __init__( self, *, data, parent=None, title="", show_text=False, help_text=None, show_copy_text_btn=False, config: SimpleConfig, ): WindowModalDialog.__init__(self, parent, title) self.config = config vbox = QVBoxLayout() qrw = QRCodeWidget(data) qr_hbox = QHBoxLayout() qr_hbox.addWidget(qrw) qr_hbox.addStretch(1) vbox.addLayout(qr_hbox) help_text = data if show_text else help_text if help_text: qr_hbox.setContentsMargins(0, 0, 0, 44) text_label = WWLabel() text_label.setText(help_text) vbox.addWidget(text_label) hbox = QHBoxLayout() hbox.addStretch(1) def print_qr(): filename = getSaveFileName( parent=self, title=_("Select where to save file"), filename="qrcode.png", config=self.config, ) if not filename: return p = qrw.grab() p.save(filename, 'png') self.show_message(_("QR code saved to file") + " " + filename) def copy_image_to_clipboard(): p = qrw.grab() QApplication.clipboard().setPixmap(p) self.show_message(_("QR code copied to clipboard")) def copy_text_to_clipboard(): QApplication.clipboard().setText(data) self.show_message(_("Text copied to clipboard")) b = QPushButton(_("Copy Image")) hbox.addWidget(b) b.clicked.connect(copy_image_to_clipboard) if show_copy_text_btn: b = QPushButton(_("Copy Text")) hbox.addWidget(b) b.clicked.connect(copy_text_to_clipboard) b = QPushButton(_("Save")) hbox.addWidget(b) b.clicked.connect(print_qr) b = QPushButton(_("Close")) hbox.addWidget(b) b.clicked.connect(self.accept) b.setDefault(True) vbox.addLayout(hbox) self.setLayout(vbox) ```
[ { "content": "Here is the snippet:\n```python\n#\n# Copyright (c) 2015 Red Hat\n# Licensed under The MIT License (MIT)\n# http://opensource.org/licenses/MIT\n#\nimport json\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import g...
[ { "content": "Here is the snippet:\n<|memory_start|>```python\n#\n# Copyright (c) 2015 Red Hat\n# Licensed under The MIT License (MIT)\n# http://opensource.org/licenses/MIT\n#\nimport json\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.urlresolvers import reverse\nfrom django.sh...
```python # # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # import json from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 from django.utils import six from django.utils.text import capfirst from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from pdc.apps.contact.models import Contact, ContactRole from pdc.apps.contact.serializers import RoleContactSerializer from pdc.apps.common.serializers import DynamicFieldsSerializerMixin, LabelSerializer, StrictSerializerMixin from pdc.apps.common.fields import ChoiceSlugField from pdc.apps.release.models import Release from pdc.apps.common.hacks import convert_str_to_int from .models import (GlobalComponent, RoleContact, ReleaseComponent, Upstream, BugzillaComponent, ReleaseComponentGroup, GroupType, ReleaseComponentType, ReleaseComponentRelationshipType, ReleaseComponentRelationship) from . import signals __all__ = ( 'GlobalComponentSerializer', 'ReleaseComponentSerializer', 'HackedContactSerializer', 'UpstreamSerializer', 'BugzillaComponentSerializer', 'GroupSerializer', 'GroupTypeSerializer' ) def reverse_url(request, view_name, **kwargs): return request.build_absolute_uri(reverse(viewname=view_name, kwargs=kwargs)) class HackedContactSerializer(RoleContactSerializer): """ Could use as a view leveled serializer to encode/decode the contact data, or as a field in the global/release component. Automatically replace the url with /[global|release]-components/<instance_pk>/contacts/<pk>. Automatically set inherited = True when serialize release component. """ def __init__(self, *args, **kwargs): self.inherited = kwargs.pop('inherited', False) self.view_name = kwargs.pop('view_name', 'globalcomponentcontact-detail') context = kwargs.get('context', None) self.instance_pk = None self.view = None # Set view/instance_pk when uses the class as a serializer. if context: self.view = context.get('view', None) extra_kwargs = context.get('extra_kwargs', None) if extra_kwargs: self.instance_pk = extra_kwargs.get('instance_pk', None) super(HackedContactSerializer, self).__init__(*args, **kwargs) def to_representation(self, obj): ret = super(HackedContactSerializer, self).to_representation(obj) request = self.context.get('request', None) url_kwargs = self.context.get('extra_kwargs', {}) # NOTE(xchu): The `instance_pk` is needed for building a valid url, # so if not provided, we should raise `KeyError`. instance_pk = url_kwargs['instance_pk'] ret['url'] = reverse_url(request, self.view_name, **{ 'instance_pk': instance_pk, 'pk': obj.pk }) if self.inherited and self.view_name == 'globalcomponentcontact-detail': ret['inherited'] = True return ret def to_internal_value(self, data): # Run StrictSerializerMixin's to_internal_value() to check if extra field exists. super(HackedContactSerializer, self).to_internal_value(data) request = self.context.get('request', None) serializer = RoleContactSerializer(data=data, many=not isinstance(data, dict), context={'request': request}) kwargs = {} kwargs['contact_role'] = data.get('contact_role') kwargs.update(data.get('contact')) try: contact = RoleContact.specific_objects.get(**kwargs) except (RoleContact.DoesNotExist, Contact.DoesNotExist, ContactRole.DoesNotExist): # If we can't get RoleContact in database, validate the input data and create the RoleContact. if serializer.is_valid(raise_exception=True): contact = RoleContact.specific_objects.create(**kwargs) if request and request.changeset: model_name = ContentType.objects.get_for_model(contact).model request.changeset.add(model_name, contact.id, 'null', json.dumps(contact.export())) component_class = self.view.model if component_class.objects.get(pk=self.instance_pk).contacts.filter(pk=contact.pk).exists(): model_name = six.text_type(capfirst(component_class._meta.verbose_name)) raise serializers.ValidationError({"detail": "%s contact with this %s and Contact already exists." % (model_name, model_name)}) else: return contact def save(self, **kwargs): """ Save the deserialized object and return it. """ instance_pk = self.context['extra_kwargs']['instance_pk'] component_class = self.context['view'].model component = component_class.objects.get(pk=instance_pk) existed_contacts = component.contacts.all() if isinstance(self.validated_data, list): contacts = [self.get_object_from_db(item) for item in self.validated_data if item not in existed_contacts] component.contacts.add(*contacts) if self.validated_data['_deleted']: [self.delete_object(item) for item in self.validated_data['_deleted']] else: contacts = self.get_object_from_db(self.validated_data) component.contacts.add(contacts) return contacts def get_object_from_db(self, item): contact = RoleContact.objects.get(**{ 'contact_role_id': item.contact_role_id, 'contact_id': item.contact_id }) return contact class Meta: model = RoleContact fields = ('url', 'contact_role', 'contact') # In order not to run parent's validators, set validators to [] validators = [] class HackedContactField(serializers.Field): """ HackedContactField is used in GlobalComponentSerializer/ReleaseComponentSerializer insteadof HackedContactSerilizer. It has the ablility to get_attribute() from GlobalComponentSerializer/ReleaseComponentSerializer. """ def __init__(self, view_name, *args, **kwargs): self.view_name = view_name super(HackedContactField, self).__init__(*args, **kwargs) def to_representation(self, value): serializer = HackedContactSerializer(value, many=True, context=self.context, view_name=self.view_name) return serializer.data def get_attribute(self, obj): """ Get attribute from the serializer which uses this field. @param obj: The model object related to the serializer. """ # NOTE(xchu): The `instance_pk` is needed for building a valid url, # it's not provided when used as a field, so we should inject one. if 'extra_kwargs' not in self.context or 'instance_pk' not in self.context['extra_kwargs']: self.context['extra_kwargs'] = {'instance_pk': obj.pk} return obj.contacts.all() class UpstreamSerializer(StrictSerializerMixin, serializers.ModelSerializer): class Meta: model = Upstream fields = ('homepage', 'scm_type', 'scm_url') class UpstreamRelatedField(serializers.RelatedField): def to_representation(self, value): serializer = UpstreamSerializer(value) return serializer.data def to_internal_value(self, value): request = self.context.get('request', None) if isinstance(value, dict): try: upstream = Upstream.objects.get(**value) except Upstream.DoesNotExist: serializer = UpstreamSerializer(data=value, many=False, context={'request': request}) if serializer.is_valid(raise_exception=True): upstream = serializer.save() model_name = ContentType.objects.get_for_model(upstream).model if request and request.changeset: request.changeset.add(model_name, upstream.id, 'null', json.dumps(upstream.export())) return upstream else: self._errors = serializer._errors except Exception as err: raise serializers.ValidationError("Can not get or create Upstream with the input(%s): %s." % (value, err)) else: return upstream else: raise serializers.ValidationError("Unsupported upstream input.") class GlobalComponentSerializer(DynamicFieldsSerializerMixin, StrictSerializerMixin, serializers.HyperlinkedModelSerializer): contacts = HackedContactField(required=False, read_only=False, view_name='globalcomponentcontact-detail') name = serializers.CharField(required=True, max_length=100) dist_git_path = serializers.CharField(required=False, max_length=200, allow_blank=True) dist_git_web_url = serializers.URLField(required=False, max_length=200) labels = LabelSerializer(many=True, required=False, read_only=True) upstream = UpstreamRelatedField(read_only=False, required=False, queryset=Upstream.objects.all()) class Meta: model = GlobalComponent fields = ('id', 'name', 'dist_git_path', 'dist_git_web_url', 'contacts', 'labels', 'upstream') class TreeForeignKeyField(serializers.Field): def to_representation(self, value): request = self.context.get("request", None) serializer = BugzillaComponentSerializer(value, context={'request': request, 'top_level': False}) return serializer.data def to_internal_value(self, data): if data.strip() == "": raise serializers.ValidationError({'bugzilla_component': 'This field is required.'}) else: components = data.strip("/").split("/") len_components = len(components) bc = None # Only Bugzilla component name exists, parent component name will be considered as None. if len_components == 1: try: bc = BugzillaComponent.objects.get(name=components[0], parent_component=None) except: raise serializers.ValidationError({'bugzilla_component': ("Bugzilla component with name %s does not exist." % data)}) # Not only bugzilla Component, but also its ancestors exist. if len_components > 1: z = zip(components, components[1:]) root_bc_name, bc_name = z[0] qs = BugzillaComponent.objects.filter(name=bc_name, parent_component__name=root_bc_name) for _, bc_name in z[1:]: qs = BugzillaComponent.objects.filter(name=bc_name, parent_component__in=qs) if not qs: raise serializers.ValidationError({'bugzilla_component': ("Bugzilla component with name %s does not exist." % data)}) if len(qs) > 1: raise serializers.ValidationError({'bugzilla_component': ("Duplicate Bugzilla component with name %s exists." % data)}) if qs: bc = qs[0] return bc class BugzillaComponentSerializer(DynamicFieldsSerializerMixin, StrictSerializerMixin, serializers.HyperlinkedModelSerializer): """ Bugzilla Component serializer. """ parent_component = serializers.CharField(required=False, max_length=200) subcomponents = serializers.SerializerMethodField() extra_fields = ['parent_pk'] def get_subcomponents(self, obj): """[string]""" return obj.get_subcomponents() class Meta: model = BugzillaComponent fields = ('id', 'name', 'parent_component', 'subcomponents') class ReleaseField(serializers.SlugRelatedField): def __init__(self, **kwargs): super(ReleaseField, self).__init__(slug_field='release_id', queryset=Release.objects.all(), **kwargs) def to_representation(self, value): return { 'release_id': value.release_id, 'active': value.active } class ReleaseComponentTypeSerializer(StrictSerializerMixin, serializers.ModelSerializer): class Meta: model = ReleaseComponentType fields = ('name',) class ReleaseComponentSerializer(DynamicFieldsSerializerMixin, StrictSerializerMixin, serializers.HyperlinkedModelSerializer): """ ReleaseComponent Serializer """ release = ReleaseField(read_only=False) global_component = serializers.SlugRelatedField(slug_field='name', read_only=False, queryset=GlobalComponent.objects.all()) contacts = HackedContactField(required=False, read_only=False, view_name='releasecomponentcontact-detail') dist_git_branch = serializers.CharField(source='inherited_dist_git_branch', required=False) dist_git_web_url = serializers.URLField(required=False, max_length=200, read_only=True) bugzilla_component = TreeForeignKeyField(read_only=False, required=False, allow_null=True) brew_package = serializers.CharField(required=False) active = serializers.BooleanField(required=False, default=True) type = ChoiceSlugField(slug_field='name', queryset=ReleaseComponentType.objects.all(), required=False, allow_null=True) def update(self, instance, validated_data): signals.releasecomponent_serializer_extract_data.send(sender=self, validated_data=validated_data) instance = super(ReleaseComponentSerializer, self).update(instance, validated_data) signals.releasecomponent_serializer_post_update.send(sender=self, release_component=instance) if hasattr(instance, 'pk'): # reload to make sure changes in mapping are reflected instance = ReleaseComponent.objects.get(pk=instance.pk) # from view's doc, for ReleaseComponent, # PUT and PATCH update works the same as each other except `name` is required when PUT update, # so there will be not setattr here. return instance def create(self, validated_data): signals.releasecomponent_serializer_extract_data.send(sender=self, validated_data=validated_data) instance = super(ReleaseComponentSerializer, self).create(validated_data) signals.releasecomponent_serializer_post_create.send(sender=self, release_component=instance) return instance def to_representation(self, instance): ret = super(ReleaseComponentSerializer, self).to_representation(instance) request = self.context.get("request", None) # Include global component contacts - PDC-184 gcs = GlobalComponentSerializer( instance=instance.global_component, context={'request': request}) # Exclude global component contacts whose contact_role are already in release component contacts gcc = gcs.data.get('contacts', []) contacts = ret.get('contacts', []) contact_role_lists = [contact['contact_role'] for contact in contacts] for contact in gcc: if contact['contact_role'] in contact_role_lists: continue contact['inherited'] = True contacts.append(contact) return ret def to_internal_value(self, data): # Raise error explictly when release and global_component are given. if self.instance: allowed_keys = self.get_allowed_keys() - set(['release', 'global_component']) extra_fields = set(data.keys()) - allowed_keys self.maybe_raise_error(extra_fields) data['release'] = self.instance.release data['global_component'] = self.instance.global_component return super(ReleaseComponentSerializer, self).to_internal_value(data) def validate_release(self, value): if not isinstance(value, Release): if isinstance(value, dict): release_id = value['release_id'] else: release_id = value if release_id is None or release_id.strip() == "": self._errors = {'release': 'This field is required.'} return release = get_object_or_404(Release, release_id=release_id) if not release.is_active(): self._errors = {'release': 'Can not create a release component with an inactive release.'} return value = release return value def validate_global_component(self, value): if not isinstance(value, GlobalComponent): global_component_name = value if global_component_name is None or global_component_name.strip() == "": self._errors = {'global_component': 'This field is required.'} return gc = get_object_or_404(GlobalComponent, name=global_component_name) value = gc return value def validate_name(self, value): if value.strip() == "": self._errors = {'name': 'This field is required.'} return value def validate_type(self, value): if not isinstance(value, ReleaseComponentType): if value is not None and value.strip() != "": value = get_object_or_404(ReleaseComponentType, name=value.strip()) else: raise serializers.ValidationError("This field can't be set to null.") return value class Meta: model = ReleaseComponent fields = ('id', 'release', 'bugzilla_component', 'brew_package', 'global_component', 'name', 'dist_git_branch', 'dist_git_web_url', 'active', 'contacts', 'type') validators = [UniqueTogetherValidator( queryset=ReleaseComponent.objects.all(), fields=('name', 'release', 'global_component') )] class GroupTypeSerializer(StrictSerializerMixin, serializers.ModelSerializer): description = serializers.CharField(required=False) class Meta: model = GroupType fields = ('id', 'name', 'description') class ReleaseComponentRelatedField(serializers.RelatedField): doc_format = '{"id": "int", "name": "string"}' def to_representation(self, value): result = dict() if value: result['id'] = value.id result['name'] = value.name return result def to_internal_value(self, data): if not isinstance(data, dict): raise serializers.ValidationError({'detail': "Input [%s] for ReleaseComponent must be a dict." % data}) if set(data.keys()) not in [set(['id']), set(['release', 'global_component', 'name'])]: raise serializers.ValidationError( {'detail': "Only accept ['id'] or ['release', 'global_component', 'name']"}) kwargs = dict() if 'id' in data: kwargs['id'] = convert_str_to_int(data.get('id')) else: kwargs['release__release_id'] = data.get('release') kwargs['global_component__name'] = data.get('global_component') kwargs['name'] = data.get('name') try: rc = ReleaseComponent.objects.get(**kwargs) except ReleaseComponent.DoesNotExist: raise serializers.ValidationError({'detail': "ReleaseComponent [%s] doesn't exist" % data}) return rc class GroupSerializer(StrictSerializerMixin, serializers.ModelSerializer): group_type = serializers.SlugRelatedField( queryset=GroupType.objects.all(), slug_field='name', required=True ) release = serializers.SlugRelatedField( queryset=Release.objects.all(), slug_field='release_id', required=True ) description = serializers.CharField(required=True) components = ReleaseComponentRelatedField( required=False, many=True, queryset=ReleaseComponent.objects.all() ) def validate(self, value): # # POST if not self.instance: components = value.get('components', []) release = value.get('release') # PUT or PATCH else: components = value.get('components', self.instance.components.all()) release = value.get('release', self.instance.release) for component in components: if component.release != release: raise serializers.ValidationError({ 'detail': 'Not allow to group release_component[%s] <release[%s]> with other release[%s].' % (component.name, component.release.release_id, release.release_id)}) return value class Meta: model = ReleaseComponentGroup fields = ('id', 'group_type', 'description', 'release', 'components') class RCRelationshipTypeSerializer(StrictSerializerMixin, serializers.ModelSerializer): class Meta: model = ReleaseComponentRelationshipType fields = ('name',) class RCForRelationshipRelatedField(ReleaseComponentRelatedField): doc_format = '{"id": "int", "name": "string", "release": "Release.release_id"}' def to_representation(self, value): result = dict() if value: result['id'] = value.id result['name'] = value.name result['release'] = value.release.release_id return result class ReleaseComponentRelationshipSerializer(StrictSerializerMixin, serializers.ModelSerializer): type = ChoiceSlugField( queryset=ReleaseComponentRelationshipType.objects.all(), slug_field='name', required=True, source='relation_type' ) from_component = RCForRelationshipRelatedField( required=True, queryset=ReleaseComponent.objects.all() ) to_component = RCForRelationshipRelatedField( required=True, queryset=ReleaseComponent.objects.all() ) class Meta: model = ReleaseComponentRelationship fields = ('id', 'type', 'from_component', 'to_component') ```
[ { "content": "Repeat the code precisely:\n```python\n# -*- coding: utf-8 -*-\n# Generated by Django 1.11.5 on 2017-10-16 20:06\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ofahrtbase', '0019_au...
[ { "content": "Repeat the code precisely:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n# Generated by Django 1.11.5 on 2017-10-16 20:06\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ofahr...
```python # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-16 20:06 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ofahrtbase', '0019_auto_20161020_1750'), ] operations = [ migrations.AlterField( model_name='ofahrt', name='max_members', field=models.IntegerField( default=70, help_text= 'Dieser Wert bestimmt die maximale Größe der Festanmeldeliste.', verbose_name='Maximale Teilnehmendenzahl'), ), migrations.AlterField( model_name='ofahrt', name='member_reg_open', field=models.BooleanField( default=False, help_text= 'Ist dieser Wert aktiviert, können sich Teilnehmer*innen registrieren.', verbose_name='Teilnehmeregistrierung'), ), migrations.AlterField( model_name='ofahrt', name='orga_reg_open', field=models.BooleanField( default=False, help_text= 'Ist dieser Wert aktiviert, können sich Studierende als Ofahrtorga bewerben.', verbose_name='Orgaregistrierung'), ), migrations.AlterField( model_name='ofahrt', name='queue_tolerance', field=models.IntegerField( default=20, help_text= 'Dieser Wert legt fest, ab wann Neuanmeldungen von Teilnehmer*innen in die Warteschlange müssen. (Warteschlange falls: aktuelle Festanmeldungen + aktuell vorläufige Anmeldungen > maximale Festanmeldungen + dieser Wert)', verbose_name='Warteschlangentoleranz'), ), migrations.AlterField( model_name='ofahrt', name='self_participation', field=models.IntegerField( default=2000, help_text='Eingenanteil der Teilnehmer*innen in Cent', verbose_name='Teilnahmebeitrag'), ), migrations.AlterField( model_name='ofahrt', name='workshop_reg_open', field=models.BooleanField( default=False, help_text= 'Ist dieser Wert aktiviert, werden derzeit Workshops gesucht.', verbose_name='Workshopregistrierung'), ), ] ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n***************************************************************************\n edgebundlingProviderPlugin.py\n ---------------------\n Date : January 2018\n Copyright : (C) 201...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n***************************************************************************\n edgebundlingProviderPlugin.py\n ---------------------\n Date : January 2018\n Copyright ...
```python # -*- coding: utf-8 -*- """ *************************************************************************** edgebundlingProviderPlugin.py --------------------- Date : January 2018 Copyright : (C) 2018 by Anita Graser Email : anitagraser@gmx.at *************************************************************************** * * * 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. * * * *************************************************************************** """ __author__ = 'Anita Graser' __date__ = 'January 2018' __copyright__ = '(C) 2018, Anita Graser' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.PyQt.QtCore import QCoreApplication, QVariant from qgis.PyQt.QtGui import QIcon from qgis.core import (QgsField, QgsFeature, QgsFeatureSink, QgsFeatureRequest, QgsProcessing, QgsProcessingAlgorithm, QgsProcessingParameterFeatureSource, QgsProcessingParameterField, QgsProcessingParameterNumber, QgsProcessingParameterBoolean, QgsProcessingParameterFeatureSink ) from processing_edgebundling.edgebundlingUtils import EdgeCluster pluginPath = os.path.dirname(__file__) class Edgebundling(QgsProcessingAlgorithm): INPUT = 'INPUT' CLUSTER_FIELD = 'CLUSTER_FIELD' USE_CLUSTERING = 'USE_CLUSTERING' INITIAL_STEP_SIZE = 'INITIAL_STEP_SIZE' COMPATIBILITY = 'COMPATIBILITY' CYCLES = 'CYCLES' ITERATIONS = 'ITERATIONS' OUTPUT = 'OUTPUT' def __init__(self): super().__init__() def createInstance(self): return type(self)() def icon(self): return QIcon(os.path.join(pluginPath, "icons", "icon.png")) def tr(self, text): return QCoreApplication.translate("edgebundling", text) def name(self): return "edgebundling" def displayName(self): return self.tr("Force-directed edge bundling") def group(self): return self.tr("Edge Bundling") def groupId(self): return "edgebundling" def tags(self): return self.tr("edgebundling,flows").split(",") def shortHelpString(self): return self.tr(""" Implementation of force-directed edge bundling for the QGIS Processing toolbox as described in https://anitagraser.com/2017/10/08/movement-data-in-gis-8-edge-bundling-for-flow-maps/ Usage: Pre-process your data first! - Use only Linestrings (no Multilinestrings) - Your data should only contain lines with exactly 2 nodes: an origin node and a destination node. - Your data should also only contain lines with a length greater than 0 ("lines" with equal origin and destination node coordinates will cause an error). Once your data is sufficiently pre-processed and fulfils all above mentioned requirements, you can either first use one of the clustering algorithms and then bundle the lines, or you can directly bundle the lines (which, on the downside, will take significantly longer). Please double check the input parameters to fit your data (e.g. the "initial step size" in the "edge bundling algorithm" dependent on the coordinate reference system of your data). """) def helpUrl(self): return "https://github.com/dts-ait/qgis-edge-bundling" def __init__(self): super().__init__() def initAlgorithm(self, config=None): self.addParameter(QgsProcessingParameterFeatureSource( self.INPUT, self.tr("Input layer"), [QgsProcessing.TypeVectorLine])) self.addParameter(QgsProcessingParameterField( self.CLUSTER_FIELD, self.tr("Cluster field"), None, self.INPUT)) self.addParameter(QgsProcessingParameterBoolean( self.USE_CLUSTERING, self.tr("Use cluster field"), defaultValue=False)) self.addParameter(QgsProcessingParameterNumber( self.INITIAL_STEP_SIZE, self.tr("Initial step size"), QgsProcessingParameterNumber.Double, 100)) self.addParameter(QgsProcessingParameterNumber( self.COMPATIBILITY, self.tr("Compatibility"), QgsProcessingParameterNumber.Double, 0.6)) self.addParameter(QgsProcessingParameterNumber( self.CYCLES, self.tr("Cycles"), QgsProcessingParameterNumber.Integer, 6)) self.addParameter(QgsProcessingParameterNumber( self.ITERATIONS, self.tr("Iterations"), QgsProcessingParameterNumber.Integer, 90)) self.addParameter(QgsProcessingParameterFeatureSink( self.OUTPUT, self.tr("Bundled edges"), QgsProcessing.TypeVectorLine)) def processAlgorithm(self, parameters, context, feedback): cluster_field = self.parameterAsFields(parameters, self.CLUSTER_FIELD, context)[0] use_clustering = self.parameterAsBool(parameters, self.USE_CLUSTERING, context) initial_step_size = self.parameterAsDouble(parameters, self.INITIAL_STEP_SIZE, context) compatibility = self.parameterAsDouble(parameters, self.COMPATIBILITY, context) cycles = self.parameterAsInt(parameters, self.CYCLES, context) iterations = self.parameterAsInt(parameters, self.ITERATIONS, context) source = self.parameterAsSource(parameters, self.INPUT, context) (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, source.fields(), source.wkbType(), source.sourceCrs()) features = source.getFeatures(QgsFeatureRequest()) total = 100.0 / source.featureCount() if source.featureCount() else 0 # Parameter vlayer = source fields = vlayer.fields() # Create edge list edges = [] for current, feat in enumerate(features): if feedback.isCanceled(): break edges.append(feat) # Create clusters clusters = [] if use_clustering == True: # Arrange edges in clusters according to cluster-id labels = [] for edge in edges: labels.append(edge[cluster_field]) feedback.pushDebugInfo(cluster_field) for l in range(0, max(labels) + 1): clusters.append(list()) for i, label in enumerate(labels): if label >= 0: clusters[label].append(edges[i]) else: clusters.append([edges[i]]) for i, cluster in enumerate(clusters): clusters[i] = EdgeCluster(cluster, initial_step_size, iterations, cycles, compatibility) else: # If clustering should not be used, create only one big cluster containing all edges cluster_field = QgsField('CLUSTER', QVariant.Int) cluster_n_field = QgsField('CLUSTER_N', QVariant.Int) fields.append(cluster_field) fields.append(cluster_n_field) clusters = [EdgeCluster(edges, initial_step_size, iterations, cycles, compatibility)] # Do edge-bundling (separately for all clusters) for c, cl in enumerate(clusters): feedback.setProgress(80 * ( 1.0 * c / len(clusters))) if feedback.isCanceled(): break if cl.E > 1: cl.force_directed_eb(feedback) feedback.setProgress(90) for cl in clusters: if feedback.isCanceled(): break for e, edge in enumerate(cl.edges): feat = QgsFeature() feat.setGeometry(edge.geometry()) if not use_clustering: attr = edge.attributes() attr.append(1) attr.append(len(edges)) feat.setAttributes(attr) else: feat.setAttributes(edge.attributes()) sink.addFeature(feat, QgsFeatureSink.FastInsert) return {self.OUTPUT: dest_id} ```
[ { "content": "Here is the code block:\n```python\n# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack import *\n\n\nclass Precice(CMakePackage):\n ...
[ { "content": "Here is the code block:\n<|memory_start|>```python\n# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n\nfrom spack import *\n\n\nclass Precice(CMak...
```python # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Precice(CMakePackage): """preCICE (Precise Code Interaction Coupling Environment) is a coupling library for partitioned multi-physics simulations. Partitioned means that preCICE couples existing programs (solvers) capable of simulating a subpart of the complete physics involved in a simulation.""" homepage = 'https://www.precice.org' git = 'https://github.com/precice/precice.git' url = 'https://github.com/precice/precice/archive/v1.2.0.tar.gz' maintainers = ['fsimonis', 'MakisH'] version('develop', branch='develop') version('2.0.2', sha256='72864480f32696e7b6da94fd404ef5cd6586e2e1640613e46b75f1afac8569ed') version('2.0.1', sha256='e4fe2d2063042761ab325f8c802f88ae088c90862af288ad1a642967d074bd50') version('2.0.0', sha256='c8979d366f06e35626a8da08a1c589df77ec13972eb524a1ba99a011e245701f') version('1.6.1', sha256='7d0c54faa2c69e52304f36608d93c408629868f16f3201f663a0f9b2008f0763') version('1.6.0', sha256='c3b16376fda9eb3449adb6cc3c1e267c3dc792a5d118e37d93a32a59b5a4bc6f') version('1.5.2', sha256='051e0d7655a91f8681901e5c92812e48f33a5779309e2f104c99f5a687e1a418') version('1.5.1', sha256='fbe151f1a9accf9154362c70d15254935d4f594d189982c3a99fdb3dd9d9e665') version('1.5.0', sha256='a2a794becd08717e3049252134ae35692fed71966ed32e22cca796a169c16c3e') version('1.4.1', sha256='dde4882edde17882340f9f601941d110d5976340bd71af54c6e6ea22ae56f1a5') version('1.4.0', sha256='3499bfc0941fb9f004d5e32eb63d64f93e17b4057fab3ada1cde40c8311bd466') version('1.3.0', sha256='610322ba1b03df8e8f7d060d57a6a5afeabd5db4e8c4a638d04ba4060a3aec96') version('1.2.0', sha256='0784ecd002092949835151b90393beb6e9e7a3e9bd78ffd40d18302d6da4b05b') # Skip version 1.1.1 entirely, the cmake was lacking install. variant('mpi', default=True, description='Enable MPI support') variant('petsc', default=True, description='Enable PETSc support') variant('python', default=False, description='Enable Python support') variant('shared', default=True, description='Build shared libraries') depends_on('cmake@3.5:', type='build') depends_on('cmake@3.10.2:', type='build', when='@1.4:') depends_on('boost@1.60.0:') depends_on('boost@1.65.1:', when='@1.4:') depends_on('boost@:1.72.99', when='@:2.0.2') depends_on('eigen@3.2:') depends_on('eigen@:3.3.7', type='build', when='@:1.5') # bug in prettyprint depends_on('libxml2') depends_on('mpi', when='+mpi') depends_on('petsc@3.6:', when='+petsc') # Python 3 support was added in version 2.0 depends_on('python@2.7:2.8', when='@:1.9+python', type=('build', 'run')) depends_on('python@3:', when='@2:+python', type=('build', 'run')) # numpy 1.17+ requires Python 3 depends_on('py-numpy@:1.16', when='@:1.9+python', type=('build', 'run')) depends_on('py-numpy@1.17:', when='@2:+python', type=('build', 'run')) # We require C++11 compiler support as well as # library support for time manipulators (N2071, N2072) conflicts('%gcc@:4') conflicts('%clang@:3.7') conflicts('%intel@:14') conflicts('%pgi@:14') def cmake_args(self): """Populate cmake arguments for precice.""" spec = self.spec # The xSDK installation policies were implemented after 1.5.2 xsdk_mode = spec.satisfies("@1.6:") # Select the correct CMake variables by version mpi_option = "MPI" if spec.satisfies("@2:"): mpi_option = "PRECICE_MPICommunication" petsc_option = "PETSC" if spec.satisfies("@2:"): petsc_option = "PRECICE_PETScMapping" python_option = "PYTHON" if spec.satisfies("@2:"): python_option = "PRECICE_PythonActions" def variant_bool(feature, on='ON', off='OFF'): """Ternary for spec variant to ON/OFF string""" if feature in spec: return on return off cmake_args = [ '-DBUILD_SHARED_LIBS:BOOL=%s' % variant_bool('+shared'), ] cmake_args.append('-D%s:BOOL=%s' % (mpi_option, variant_bool('+mpi'))) # Boost if xsdk_mode: cmake_args.append('-DTPL_ENABLE_BOOST=ON') cmake_args.append('-DBOOST_ROOT=%s' % spec['boost'].prefix) # Eigen3 if xsdk_mode: cmake_args.append('-DTPL_ENABLE_EIGEN3=ON') cmake_args.append( '-DEIGEN3_INCLUDE_DIR=%s' % spec['eigen'].headers.directories[0]) # LibXML2 if xsdk_mode: cmake_args.append('-DTPL_ENABLE_LIBXML2=ON') libxml2_includes = spec['libxml2'].headers.directories[0] cmake_args.extend([ '-DLIBXML2_INCLUDE_DIRS=%s' % libxml2_includes, '-DLIBXML2_LIBRARIES=%s' % spec['libxml2'].libs[0], ]) # PETSc if '+petsc' in spec: if xsdk_mode: cmake_args.append('-DTPL_ENABLE_PETSC:BOOL=ON') else: cmake_args.append('-D%s:BOOL=ON' % petsc_option) cmake_args.extend([ '-DPETSC_DIR=%s' % spec['petsc'].prefix, '-DPETSC_ARCH=.' ]) else: cmake_args.append('-D%s:BOOL=OFF' % petsc_option) # Python if '+python' in spec: python_library = spec['python'].libs[0] python_include = spec['python'].headers.directories[0] numpy_include = join_path( spec['py-numpy'].prefix, spec['python'].package.site_packages_dir, 'numpy', 'core', 'include') if xsdk_mode: cmake_args.append('-DTPL_ENABLE_PYTHON:BOOL=ON') else: cmake_args.append('-D%s:BOOL=ON' % python_option) cmake_args.extend([ '-DPYTHON_INCLUDE_DIR=%s' % python_include, '-DNumPy_INCLUDE_DIR=%s' % numpy_include, '-DPYTHON_LIBRARY=%s' % python_library ]) else: cmake_args.append('-D%s:BOOL=OFF' % python_option) return cmake_args ```
[ { "content": "Replicate the source code:\n```python\nfrom __future__ import absolute_import, print_function\n\nimport os.path\nfrom uuid import uuid4\nfrom functools import wraps\n\nimport warnings\nimport logging\nlogger = logging.getLogger(__file__)\n\nfrom six import add_metaclass, iteritems\nfrom six.moves....
[ { "content": "Replicate the source code:\n<|memory_start|>```python\nfrom __future__ import absolute_import, print_function\n\nimport os.path\nfrom uuid import uuid4\nfrom functools import wraps\n\nimport warnings\nimport logging\nlogger = logging.getLogger(__file__)\n\nfrom six import add_metaclass, iteritems\...
```python from __future__ import absolute_import, print_function import os.path from uuid import uuid4 from functools import wraps import warnings import logging logger = logging.getLogger(__file__) from six import add_metaclass, iteritems from six.moves.urllib.parse import urlsplit from .embed import autoload_static, autoload_server from .properties import HasProps, MetaHasProps, Instance from .protocol import serialize_json from .utils import get_ref, convert_references, dump class Viewable(MetaHasProps): """ Any plot object (Data Model) which has its own View Model in the persistence layer. Adds handling of a __view_model__ attribute to the class (which is provided by default) which tells the View layer what View class to create. One thing to keep in mind is that a Viewable should have a single unique representation in the persistence layer, but it might have multiple concurrent client-side Views looking at it. Those may be from different machines altogether. """ # Stores a mapping from subclass __view_model__ names to classes model_class_reverse_map = {} # Mmmm.. metaclass inheritance. On the one hand, it seems a little # overkill. On the other hand, this is exactly the sort of thing # it's meant for. def __new__(cls, class_name, bases, class_dict): if "__view_model__" not in class_dict: class_dict["__view_model__"] = class_name class_dict["get_class"] = Viewable.get_class # Create the new class newcls = super(Viewable,cls).__new__(cls, class_name, bases, class_dict) entry = class_dict["__view_model__"] # Add it to the reverse map, but check for duplicates first if entry in Viewable.model_class_reverse_map: raise Warning("Duplicate __view_model__ declaration of '%s' for " \ "class %s. Previous definition: %s" % \ (entry, class_name, Viewable.model_class_reverse_map[entry])) Viewable.model_class_reverse_map[entry] = newcls return newcls @classmethod def _preload_models(cls): from . import objects, widgetobjects @classmethod def get_class(cls, view_model_name): """ Given a __view_model__ name, returns the corresponding class object """ cls._preload_models() d = Viewable.model_class_reverse_map if view_model_name in d: return d[view_model_name] else: raise KeyError("View model name '%s' not found" % view_model_name) def usesession(meth): """ Checks for 'session' in kwargs and in **self**, and guarantees that **kw** always has a valid 'session' parameter. Wrapped methods should define 'session' as an optional argument, and in the body of the method, should expect an """ @wraps(meth) def wrapper(self, *args, **kw): session = kw.get("session", None) if session is None: session = getattr(self, "session") if session is None: raise RuntimeError("Call to %s needs a session" % meth.__name__) kw["session"] = session return meth(self, *args, **kw) return wrapper def is_ref(frag): return isinstance(frag, dict) and \ frag.get('type') and \ frag.get('id') def json_apply(fragment, check_func, func): """recursively searches through a nested dict/lists if check_func(fragment) is True, then we return func(fragment) """ if check_func(fragment): return func(fragment) elif isinstance(fragment, list): output = [] for val in fragment: output.append(json_apply(val, check_func, func)) return output elif isinstance(fragment, dict): output = {} for k, val in fragment.items(): output[k] = json_apply(val, check_func, func) return output else: return fragment def resolve_json(fragment, models): check_func = is_ref def func(fragment): if fragment['id'] in models: return models[fragment['id']] else: logging.error("model not found for %s", fragment) return None return json_apply(fragment, check_func, func) @add_metaclass(Viewable) class PlotObject(HasProps): """ Base class for all plot-related objects """ session = Instance(".session.Session") def __init__(self, **kwargs): # Eventually should use our own memo instead of storing # an attribute on the class if "id" in kwargs: self._id = kwargs.pop("id") else: self._id = str(uuid4()) self._dirty = True self._callbacks_dirty = False self._callbacks = {} self._callback_queue = [] self._block_callbacks = False block_events = kwargs.pop('_block_events', False) if not block_events: super(PlotObject, self).__init__(**kwargs) self.setup_events() else: self._block_callbacks = True super(PlotObject, self).__init__(**kwargs) def get_ref(self): return { 'type': self.__view_model__, 'id': self._id, } def setup_events(self): pass @classmethod def load_json(cls, attrs, instance=None): """Loads all json into a instance of cls, EXCEPT any references which are handled in finalize """ if 'id' not in attrs: raise RuntimeError("Unable to find 'id' attribute in JSON: %r" % attrs) _id = attrs.pop('id') if not instance: instance = cls(id=_id, _block_events=True) _doc = attrs.pop("doc", None) ref_props = {} for p in instance.properties_with_refs(): if p in attrs: ref_props[p] = attrs.pop(p) special_props = {} for p in dict(attrs): if p not in instance.properties(): special_props[p] = attrs.pop(p) instance._ref_props = ref_props instance._special_props = special_props instance.update(**attrs) return instance def finalize(self, models): """Convert any references into instances models is a dict of id->model mappings """ if hasattr(self, "_ref_props"): return resolve_json(self._ref_props, models) else: return {} @classmethod def collect_plot_objects(cls, *input_objs): """ Iterate over ``input_objs`` and descend through their structure collecting all nested ``PlotObjects`` on the go. The resulting list is duplicate-free based on objects' identifiers. """ ids = set([]) objs = [] def descend_props(obj): for attr in obj.properties_with_refs(): descend(getattr(obj, attr)) def descend(obj): if isinstance(obj, PlotObject): if obj._id not in ids: ids.add(obj._id) descend_props(obj) objs.append(obj) elif isinstance(obj, HasProps): descend_props(obj) elif isinstance(obj, (list, tuple)): for item in obj: descend(item) elif isinstance(obj, dict): for key, value in iteritems(obj): descend(key); descend(value) descend(input_objs) return objs def references(self): """Returns all ``PlotObjects`` that this object has references to. """ return set(self.collect_plot_objects(self)) #--------------------------------------------------------------------- # View Model connection methods # # Whereas a rich client rendering framework can maintain view state # alongside model state, we need an explicit send/receive protocol for # communicating with a set of view models that reside on the front end. # Many of the calls one would expect in a rich client map instead to # batched updates on the M-VM-V approach. #--------------------------------------------------------------------- def vm_props(self): """ Returns the ViewModel-related properties of this object. """ props = self.changed_properties_with_values() props.pop("session", None) return props def vm_serialize(self): """ Returns a dictionary of the attributes of this object, in a layout corresponding to what BokehJS expects at unmarshalling time. """ attrs = self.vm_props() attrs['id'] = self._id return attrs def dump(self, docid=None): """convert all references to json """ models = self.references() return dump(models, docid=docid) def update(self, **kwargs): for k,v in kwargs.items(): setattr(self, k, v) def __str__(self): return "%s, ViewModel:%s, ref _id: %s" % (self.__class__.__name__, self.__view_model__, getattr(self, "_id", None)) def on_change(self, attrname, obj, callbackname=None): """when attrname of self changes, call callbackname on obj """ callbacks = self._callbacks.setdefault(attrname, []) callback = dict(obj=obj, callbackname=callbackname) if callback not in callbacks: callbacks.append(callback) self._callbacks_dirty = True def _trigger(self, attrname, old, new): """attrname of self changed. So call all callbacks """ callbacks = self._callbacks.get(attrname) if callbacks: for callback in callbacks: obj = callback.get('obj') callbackname = callback.get('callbackname') fn = obj if callbackname is None else getattr(obj, callbackname) fn(self, attrname, old, new) # TODO: deprecation warnign about args change (static_path) def create_html_snippet( self, server=False, embed_base_url="", embed_save_loc=".", static_path="http://localhost:5006/bokehjs/static"): """create_html_snippet is used to embed a plot in an html page. create_html_snippet returns the embed string to be put in html. This will be a <script> tag. To embed a plot dependent on the Bokeh Plot Server, set server=True, otherwise a file with the data for the plot will be built. embed_base_url is used for non-server embedding. This is used as the root of the url where the embed.js file will be saved. embed_save_loc controls where the embed.js will be actually written to. static_path controls where the embed snippet looks to find bokeh.js and the other resources it needs for bokeh. """ if server: from .session import Session if embed_base_url: session = Session(root_url=server_url) else: session = Session() return autoload_server(self, session) from .templates import AUTOLOAD, AUTOLOAD_STATIC import uuid js_filename = "%s.embed.js" % self._id script_path = embed_base_url + js_filename elementid = str(uuid.uuid4()) js = AUTOLOAD.render( all_models = serialize_json(self.dump()), js_url = static_path + "js/bokeh.min.js", css_files = [static_path + "css/bokeh.min.css"], elementid = elementid, ) tag = AUTOLOAD_STATIC.render( src_path = script_path, elementid = elementid, modelid = self._id, modeltype = self.__view_model__, ) save_path = os.path.join(embed_save_loc, js_filename) with open(save_path,"w") as f: f.write(js) return tag def inject_snippet( self, server=False, embed_base_url="", embed_save_loc=".", static_path="http://localhost:5006/bokeh/static/"): warnings.warn("inject_snippet is deprecated, please use create_html_snippet") return self.create_html_snippet( server, embed_base_url, embed_save_loc, static_path) def _build_server_snippet(self, base_url=False): sess = self._session modelid = self._id typename = self.__view_model__ if not base_url: base_url = sess.root_url split = urlsplit(base_url) if split.scheme == 'http': ws_conn_string = "ws://%s/bokeh/sub" % split.netloc else: ws_conn_string = "wss://%s/bokeh/sub" % split.netloc f_dict = dict( docid = sess.docid, ws_conn_string = ws_conn_string, docapikey = sess.apikey, root_url = base_url, modelid = modelid, modeltype = typename, script_url = base_url + "bokeh/embed.js") e_str = '''<script src="%(script_url)s" bokeh_plottype="serverconn" bokeh_docid="%(docid)s" bokeh_ws_conn_string="%(ws_conn_string)s" bokeh_docapikey="%(docapikey)s" bokeh_root_url="%(root_url)s" bokeh_modelid="%(modelid)s" bokeh_modeltype="%(modeltype)s" async="true"></script> ''' return "", e_str % f_dict def _build_static_embed_snippet(self, static_path, embed_base_url): embed_filename = "%s.embed.js" % self._id full_embed_path = embed_base_url + embed_filename js_str = self._session.embed_js(self._id, static_path) sess = self._session modelid = self._id typename = self.__view_model__ embed_filename = full_embed_path f_dict = dict(modelid = modelid, modeltype = typename, embed_filename=embed_filename) e_str = '''<script src="%(embed_filename)s" bokeh_plottype="embeddata" bokeh_modelid="%(modelid)s" bokeh_modeltype="%(modeltype)s" async="true"></script> ''' return js_str, e_str % f_dict ```
[ { "content": "Reconstruct the code exactly:\n```python\n\"\"\"Component is the building block for desmod models.\n\nHierarchy\n---------\n\nA desmod model consists of a directed acyclical graph (DAG) of\n:class:`Component` subclasses. Each Component is composed of zero or more child\nComponents. A single top-le...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n\"\"\"Component is the building block for desmod models.\n\nHierarchy\n---------\n\nA desmod model consists of a directed acyclical graph (DAG) of\n:class:`Component` subclasses. Each Component is composed of zero or more child\nComponents....
```python """Component is the building block for desmod models. Hierarchy --------- A desmod model consists of a directed acyclical graph (DAG) of :class:`Component` subclasses. Each Component is composed of zero or more child Components. A single top-level Component class is passed to the :func:`~desmod.simulation.simulate()` function to initiate simulation. The :class:`Component` hierarchy does not define the behavior of a model, but instead exists as a tool to build large models out of composable and encapsulated pieces. Connections ----------- Components connect to other components via connection objects. Each component is responsible for declaring the names of external connections as well as make connections for its child components. The final network of inter-component connections is neither directed (a connection object may enable two-way communication), acyclic (groups of components may form cyclical connections), nor constrained to match the component hierarchy. Ultimately, a connection between two components means that each component instance has a [pythonic] reference to the connection object. In the spirit of Python, the types connection objects are flexible and dynamic. A connection object may be of any type--it is up to the connected components to cooperatively decide how to use the connection object for communication. That said, some object types are more useful than others for connections. Some useful connection object types include: * :class:`desmod.queue.Queue` * :class:`simpy.resources.resource.Resource` Processes --------- A component may have zero or more simulation processes (:class:`simpy.events.Process`). It is these processes that give a model its simulation-time behavior. The process methods declared by components are started at simulation time. These "standing" processes may dynamically launch addtional processes using `self.env.process()`. Use Cases --------- Given the flexibility components to have zero or more children, zero or more processes, and zero or more connections, it can be helpful to give names to the various roles components may play in a model. * Structural Component -- a component with child components, but no processes * Behavioral Component -- a component with processes, but no child components * Hybrid Component -- a component with child components and processes * State Component -- a component with neither children or processes It is typical for the top-level component in a model to be purely structural, while behavioral components are leaves in the model DAG. A component with neither children or processes may still be useful. Such a component could, for example, be used as a connection object. """ class ConnectError(Exception): pass class Component(object): """Building block for composing models. This class is meant to be subclassed. Component subclasses must declare their children, connections, and processes. :param Component parent: Parent component or None for top-level Component. :param SimEnvironment env: SimPy simulation environment. :param str name: Optional name of Component instance. :param int index: Optional index of Component. This is used when multiple sibling components of the same type are instantiated as an array/list. """ #: Short/friendly name used in the scope (class attribute). base_name = '' def __init__(self, parent, env=None, name=None, index=None): assert parent or env #: The simulation environment; a :class:`SimEnvironment` instance. self.env = parent.env if env is None else env #: The component name (str). self.name = ((self.base_name if name is None else name) + ('' if index is None else str(index))) #: Index of Component instance within group of sibling instances. #: Will be None for un-grouped Components. self.index = index if parent is None or not parent.scope: #: String indicating the full scope of Component instance in the #: Component DAG. self.scope = self.name else: self.scope = parent.scope + '.' + self.name if parent: parent._children.append(self) self._children = [] self._processes = [] self._connections = [] self._not_connected = set() #: Log an error message. self.error = self.env.tracemgr.get_trace_function( self.scope, log={'level': 'ERROR'}) #: Log a warning message. self.warn = self.env.tracemgr.get_trace_function( self.scope, log={'level': 'WARNING'}) #: Log an informative message. self.info = self.env.tracemgr.get_trace_function( self.scope, log={'level': 'INFO'}) #: Log a debug message. self.debug = self.env.tracemgr.get_trace_function( self.scope, log={'level': 'DEBUG'}) def add_process(self, process_func, *args, **kwargs): """Add a process method to be run at simulation-time. Subclasses should call this in `__init__()` to declare the process methods to be started at simulation-time. :param function process_func: Typically a bound method of the Component subclass. :param args: arguments to pass to `process_func`. :param kwargs: keyword arguments to pass to `process_func`. """ self._processes.append((process_func, args, kwargs)) def add_processes(self, *process_funcs): """Declare multiple processes at once. This is a convenience wrapper for :meth:`add_process()` that may be used to quickly declare a list of process methods that do not require any arguments. :param process_funcs: argument-less process functions (methods). """ for process_func in process_funcs: self.add_process(process_func) def add_connections(self, *connection_names): """Declare names of externally-provided connection objects. The named connections must be connected (assigned) by an ancestor at elaboration time. """ self._not_connected.update(connection_names) def connect(self, dst, dst_connection, src=None, src_connection=None, conn_obj=None): """Assign connection object from source to destination component. At elaboration-time, Components must call `connect()` to make the connections declared by descendant (child, grandchild, etc.) components. .. Note:: :meth:`connect()` is nominally called from :meth:`connect_children()`. :param Component dst: Destination component being assigned the connection object. :param str dst_connection: Destination's name for the connection object. :param Component src: Source component providing the connection object. If omitted, the source component is assumed to be `self`. :param str src_connection: Source's name for the connection object. If omitted, `dst_connection` is used. :param conn_obj: The connection object to be assigned to the destination component. This parameter may typically be omitted in which case the connection object is resolved using `src` and `src_connection`. """ if src is None: src = self if src_connection is None: src_connection = dst_connection if conn_obj is None: if hasattr(src, src_connection): conn_obj = getattr(src, src_connection) else: raise ConnectError( 'src "{}" (class {}) does not have attr "{}"'.format( src.scope, type(src).__name__, src_connection)) if dst_connection in dst._not_connected: setattr(dst, dst_connection, conn_obj) dst._not_connected.remove(dst_connection) dst._connections.append( (dst_connection, src, src_connection, conn_obj)) else: raise ConnectError( 'dst "{}" (class {}) does not declare connection "{}"'.format( dst.scope, type(dst).__name__, dst_connection)) def connect_children(self): """Make connections for descendant components. This method must be overridden in Component subclasses that need to make any connections on behalf of its descendant components. Connections are made using :meth:`connect()`. """ if any(child._not_connected for child in self._children): raise ConnectError( '{0} has unconnected children; implement ' '{0}.connect_children()'.format(type(self).__name__)) def auto_probe(self, name, target=None, **hints): if target is None: target = getattr(self, name) target_scope = '.'.join([self.scope, name]) self.env.tracemgr.auto_probe(target_scope, target, **hints) def get_trace_function(self, name, **hints): target_scope = '.'.join([self.scope, name]) return self.env.tracemgr.get_trace_function(target_scope, **hints) @classmethod def pre_init(cls, env): """Override-able class method called prior to model initialization. Component subclasses may override this classmethod to gain access to the simulation environment (`env`) prior to :meth:`__init__()` being called. """ pass def elaborate(self): """Recursively elaborate the model. The elaboration phase prepares the model for simulation. Descendant connections are made and components' processes are started at elaboration-time. """ self.connect_children() for child in self._children: if child._not_connected: raise ConnectError('{scope}.{conn_name} not connected'.format( scope=child.scope, conn_name=child._not_connected.pop())) child.elaborate() for proc, args, kwargs in self._processes: self.env.process(proc(*args, **kwargs)) self.elab_hook() def elab_hook(self): """Hook called after elaboration and before simulation phase. Component subclasses may override :meth:`elab_hook()` to inject behavior after elaboration, but prior to simulation. """ pass def post_simulate(self): """Recursively run post-simulation hooks.""" for child in self._children: child.post_simulate() self.post_sim_hook() def post_sim_hook(self): """Hook called after simulation completes. Component subclasses may override `post_sim_hook()` to inject behavior after the simulation completes successfully. Note that `post_sim_hook()` will not be called if the simulation terminates with an unhandled exception. """ pass def get_result(self, result): """Recursively compose simulation result dict. Upon successful completion of the simulation phase, each component in the model has the opportunity to add-to or modify the `result` dict via its :meth:`get_result_hook` method. The fully composed `result` dict is returned by :func:`simulate`. :param dict result: Result dictionary to be modified. """ for child in self._children: child.get_result(result) self.get_result_hook(result) def get_result_hook(self, result): """Hook called after result is composed by descendant components.""" pass ```
[ { "content": "```python\ndef bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0):\n Xmu = X-mux\n Ymu = Y-muy\n rho = sigmaxy/(sigmax*sigmay)\n z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay)\n denom = 2*np.pi*sigmax*sigmay*np.sqrt(1-rho**2)\n ...
[ { "content": "<|memory_start|>```python\ndef bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0):\n Xmu = X-mux\n Ymu = Y-muy\n rho = sigmaxy/(sigmax*sigmay)\n z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay)\n denom = 2*np.pi*sigmax*sigmay*np.sqrt...
```python def bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0): Xmu = X-mux Ymu = Y-muy rho = sigmaxy/(sigmax*sigmay) z = Xmu**2/sigmax**2 + Ymu**2/sigmay**2 - 2*rho*Xmu*Ymu/(sigmax*sigmay) denom = 2*np.pi*sigmax*sigmay*np.sqrt(1-rho**2) return np.exp(-z/(2*(1-rho**2))) / denom def MolToMPL(mol,size=(300,300),kekulize=True, wedgeBonds=True, imageType=None, fitImage=False, options=None, **kwargs): if not mol: raise ValueError('Null molecule provided') from rdkit.Chem.Draw.mplCanvas import Canvas canvas = Canvas(size) if options is None: options = DrawingOptions() options.bgColor=None if fitImage: drawingOptions.dotsPerAngstrom = int(min(size) / 10) options.wedgeDashedBonds=wedgeBonds drawer = MolDrawing(canvas=canvas, drawingOptions=options) omol=mol if kekulize: from rdkit import Chem mol = Chem.Mol(mol.ToBinary()) Chem.Kekulize(mol) if not mol.GetNumConformers(): from rdkit.Chem import AllChem AllChem.Compute2DCoords(mol) drawer.AddMol(mol,**kwargs) omol._atomPs=drawer.atomPs[mol] for k,v in iteritems(omol._atomPs): omol._atomPs[k]=canvas.rescalePt(v) canvas._figure.set_size_inches(float(size[0])/100,float(size[1])/100) return canvas._figure def calcAtomGaussians(mol,a=0.03,step=0.02,weights=None): import numpy from matplotlib import mlab x = numpy.arange(0,1,step) y = numpy.arange(0,1,step) X,Y = numpy.meshgrid(x,y) if weights is None: weights=[1.]*mol.GetNumAtoms() Z = mlab.bivariate_normal(X,Y,a,a,mol._atomPs[0][0], mol._atomPs[0][1])*weights[0] # this is not bivariate case ... only univariate no mixtures #matplotlib.mlab.bivariate_normal(X, Y, sigmax=1.0, sigmay=1.0, mux=0.0, muy=0.0, sigmaxy=0.0) for i in range(1,mol.GetNumAtoms()): Zp = mlab.bivariate_normal(X,Y,a,a,mol._atomPs[i][0], mol._atomPs[i][1]) Z += Zp*weights[i] return X,Y,Z def GetSimilarityMapFromWeights(mol, weights, colorMap=cm.PiYG, scale=-1, size=(250, 250), sigma=None, #@UndefinedVariable #pylint: disable=E1101 coordScale=1.5, step=0.01, colors='k', contourLines=10, alpha=0.5, **kwargs): if mol.GetNumAtoms() < 2: raise ValueError("too few atoms") fig = Draw.MolToMPL(mol, coordScale=coordScale, size=size, **kwargs) if sigma is None: if mol.GetNumBonds() > 0: bond = mol.GetBondWithIdx(0) idx1 = bond.GetBeginAtomIdx() idx2 = bond.GetEndAtomIdx() sigma = 0.3 * math.sqrt(sum([(mol._atomPs[idx1][i]-mol._atomPs[idx2][i])**2 for i in range(2)])) else: sigma = 0.3 * math.sqrt(sum([(mol._atomPs[0][i]-mol._atomPs[1][i])**2 for i in range(2)])) sigma = round(sigma, 2) x, y, z = Draw.calcAtomGaussians(mol, sigma, weights=weights, step=step) # scaling if scale <= 0.0: maxScale = max(math.fabs(numpy.min(z)), math.fabs(numpy.max(z))) else: maxScale = scale # coloring fig.axes[0].imshow(z, cmap=colorMap, interpolation='bilinear', origin='lower', extent=(0,1,0,1), vmin=-maxScale, vmax=maxScale) # contour lines # only draw them when at least one weight is not zero if len([w for w in weights if w != 0.0]): fig.axes[0].contour(x, y, z, contourLines, colors=colors, alpha=alpha, **kwargs) return fig ```
[ { "content": "Here is a code file:\n```python\nimport shelve\n\n\nclass InvalidationError(Exception):\n pass\n\nclass ShelfProxy(Proxy):\n __slots__ = [\"_key\", \"_shelf\", \"_invalidated\"]\n \n def __init__(self, obj, shelf, key):\n Proxy.__init__(self, obj)\n object.__setattr__(sel...
[ { "content": "Here is a code file:\n<|memory_start|>```python\nimport shelve\n\n\nclass InvalidationError(Exception):\n pass\n\nclass ShelfProxy(Proxy):\n __slots__ = [\"_key\", \"_shelf\", \"_invalidated\"]\n \n def __init__(self, obj, shelf, key):\n Proxy.__init__(self, obj)\n object...
```python import shelve class InvalidationError(Exception): pass class ShelfProxy(Proxy): __slots__ = ["_key", "_shelf", "_invalidated"] def __init__(self, obj, shelf, key): Proxy.__init__(self, obj) object.__setattr__(self, "_shelf", shelf) object.__setattr__(self, "_key", key) object.__setattr__(self, "_invalidated", False) def __del__(self): try: sync_proxy(self) except InvalidationError: pass class ShelfWrapper(object): def __init__(self, shelf): self.__shelf = shelf self.__cache = {} def __del__(self): self.close() def __getattr__(self, name): return getattr(self.__shelf, name) def __contains__(self, key): return key in self.__shelf def __len__(self, key): return len(self.__shelf) def __delitem__(self, key): if key in self.__cache: object.__setattr__(self.__cache[key], "_invalidated", True) del self.__cache[key] del self.__shelf[key] def __getitem__(self, key): try: obj = self.__cache[key] except KeyError: self.__cache[key] = obj = ShelfProxy(self.__shelf[key], self.__shelf, key) return obj def __setitem__(self, key, value): if key in self.__cache: object.__setattr__(self.__cache[key], "_invalidated", True) self.__cache[key] = ShelfProxy(value, self.__shelf, key) self.__shelf[key] = value def sync(self): for obj in self.__cache.itervalues(): try: sync_proxy(obj) except InvalidationError: pass def close(self): self.sync() self.__cache.clear() self.__shelf.close() def sync_proxy(proxy): if object.__getattribute__(proxy, "_invalidated"): raise InvalidationError("the proxy has been invalidated (the key was reassigned)") shelf = object.__getattribute__(proxy, "_shelf") key = object.__getattribute__(proxy, "_key") obj = object.__getattribute__(proxy, "_obj") shelf[key] = obj shelf.sync() def open(*args): return ShelfWrapper( shelve.open(*args) ) ------ example ------ >>> db = open("blah.db") >>> db["mylist"]=[1,2,3] >>> db["mylist"].append(4) >>> db["mylist"] [1, 2, 3, 4] >>> p = db["mylist"] >>> type(p) <class '__main__.ShelfProxy(list)'> >>> p.append(5) >>> p2 = db["mylist"] >>> p2 [1, 2, 3, 4, 5] >>> p2 is p True ----- invalidation ----- When we reassign a key that have been proxies earlier, the proxy instance becomes invalidated, so it will not override the new value. >>> db["mylist"] = 19 >>> sync_proxy(p) Traceback (most recent call last): File "<stdin>", line 1, in ? File "Proxy.py", line 152, in sync_proxy raise InvalidationError("the proxy has been invalidated (the key was reassigned)") __main__.InvalidationError: the proxy has been invalidated (the key was reassigned) >>> >>> db["mylist"] += 1 >>> db["mylist"] 20 ```
[ { "content": "Return the code exactly, with no changes:\n```python\n# -----------------\n# normal decorators\n# -----------------\n\ndef decorator(func):\n def wrapper(*args):\n return func(1, *args)\n return wrapper\n\n@decorator\ndef decorated(a,b):\n return a,b\n\nexe = decorated(set, '')\n\n...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\n# -----------------\n# normal decorators\n# -----------------\n\ndef decorator(func):\n def wrapper(*args):\n return func(1, *args)\n return wrapper\n\n@decorator\ndef decorated(a,b):\n return a,b\n\nexe = decora...
```python # ----------------- # normal decorators # ----------------- def decorator(func): def wrapper(*args): return func(1, *args) return wrapper @decorator def decorated(a,b): return a,b exe = decorated(set, '') #? set exe[1] #? int() exe[0] # more complicated with args/kwargs def dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @dec def fu(a, b, c, *args, **kwargs): return a, b, c, args, kwargs exe = fu(list, c=set, b=3, d='') #? list exe[0] #? int() exe[1] #? set exe[2] #? [] exe[3][0]. #? str() exe[4]['d'] exe = fu(list, set, 3, '', d='') #? str() exe[3][0] # ----------------- # multiple decorators # ----------------- def dec2(func2): def wrapper2(first_arg, *args2, **kwargs2): return func2(first_arg, *args2, **kwargs2) return wrapper2 @dec2 @dec def fu2(a, b, c, *args, **kwargs): return a, b, c, args, kwargs exe = fu2(list, c=set, b=3, d='str') #? list exe[0] #? int() exe[1] #? set exe[2] #? [] exe[3][0]. #? str() exe[4]['d'] # ----------------- # Decorator is a class # ----------------- def same_func(func): return func class Decorator(object): def __init__(self, func): self.func = func def __call__(self, *args, **kwargs): return self.func(1, *args, **kwargs) @Decorator def nothing(a,b,c): return a,b,c #? int() nothing("")[0] #? str() nothing("")[1] @same_func @Decorator def nothing(a,b,c): return a,b,c #? int() nothing("")[0] class MethodDecoratorAsClass(): class_var = 3 @Decorator def func_without_self(arg, arg2): return arg, arg2 @Decorator def func_with_self(self, arg): return self.class_var #? int() MethodDecoratorAsClass().func_without_self('')[0] #? str() MethodDecoratorAsClass().func_without_self('')[1] #? MethodDecoratorAsClass().func_with_self(1) class SelfVars(): """Init decorator problem as an instance, #247""" @Decorator def __init__(self): """ __init__ decorators should be ignored when looking up variables in the class. """ self.c = list @Decorator def shouldnt_expose_var(not_self): """ Even though in real Python this shouldn't expose the variable, in this case Jedi exposes the variable, because these kind of decorators are normally descriptors, which SHOULD be exposed (at least 90%). """ not_self.b = 1.0 def other_method(self): #? float() self.b #? list self.c # ----------------- # not found decorators (are just ignored) # ----------------- @not_found_decorator def just_a_func(): return 1 #? int() just_a_func() #? ['__closure__'] just_a_func.__closure__ class JustAClass: @not_found_decorator2 def a(self): return 1 #? ['__call__'] JustAClass().a.__call__ #? int() JustAClass().a() #? ['__call__'] JustAClass.a.__call__ #? int() JustAClass.a() # ----------------- # illegal decorators # ----------------- class DecoratorWithoutCall(): def __init__(self, func): self.func = func @DecoratorWithoutCall def f(): return 1 # cannot be resolved - should be ignored @DecoratorWithoutCall(None) def g(): return 1 #? f() #? int() g() class X(): @str def x(self): pass def y(self): #? str() self.x #? self.x() def decorator_var_args(function, *args): return function(*args) @decorator_var_args def function_var_args(param): return param #? int() function_var_args(1) # ----------------- # method decorators # ----------------- def dec(f): def wrapper(s): return f(s) return wrapper class MethodDecorators(): _class_var = 1 def __init__(self): self._method_var = '' @dec def constant(self): return 1.0 @dec def class_var(self): return self._class_var @dec def method_var(self): return self._method_var #? float() MethodDecorators().constant() #? int() MethodDecorators().class_var() #? str() MethodDecorators().method_var() class Base(): @not_existing def __init__(self): pass @not_existing def b(self): return '' @dec def c(self): return 1 class MethodDecoratorDoesntExist(Base): """#272 github: combination of method decorators and super()""" def a(self): #? super().__init__() #? str() super().b() #? int() super().c() #? float() self.d() @doesnt_exist def d(self): return 1.0 # ----------------- # others # ----------------- def memoize(function): def wrapper(*args): if random.choice([0, 1]): pass else: rv = function(*args) return rv return wrapper @memoize def follow_statement(stmt): return stmt # here we had problems with the else clause, because the parent was not right. #? int() follow_statement(1) # ----------------- # class decorators # ----------------- # class decorators should just be ignored @should_ignore class A(): def ret(self): return 1 #? int() A().ret() # ----------------- # On decorator completions # ----------------- import abc #? ['abc'] @abc #? ['abstractmethod'] @abc.abstractmethod ```
[ { "content": "```python\n# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport functools\nimport itertools\nimport operator\nimport re\n\nfrom .common import InfoExtractor\nfrom ..compat import (\n compat_HTTPError,\n compat_str,\n compat_urllib_request,\n)\nfrom .openload import PhantomJS...
[ { "content": "<|memory_start|>```python\n# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport functools\nimport itertools\nimport operator\nimport re\n\nfrom .common import InfoExtractor\nfrom ..compat import (\n compat_HTTPError,\n compat_str,\n compat_urllib_request,\n)\nfrom .openload ...
```python # coding: utf-8 from __future__ import unicode_literals import functools import itertools import operator import re from .common import InfoExtractor from ..compat import ( compat_HTTPError, compat_str, compat_urllib_request, ) from .openload import PhantomJSwrapper from ..utils import ( determine_ext, ExtractorError, int_or_none, merge_dicts, NO_DEFAULT, orderedSet, remove_quotes, str_to_int, update_url_query, urlencode_postdata, url_or_none, ) class PornHubBaseIE(InfoExtractor): _NETRC_MACHINE = 'pornhub' def _download_webpage_handle(self, *args, **kwargs): def dl(*args, **kwargs): return super(PornHubBaseIE, self)._download_webpage_handle(*args, **kwargs) ret = dl(*args, **kwargs) if not ret: return ret webpage, urlh = ret if any(re.search(p, webpage) for p in ( r'<body\b[^>]+\bonload=["\']go\(\)', r'document\.cookie\s*=\s*["\']RNKEY=', r'document\.location\.reload\(true\)')): url_or_request = args[0] url = (url_or_request.get_full_url() if isinstance(url_or_request, compat_urllib_request.Request) else url_or_request) phantom = PhantomJSwrapper(self, required_version='2.0') phantom.get(url, html=webpage) webpage, urlh = dl(*args, **kwargs) return webpage, urlh def _real_initialize(self): self._logged_in = False def _login(self, host): if self._logged_in: return site = host.split('.')[0] # Both sites pornhub and pornhubpremium have separate accounts # so there should be an option to provide credentials for both. # At the same time some videos are available under the same video id # on both sites so that we have to identify them as the same video. # For that purpose we have to keep both in the same extractor # but under different netrc machines. username, password = self._get_login_info(netrc_machine=site) if username is None: return login_url = 'https://www.%s/%slogin' % (host, 'premium/' if 'premium' in host else '') login_page = self._download_webpage( login_url, None, 'Downloading %s login page' % site) def is_logged(webpage): return any(re.search(p, webpage) for p in ( r'class=["\']signOut', r'>Sign\s+[Oo]ut\s*<')) if is_logged(login_page): self._logged_in = True return login_form = self._hidden_inputs(login_page) login_form.update({ 'username': username, 'password': password, }) response = self._download_json( 'https://www.%s/front/authenticate' % host, None, 'Logging in to %s' % site, data=urlencode_postdata(login_form), headers={ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'Referer': login_url, 'X-Requested-With': 'XMLHttpRequest', }) if response.get('success') == '1': self._logged_in = True return message = response.get('message') if message is not None: raise ExtractorError( 'Unable to login: %s' % message, expected=True) raise ExtractorError('Unable to log in') class PornHubIE(PornHubBaseIE): IE_DESC = 'PornHub and Thumbzilla' _VALID_URL = r'''(?x) https?:// (?: (?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?:(?:view_video\.php|video/show)\?viewkey=|embed/)| (?:www\.)?thumbzilla\.com/video/ ) (?P<id>[\da-z]+) ''' _TESTS = [{ 'url': 'http://www.pornhub.com/view_video.php?viewkey=648719015', 'md5': 'a6391306d050e4547f62b3f485dd9ba9', 'info_dict': { 'id': '648719015', 'ext': 'mp4', 'title': 'Seductive Indian beauty strips down and fingers her pink pussy', 'uploader': 'Babes', 'upload_date': '20130628', 'timestamp': 1372447216, 'duration': 361, 'view_count': int, 'like_count': int, 'dislike_count': int, 'comment_count': int, 'age_limit': 18, 'tags': list, 'categories': list, }, }, { # non-ASCII title 'url': 'http://www.pornhub.com/view_video.php?viewkey=1331683002', 'info_dict': { 'id': '1331683002', 'ext': 'mp4', 'title': '重庆婷婷女王足交', 'upload_date': '20150213', 'timestamp': 1423804862, 'duration': 1753, 'view_count': int, 'like_count': int, 'dislike_count': int, 'comment_count': int, 'age_limit': 18, 'tags': list, 'categories': list, }, 'params': { 'skip_download': True, }, }, { # subtitles 'url': 'https://www.pornhub.com/view_video.php?viewkey=ph5af5fef7c2aa7', 'info_dict': { 'id': 'ph5af5fef7c2aa7', 'ext': 'mp4', 'title': 'BFFS - Cute Teen Girls Share Cock On the Floor', 'uploader': 'BFFs', 'duration': 622, 'view_count': int, 'like_count': int, 'dislike_count': int, 'comment_count': int, 'age_limit': 18, 'tags': list, 'categories': list, 'subtitles': { 'en': [{ "ext": 'srt' }] }, }, 'params': { 'skip_download': True, }, 'skip': 'This video has been disabled', }, { 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph557bbb6676d2d', 'only_matching': True, }, { # removed at the request of cam4.com 'url': 'http://fr.pornhub.com/view_video.php?viewkey=ph55ca2f9760862', 'only_matching': True, }, { # removed at the request of the copyright owner 'url': 'http://www.pornhub.com/view_video.php?viewkey=788152859', 'only_matching': True, }, { # removed by uploader 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph572716d15a111', 'only_matching': True, }, { # private video 'url': 'http://www.pornhub.com/view_video.php?viewkey=ph56fd731fce6b7', 'only_matching': True, }, { 'url': 'https://www.thumbzilla.com/video/ph56c6114abd99a/horny-girlfriend-sex', 'only_matching': True, }, { 'url': 'http://www.pornhub.com/video/show?viewkey=648719015', 'only_matching': True, }, { 'url': 'https://www.pornhub.net/view_video.php?viewkey=203640933', 'only_matching': True, }, { 'url': 'https://www.pornhub.org/view_video.php?viewkey=203640933', 'only_matching': True, }, { 'url': 'https://www.pornhubpremium.com/view_video.php?viewkey=ph5e4acdae54a82', 'only_matching': True, }, { # Some videos are available with the same id on both premium # and non-premium sites (e.g. this and the following test) 'url': 'https://www.pornhub.com/view_video.php?viewkey=ph5f75b0f4b18e3', 'only_matching': True, }, { 'url': 'https://www.pornhubpremium.com/view_video.php?viewkey=ph5f75b0f4b18e3', 'only_matching': True, }] @staticmethod def _extract_urls(webpage): return re.findall( r'<iframe[^>]+?src=["\'](?P<url>(?:https?:)?//(?:www\.)?pornhub(?:premium)?\.(?:com|net|org)/embed/[\da-z]+)', webpage) def _extract_count(self, pattern, webpage, name): return str_to_int(self._search_regex( pattern, webpage, '%s count' % name, fatal=False)) def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) host = mobj.group('host') or 'pornhub.com' video_id = mobj.group('id') self._login(host) self._set_cookie(host, 'age_verified', '1') def dl_webpage(platform): self._set_cookie(host, 'platform', platform) return self._download_webpage( 'https://www.%s/view_video.php?viewkey=%s' % (host, video_id), video_id, 'Downloading %s webpage' % platform) webpage = dl_webpage('pc') error_msg = self._html_search_regex( r'(?s)<div[^>]+class=(["\'])(?:(?!\1).)*\b(?:removed|userMessageSection)\b(?:(?!\1).)*\1[^>]*>(?P<error>.+?)</div>', webpage, 'error message', default=None, group='error') if error_msg: error_msg = re.sub(r'\s+', ' ', error_msg) raise ExtractorError( 'PornHub said: %s' % error_msg, expected=True, video_id=video_id) # video_title from flashvars contains whitespace instead of non-ASCII (see # http://www.pornhub.com/view_video.php?viewkey=1331683002), not relying # on that anymore. title = self._html_search_meta( 'twitter:title', webpage, default=None) or self._html_search_regex( (r'(?s)<h1[^>]+class=["\']title["\'][^>]*>(?P<title>.+?)</h1>', r'<div[^>]+data-video-title=(["\'])(?P<title>(?:(?!\1).)+)\1', r'shareTitle["\']\s*[=:]\s*(["\'])(?P<title>(?:(?!\1).)+)\1'), webpage, 'title', group='title') video_urls = [] video_urls_set = set() subtitles = {} flashvars = self._parse_json( self._search_regex( r'var\s+flashvars_\d+\s*=\s*({.+?});', webpage, 'flashvars', default='{}'), video_id) if flashvars: subtitle_url = url_or_none(flashvars.get('closedCaptionsFile')) if subtitle_url: subtitles.setdefault('en', []).append({ 'url': subtitle_url, 'ext': 'srt', }) thumbnail = flashvars.get('image_url') duration = int_or_none(flashvars.get('video_duration')) media_definitions = flashvars.get('mediaDefinitions') if isinstance(media_definitions, list): for definition in media_definitions: if not isinstance(definition, dict): continue video_url = definition.get('videoUrl') if not video_url or not isinstance(video_url, compat_str): continue if video_url in video_urls_set: continue video_urls_set.add(video_url) video_urls.append( (video_url, int_or_none(definition.get('quality')))) else: thumbnail, duration = [None] * 2 def extract_js_vars(webpage, pattern, default=NO_DEFAULT): assignments = self._search_regex( pattern, webpage, 'encoded url', default=default) if not assignments: return {} assignments = assignments.split(';') js_vars = {} def parse_js_value(inp): inp = re.sub(r'/\*(?:(?!\*/).)*?\*/', '', inp) if '+' in inp: inps = inp.split('+') return functools.reduce( operator.concat, map(parse_js_value, inps)) inp = inp.strip() if inp in js_vars: return js_vars[inp] return remove_quotes(inp) for assn in assignments: assn = assn.strip() if not assn: continue assn = re.sub(r'var\s+', '', assn) vname, value = assn.split('=', 1) js_vars[vname] = parse_js_value(value) return js_vars def add_video_url(video_url): v_url = url_or_none(video_url) if not v_url: return if v_url in video_urls_set: return video_urls.append((v_url, None)) video_urls_set.add(v_url) def parse_quality_items(quality_items): q_items = self._parse_json(quality_items, video_id, fatal=False) if not isinstance(q_items, list): return for item in q_items: if isinstance(item, dict): add_video_url(item.get('url')) if not video_urls: FORMAT_PREFIXES = ('media', 'quality', 'qualityItems') js_vars = extract_js_vars( webpage, r'(var\s+(?:%s)_.+)' % '|'.join(FORMAT_PREFIXES), default=None) if js_vars: for key, format_url in js_vars.items(): if key.startswith(FORMAT_PREFIXES[-1]): parse_quality_items(format_url) elif any(key.startswith(p) for p in FORMAT_PREFIXES[:2]): add_video_url(format_url) if not video_urls and re.search( r'<[^>]+\bid=["\']lockedPlayer', webpage): raise ExtractorError( 'Video %s is locked' % video_id, expected=True) if not video_urls: js_vars = extract_js_vars( dl_webpage('tv'), r'(var.+?mediastring.+?)</script>') add_video_url(js_vars['mediastring']) for mobj in re.finditer( r'<a[^>]+\bclass=["\']downloadBtn\b[^>]+\bhref=(["\'])(?P<url>(?:(?!\1).)+)\1', webpage): video_url = mobj.group('url') if video_url not in video_urls_set: video_urls.append((video_url, None)) video_urls_set.add(video_url) upload_date = None formats = [] for video_url, height in video_urls: if not upload_date: upload_date = self._search_regex( r'/(\d{6}/\d{2})/', video_url, 'upload data', default=None) if upload_date: upload_date = upload_date.replace('/', '') ext = determine_ext(video_url) if ext == 'mpd': formats.extend(self._extract_mpd_formats( video_url, video_id, mpd_id='dash', fatal=False)) continue elif ext == 'm3u8': formats.extend(self._extract_m3u8_formats( video_url, video_id, 'mp4', entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)) continue tbr = None mobj = re.search(r'(?P<height>\d+)[pP]?_(?P<tbr>\d+)[kK]', video_url) if mobj: if not height: height = int(mobj.group('height')) tbr = int(mobj.group('tbr')) formats.append({ 'url': video_url, 'format_id': '%dp' % height if height else None, 'height': height, 'tbr': tbr, }) self._sort_formats(formats) video_uploader = self._html_search_regex( r'(?s)From:&nbsp;.+?<(?:a\b[^>]+\bhref=["\']/(?:(?:user|channel)s|model|pornstar)/|span\b[^>]+\bclass=["\']username)[^>]+>(.+?)<', webpage, 'uploader', default=None) def extract_vote_count(kind, name): return self._extract_count( (r'<span[^>]+\bclass="votes%s"[^>]*>([\d,\.]+)</span>' % kind, r'<span[^>]+\bclass=["\']votes%s["\'][^>]*\bdata-rating=["\'](\d+)' % kind), webpage, name) view_count = self._extract_count( r'<span class="count">([\d,\.]+)</span> [Vv]iews', webpage, 'view') like_count = extract_vote_count('Up', 'like') dislike_count = extract_vote_count('Down', 'dislike') comment_count = self._extract_count( r'All Comments\s*<span>\(([\d,.]+)\)', webpage, 'comment') def extract_list(meta_key): div = self._search_regex( r'(?s)<div[^>]+\bclass=["\'].*?\b%sWrapper[^>]*>(.+?)</div>' % meta_key, webpage, meta_key, default=None) if div: return re.findall(r'<a[^>]+\bhref=[^>]+>([^<]+)', div) info = self._search_json_ld(webpage, video_id, default={}) # description provided in JSON-LD is irrelevant info['description'] = None return merge_dicts({ 'id': video_id, 'uploader': video_uploader, 'upload_date': upload_date, 'title': title, 'thumbnail': thumbnail, 'duration': duration, 'view_count': view_count, 'like_count': like_count, 'dislike_count': dislike_count, 'comment_count': comment_count, 'formats': formats, 'age_limit': 18, 'tags': extract_list('tags'), 'categories': extract_list('categories'), 'subtitles': subtitles, }, info) class PornHubPlaylistBaseIE(PornHubBaseIE): def _extract_page(self, url): return int_or_none(self._search_regex( r'\bpage=(\d+)', url, 'page', default=None)) def _extract_entries(self, webpage, host): # Only process container div with main playlist content skipping # drop-down menu that uses similar pattern for videos (see # https://github.com/ytdl-org/youtube-dl/issues/11594). container = self._search_regex( r'(?s)(<div[^>]+class=["\']container.+)', webpage, 'container', default=webpage) return [ self.url_result( 'http://www.%s/%s' % (host, video_url), PornHubIE.ie_key(), video_title=title) for video_url, title in orderedSet(re.findall( r'href="/?(view_video\.php\?.*\bviewkey=[\da-z]+[^"]*)"[^>]*\s+title="([^"]+)"', container)) ] class PornHubUserIE(PornHubPlaylistBaseIE): _VALID_URL = r'(?P<url>https?://(?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?:(?:user|channel)s|model|pornstar)/(?P<id>[^/?#&]+))(?:[?#&]|/(?!videos)|$)' _TESTS = [{ 'url': 'https://www.pornhub.com/model/zoe_ph', 'playlist_mincount': 118, }, { 'url': 'https://www.pornhub.com/pornstar/liz-vicious', 'info_dict': { 'id': 'liz-vicious', }, 'playlist_mincount': 118, }, { 'url': 'https://www.pornhub.com/users/russianveet69', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/channels/povd', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/model/zoe_ph?abc=1', 'only_matching': True, }, { # Unavailable via /videos page, but available with direct pagination # on pornstar page (see [1]), requires premium # 1. https://github.com/ytdl-org/youtube-dl/issues/27853 'url': 'https://www.pornhubpremium.com/pornstar/sienna-west', 'only_matching': True, }, { # Same as before, multi page 'url': 'https://www.pornhubpremium.com/pornstar/lily-labeau', 'only_matching': True, }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) user_id = mobj.group('id') videos_url = '%s/videos' % mobj.group('url') page = self._extract_page(url) if page: videos_url = update_url_query(videos_url, {'page': page}) return self.url_result( videos_url, ie=PornHubPagedVideoListIE.ie_key(), video_id=user_id) class PornHubPagedPlaylistBaseIE(PornHubPlaylistBaseIE): @staticmethod def _has_more(webpage): return re.search( r'''(?x) <li[^>]+\bclass=["\']page_next| <link[^>]+\brel=["\']next| <button[^>]+\bid=["\']moreDataBtn ''', webpage) is not None def _entries(self, url, host, item_id): page = self._extract_page(url) VIDEOS = '/videos' def download_page(base_url, num, fallback=False): note = 'Downloading page %d%s' % (num, ' (switch to fallback)' if fallback else '') return self._download_webpage( base_url, item_id, note, query={'page': num}) def is_404(e): return isinstance(e.cause, compat_HTTPError) and e.cause.code == 404 base_url = url has_page = page is not None first_page = page if has_page else 1 for page_num in (first_page, ) if has_page else itertools.count(first_page): try: try: webpage = download_page(base_url, page_num) except ExtractorError as e: # Some sources may not be available via /videos page, # trying to fallback to main page pagination (see [1]) # 1. https://github.com/ytdl-org/youtube-dl/issues/27853 if is_404(e) and page_num == first_page and VIDEOS in base_url: base_url = base_url.replace(VIDEOS, '') webpage = download_page(base_url, page_num, fallback=True) else: raise except ExtractorError as e: if is_404(e) and page_num != first_page: break raise page_entries = self._extract_entries(webpage, host) if not page_entries: break for e in page_entries: yield e if not self._has_more(webpage): break def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) host = mobj.group('host') item_id = mobj.group('id') self._login(host) return self.playlist_result(self._entries(url, host, item_id), item_id) class PornHubPagedVideoListIE(PornHubPagedPlaylistBaseIE): _VALID_URL = r'https?://(?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?P<id>(?:[^/]+/)*[^/?#&]+)' _TESTS = [{ 'url': 'https://www.pornhub.com/model/zoe_ph/videos', 'only_matching': True, }, { 'url': 'http://www.pornhub.com/users/rushandlia/videos', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos', 'info_dict': { 'id': 'pornstar/jenny-blighe/videos', }, 'playlist_mincount': 149, }, { 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos?page=3', 'info_dict': { 'id': 'pornstar/jenny-blighe/videos', }, 'playlist_mincount': 40, }, { # default sorting as Top Rated Videos 'url': 'https://www.pornhub.com/channels/povd/videos', 'info_dict': { 'id': 'channels/povd/videos', }, 'playlist_mincount': 293, }, { # Top Rated Videos 'url': 'https://www.pornhub.com/channels/povd/videos?o=ra', 'only_matching': True, }, { # Most Recent Videos 'url': 'https://www.pornhub.com/channels/povd/videos?o=da', 'only_matching': True, }, { # Most Viewed Videos 'url': 'https://www.pornhub.com/channels/povd/videos?o=vi', 'only_matching': True, }, { 'url': 'http://www.pornhub.com/users/zoe_ph/videos/public', 'only_matching': True, }, { # Most Viewed Videos 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=mv', 'only_matching': True, }, { # Top Rated Videos 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=tr', 'only_matching': True, }, { # Longest Videos 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=lg', 'only_matching': True, }, { # Newest Videos 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos?o=cm', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos/paid', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/pornstar/liz-vicious/videos/fanonly', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/video', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/video?page=3', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/video/search?search=123', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/categories/teen', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/categories/teen?page=3', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/hd', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/hd?page=3', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/described-video', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/described-video?page=2', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/video/incategories/60fps-1/hd-porn', 'only_matching': True, }, { 'url': 'https://www.pornhub.com/playlist/44121572', 'info_dict': { 'id': 'playlist/44121572', }, 'playlist_mincount': 132, }, { 'url': 'https://www.pornhub.com/playlist/4667351', 'only_matching': True, }, { 'url': 'https://de.pornhub.com/playlist/4667351', 'only_matching': True, }] @classmethod def suitable(cls, url): return (False if PornHubIE.suitable(url) or PornHubUserIE.suitable(url) or PornHubUserVideosUploadIE.suitable(url) else super(PornHubPagedVideoListIE, cls).suitable(url)) class PornHubUserVideosUploadIE(PornHubPagedPlaylistBaseIE): _VALID_URL = r'(?P<url>https?://(?:[^/]+\.)?(?P<host>pornhub(?:premium)?\.(?:com|net|org))/(?:(?:user|channel)s|model|pornstar)/(?P<id>[^/]+)/videos/upload)' _TESTS = [{ 'url': 'https://www.pornhub.com/pornstar/jenny-blighe/videos/upload', 'info_dict': { 'id': 'jenny-blighe', }, 'playlist_mincount': 129, }, { 'url': 'https://www.pornhub.com/model/zoe_ph/videos/upload', 'only_matching': True, }] ```
[ { "content": "```python\n#! /usr/bin/python3\n\n## Hackish example script to compare some results output by process-discogs-chunks.py\n##\n## Licensed under the terms of the General Public License version 3\n##\n## SPDX-License-Identifier: GPL-3.0\n##\n## Copyright 2017-2019 - Armijn Hemel\n\nimport os\nimport ...
[ { "content": "<|memory_start|>```python\n#! /usr/bin/python3\n\n## Hackish example script to compare some results output by process-discogs-chunks.py\n##\n## Licensed under the terms of the General Public License version 3\n##\n## SPDX-License-Identifier: GPL-3.0\n##\n## Copyright 2017-2019 - Armijn Hemel\n\nim...
```python #! /usr/bin/python3 ## Hackish example script to compare some results output by process-discogs-chunks.py ## ## Licensed under the terms of the General Public License version 3 ## ## SPDX-License-Identifier: GPL-3.0 ## ## Copyright 2017-2019 - Armijn Hemel import os import sys import argparse def main(): parser = argparse.ArgumentParser() # the following options are provided on the commandline parser.add_argument("-f", "--first", action="store", dest="first", help="path to first file", metavar="FILE") parser.add_argument("-s", "--second", action="store", dest="second", help="path to second file", metavar="FILE") parser.add_argument("-a", "--all", action="store", dest="all", help="path to all hashes (example: sha256-201909", metavar="FILE") parser.add_argument("-p", "--printchanged", action="store_true", dest="printchanged", help="print changed entries instead of statistics") args = parser.parse_args() # then some sanity checks for the data files if args.first is None: parser.error("Path to first file missing") if not os.path.exists(args.first): parser.error("First file %s does not exist" % args.first) if args.second is None: parser.error("Path to second file missing") if not os.path.exists(args.second): parser.error("Second file %s does not exist" % args.second) if args.all is None: parser.error("Path to file with all hashes missing") if not os.path.exists(args.all): parser.error("All hashes file %s does not exist" % args.all) all_releases = set() try: shafile1 = open(args.all, 'r') except: print("Could not open %s, exiting" % args.all, file=sys.stderr) sys.exit(1) for i in shafile1: (release_id, sha) = i.split('\t') release = release_id.split('.')[0] all_releases.add(release) release_to_status1 = {} notacceptedfile1 = open(args.first, 'r') for i in notacceptedfile1: (release_id, status) = i.split('\t') release = release_id.split('.')[0] release_to_status1[release] = i[1].strip() notacceptedfile1.close() release_to_status2 = {} notacceptedfile2 = open(args.second, 'r') for i in notacceptedfile2: (release_id, status) = i.split('\t') release = release_id.split('.')[0] release_to_status2[release] = i[1].strip() notacceptedfile2.close() notkeys1 = set(release_to_status1.keys()) notkeys2 = set(release_to_status2.keys()) print("%d releases in not1 that are not in not2" % len(notkeys1.difference(notkeys2))) print("%d releases in not2 that are not in not1" % len(notkeys2.difference(notkeys1))) for i in sorted(notkeys1.difference(notkeys2)): print(i, i in all_releases) if __name__ == "__main__": main() ```
[ { "content": "Here is the code content:\n```python\n###\n### this script assigns most voted class to corems\n###\n\nimport sys\n\n# 0. user defined variables\ngene2ClassFile='/Volumes/omics4tb/alomana/projects/TLR/data/annotation/si.table.1.si.ribosomal.protein.index.information.csv'\ngeneDictionaryFile='/Volum...
[ { "content": "Here is the code content:\n<|memory_start|>```python\n###\n### this script assigns most voted class to corems\n###\n\nimport sys\n\n# 0. user defined variables\ngene2ClassFile='/Volumes/omics4tb/alomana/projects/TLR/data/annotation/si.table.1.si.ribosomal.protein.index.information.csv'\ngeneDictio...
```python ### ### this script assigns most voted class to corems ### import sys # 0. user defined variables gene2ClassFile='/Volumes/omics4tb/alomana/projects/TLR/data/annotation/si.table.1.si.ribosomal.protein.index.information.csv' geneDictionaryFile='/Volumes/omics4tb/alomana/projects/TLR/data/annotation/si.table.1.gene.dictionary.csv' coremsFile='/Volumes/omics4tb/alomana/projects/TLR/data/annotation/si.table.1.corem.index.information.txt' outputFile='/Volumes/omics4tb/alomana/projects/TLR/data/annotation/coremClasses.csv' acceptedClasses=['Blue','Red','Green','Magenta'] # 1. building a dictionary of names synonyms={} with open(geneDictionaryFile,'r') as f: for line in f: vector=line.split(',') geneName=vector[1] riboName=vector[2].replace('\n','') synonyms[geneName]=riboName # 2. associate genes to class gene2Class={} with open(gene2ClassFile,'r') as f: for line in f: vector=line.split(',') name=vector[1] theClass=vector[2] if theClass in acceptedClasses: gene2Class[synonyms[name]]=theClass # 3. associate corems to class g=open(outputFile,'w') g.write('coremID,ribosomal.class\n') coremClasses={} with open(coremsFile,'r') as f: next(f) for line in f: vector=line.split('\t') coremID=int(vector[1]) pre=vector[4] pro=pre.split(',') pru=[element.replace('"','') for element in pro] proteins=[element.replace(' ','') for element in pru] foundClasses=[gene2Class[element] for element in proteins] democracy=max(set(foundClasses), key=foundClasses.count) g.write('corem.{},{}\n'.format(coremID,democracy.lower())) print(democracy) g.close() ```
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n```python\n#!/usr/bin/env python\n\nfrom settings import *\nimport os.path, Tkinter, tkFont, tkFileDialog\nimport taxonutils\n\n\nclass TaxonLinker():\n\n def __init__(self,root):\n \n self.taxondict = DICTIONARY_FILE\n self.nameslist =...
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n<|memory_start|>```python\n#!/usr/bin/env python\n\nfrom settings import *\nimport os.path, Tkinter, tkFont, tkFileDialog\nimport taxonutils\n\n\nclass TaxonLinker():\n\n def __init__(self,root):\n \n self.taxondict = DICTIONARY_FILE\n ...
```python #!/usr/bin/env python from settings import * import os.path, Tkinter, tkFont, tkFileDialog import taxonutils class TaxonLinker(): def __init__(self,root): self.taxondict = DICTIONARY_FILE self.nameslist = [] self.results = [] self.dictload = False self.nmload = False # options and format definitions sans10px = tkFont.Font(family='Arial',size=-15) button_opt = {'padx': 5, 'pady': 5, 'side': Tkinter.LEFT} entry_opt = {'padx': 5, 'pady': 5, 'side': Tkinter.LEFT, 'fill': Tkinter.X, 'expand': 1} self.ftypes=(('Text files', '*.txt'),('CSV files', '*.csv'), ('All files','*.*')) # loading buttons frame buttonframe = Tkinter.Frame(root) Tkinter.Button(buttonframe,text='Load Dictionary', command=self.load_dict).pack(**button_opt) Tkinter.Button(buttonframe,text='Load Names', command=self.load_names).pack(**button_opt) buttonframe.pack(fill=Tkinter.X,expand=1) # current taxon frame taxonframe = Tkinter.Frame(root) self.taxonentry = Tkinter.Text(taxonframe,width='110',height='2', wrap='word',font=sans10px) self.taxonentry.pack(**entry_opt) Tkinter.Button(taxonframe,text='Check Updated Name', command=self.check_updated).pack(**button_opt) taxonframe.pack(fill=Tkinter.X,expand=1) # select frame with buttons on the right Tkinter.Label(root,text='Select correct taxon:').pack(side=Tkinter.TOP, anchor=Tkinter.W,padx=5) selectframe = Tkinter.Frame(root) self.select = Tkinter.Listbox(selectframe,width=100,height=8,font=sans10px) self.select.bind('<<ListboxSelect>>') self.select.pack(side=Tkinter.LEFT,fill=Tkinter.BOTH,expand=1, anchor=Tkinter.W,padx=5,pady=5) buttonframe = Tkinter.Frame(selectframe) self.savebtn = Tkinter.Button(buttonframe,text='Save', state=Tkinter.DISABLED, command=self.save) self.savebtn.pack(fill=Tkinter.BOTH,padx=5,pady=5) self.skipbtn = Tkinter.Button(buttonframe,text='Skip', state=Tkinter.DISABLED, command=self.skip) self.skipbtn.pack(fill=Tkinter.BOTH,padx=5,pady=5) buttonframe.pack(side=Tkinter.LEFT,padx=5,pady=5,anchor=Tkinter.W) selectframe.pack(anchor=Tkinter.NW,fill=Tkinter.BOTH,expand=1) # status bar at the bottom self.status = Tkinter.Label(root,text='') self.status.pack(side=Tkinter.LEFT,anchor=Tkinter.W,padx=5,pady=5) # check if dictionary file exists, and if so, load it if os.path.isfile(self.taxondict): self.dictionary = taxonutils.TaxonIndex(self.taxondict) self.dictload = True # check if there's a current batch of names, and if so, load it if os.path.isfile(CURRENT_BATCH): with open(CURRENT_BATCH,'r') as f: for line in f: self.nameslist.append(line.strip()) self.nmload = True self.readnext() self.update_status() def load_dict(self): self.taxondict = tkFileDialog.askopenfilename(filetypes=self.ftypes, title="Please select dictionary file") if self.taxondict: self.dictionary = taxonutils.TaxonIndex(self.taxondict) self.dictload = True self.update_status() def load_names(self): fn = tkFileDialog.askopenfilename(filetypes=self.ftypes, title="Please select input names file") if fn: self.nameslist = [] with open(fn,'r') as f: for line in f: self.nameslist.append(line.rstrip('\n')) self.nmload = True self.readnext() def check_updated(self): self.process_taxon() def save(self,taxon=''): """log current taxon to output file""" # Todo: handle case when relatedResourceID field is not in the dictionary if taxon == '': taxon = self.results[int(self.select.curselection()[0])] if 'taxonomicStatus' in self.dictionary.taxonindex[taxon].keys(): if self.dictionary.taxonindex[taxon]['taxonomicStatus'].lower() == \ 'synonym' and self.dictionary.taxonindex[taxon]\ ['relatedResourceID'] != '': # if it's a synonym, save the linked ID for the synonym self.log(self.nameslist[0].strip()+FIELD_SEP+self.dictionary.\ taxonindex[taxon]['relatedResourceID'],OUTPUT_FILE) if self.dictionary.taxonindex[taxon]['taxonomicStatus'].lower() not in \ ['accepted','valid','synonym']: # if the status is not valid or synonym, save it to work on separately self.log(self.nameslist[0].strip()+FIELD_SEP+self.dictionary.\ taxonindex[taxon]['taxonID'],NOTVALID_FILE) else: # if it's not a synonym save the ID self.log(self.nameslist[0].strip()+FIELD_SEP+self.dictionary.\ taxonindex[taxon]['taxonID'],OUTPUT_FILE) else: # if there's no taxonomicStatus field, just save the taxonID self.log(self.nameslist[0].strip()+FIELD_SEP+self.dictionary.\ taxonindex[taxon]['taxonID'],OUTPUT_FILE) self.skip('save') def skip(self,reason='button'): """Log skipped name with reason, and move to the next record.""" if reason == 'genus': self.log(self.nameslist[0].strip()+" (couldn't find genus)",LOGFILE) elif reason == 'button': self.log(self.nameslist[0].strip()+" (skip button)",LOGFILE) if len(self.nameslist) > 1: self.nameslist = self.nameslist[1:] self.taxonentry.delete('1.0','end') self.taxonentry.insert('1.0',self.nameslist[0].strip()) self.readnext() else: self.nameslist = [] self.taxonentry.delete('1.0','end') self.taxonentry.insert('1.0','No more unmatched names.') self.savebtn.configure(state=Tkinter.DISABLED) self.skipbtn.configure(state=Tkinter.DISABLED) self.nmload = False def update_status(self): """Update the status bar.""" if not self.dictload and not self.nmload: self.status.configure(text="Dictionary not loaded; Names not loaded.") elif self.dictload and not self.nmload: s = '{:,}'.format(len(self.dictionary.taxonindex)) self.status.configure(text="Dictionary loaded with %s taxa; Names not " "loaded." % s) elif not self.dictload and self.nmload: s = '{:,}'.format(len(self.nameslist)) self.status.configure(text="Dictionary not loaded; %s names remaining to " "process." % s) elif self.dictload and self.nmload: self.savebtn.configure(state=Tkinter.NORMAL) self.skipbtn.configure(state=Tkinter.NORMAL) s = ('{:,}'.format(len(self.dictionary.taxonindex)), '{:,}'.format(len(self.nameslist))) self.status.configure(text="Dictionary loaded with %s taxa; %s names " "remaining to process." % s) else: self.status.configure(text="Error updating status.") def log(self,s,f): """Driver for writing text to a specified log file.""" d = os.path.dirname(f) if not os.path.exists(d) and not d=='': os.makedirs(d) open(f, 'a+').writelines(s.strip() + '\n') def process_taxon(self): """Uses certainty cutoff levels to automatically skip or match taxa, and ask the user if uncertain. """ self.select.delete(0,'end') #First look for genus match to speed up performance genus = self.dictionary.matchgenera(self.taxonentry.get('1.0','end'), 1,GENUS_CUTOFF) if len(genus) > 0: self.results = self.dictionary.matchtaxa(self.taxonentry.get('1.0','end'), genus[0],8,FUZZY_CUTOFF) if len(self.results) > 0: # if first match is good enough, save automatically, else wait for user # to skip or select and save. if taxonutils.ratio(self.taxonentry.get('1.0','end'), self.results[0]) >= PERFECT_CUTOFF: self.select.select_set(0) self.log(self.nameslist[0].strip() + " -> " + self.results[0],AUTOLOG) self.save(self.results[0]) else: for taxon in self.results: if 'taxonomicStatus' in self.dictionary.taxonindex[taxon].keys(): if self.dictionary.taxonindex[taxon]['taxonomicStatus'].lower()\ in ['current', 'valid']: self.select.insert('end',taxon) elif self.dictionary.taxonindex[taxon]['taxonomicStatus'].lower()\ == 'synonym' and self.dictionary.taxonindex[taxon]\ ['relatedResourceID'] != '': synonym = self.dictionary.idindex[self.dictionary.\ taxonindex[taxon]['relatedResourceID']]['scientificName'] self.select.insert('end',"*" + taxon + " = " + synonym) else: self.select.insert('end',"*" + taxon + " (not current)") else: self.select.insert('end',taxon) self.select.select_set(0) else: self.skip('genus') def readnext(self): """Load the next name to be processed.""" if self.nameslist is not None and len(self.nameslist) > 0: self.taxonentry.delete('1.0','end') self.taxonentry.insert('1.0',self.nameslist[0]) self.process_taxon() self.update_status() else: raise TypeError("No names to process.") def on_exit(self): """Write current file on exit.""" if len(self.nameslist)>0: with open(CURRENT_BATCH,'w+') as f: for n in self.nameslist: f.write(n+'\n') root.destroy() else: try: os.remove(CURRENT_BATCH) except OSError: pass root.destroy() if __name__=='__main__': root = Tkinter.Tk() root.wm_title("Taxon Linker") myapp = TaxonLinker(root) root.protocol("WM_DELETE_WINDOW", myapp.on_exit) root.mainloop() ```
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n```python\nimport logging\nfrom pyvisdk.exceptions import InvalidArgumentError\n\n########################################\n# Automatically generated, do not edit.\n########################################\n\nlog = logging.getLogger(__name__)\n...
[ { "content": "Reconstruct the code file line-for-line, unmodified:\n<|memory_start|>```python\nimport logging\nfrom pyvisdk.exceptions import InvalidArgumentError\n\n########################################\n# Automatically generated, do not edit.\n########################################\n\nlog = logging.getLo...
```python import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def GuestWindowsFileAttributes(vim, *args, **kwargs): '''Different attributes for a Windows guest file.''' obj = vim.client.factory.create('ns0:GuestWindowsFileAttributes') # do some validation checking... if (len(args) + len(kwargs)) < 0: raise IndexError('Expected at least 1 arguments got: %d' % len(args)) required = [ ] optional = [ 'createTime', 'hidden', 'readOnly', 'accessTime', 'modificationTime', 'symlinkTarget', 'dynamicProperty', 'dynamicType' ] for name, arg in zip(required+optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, name, value) else: raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) return obj ```
[ { "content": "Here is a code file:\n```python\n# Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS\r\n# \r\n# This file is part of PyAnalyzer.\r\n#\r\n# PyAnalyzer is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as published by\r\n# the ...
[ { "content": "Here is a code file:\n<|memory_start|>```python\n# Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS\r\n# \r\n# This file is part of PyAnalyzer.\r\n#\r\n# PyAnalyzer is free software: you can redistribute it and/or modify\r\n# it under the terms of the GNU General Public License as publis...
```python # Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS # # This file is part of PyAnalyzer. # # PyAnalyzer 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/>. # or see <http://www.opensource.org/licenses/gpl-3.0.html> # # Contact: # Junior FLEURIAL MONFILS <frederic dot fleurialmonfils at cetic dot be> __author__ = "Frederic F. MONFILS" __version__ = "$Revision: $".split()[1] __revision__ = __version__ # $Source: $ __date__ = "$Date: $" __copyright__ = "Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS" __license__ = "GPLv3" __contact__ = "ffm at cetic.be" import compiler from core.metric import Metric class HalsteadLength(Metric): """Halstead Lenght of a (Project, Module, Function) The program length (N) is the sum of the total number of operators and operands in the module or function: N = N1 + N2 source: http://www.verifysoft.com/en_halstead_metrics.html """ requires = ('HalsteadMeasures',) def countHalsteadLength(self, node, *args): n1, n2, N1, N2 = node.HalsteadMeasures node.HalsteadLength = N1 + N2 visitFunction = countHalsteadLength def visitProject(self, node, *args): self.countHalsteadLength(node) self.default(node) visitModule = visitProject ```
[ { "content": "Repeat the code exactly:\n```python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function, division, absolute_import\n\n#\n# Copyright (c) 2011 Red Hat, Inc.\n#\n# This software is licensed to you under the GNU General Public\n# License as published by the Free Software Foundation; eit...
[ { "content": "Repeat the code exactly:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function, division, absolute_import\n\n#\n# Copyright (c) 2011 Red Hat, Inc.\n#\n# This software is licensed to you under the GNU General Public\n# License as published by the Free Software...
```python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import # # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the implied warranties of MERCHANTABILITY, # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should # have received a copy of GPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # try: import unittest2 as unittest except ImportError: import unittest import os import logging import random import shutil import socket import tempfile import time from mock import Mock, patch, mock_open # used to get a user readable cfg class for test cases from .stubs import StubProduct, StubProductCertificate, StubCertificateDirectory, \ StubEntitlementCertificate, StubPool, StubEntitlementDirectory from .fixture import SubManFixture from rhsm import ourjson as json from subscription_manager.cache import ProfileManager, \ InstalledProductsManager, EntitlementStatusCache, \ PoolTypeCache, ReleaseStatusCache, ContentAccessCache, \ PoolStatusCache, ContentAccessModeCache, SupportedResourcesCache, \ AvailableEntitlementsCache from rhsm.profile import Package, RPMProfile, EnabledReposProfile, ModulesProfile from rhsm.connection import RestlibException, UnauthorizedException, \ RateLimitExceededException from subscription_manager import injection as inj from subscription_manager import isodate, cache log = logging.getLogger(__name__) class _FACT_MATCHER(object): def __eq__(self, other): return True FACT_MATCHER = _FACT_MATCHER() CONTENT_REPO_FILE = """ [awesome-os-for-x86_64-upstream-rpms] name = Awesome OS for x86_64 - Upstream (RPMs) baseurl = https://cdn.awesome.com/content/dist/awesome/$releasever/x86_64/upstream/os enabled = 1 gpgcheck = 1 gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-awesome-release sslverify = 1 sslcacert = /etc/rhsm/ca/awesome-uep.pem sslclientkey = /etc/pki/entitlement/0123456789012345678-key.pem sslclientcert = /etc/pki/entitlement/0123456789012345678.pem metadata_expire = 86400 ui_repoid_vars = releasever [awesome-os-for-x86_64-debug-rpms] name = Awesome OS for x86_64 - Debug (RPMs) baseurl = https://cdn.awesome.com/content/dist/awesome/$releasever/x86_64/upstream/debug enabled = 0 gpgcheck = 1 gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-awesome-release sslverify = 1 sslcacert = /etc/rhsm/ca/awesome-uep.pem sslclientkey = /etc/pki/entitlement/0123456789012345678-key.pem sslclientcert = /etc/pki/entitlement/0123456789012345678.pem metadata_expire = 86400 ui_repoid_vars = releasever """ ENABLED_MODULES = [ { "name": "duck", "stream": 0, "version": "20180730233102", "context": "deadbeef", "arch": "noarch", "profiles": ["default"], "installed_profiles": [], "status": "enabled" }, { "name": "flipper", "stream": 0.69, "version": "20180707144203", "context": "c0ffee42", "arch": "x86_64", "profiles": ["default", "server"], "installed_profiles": ["server"], "status": "unknown" } ] class TestProfileManager(unittest.TestCase): def setUp(self): current_pkgs = [ Package(name="package1", version="1.0.0", release=1, arch="x86_64"), Package(name="package2", version="2.0.0", release=2, arch="x86_64") ] temp_repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_repo_dir) repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo') with open(repo_file_name, 'w') as repo_file: repo_file.write(CONTENT_REPO_FILE) patcher = patch('rhsm.profile.dnf') self.addCleanup(patcher.stop) dnf_mock = patcher.start() dnf_mock.dnf = Mock() mock_db = Mock() mock_db.conf = Mock() mock_db.conf.substitutions = {'releasever': '1', 'basearch': 'x86_64'} dnf_mock.dnf.Base = Mock(return_value=mock_db) self.current_profile = self._mock_pkg_profile(current_pkgs, repo_file_name, ENABLED_MODULES) self.profile_mgr = ProfileManager() self.profile_mgr.current_profile = self.current_profile @patch('subscription_manager.cache.get_supported_resources') def test_update_check_no_change(self, mock_get_supported_resources): mock_get_supported_resources.return_value = ['packages'] uuid = 'FAKEUUID' uep = Mock() uep.updatePackageProfile = Mock() self.profile_mgr.has_changed = Mock(return_value=False) self.profile_mgr.write_cache = Mock() self.profile_mgr.update_check(uep, uuid) self.assertEqual(0, uep.updatePackageProfile.call_count) self.assertEqual(0, self.profile_mgr.write_cache.call_count) @patch('subscription_manager.cache.get_supported_resources') def test_update_check_has_changed(self, mock_get_supported_resources): mock_get_supported_resources.return_value = ['packages'] uuid = 'FAKEUUID' uep = Mock() uep.has_capability = Mock(return_value=False) uep.updatePackageProfile = Mock() self.profile_mgr.has_changed = Mock(return_value=True) self.profile_mgr.write_cache = Mock() self.profile_mgr.update_check(uep, uuid, True) uep.updatePackageProfile.assert_called_with(uuid, FACT_MATCHER) self.assertEqual(1, self.profile_mgr.write_cache.call_count) @patch('subscription_manager.cache.get_supported_resources') def test_combined_profile_update_check_has_changed(self, mock_get_supported_resources): mock_get_supported_resources.return_value = ["packages"] uuid = 'FAKEUUID' uep = Mock() uep.has_capability = Mock(return_value=True) uep.updateCombinedProfile = Mock() self.profile_mgr.has_changed = Mock(return_value=True) self.profile_mgr.write_cache = Mock() self.profile_mgr.update_check(uep, uuid, True) uep.updateCombinedProfile.assert_called_with(uuid, FACT_MATCHER) self.assertEqual(1, self.profile_mgr.write_cache.call_count) @patch('subscription_manager.cache.get_supported_resources') def test_update_check_packages_not_supported(self, mock_get_supported_resources): # support anything else but not 'packages' mock_get_supported_resources.return_value = ['foo', 'bar'] uuid = 'FAKEUUID' uep = Mock() uep.updatePackageProfile = Mock() self.profile_mgr.has_changed = Mock(return_value=True) self.profile_mgr.write_cache = Mock() self.profile_mgr.update_check(uep, uuid) self.assertEqual(0, uep.updatePackageProfile.call_count) mock_get_supported_resources.assert_called_once() self.assertEqual(0, self.profile_mgr.write_cache.call_count) @patch('subscription_manager.cache.get_supported_resources') def test_update_check_packages_disabled(self, mock_get_supported_resources): mock_get_supported_resources.return_value = ['packages'] uuid = 'FAKEUUID' uep = Mock() self.profile_mgr.report_package_profile = 0 uep.updatePackageProfile = Mock() self.profile_mgr.has_changed = Mock(return_value=True) self.profile_mgr.write_cache = Mock() self.profile_mgr.update_check(uep, uuid) self.assertEqual(0, uep.updatePackageProfile.call_count) mock_get_supported_resources.assert_called_once() self.assertEqual(0, self.profile_mgr.write_cache.call_count) def test_report_package_profile_environment_variable(self): with patch.dict('os.environ', {'SUBMAN_DISABLE_PROFILE_REPORTING': '1'}), \ patch.object(cache, 'conf') as conf: # report_package_profile is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is set to 1, the # package profile should not be reported. conf.__getitem__.return_value.get_int.return_value = 1 self.assertFalse(self.profile_mgr.profile_reporting_enabled()) # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is set # to 1, the package profile should not be reported. conf.__getitem__.return_value.get_int.return_value = 0 self.assertFalse(self.profile_mgr.profile_reporting_enabled()) with patch.dict('os.environ', {'SUBMAN_DISABLE_PROFILE_REPORTING': '0'}), \ patch.object(cache, 'conf') as conf: # report_package_profile in rhsm.conf is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is set # to 0, the package profile should be reported. conf.__getitem__.return_value.get_int.return_value = 1 self.assertTrue(self.profile_mgr.profile_reporting_enabled()) # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is set # to 0, the package profile should not be reported. conf.__getitem__.return_value.get_int.return_value = 0 self.assertFalse(self.profile_mgr.profile_reporting_enabled()) with patch.dict('os.environ', {}), patch.object(cache, 'conf') as conf: # report_package_profile in rhsm.conf is set to 1 and SUBMAN_DISABLE_PROFILE_REPORTING is not # set, the package profile should be reported. conf.__getitem__.return_value.get_int.return_value = 1 self.assertTrue(self.profile_mgr.profile_reporting_enabled()) # report_package_profile in rhsm.conf is set to 0 and SUBMAN_DISABLE_PROFILE_REPORTING is not # set, the package profile should not be reported. conf.__getitem__.return_value.get_int.return_value = 0 self.assertFalse(self.profile_mgr.profile_reporting_enabled()) @patch('subscription_manager.cache.get_supported_resources') def test_update_check_error_uploading(self, mock_get_supported_resources): mock_get_supported_resources.return_value = ['packages'] uuid = 'FAKEUUID' uep = Mock() uep.has_capability = Mock(return_value=False) self.profile_mgr.has_changed = Mock(return_value=True) self.profile_mgr.write_cache = Mock() # Throw an exception when trying to upload: uep.updatePackageProfile = Mock(side_effect=Exception('BOOM!')) self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid, True) uep.updatePackageProfile.assert_called_with(uuid, FACT_MATCHER) self.assertEqual(0, self.profile_mgr.write_cache.call_count) @patch('subscription_manager.cache.get_supported_resources') def test_combined_profile_update_check_error_uploading(self, mock_get_supported_resources): mock_get_supported_resources.return_value = ['packages'] uuid = 'FAKEUUID' uep = Mock() uep.has_capability = Mock(return_value=True) self.profile_mgr.has_changed = Mock(return_value=True) self.profile_mgr.write_cache = Mock() # Throw an exception when trying to upload: uep.updateCombinedProfile = Mock(side_effect=Exception('BOOM!')) self.assertRaises(Exception, self.profile_mgr.update_check, uep, uuid, True) uep.updateCombinedProfile.assert_called_with(uuid, FACT_MATCHER) self.assertEqual(0, self.profile_mgr.write_cache.call_count) def test_has_changed_no_cache(self): self.profile_mgr._cache_exists = Mock(return_value=False) self.assertTrue(self.profile_mgr.has_changed()) def test_has_changed_no_changes(self): cached_pkgs = [ Package(name="package1", version="1.0.0", release=1, arch="x86_64"), Package(name="package2", version="2.0.0", release=2, arch="x86_64") ] temp_repo_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_repo_dir) repo_file_name = os.path.join(temp_repo_dir, 'awesome.repo') with open(repo_file_name, 'w') as repo_file: repo_file.write(CONTENT_REPO_FILE) cached_profile = self._mock_pkg_profile(cached_pkgs, repo_file_name, ENABLED_MODULES) self.profile_mgr._cache_exists = Mock(return_value=True) self.profile_mgr._read_cache = Mock(return_value=cached_profile) self.assertFalse(self.profile_mgr.has_changed()) self.profile_mgr._read_cache.assert_called_with() def test_has_changed(self): cached_pkgs = [ Package(name="package1", version="1.0.0", release=1, arch="x86_64"), Package(name="package3", version="3.0.0", release=3, arch="x86_64") ] cached_profile = self._mock_pkg_profile(cached_pkgs, "/non/existing/path/to/repo/file", []) self.profile_mgr._cache_exists = Mock(return_value=True) self.profile_mgr._read_cache = Mock(return_value=cached_profile) self.assertTrue(self.profile_mgr.has_changed()) self.profile_mgr._read_cache.assert_called_with() @patch('subscription_manager.cache.get_supported_resources') def test_update_check_consumer_uuid_none(self, mock_get_supported_resources): mock_get_supported_resources.return_value = ['packages'] uuid = None uep = Mock() self.profile_mgr.has_changed = Mock(return_value=True) self.profile_mgr.write_cache = Mock() res = self.profile_mgr.update_check(uep, uuid) self.assertEqual(0, res) def test_package_json_handles_non_unicode(self): package = Package(name=b'\xf6', version=b'\xf6', release=b'\xf6', arch=b'\xf6', vendor=b'\xf6') data = package.to_dict() json_str = json.dumps(data) # to json data = json.loads(json_str) # and back to an object for attr in ['name', 'version', 'release', 'arch', 'vendor']: self.assertEqual(u'\ufffd', data[attr]) def test_package_json_as_unicode_type(self): # note that the data type at time of writing is bytes, so this is just defensive coding package = Package(name=u'Björk', version=u'Björk', release=u'Björk', arch=u'Björk', vendor=u'Björk') data = package.to_dict() json_str = json.dumps(data) # to json data = json.loads(json_str) # and back to an object for attr in ['name', 'version', 'release', 'arch', 'vendor']: self.assertEqual(u'Björk', data[attr]) def test_package_json_missing_attributes(self): package = Package(name=None, version=None, release=None, arch=None, vendor=None) data = package.to_dict() json_str = json.dumps(data) # to json data = json.loads(json_str) # and back to an object for attr in ['name', 'version', 'release', 'arch', 'vendor']: self.assertEqual(None, data[attr]) def test_module_md_uniquify(self): modules_input = [ { "name": "duck", "stream": 0, "version": "20180730233102", "context": "deadbeef", "arch": "noarch", "profiles": ["default"], "installed_profiles": [], "status": "enabled" }, { "name": "duck", "stream": 0, "version": "20180707144203", "context": "c0ffee42", "arch": "noarch", "profiles": ["default", "server"], "installed_profiles": ["server"], "status": "unknown" } ] self.assertEqual(modules_input, ModulesProfile._uniquify(modules_input)) # now test dup modules self.assertEqual(modules_input, ModulesProfile._uniquify(modules_input + [modules_input[0]])) @staticmethod def _mock_pkg_profile(packages, repo_file, enabled_modules): """ Turn a list of package objects into an RPMProfile object. """ dict_list = [] for pkg in packages: dict_list.append(pkg.to_dict()) mock_file = Mock() mock_file.read = Mock(return_value=json.dumps(dict_list)) mock_rpm_profile = RPMProfile(from_file=mock_file) mock_enabled_repos_profile = EnabledReposProfile(repo_file=repo_file) mock_module_profile = ModulesProfile() mock_module_profile.collect = Mock(return_value=enabled_modules) mock_profile = { "rpm": mock_rpm_profile, "enabled_repos": mock_enabled_repos_profile, "modulemd": mock_module_profile } return mock_profile class TestInstalledProductsCache(SubManFixture): def setUp(self): super(TestInstalledProductsCache, self).setUp() self.prod_dir = StubCertificateDirectory([ StubProductCertificate(StubProduct('a-product', name="Product A", provided_tags="product,product-a")), StubProductCertificate(StubProduct('b-product', name="Product B", provided_tags="product,product-b")), StubProductCertificate(StubProduct('c-product', name="Product C", provided_tags="product-c")), ]) inj.provide(inj.PROD_DIR, self.prod_dir) self.mgr = InstalledProductsManager() def test_cert_parsing(self): self.assertEqual(3, len(list(self.mgr.installed.keys()))) self.assertTrue('a-product' in self.mgr.installed) self.assertTrue('b-product' in self.mgr.installed) self.assertTrue('c-product' in self.mgr.installed) self.assertEqual("Product A", self.mgr.installed['a-product']['productName']) self.assertEqual(set(["product", "product-a", "product-b", "product-c"]), set(self.mgr.tags)) def test_load_data(self): cached = { 'products': { 'prod1': 'Product 1', 'prod2': 'Product 2' }, 'tags': ['p1', 'p2'] } mock_file = Mock() mock_file.read = Mock(return_value=json.dumps(cached)) data = self.mgr._load_data(mock_file) self.assertEqual(data, cached) def test_has_changed(self): cached = { 'products': { 'prod1': 'Product 1', 'prod2': 'Product 2' }, 'tags': ['p1', 'p2'] } self.mgr._read_cache = Mock(return_value=cached) self.mgr._cache_exists = Mock(return_value=True) self.assertTrue(self.mgr.has_changed()) def test_has_changed_with_tags_only(self): cached = { 'products': { 'a-product': {'productName': 'Product A', 'productId': 'a-product', 'version': '1.0', 'arch': 'x86_64'}, 'b-product': {'productName': 'Product B', 'productId': 'b-product', 'version': '1.0', 'arch': 'x86_64'}, 'c-product': {'productName': 'Product C', 'productId': 'c-product', 'version': '1.0', 'arch': 'x86_64'} }, 'tags': ['different'] } self.mgr._read_cache = Mock(return_value=cached) self.mgr._cache_exists = Mock(return_value=True) self.assertTrue(self.mgr.has_changed()) def test_old_format_seen_as_invalid(self): cached = { 'a-product': {'productName': 'Product A', 'productId': 'a-product', 'version': '1.0', 'arch': 'x86_64'}, 'b-product': {'productName': 'Product B', 'productId': 'b-product', 'version': '1.0', 'arch': 'x86_64'}, 'c-product': {'productName': 'Product C', 'productId': 'c-product', 'version': '1.0', 'arch': 'x86_64'} } self.mgr._read_cache = Mock(return_value=cached) self.mgr._cache_exists = Mock(return_value=True) self.assertTrue(self.mgr.has_changed()) def test_has_not_changed(self): cached = { 'products': { 'a-product': {'productName': 'Product A', 'productId': 'a-product', 'version': '1.0', 'arch': 'x86_64'}, 'b-product': {'productName': 'Product B', 'productId': 'b-product', 'version': '1.0', 'arch': 'x86_64'}, 'c-product': {'productName': 'Product C', 'productId': 'c-product', 'version': '1.0', 'arch': 'x86_64'} }, 'tags': ['product-a', 'product-b', 'product-c', 'product'] } self.mgr._read_cache = Mock(return_value=cached) self.mgr._cache_exists = Mock(return_value=True) self.assertFalse(self.mgr.has_changed()) def test_update_check_no_change(self): uuid = 'FAKEUUID' uep = Mock() uep.updateConsumer = Mock() self.mgr.has_changed = Mock(return_value=False) self.mgr.write_cache = Mock() self.mgr.update_check(uep, uuid) self.assertEqual(0, uep.updateConsumer.call_count) self.assertEqual(0, self.mgr.write_cache.call_count) def test_update_check_has_changed(self): uuid = 'FAKEUUID' uep = Mock() uep.updateConsumer = Mock() self.mgr.has_changed = Mock(return_value=True) self.mgr.write_cache = Mock() self.mgr.update_check(uep, uuid, True) expected = ["product", "product-a", "product-b", "product-c"] uep.updateConsumer.assert_called_with(uuid, content_tags=set(expected), installed_products=self.mgr.format_for_server()) self.assertEqual(1, self.mgr.write_cache.call_count) def test_update_check_error_uploading(self): uuid = 'FAKEUUID' uep = Mock() self.mgr.has_changed = Mock(return_value=True) self.mgr.write_cache = Mock() # Throw an exception when trying to upload: uep.updateConsumer = Mock(side_effect=Exception('BOOM!')) self.assertRaises(Exception, self.mgr.update_check, uep, uuid, True) expected = ["product", "product-a", "product-b", "product-c"] uep.updateConsumer.assert_called_with(uuid, content_tags=set(expected), installed_products=self.mgr.format_for_server()) self.assertEqual(0, self.mgr.write_cache.call_count) class TestReleaseStatusCache(SubManFixture): def setUp(self): super(TestReleaseStatusCache, self).setUp() self.release_cache = ReleaseStatusCache() self.release_cache.write_cache = Mock() def test_load_from_server(self): uep = Mock() dummy_release = {'releaseVer': 'MockServer'} uep.getRelease = Mock(return_value=dummy_release) self.release_cache.read_status(uep, "THISISAUUID") self.assertEqual(dummy_release, self.release_cache.server_status) def test_server_no_release_call(self): uep = Mock() uep.getRelease = Mock(side_effect=RestlibException("boom")) status = self.release_cache.read_status(uep, "SOMEUUID") self.assertEqual(None, status) def test_server_network_error_no_cache(self): uep = Mock() uep.getRelease = Mock(side_effect=socket.error("boom")) self.release_cache._cache_exists = Mock(return_value=False) self.assertEqual(None, self.release_cache.read_status(uep, "SOMEUUID")) def test_server_network_error_with_cache(self): uep = Mock() uep.getRelease = Mock(side_effect=socket.error("boom")) dummy_release = {'releaseVer': 'MockServer'} self.release_cache._read_cache = Mock(return_value=dummy_release) self.release_cache._cache_exists = Mock(return_value=True) self.assertEqual(dummy_release, self.release_cache.read_status(uep, "SOMEUUID")) def test_rate_limit_exceed_with_cache(self): uep = Mock() uep.getRelease = Mock(side_effect=RateLimitExceededException(429)) dummy_release = {'releaseVer': 'MockServer'} self.release_cache._read_cache = Mock(return_value=dummy_release) self.release_cache._cache_exists = Mock(return_value=True) self.assertEqual(dummy_release, self.release_cache.read_status(uep, "SOMEUUID")) def test_server_network_works_with_cache(self): uep = Mock() dummy_release = {'releaseVer': 'MockServer'} uep.getRelease = Mock(return_value=dummy_release) self.release_cache._cache_exists = Mock(return_value=True) self.release_cache._read_cache = Mock(return_value=dummy_release) self.assertEqual(dummy_release, self.release_cache.read_status(uep, "SOMEUUID")) self.assertEqual(1, self.release_cache.write_cache.call_count) self.assertEqual(0, self.release_cache._read_cache.call_count) self.assertEqual(dummy_release, self.release_cache.read_status(uep, "SOMEUUID")) self.assertEqual(1, uep.getRelease.call_count) def test_server_network_works_cache_caches(self): uep = Mock() dummy_release = {'releaseVer': 'MockServer'} uep.getRelease = Mock(return_value=dummy_release) self.release_cache._cache_exists = Mock(return_value=False) self.release_cache.server_status = None self.release_cache._read_cache = Mock(return_value=dummy_release) self.assertEqual(dummy_release, self.release_cache.read_status(uep, "SOMEUUID")) self.assertEqual(1, self.release_cache.write_cache.call_count) self.assertEqual(0, self.release_cache._read_cache.call_count) self.release_cache._cache_exists = Mock(return_value=True) self.assertEqual(dummy_release, self.release_cache.read_status(uep, "SOMEUUID")) self.assertEqual(1, self.release_cache.write_cache.call_count) self.assertEqual(1, uep.getRelease.call_count) class TestEntitlementStatusCache(SubManFixture): def setUp(self): super(TestEntitlementStatusCache, self).setUp() self.status_cache = EntitlementStatusCache() self.status_cache.write_cache = Mock() def test_load_from_server(self): uep = Mock() dummy_status = {"a": "1"} uep.getCompliance = Mock(return_value=dummy_status) self.status_cache.load_status(uep, "SOMEUUID") self.assertEqual(dummy_status, self.status_cache.server_status) self.assertEqual(1, self.status_cache.write_cache.call_count) def test_load_from_server_on_date_args(self): uep = Mock() dummy_status = {"a": "1"} uep.getCompliance = Mock(return_value=dummy_status) self.status_cache.load_status(uep, "SOMEUUID", "2199-12-25") self.assertEqual(dummy_status, self.status_cache.server_status) self.assertEqual(1, self.status_cache.write_cache.call_count) def test_load_from_server_on_date_kwargs(self): uep = Mock() dummy_status = {"a": "1"} uep.getCompliance = Mock(return_value=dummy_status) self.status_cache.load_status(uep, "SOMEUUID", on_date="2199-12-25") self.assertEqual(dummy_status, self.status_cache.server_status) self.assertEqual(1, self.status_cache.write_cache.call_count) def test_server_no_compliance_call(self): uep = Mock() uep.getCompliance = Mock(side_effect=RestlibException("boom")) status = self.status_cache.load_status(uep, "SOMEUUID") self.assertEqual(None, status) def test_server_network_error(self): dummy_status = {"a": "1"} uep = Mock() uep.getCompliance = Mock(side_effect=socket.error("boom")) self.status_cache._cache_exists = Mock(return_value=True) self.status_cache._read_cache = Mock(return_value=dummy_status) status = self.status_cache.load_status(uep, "SOMEUUID") self.assertEqual(dummy_status, status) self.assertEqual(1, self.status_cache._read_cache.call_count) # Extremely unlikely but just in case: def test_server_network_error_no_cache(self): uep = Mock() uep.getCompliance = Mock(side_effect=socket.error("boom")) self.status_cache._cache_exists = Mock(return_value=False) self.assertEqual(None, self.status_cache.load_status(uep, "SOMEUUID")) def test_write_cache(self): mock_server_status = {'fake server status': random.uniform(1, 2 ** 32)} status_cache = EntitlementStatusCache() status_cache.server_status = mock_server_status cache_dir = tempfile.mkdtemp() cache_file = os.path.join(cache_dir, 'status_cache.json') status_cache.CACHE_FILE = cache_file status_cache.write_cache() # try to load the file 5 times, if # we still can't read it, fail # we don't know when the write_cache thread ends or # when it starts. Need to track the cache threads # but we do not... tries = 0 while tries <= 5: try: new_status_buf = open(cache_file).read() new_status = json.loads(new_status_buf) break except Exception as e: log.exception(e) tries += 1 time.sleep(.1) continue shutil.rmtree(cache_dir) self.assertEqual(new_status, mock_server_status) def test_unauthorized_exception_handled(self): uep = Mock() uep.getCompliance = Mock(side_effect=UnauthorizedException(401, "GET")) self.assertEqual(None, self.status_cache.load_status(uep, "aaa")) class TestPoolStatusCache(SubManFixture): """ Class for testing PoolStatusCache """ def setUp(self): super(TestPoolStatusCache, self).setUp() self.pool_status_cache = PoolStatusCache() self.pool_status_cache.write_cache = Mock() def test_load_data(self): cached = { 'pools': { 'pool1': 'Pool 1', 'pool2': 'Pool 2' }, 'tags': ['p1', 'p2'] } mock_file = Mock() mock_file.read = Mock(return_value=json.dumps(cached)) data = self.pool_status_cache._load_data(mock_file) self.assertEqual(data, cached) def test_load_from_server(self): uep = Mock() dummy_pools = { 'pools': { 'pool1': 'Pool 1', 'pool2': 'Pool 2' }, 'tags': ['p1', 'p2'] } uep.getEntitlementList = Mock(return_value=dummy_pools) self.pool_status_cache.read_status(uep, "THISISAUUID") self.assertEqual(dummy_pools, self.pool_status_cache.server_status) class TestPoolTypeCache(SubManFixture): """ Class for testing PoolTypeCache """ def setUp(self): super(TestPoolTypeCache, self).setUp() self.cp_provider = inj.require(inj.CP_PROVIDER) self.cp_provider.consumer_auth_cp = Mock() self.cp = self.cp_provider.consumer_auth_cp certs = [StubEntitlementCertificate(StubProduct('pid1'), pool=StubPool('someid'))] self.ent_dir = StubEntitlementDirectory(certificates=certs) self.pool_cache = inj.require(inj.POOL_STATUS_CACHE) self.pool_cache.write_cache = Mock() def test_empty_cache(self): pooltype_cache = PoolTypeCache() result = pooltype_cache.get("some id") self.assertEqual('', result) def test_get_pooltype(self): self.cp.getEntitlementList.return_value = [self._build_ent_json('poolid', 'some type')] pooltype_cache = PoolTypeCache() pooltype_cache._do_update() result = pooltype_cache.get("poolid") self.assertEqual('some type', result) def test_requires_update(self): pooltype_cache = PoolTypeCache() pooltype_cache.ent_dir = self.ent_dir # Doesn't have data for pool with id 'someid' self.assertTrue(pooltype_cache.requires_update()) pooltype_cache.pooltype_map['someid'] = 'some type' # After adding data for that entitlements pool, it shouldn't need an update self.assertFalse(pooltype_cache.requires_update()) def test_update(self): pooltype_cache = PoolTypeCache() pooltype_cache.ent_dir = self.ent_dir self.cp.getEntitlementList.return_value = [ self._build_ent_json('poolid', 'some type'), self._build_ent_json('poolid2', 'some other type')] # requires_update should be true, and should allow this method # to generate a correct mapping pooltype_cache.update() self.assertEqual(2, len(pooltype_cache.pooltype_map)) self.assertEqual('some type', pooltype_cache.get('poolid')) self.assertEqual('some other type', pooltype_cache.get('poolid2')) # This is populated when available subs are refreshed def test_update_from_pools(self): # Input is a map of pool ids to pool json pools_map = {} for i in range(5): pool_id = 'poolid' + str(i) pools_map[pool_id] = self._build_pool_json(pool_id, 'some type') pooltype_cache = PoolTypeCache() pooltype_cache.update_from_pools(pools_map) self.assertEqual(5, len(pooltype_cache.pooltype_map)) for i in range(5): expected_id = 'poolid' + str(i) self.assertEqual('some type', pooltype_cache.get(expected_id)) def test_requires_update_ents_with_no_pool(self): pooltype_cache = PoolTypeCache() pooltype_cache.ent_dir = self.ent_dir for ent in self.ent_dir.certs: ent.pool = None # No ents have pools so there is nothing we can update self.assertFalse(pooltype_cache.requires_update()) def test_reading_pool_type_from_json_cache(self): pool_status = [self._build_ent_json('poolid', 'some type')] self.pool_cache.load_status = Mock() self.pool_cache.server_status = pool_status pooltype_cache = PoolTypeCache() pooltype_cache._do_update() result = pooltype_cache.get("poolid") self.assertEqual('some type', result) def _build_ent_json(self, pool_id, pool_type): result = {} result['id'] = "1234" result['pool'] = self._build_pool_json(pool_id, pool_type) return result def _build_pool_json(self, pool_id, pool_type): return {'id': pool_id, 'calculatedAttributes': {'compliance_type': pool_type}} class TestContentAccessCache(SubManFixture): MOCK_CONTENT = { "lastUpdate": "2016-12-01T21:56:35+0000", "contentListing": {"42": ["cert-part1", "cert-part2"]} } MOCK_CONTENT_EMPTY_CONTENT_LISTING = { "lastUpdate": "2016-12-01T21:56:35+0000", "contentListing": None } MOCK_CERT = """ before -----BEGIN ENTITLEMENT DATA----- entitlement data goes here -----END ENTITLEMENT DATA----- after """ MOCK_OPEN_EMPTY = mock_open() MOCK_OPEN_CACHE = mock_open(read_data=json.dumps(MOCK_CONTENT)) def setUp(self): super(TestContentAccessCache, self).setUp() self.cache = ContentAccessCache() self.cache.cp_provider = Mock() self.mock_uep = Mock() self.mock_uep.getAccessibleContent = Mock(return_value=self.MOCK_CONTENT) self.cache.cp_provider.get_consumer_auth_cp = Mock(return_value=self.mock_uep) self.cache.identity = Mock() self.cert = Mock() @patch('subscription_manager.cache.open', MOCK_OPEN_EMPTY) def test_empty_cache(self): self.assertFalse(self.cache.exists()) @patch('subscription_manager.cache.open', MOCK_OPEN_EMPTY) def test_writes_to_cache_after_read(self): self.cache.check_for_update() self.MOCK_OPEN_EMPTY.assert_any_call(ContentAccessCache.CACHE_FILE, 'w') self.MOCK_OPEN_EMPTY().write.assert_any_call(json.dumps(self.MOCK_CONTENT)) @patch('subscription_manager.cache.open', MOCK_OPEN_EMPTY) def test_cert_updated_after_read(self): self.cert.serial = 42 update_data = self.cache.check_for_update() self.cache.update_cert(self.cert, update_data) self.MOCK_OPEN_EMPTY.assert_any_call(self.cert.path, 'w') self.MOCK_OPEN_EMPTY().write.assert_any_call(''.join(self.MOCK_CONTENT['contentListing']['42'])) @patch('subscription_manager.cache.open', MOCK_OPEN_CACHE) def test_check_for_update_provides_date(self): mock_exists = Mock(return_value=True) with patch('os.path.exists', mock_exists): self.cache.check_for_update() date = isodate.parse_date("2016-12-01T21:56:35+0000") self.mock_uep.getAccessibleContent.assert_called_once_with(self.cache.identity.uuid, if_modified_since=date) @patch('os.path.exists', Mock(return_value=True)) def test_cache_remove_deletes_file(self): mock_remove = Mock() with patch('os.remove', mock_remove): self.cache.remove() mock_remove.assert_called_once_with(ContentAccessCache.CACHE_FILE) @patch('subscription_manager.cache.open', MOCK_OPEN_EMPTY) def test_cache_handles_empty_content_listing(self): self.mock_uep.getAccessibleContent = Mock(return_value=self.MOCK_CONTENT_EMPTY_CONTENT_LISTING) self.cache.check_for_update() # getting this far means we did not raise an exception :-) @patch('subscription_manager.cache.open', MOCK_OPEN_EMPTY) def test_cache_fails_server_issues_gracefully(self): self.mock_uep.getAccessibleContent = Mock(side_effect=RestlibException(404)) self.cache.check_for_update() # getting this far means we did not raise an exception :-) class TestContentAccessModeCache(SubManFixture): MOCK_CACHE_FILE_CONTENT = '{"7f85da06-5c35-44ba-931d-f11f6e581f89": "entitlement"}' def setUp(self): super(TestContentAccessModeCache, self).setUp() self.cache = ContentAccessModeCache() def test_reading_nonexisting_cache(self): data = self.cache.read_cache_only() self.assertIsNone(data) def test_reading_existing_cache(self): temp_cache_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_cache_dir) self.cache.CACHE_FILE = os.path.join(temp_cache_dir, 'content_access_mode.json') with open(self.cache.CACHE_FILE, 'w') as cache_file: cache_file.write(self.MOCK_CACHE_FILE_CONTENT) data = self.cache.read_cache_only() self.assertTrue("7f85da06-5c35-44ba-931d-f11f6e581f89" in data) self.assertEqual(data["7f85da06-5c35-44ba-931d-f11f6e581f89"], "entitlement") class TestSupportedResourcesCache(SubManFixture): MOCK_CACHE_FILE_CONTENT = '{"a3f43883-315b-4cc4-bfb5-5771946d56d7": {"": "/", "cdn": "/cdn"}}' MOCK_SUPPORTED_RESOURCES_RESPONSE = {"pools": "/pools", "roles": "/roles", "users": "/users"} def setUp(self): super(TestSupportedResourcesCache, self).setUp() self.cache = SupportedResourcesCache() def test_reading_nonexisting_cache(self): data = self.cache.read_cache_only() self.assertIsNone(data) def test_reading_existing_cache(self): temp_cache_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_cache_dir) self.cache.CACHE_FILE = os.path.join(temp_cache_dir, 'supported_resources.json') with open(self.cache.CACHE_FILE, 'w') as cache_file: cache_file.write(self.MOCK_CACHE_FILE_CONTENT) data = self.cache.read_cache_only() self.assertTrue("a3f43883-315b-4cc4-bfb5-5771946d56d7" in data) self.assertEqual(data["a3f43883-315b-4cc4-bfb5-5771946d56d7"], {"": "/", "cdn": "/cdn"}) def test_cache_is_obsoleted_by_new_identity(self): temp_cache_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_cache_dir) self.cache.CACHE_FILE = os.path.join(temp_cache_dir, 'supported_resources.json') with open(self.cache.CACHE_FILE, 'w') as cache_file: cache_file.write(self.MOCK_CACHE_FILE_CONTENT) mock_uep = Mock() mock_uep.get_supported_resources = Mock(return_value=self.MOCK_SUPPORTED_RESOURCES_RESPONSE) mock_identity = Mock() mock_identity.uuid = 'f0000000-aaaa-bbbb-bbbb-5771946d56d8' data = self.cache.read_data(uep=mock_uep, identity=mock_identity) self.assertEqual(data, self.MOCK_SUPPORTED_RESOURCES_RESPONSE) def test_cache_is_obsoleted_by_timeout(self): old_timeout = self.cache.TIMEOUT self.cache.TIMEOUT = 1 temp_cache_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_cache_dir) self.cache.CACHE_FILE = os.path.join(temp_cache_dir, 'supported_resources.json') with open(self.cache.CACHE_FILE, 'w') as cache_file: cache_file.write(self.MOCK_CACHE_FILE_CONTENT) mock_uep = Mock() mock_uep.get_supported_resources = Mock(return_value=self.MOCK_SUPPORTED_RESOURCES_RESPONSE) mock_identity = Mock() mock_identity.uuid = 'a3f43883-315b-4cc4-bfb5-5771946d56d7' time.sleep(2) data = self.cache.read_data(uep=mock_uep, identity=mock_identity) self.assertEqual(data, self.MOCK_SUPPORTED_RESOURCES_RESPONSE) self.cache.TIMEOUT = old_timeout class TestAvailableEntitlementsCache(SubManFixture): MOCK_CACHE_FILE_CONTENT = '''{ "b1002709-6d67-443e-808b-a7afcbe5b47e": { "filter_options": { "after_date": null, "future": null, "match_installed": null, "matches": "*fakeos*", "no_overlap": null, "on_date": null, "service_level": null, "show_all": null }, "pools": [ { "addons": null, "attributes": [], "contractNumber": "0", "endDate": "01/16/2021", "id": "ff8080816fb38f78016fb392d26f0267", "management_enabled": false, "pool_type": "Standard", "productId": "fakeos-bits", "productName": "Fake OS Bits", "providedProducts": { "38072": "Fake OS Bits" }, "quantity": "5", "roles": null, "service_level": null, "service_type": null, "startDate": "01/17/2020", "suggested": 1, "usage": null } ], "timeout": 1579613054.079684 } } ''' def setUp(self): super(TestAvailableEntitlementsCache, self).setUp() self.cache = AvailableEntitlementsCache() def test_reading_nonexisting_cache(self): """ Test reading cache, when there is no cache file yet """ data = self.cache.read_cache_only() self.assertIsNone(data) def test_reading_existing_cache(self): """ Test reading cache from file """ temp_cache_dir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, temp_cache_dir) self.cache.CACHE_FILE = os.path.join(temp_cache_dir, 'available_entitlements.json') with open(self.cache.CACHE_FILE, 'w') as cache_file: cache_file.write(self.MOCK_CACHE_FILE_CONTENT) data = self.cache.read_cache_only() self.assertTrue("b1002709-6d67-443e-808b-a7afcbe5b47e" in data) self.assertEqual(data["b1002709-6d67-443e-808b-a7afcbe5b47e"]["timeout"], 1579613054.079684) self.assertEqual(data["b1002709-6d67-443e-808b-a7afcbe5b47e"]["filter_options"]["matches"], "*fakeos*") self.assertEqual(len(data["b1002709-6d67-443e-808b-a7afcbe5b47e"]["pools"]), 1) def test_timeout(self): """ Test computing timeout of cache based on smoothed response time (SRT) """ uep = inj.require(inj.CP_PROVIDER).get_consumer_auth_cp() uep.conn.smoothed_rt = 3.0 timeout = self.cache.timeout() self.assertTrue(timeout >= self.cache.LBOUND) self.assertTrue(timeout <= self.cache.UBOUND) def test_timeout_no_srt(self): """ Test computing timeout, when there is no SRT yet """ uep = inj.require(inj.CP_PROVIDER).get_consumer_auth_cp() uep.conn.smoothed_rt = None timeout = self.cache.timeout() self.assertEqual(timeout, self.cache.LBOUND) def test_min_timeout(self): """ Test computing timout, when SRT is smaller than lower bound """ uep = inj.require(inj.CP_PROVIDER).get_consumer_auth_cp() uep.conn.smoothed_rt = 0.01 timeout = self.cache.timeout() self.assertEqual(timeout, self.cache.LBOUND) def test_max_timeout(self): """ Test computing timout, when SRT is bigger than upper bound """ uep = inj.require(inj.CP_PROVIDER).get_consumer_auth_cp() uep.conn.smoothed_rt = 20.0 timeout = self.cache.timeout() self.assertEqual(timeout, self.cache.UBOUND) ```
[ { "content": "Here is the source code:\n```python\n# -*- coding: UTF-8 -*-\n\n# © Copyright 2009 Wolodja Wentland. All Rights Reserved.\n\n# This file is part of wp-import.\n#\n# wp-import is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as publishe...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# -*- coding: UTF-8 -*-\n\n# © Copyright 2009 Wolodja Wentland. All Rights Reserved.\n\n# This file is part of wp-import.\n#\n# wp-import is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public Lic...
```python # -*- coding: UTF-8 -*- # © Copyright 2009 Wolodja Wentland. All Rights Reserved. # This file is part of wp-import. # # wp-import 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. # # wp-import 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 wp-import. If not, see <http://www.gnu.org/licenses/>. """Tests for wp_import.postgresql """ from __future__ import absolute_import from __future__ import unicode_literals import os import re import tempfile from nose.tools import * import wp_import.utils as wpi_utils import wp_import.postgresql as wpi_psql PREFIX = os.path.join(*os.path.split(os.path.dirname(__file__))[:-1]) TEST_DATA_DIR = os.path.join(PREFIX, 'test', 'data') DOWNLOAD_DIR = os.path.join(TEST_DATA_DIR, 'download') EXPECTED_STMTS = { 'categorylinks': [ """INSERT INTO "categorylinks" VALUES """ \ "(130,'Linux','Linux\u5185\u6838','2006-07-25T19:03:22Z')"], 'langlinks': [ """INSERT INTO "langlinks" VALUES """ \ "(43017,'af','Dante Alighieri')"], 'pagelinks': [ """INSERT INTO "pagelinks" VALUES (12,0,'P/NP\u554f\u984c')"""], 'redirect': [ """INSERT INTO "redirect" VALUES (71247,0,'ASCII\u827a\u672f')"""]} class FakeOptions(object): pass def test_insert_statements(): fn_pat = re.compile( r'''(?P<language>\w+)wiki-(?P<date>\d{8})-(?P<table>[\w_]+).*''') for dump_path in sorted(wpi_utils.find('*.sql.gz', DOWNLOAD_DIR)): filename = os.path.basename(dump_path) mat = fn_pat.match(filename) stmts = list(wpi_psql.insert_statements(dump_path)) eq_(list(wpi_psql.insert_statements(dump_path)), EXPECTED_STMTS[mat.group('table')]) def test_categorylink_pipeline(): for file_path in wpi_utils.find('*categorylinks*.sql.gz', DOWNLOAD_DIR): with wpi_utils.open_compressed(file_path) as cl_file: eq_(list(wpi_psql.categorylinks_pipeline(cl_file)), EXPECTED_STMTS['categorylinks']) def test_psql_quotation(): eq_(list(wpi_psql.psql_quotation(['f `b`', 'baz', 'shrubbery ``'])), ['f "b"', 'baz', 'shrubbery ""']) def test_timestamp_to_iso_8601(): eq_(list(wpi_psql.timestamp_to_iso_8601([',20080218135752) foo'])), [",'2008-02-18T13:57:52Z') foo"]) def test_parse_pgpass(): with tempfile.NamedTemporaryFile() as tmp_f: tmp_f.write('*:*:*:*:GrailQuest\n') tmp_f.seek(0) eq_(wpi_psql._parse_pgpass(tmp_f.name).next(), {'user': '*', 'host': '*', 'port': '*', 'database': '*', 'password': 'GrailQuest'}) tmp_f.write('hostname:port:database:username:password\n') tmp_f.seek(0) eq_(wpi_psql._parse_pgpass(tmp_f.name).next(), {'user': 'username', 'host': 'hostname', 'port': 'port', 'database': 'database', 'password': 'password'}) def test_password_from_pgpass(): with tempfile.NamedTemporaryFile() as tmp_f: options = FakeOptions() options.pg_passfile = tmp_f.name options.pg_user = 'KingArthur' options.pg_port = '2342' options.pg_host = 'Camelot' # test generic pgpass line tmp_f.write('*:*:*:*:GrailQuest\n') tmp_f.seek(0) eq_(wpi_psql.password_from_pgpass(options), 'GrailQuest') # test specific pgpass line tmp_f.write('Camelot:2342:postgres:KingArthur:GrailQuest\n') tmp_f.seek(0) eq_(wpi_psql.password_from_pgpass(options), 'GrailQuest') # test pick most specific tmp_f.write('Jerusalem:2342:postgres:Brian:Jehova\n') tmp_f.write('Camelot:2342:postgres:KingArthur:GrailQuest\n') tmp_f.write('*:*:*:*:UnladenSwallow\n') tmp_f.seek(0) eq_(wpi_psql.password_from_pgpass(options), 'GrailQuest') tmp_f.write('*:*:*:*\n') tmp_f.seek(0) assert_raises(KeyError, wpi_psql.password_from_pgpass, options=options) ```
[ { "content": "Here is the code block:\n```python\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport traceback\n\nimport lxml.etree\n\nfrom django.core.management.base import BaseCommand\nfrom fs.osfs import OSFS\nfrom path import Path as path\nfrom xmodule.modulestore.xml import XMLModuleSt...
[ { "content": "Here is the code block:\n<|memory_start|>```python\nfrom __future__ import print_function\n\nimport os\nimport sys\nimport traceback\n\nimport lxml.etree\n\nfrom django.core.management.base import BaseCommand\nfrom fs.osfs import OSFS\nfrom path import Path as path\nfrom xmodule.modulestore.xml im...
```python from __future__ import print_function import os import sys import traceback import lxml.etree from django.core.management.base import BaseCommand from fs.osfs import OSFS from path import Path as path from xmodule.modulestore.xml import XMLModuleStore def traverse_tree(course): """ Load every descriptor in course. Return bool success value. """ queue = [course] while len(queue) > 0: node = queue.pop() queue.extend(node.get_children()) return True def export(course, export_dir): """ Export the specified course to course_dir. Creates dir if it doesn't exist. Overwrites files, does not clean out dir beforehand. """ fs = OSFS(export_dir, create=True) if not fs.isdirempty('.'): print(u'WARNING: Directory {dir} not-empty. May clobber/confuse things'.format(dir=export_dir)) try: course.runtime.export_fs = fs root = lxml.etree.Element('root') course.add_xml_to_node(root) with fs.open('course.xml', mode='w') as f: root.write(f) return True except: print('Export failed!') traceback.print_exc() return False def import_with_checks(course_dir): all_ok = True print(u'Attempting to load "{}"'.format(course_dir)) course_dir = path(course_dir) data_dir = course_dir.dirname() source_dirs = [course_dir.basename()] # No default class--want to complain if it doesn't find plugins for any # module. modulestore = XMLModuleStore( data_dir, default_class=None, source_dirs=source_dirs ) def str_of_err(tpl): (msg, exc_str) = tpl return '{msg}\n{exc}'.format(msg=msg, exc=exc_str) courses = modulestore.get_courses() n = len(courses) if n != 1: print(u'ERROR: Expect exactly 1 course. Loaded {n}: {lst}'.format(n=n, lst=courses)) return (False, None) course = courses[0] errors = modulestore.get_course_errors(course.id) if len(errors) != 0: all_ok = False print( '\n' + '========================================' + 'ERRORs during import:' + '\n'.join(map(str_of_err, errors)) + '========================================' + '\n' ) # print course validators = ( traverse_tree, ) print('========================================') print('Running validators...') for validate in validators: print(u'Running {}'.format(validate.__name__)) all_ok = validate(course) and all_ok if all_ok: print('Course passes all checks!') else: print('Course fails some checks. See above for errors.') return all_ok, course def check_roundtrip(course_dir): """ Check that import->export leaves the course the same """ print('====== Roundtrip import =======') (ok, course) = import_with_checks(course_dir) if not ok: raise Exception('Roundtrip import failed!') print('====== Roundtrip export =======') export_dir = course_dir + '.rt' export(course, export_dir) # dircmp doesn't do recursive diffs. # diff = dircmp(course_dir, export_dir, ignore=[], hide=[]) print('======== Roundtrip diff: =========') sys.stdout.flush() # needed to make diff appear in the right place os.system(u'diff -r {} {}'.format(course_dir, export_dir)) print('======== ideally there is no diff above this =======') class Command(BaseCommand): help = 'Imports specified course, validates it, then exports it in a canonical format.' def add_arguments(self, parser): parser.add_argument('course_dir', help='path to the input course directory') parser.add_argument('output_dir', help='path to the output course directory') parser.add_argument('--force', action='store_true', help='export course even if there were import errors') def handle(self, *args, **options): course_dir = options['course_dir'] output_dir = options['output_dir'] force = options['force'] (ok, course) = import_with_checks(course_dir) if ok or force: if not ok: print('WARNING: Exporting despite errors') export(course, output_dir) check_roundtrip(output_dir) else: print('Did NOT export') ```
[ { "content": "```python\n#\n# Copyright (c) 2020 SUNET\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyri...
[ { "content": "<|memory_start|>```python\n#\n# Copyright (c) 2020 SUNET\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain ...
```python # # Copyright (c) 2020 SUNET # All rights reserved. # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # 3. Neither the name of the SUNET 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # from enum import unique from eduid_common.api.messages import TranslatableMsg @unique class PDataMsg(TranslatableMsg): """ Messages sent to the front end with information on the results of the attempted operations on the back end. """ # successfully saved personal data save_success = 'pd.save-success' # validation error: missing required field required = 'pdata.field_required' # validation error: illegal characters special_chars = 'only allow letters' ```
[ { "content": "Repeat the code exactly as the original, including blank lines:\n```python\n\"\"\"\nUtil functions\n\"\"\"\nimport os\nimport shlex\nfrom subprocess import Popen, PIPE\n\nfrom six import string_types\n\nfrom .exceptions import ShellError\nfrom . import report\n\n\nclass ShellOutput(str):\n def ...
[ { "content": "Repeat the code exactly as the original, including blank lines:\n<|memory_start|>```python\n\"\"\"\nUtil functions\n\"\"\"\nimport os\nimport shlex\nfrom subprocess import Popen, PIPE\n\nfrom six import string_types\n\nfrom .exceptions import ShellError\nfrom . import report\n\n\nclass ShellOutput...
```python """ Util functions """ import os import shlex from subprocess import Popen, PIPE from six import string_types from .exceptions import ShellError from . import report class ShellOutput(str): def __new__(cls, stdout, stderr): # Store raw stdout = stdout.strip() if stdout else '' stderr = stderr.strip() if stderr else '' # Join stdout and stderr value = stdout if stderr: if stdout: value += '\n' value += stderr self = super(ShellOutput, cls).__new__(cls, value) self.stdout = stdout self.stderr = stderr return self def shell(cmd, cd=None, stdin=None, expect_errors=False): """ Perform a shell command Arguments: cmd Shell command to execute Returns out Output string out.stdout The stdout out.stderr The stderr out.return_code The return code """ cmd_display = cmd if not isinstance(cmd, string_types): cmd = map(str, cmd) cmd_display = ' '.join(cmd) if isinstance(cmd, string_types): cmd = shlex.split(cmd) old_dir = os.getcwd() if cd: report.info('$ cd {}'.format(cd)) os.chdir(cd) report.info('$ {}'.format(cmd_display), label='shell') process = Popen(cmd, shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE) if stdin: process.stdin.write(stdin) stdout, stderr = process.communicate() out = ShellOutput(stdout, stderr) out.cmd = cmd out.return_code = process.returncode report.info(out, label='shell') if cd: os.chdir(old_dir) if not expect_errors and out.return_code != 0: msg = 'Unexpected return code {code} from {cmd}: {out}' raise ShellError(msg.format( code=out.return_code, cmd=cmd_display, out=out, )) return out ```
[ { "content": "Provide a verbatim copy of the code:\n```python\nfrom django.utils.translation import ugettext as _, ugettext_lazy \nfrom django.db.models.signals import post_syncdb\n\nimport permissions\nfrom permissions.utils import register_role, register_permission\n\n## role-related constants\nNOBODY = 'NOBO...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\nfrom django.utils.translation import ugettext as _, ugettext_lazy \nfrom django.db.models.signals import post_syncdb\n\nimport permissions\nfrom permissions.utils import register_role, register_permission\n\n## role-related constants...
```python from django.utils.translation import ugettext as _, ugettext_lazy from django.db.models.signals import post_syncdb import permissions from permissions.utils import register_role, register_permission ## role-related constants NOBODY = 'NOBODY' GAS_MEMBER = 'GAS_MEMBER' GAS_REFERRER_SUPPLIER = 'GAS_REFERRER_SUPPLIER' GAS_REFERRER_ORDER = 'GAS_REFERRER_ORDER' GAS_REFERRER_WITHDRAWAL = 'GAS_REFERRER_WITHDRAWAL' GAS_REFERRER_DELIVERY = 'GAS_REFERRER_DELIVERY' GAS_REFERRER_CASH = 'GAS_REFERRER_CASH' GAS_REFERRER_TECH = 'GAS_REFERRER_TECH' SUPPLIER_REFERRER = 'SUPPLIER_REFERRER' ROLES_LIST = [ (NOBODY, _('Nobody')), (SUPPLIER_REFERRER, _('Supplier referrer')), (GAS_MEMBER, _('GAS member')), (GAS_REFERRER_SUPPLIER, _('GAS supplier referrer')), (GAS_REFERRER_ORDER, _('GAS order referrer')), (GAS_REFERRER_WITHDRAWAL, _('GAS withdrawal referrer')), (GAS_REFERRER_DELIVERY, _('GAS delivery referrer')), (GAS_REFERRER_CASH, _('GAS cash referrer')), (GAS_REFERRER_TECH, _('GAS technical referrer')), ] valid_params_for_roles = ( ## format # (Role' codename, allowed model for 1st param, allowed model for 2nd param) (SUPPLIER_REFERRER, 'supplier.Supplier', ''), (GAS_MEMBER, 'gas.GAS', ''), (GAS_REFERRER_CASH, 'gas.GAS', '' ), (GAS_REFERRER_TECH, 'gas.GAS', ''), (GAS_REFERRER_SUPPLIER, 'gas.GAS', 'supplier.Supplier'), (GAS_REFERRER_ORDER, 'gas.GASSupplierOrder', ''), (GAS_REFERRER_WITHDRAWAL, 'gas.Withdrawal', ''), (GAS_REFERRER_DELIVERY, 'gas.Delivery', ''), ) ## permission-related constants VIEW = 'view' LIST = 'list' CREATE = 'create' EDIT = 'edit' DELETE = 'delete' ALL = 'all' # catchall PERMISSIONS_LIST = [ (VIEW, _('View')), (LIST, _('List')), (CREATE, _('Create')), (EDIT, _('Edit')), (DELETE, _('Delete')), (ALL, _('All')), # catchall ] class PermissionsRegister(object): """Support global register to hold Role and Permissions dicts""" # a dictionary holding Roles model instances, keyed by name roles_dict = {} # a dictionary holding Permission model instances, keyed by Permission's codename perms_dict = {} @property def roles(cls): return cls.roles_dict.values() @property def perms(cls): return cls.perms_dict.values() @property def role_names(cls): return cls.roles_dict.keys() @property def perm_names(cls): return cls.perms_dict.keys() def get_role(cls, code): return cls.roles_dict[code] def get_perm(cls, code): return cls.perms_dict[code] def init_permissions(sender, **kwargs): ## register project-level Roles for (name, description) in ROLES_LIST: PermissionsRegister.roles_dict[name] = register_role(name) ## register project-level Permissions for (codename, name) in PERMISSIONS_LIST: PermissionsRegister.perms_dict[codename] = register_permission(name, codename) return post_syncdb.connect(init_permissions, sender=permissions.models) ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\nimport simplejson\nimport psycopg2\nfrom types import DictType\n\n\nclass DBMSPostgreSQL:\n\n # User's parameters\n db_name = None\n username = None\n password = None\n host = None\n port = None\n ...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\nimport simplejson\nimport psycopg2\nfrom types import DictType\n\n\nclass DBMSPostgreSQL:\n\n # User's parameters\n db_name = None\n username = None\n password = None\n host = None\n p...
```python import simplejson import psycopg2 from types import DictType class DBMSPostgreSQL: # User's parameters db_name = None username = None password = None host = None port = None schema = None # Computed variables. connection = None def __init__(self, db_name, username, password, host='localhost', port=5432, schema="public"): # Store user parameters. self.db_name = db_name self.username = username self.password = password self.host = host self.port = port self.schema = schema # Connect to the DB self.connect() def __init__(self, db_settings): # Store user parameters. self.db_name = db_settings["dbname"] self.username = db_settings["username"] self.password = db_settings["password"] self.host = "localhost" if "host" not in db_settings else db_settings["host"] self.port = 5432 if "port" not in db_settings else db_settings["port"] self.schema = "public" if "schema" not in db_settings else db_settings["schema"] # Connect to the DB self.connect() def connect(self): try: self.connection = psycopg2.connect(self.get_connection_string()) self.connection.autocommit = True # set search_path to a specific schema if self.schema is not "public" and self.schema is not None: search_path = "SET search_path TO %s, public" % self.schema self.connection.cursor().execute(search_path) self.connection.commit() except Exception, e: raise Exception('Unable to connect to the DB. ' + str(e)) def query(self, sql, output_json=False): if self.check_query(sql): cur = self.connection.cursor() cur.execute(sql) rows = cur.fetchall() if output_json: return simplejson.dumps(rows) return rows else: raise Exception("Query not allowed: " + sql) def query_extented(self, select, table, where, output_json=False): sql = "SELECT " + select + " FROM " + table if where is not None: sql += " WHERE " + where if self.check_query(sql): cur = self.connection.cursor() cur.execute(sql) rows = cur.fetchall() if output_json: return simplejson.dumps(rows) return rows else: raise Exception("Query not allowed: " + sql) def select_all(self, table_name, output_json=False): cur = self.connection.cursor() cur.execute('SELECT * FROM ' + table_name) rows = cur.fetchall() if output_json: return simplejson.dumps(rows) return rows def select_by_id(self, table_name, item_id, output_json=False): cur = self.connection.cursor() cur.execute("SELECT * FROM " + table_name + " WHERE id = '" + item_id + "' ") rows = cur.fetchall() if output_json: return simplejson.dumps(rows) return rows def select_by_field(self, table_name, field_name, field_value, output_json=False): cur = self.connection.cursor() cur.execute("SELECT * FROM " + table_name + " WHERE " + field_name + " = '" + field_value + "' ") rows = cur.fetchall() if simplejson: return simplejson.dumps(rows) return rows def insert(self, table_name, item): sql = '' if type(item) is DictType: sql += "INSERT INTO " + table_name + " (" for key in item: sql += key + ',' sql = sql[0:len(sql) - 1] sql += ") VALUES (" for key in item: sql += "'" + item[key] + "'," sql = sql[0:len(sql) - 1] sql += ")" else: sql = item cur = self.connection.cursor() return cur.execute(sql) def get_connection_string(self, add_pg=False): db_connection_string = "" if add_pg is True: db_connection_string += "PG:" db_connection_string += "schemas='public,%s' " % self.schema db_connection_string += "host='%s' port=%s dbname='%s' user='%s' password='%s'" % (self.host, self.port, self.db_name, self.username, self.password) return db_connection_string # blacklist methods not allowed def check_query(self, query): q = query.lower() if "insert" in q or "update" in q or "delete" in q: return False return True def close_connection(self): if self.connection is not None: self.connection.close() def __del__(self): self.close_connection() def __exit__(self): self.close_connection() ```
[ { "content": "```python\n# python\n# Steady hands game\n# run with - sudo python SteadyRa.py\n# updated to be Revision Aware, to cope with board revisions 1 & 2 \n\nimport RPi.GPIO as GPIO\nimport time\n\ndef findRevision():\n global boardRevision\n fin = open('/proc/cpuinfo')\n boardRevision = -1\n ...
[ { "content": "<|memory_start|>```python\n# python\n# Steady hands game\n# run with - sudo python SteadyRa.py\n# updated to be Revision Aware, to cope with board revisions 1 & 2 \n\nimport RPi.GPIO as GPIO\nimport time\n\ndef findRevision():\n global boardRevision\n fin = open('/proc/cpuinfo')\n boardRe...
```python # python # Steady hands game # run with - sudo python SteadyRa.py # updated to be Revision Aware, to cope with board revisions 1 & 2 import RPi.GPIO as GPIO import time def findRevision(): global boardRevision fin = open('/proc/cpuinfo') boardRevision = -1 while True: # go through the file line by line line = fin.readline() if not line: break # end if reached the end of the file if "Revision" in line: rev = line[11:15] if rev == "0002" or rev == "0003" : boardRevision = 1 if rev == "0004" or rev == "0005" or rev == "0006" : boardRevision = 2 fin.close() if boardRevision == -1: print "Error can't find board revision" # end of function definitions # use BCM GPIO numbering - use anything else and you are an idiot! GPIO.setmode(GPIO.BCM) boardRevision = -1 findRevision() print("Hi from Python :- Steady Hands game") delay = range(0,5000) dum = 0 if boardRevision == 1: wire = 1 end_rest = 0 print "On a revision 1 board" if boardRevision == 2: wire = 3 end_rest = 2 print "On a revision 2 board" start_rest = 4 # set up GPIO input pins # (pull_up_down be PUD_OFF, PUD_UP or PUD_DOWN, default PUD_OFF) GPIO.setup(start_rest, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Physical pins 0 & 1 have hardware pull ups fitted in the Pi so don't enable them GPIO.setup(wire, GPIO.IN, pull_up_down=GPIO.PUD_OFF) GPIO.setup(end_rest, GPIO.IN, pull_up_down=GPIO.PUD_OFF) while True: #wait until the wand is at the start print("Move the loop to the start rest") while GPIO.input(start_rest) != 0: time.sleep(0.8) #now we are at the start of the bendy wire print("Start when you are ready") #wait until the loop is lifted off the wire while GPIO.input(start_rest) == 0: time.sleep(0.1) print("Your off") #time the run to the other rest penalty = 0 run_time = time.clock() while GPIO.input(end_rest) != 0: if GPIO.input(wire) == 0: penalty = penalty + 1 print("Penalties total", penalty, " points") time.sleep(0.07) score = time.clock() - run_time + (penalty * 0.07) print("The run time was", score, "seconds with", penalty, "Penalty points") #finished a run so start again ```
[ { "content": "Repeat the code precisely as written (spacing intact):\n```python\nimport sublime\n\nimport os.path\nimport shutil\nimport textwrap\nimport time\nimport uuid\n\nfrom YetAnotherCodeSearch.tests import CommandTestCase\n\n\n_NEEDLE_IN_HAYSTACK = 'cc5b252b-e7fb-5145-bf8a-ed272e3aa7bf'\n\n\nclass Csear...
[ { "content": "Repeat the code precisely as written (spacing intact):\n<|memory_start|>```python\nimport sublime\n\nimport os.path\nimport shutil\nimport textwrap\nimport time\nimport uuid\n\nfrom YetAnotherCodeSearch.tests import CommandTestCase\n\n\n_NEEDLE_IN_HAYSTACK = 'cc5b252b-e7fb-5145-bf8a-ed272e3aa7bf'\...
```python import sublime import os.path import shutil import textwrap import time import uuid from YetAnotherCodeSearch.tests import CommandTestCase _NEEDLE_IN_HAYSTACK = 'cc5b252b-e7fb-5145-bf8a-ed272e3aa7bf' class CsearchCommandTest(CommandTestCase): def setUp(self): super(CsearchCommandTest, self).setUp() if os.path.isfile(self.index): return self.window.run_command('cindex', {'index_project': True}) self._wait_for_status(self.view) assert os.path.isfile(self.index) def test_csearch_exists(self): self.assertIsNotNone(shutil.which('csearch')) def test_csearch(self): results_view = self._search(_NEEDLE_IN_HAYSTACK) expected = textwrap.dedent("""\ Searching for "{0}" {1}/test_csearch.py: 12: _NEEDLE_IN_HAYSTACK = '{0}' 1 matches across 1 files """).format(_NEEDLE_IN_HAYSTACK, self.project_path) actual = results_view.substr(sublime.Region(0, results_view.size())) self.assertEquals(expected, actual) def test_csearch_no_matches(self): query = str(uuid.uuid4()) results_view = self._search(query) expected = textwrap.dedent("""\ Searching for "{0}" No matches found """).format(query, self.project_path) actual = results_view.substr(sublime.Region(0, results_view.size())) self.assertEquals(expected, actual) def test_csearch_go_to_file(self): results_view = self._search(_NEEDLE_IN_HAYSTACK) pt = results_view.text_point(3, 10) # Line 4, 10 characters in results_view.sel().clear() results_view.sel().add(sublime.Region(pt)) self.window.run_command('code_search_results_go_to_file') self.assertEquals('{0}/test_csearch.py'.format(self.project_path), self.window.active_view().file_name()) def _wait_for_status(self, view): max_iters = 10 while max_iters > 0 and view.get_status('YetAnotherCodeSearch') != '': time.sleep(0.1) max_iters -= 1 assert '' == view.get_status('YetAnotherCodeSearch') def _search(self, query): self.window.run_command('csearch', {'query': query}) results_view = next((view for view in self.window.views() if view.name() == 'Code Search Results')) self._wait_for_status(results_view) return results_view ```
[ { "content": "Here is some code:\n```python\n# /usr/bin/env python\n'''\nWritten by Kong Xiaolu and CBIG under MIT license:\nhttps://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md\n'''\n\nimport os\nimport numpy as np\nimport torch\nimport CBIG_pMFM_basic_functions_main as fc\nimport warnings\n\n\ndef CBIG...
[ { "content": "Here is some code:\n<|memory_start|>```python\n# /usr/bin/env python\n'''\nWritten by Kong Xiaolu and CBIG under MIT license:\nhttps://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md\n'''\n\nimport os\nimport numpy as np\nimport torch\nimport CBIG_pMFM_basic_functions_main as fc\nimport warnin...
```python # /usr/bin/env python ''' Written by Kong Xiaolu and CBIG under MIT license: https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md ''' import os import numpy as np import torch import CBIG_pMFM_basic_functions_main as fc import warnings def CBIG_mfm_test_desikan_main(gpu_index=0): ''' This function is to implement the testing processes of mean field model. The objective function is the summation of FC correlation cost and FCD KS statistics cost. Args: gpu_index: index of gpu used for optimization Returns: None ''' # Setting random seed and GPU torch.cuda.set_device(gpu_index) torch.cuda.manual_seed(1) # Create output folder input_path = '../output/step2_validation_results/' output_path = '../output/step3_test_results/' if not os.path.isdir(output_path): os.makedirs(output_path) # Setting hyper-parameters n_set = 100 n_dup = 10 n_node = 68 vali_raw_all = np.zeros((3 * n_node + 1 + 8, 1)) for i in range(1, 11): load_file = 'random_initialization_' + str(i) + '.csv' load_path = os.path.join(input_path, load_file) xmin = fc.csv_matrix_read(load_path) index_mat = np.zeros((2, xmin.shape[1])) index_mat[0, :] = i index_mat[1, :] = np.arange(xmin.shape[1]) xmin = np.concatenate((index_mat, xmin), axis=0) vali_raw_all = np.concatenate((vali_raw_all, xmin), axis=1) vali_raw_all = vali_raw_all[:, 1:] vali_index = np.argsort(vali_raw_all[7, :]) vali_sort_all = vali_raw_all[:, vali_index] vali_sel_num = 10 i = 0 vali_sel = np.zeros((vali_raw_all.shape[0], vali_sel_num)) p = 0 p_set = np.zeros(vali_sel_num) while i < vali_sel_num and p < vali_raw_all.shape[1]: corr_t = np.zeros(vali_sel_num, dtype=bool) corr_tr = np.zeros((vali_sel_num, 3)) for j in range(vali_sel_num): w_corr = np.corrcoef(vali_sel[8:8 + n_node, j:j + 1].T, vali_sort_all[8:8 + n_node, p:p + 1].T) i_corr = np.corrcoef( vali_sel[8 + n_node:8 + 2 * n_node, j:j + 1].T, vali_sort_all[8 + n_node:8 + 2 * n_node, p:p + 1].T) s_corr = np.corrcoef(vali_sel[9 + 2 * n_node:, j:j + 1].T, vali_sort_all[9 + 2 * n_node:, p:p + 1].T) corr_tr[j, 0] = w_corr[0, 1] corr_tr[j, 1] = i_corr[0, 1] corr_tr[j, 2] = s_corr[0, 1] for k in range(vali_sel_num): corr_t[k] = (corr_tr[k, :] > 0.98).all() if not corr_t.any(): vali_sel[:, i] = vali_sort_all[:, p] p_set[i] = p i += 1 p += 1 result_save = np.zeros((3 * n_node + 1 + 11, vali_sel_num)) result_save[0:8, :] = vali_sel[0:8, :] result_save[11:, :] = vali_sel[8:, :] for j in range(vali_sel_num): test_cost = np.zeros((3, n_set * 10)) for k in range(10): arx = np.tile(vali_sel[8:, j:j + 1], [1, n_set]) total_cost, fc_cost, fcd_cost = fc.CBIG_combined_cost_test( arx, n_dup) test_cost[0, n_set * k:n_set * (k + 1)] = fc_cost test_cost[1, n_set * k:n_set * (k + 1)] = fcd_cost test_cost[2, n_set * k:n_set * (k + 1)] = total_cost test_file = os.path.join(output_path, 'test_num_' + str(j + 1) + '.csv') np.savetxt(test_file, test_cost, delimiter=',') result_save[8, j] = np.nanmean(test_cost[0, :]) result_save[9, j] = np.nanmean(test_cost[1, :]) result_save[10, j] = np.nanmean(test_cost[2, :]) print('**************** finish top ' + str(j + 1) + ' test ****************') test_file_all = os.path.join(output_path, 'test_all.csv') np.savetxt(test_file_all, result_save, delimiter=',') if __name__ == '__main__': warnings.filterwarnings("ignore", category=RuntimeWarning) CBIG_mfm_test_desikan_main() ```
[ { "content": "Return the code unaltered:\n```python\n#\n# Copy right YMSys, 2015,2016 Zhaoming Yin\n#\n# @brief This script performs data analytics\n# 1) it can list:\n# name, numV, numE, numCC, avgDiam, varDiam, avgCluCoeff, varCluCoeff\n# 2) it can draw distribution of \n# ...
[ { "content": "Return the code unaltered:\n<|memory_start|>```python\n#\n# Copy right YMSys, 2015,2016 Zhaoming Yin\n#\n# @brief This script performs data analytics\n# 1) it can list:\n# name, numV, numE, numCC, avgDiam, varDiam, avgCluCoeff, varCluCoeff\n# 2) it can draw dist...
```python # # Copy right YMSys, 2015,2016 Zhaoming Yin # # @brief This script performs data analytics # 1) it can list: # name, numV, numE, numCC, avgDiam, varDiam, avgCluCoeff, varCluCoeff # 2) it can draw distribution of # clique, truss # # # MODIFIED (MM/DD/YY) # stplaydog 10/21/16 - Clustering coefficient analysis # stplaydog 08/27/16 - Add data plot functions # stplaydog 08/20/16 - Implementation # stplaydog 08/07/16 - Creation # import sys import json import numpy import datetime import time import argparse from enum import Enum import glob, os import re from os.path import basename import math import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from scipy.interpolate import spline from pandas import DataFrame import pandas as pd import rpy2.robjects as robj import rpy2.robjects.pandas2ri # for dataframe conversion from rpy2.robjects.packages import importr from rpy2.robjects.lib import ggplot2 from subprocess import call import os class JsonStats: def __init__(self, file): with open(file) as data_file: data = json.load(data_file) #name_items = basename(file).replace(".json", "").split("_") #self.name = "long_" if name_items[2] == "200" else "short_" self.name = "" self.numV = data["content"]["graph property"]["numV"] self.numE = data["content"]["graph property"]["numE"] self.numCC = data["content"]["graph property"]["numCC"] numDiam = data["content"]["graph property"]["diameter"].split(",") LDiam = [float(n) for n in numDiam if n] self.avgDiam = str(numpy.average(LDiam)) self.varDiam = str(numpy.var(LDiam)) numClu = data["content"]["graph property"]["clusterCoeff"].split(",") LClu = [float(n) for n in numClu if n] self.avgCluCoeff = str(numpy.average(LClu)) self.varCluCoeff = str(numpy.var(LClu)) self.clique = self.reduce(data["content"]["graph property"]["clique"], True) self.truss = self.reduce(data["content"]["graph property"]["truss"], True) self.core = self.reduce(data["content"]["graph property"]["dbscan"], True) self.dbscan = self.reduce(data["content"]["graph property"]["core"], True) self.cliqueSize = self.reduce(data["content"]["graph property"]["clique"], False) self.trussSize = self.reduce(data["content"]["graph property"]["truss"], False) self.coreSize = self.reduce(data["content"]["graph property"]["dbscan"], False) self.dbscanSize = self.reduce(data["content"]["graph property"]["core"], False) self.cliqueSize = self.getSizeMean(self.clique, self.cliqueSize) self.trussSize = self.getSizeMean(self.truss, self.trussSize) self.coreSize = self.getSizeMean(self.core, self.coreSize) self.dbscanSize = self.getSizeMean(self.dbscan, self.dbscanSize) self.trussCoe = self.reduce(data["content"]["graph property"]["truss_coe"], False) self.coreCoe = self.reduce(data["content"]["graph property"]["dbscan_coe"], False) self.dbscanCoe = self.reduce(data["content"]["graph property"]["core_coe"], False) self.trussCoe = self.getSizeMean(self.truss, self.trussCoe) self.coreCoe = self.getSizeMean(self.core, self.coreCoe) self.dbscanCoe = self.getSizeMean(self.dbscan, self.dbscanCoe) def reduce(self, stats_str, if_freq): stats_item = {} items = stats_str.split("\n") for item in items: if item == "": continue pair = item.split(",") if int(pair[0]) in stats_item: if if_freq: stats_item[int(pair[0])] += 1 else: stats_item[int(pair[0])] += float(pair[1]) else: if if_freq: stats_item[int(pair[0])] = 1 else: stats_item[int(pair[0])] = float(pair[1]) X = [0] * len(stats_item) Y = [0] * len(stats_item) i=0 for key in stats_item: X[i] = int(key) Y[i] = stats_item[key] i+=1 return {'x':X,'y':Y} def getSizeMean(self, freq, size): for i in range(0, len(freq['y'])): size['y'][i] = float(size['y'][i]) / float(freq['y'][i]) return size def smooth_plot(self, item, plt, c, ls, mar, la): if len(item['x']) == 0: return arr = numpy.array(item['x']) xnew = numpy.linspace(arr.min(),arr.max(),300) smooth = spline(item['x'], item['y'], xnew) plt.plot(xnew, smooth, color=c, linestyle=ls, marker=mar, label = la) def plot(self, ofname): plt.plot(self.clique['x'], self.clique['y'], color='k', linestyle='-', marker=',', label = 'k-clique') plt.plot(self.truss['x'], self.truss['y'], color='k', linestyle='-', marker='.', label = 'k-truss') plt.plot(self.dbscan['x'], self.clique['y'], color='k', linestyle='-', marker='v', label = 'dbscan') plt.plot(self.core['x'], self.core['y'], color='k', linestyle='-', marker='o', label = 'k-core') plt.legend( loc='lower right', numpoints = 1, prop={'size':15} ) plt.tick_params(labelsize=15) plt.xlabel("K", fontsize=20) plt.ylabel("number of cohesive subgraphs", fontsize=20) plt.tight_layout() plt.savefig(ofname) plt.close() def summary(self): list = [self.name, str(self.numV), str(self.numE), \ str(self.numCC), str(round(self.avgDiam,2)), str(round(self.varDiam,2)), \ str(round(self.avgCluCoeff,2)), str(round(self.varCluCoeff,2)) ] return ",".join(list) class JsonStatsCollections: def __init__(self, dir, prefix): os.chdir(dir) self.coll = {} for file in glob.glob("*.json"): try: if file.find(prefix) != -1: stats = JsonStats(file) self.coll[file] = stats except Exception, e: print e print "Data Corruption in " + file def plot(self, ofname, is_freq): colors = ['k', 'b', 'r', 'g'] i = 0 for c in self.coll: if is_freq == False: self.coll[c].smooth_plot(self.coll[c].cliqueSize, plt, colors[i], '--', ',', self.coll[c].name+'-clique') self.coll[c].smooth_plot(self.coll[c].trussSize, plt, colors[i], '--', '.', self.coll[c].name+'-truss') self.coll[c].smooth_plot(self.coll[c].coreSize, plt, colors[i], '-', 'v', self.coll[c].name+'-core') self.coll[c].smooth_plot(self.coll[c].dbscanSize, plt, colors[i], '-', 'o', self.coll[c].name+'-dbscan') elif is_freq == True: plt.plot(self.coll[c].clique['x'], self.coll[c].clique['y'], color=colors[i], linestyle='--', marker=',', label = self.coll[c].name+'-clique') plt.plot(self.coll[c].truss['x'], self.coll[c].truss['y'], color=colors[i], linestyle='--', marker='.', label = self.coll[c].name+'-truss') plt.plot(self.coll[c].core['x'], self.coll[c].core['y'], color=colors[i], linestyle='-', marker='v', label = self.coll[c].name+'-core') plt.plot(self.coll[c].dbscan['x'], self.coll[c].dbscan['y'], color=colors[i], linestyle='-', marker='o', label = self.coll[c].name+'-dbscan') i += 1 plt.legend( loc=0, numpoints = 1, prop={'size':15} ) plt.tick_params(labelsize=15) plt.xlabel("K", fontsize=20) plt.ylabel("number of cohesive subgraphs", fontsize=20) plt.tight_layout() plt.savefig(ofname) plt.close() def gplot(self, ofname, is_freq): i = 0 d = [] for c in self.coll: if is_freq == 1: d = self.transformDataGgPlot(c, d) elif is_freq == 2: d = self.transformDataGgPlotSize(c, d) elif is_freq == 3: d = self.transformDataGgPlotCoe(c, d) f = DataFrame(d) print ofname f.to_csv(ofname.replace("png", "csv"), sep=',') call(["Rscript", "../../../scripts/data_analysis.R", ofname.replace("png", "csv"), ofname ]) def transformDataGgPlotSize(self, c, ret): item = self.coll[c].trussSize for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'truss', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].cliqueSize for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'clique', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].coreSize for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'core', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].dbscanSize for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'dbscan', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) def transformDataGgPlotCoe(self, c, ret): item = self.coll[c].trussCoe for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'truss_coe', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].coreCoe for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'core_coe', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].dbscanCoe for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'dbscan_coe', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) return ret def transformDataGgPlot(self, c, ret): item = self.coll[c].truss for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'truss', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].clique for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'clique', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].core for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'core', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) item = self.coll[c].dbscan for i in range(0, len(item['x'])): trip = {'data': self.coll[c].name+'dbscan', 'x': item['x'][i], 'y' : item['y'][i]} ret.append(trip) return ret def main(argv): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument("-f", "--file", action="store_true") group.add_argument("-d", "--directory", action="store_true") group.add_argument("-p", "--prefix", action="store_true") parser.add_argument("fname", help="file/directory name") args = parser.parse_args() if args.file: stats = JsonStats(args.fname) print stats.summary() ofname = args.fname.replace('json', '') + 'png' stats.plot(ofname) elif args.directory: os.chdir(args.fname) for file in glob.glob("*.json"): try: stats = JsonStats(file) print stats.summary() ofname = file.replace("json", "") + "png" stats.plot(ofname) except: print "Data Corruption in " + file elif args.prefix: config = open(args.fname) lines = config.readlines() for line in lines: if line.find("directory") != -1: dir = line.strip().split(" ")[1] if line.find("prefix") != -1: pfx = line.strip().split(" ")[1] coll = JsonStatsCollections(dir, pfx) oname1 = dir + pfx + '.png' oname2 = dir + pfx + '_size.png' oname3 = dir + pfx + '_coe.png' #coll.plot(oname2, False) #coll.plot(oname1, True) coll.gplot(oname1, 1) coll.gplot(oname2, 2) coll.gplot(oname3, 3) if __name__ == "__main__": main(sys.argv) ```
[ { "content": "Here is the code content:\n```python\nimport base64\nimport importlib\nimport sys\n\nfrom metamagic.json import dumps, dumpb, loadb\n\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = 'Import a model'\n\n def add_arguments(self, parser):\n ...
[ { "content": "Here is the code content:\n<|memory_start|>```python\nimport base64\nimport importlib\nimport sys\n\nfrom metamagic.json import dumps, dumpb, loadb\n\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n help = 'Import a model'\n\n def add_arguments(self, pa...
```python import base64 import importlib import sys from metamagic.json import dumps, dumpb, loadb from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Import a model' def add_arguments(self, parser): parser.add_argument('-i,--import', dest='import', help='File to import from') parser.add_argument('-m,--model', dest='model', help='Models to restrict to') def class_for_name(self, class_name): class_parts = class_name.split('.') module_name = '.'.join(class_parts[0:-1]) class_name = class_parts[-1] m = importlib.import_module(module_name) c = getattr(m, class_name) return c def handle(self, *args, **options): if 'import' not in options or not options['import']: print("-i <file> option required.") sys.exit(-1) models = None if 'model' in options and options['model']: models = options['model'].split(',') f = open(options['import'], "r") count = 0 errors = 0 for file_rec in f: dec_val = loadb(base64.b64decode(file_rec)) model_class = self.class_for_name(dec_val['_class']['model']) if models and model_class not in models: continue rec = model_class() for field in dec_val.keys(): if field == '_class': continue setattr(rec, field, dec_val[field]) try: rec.save() count += 1 print(" ---- SAVED") except Exception as e: errors += 1 print(" ---- ERROR - (%s) %s" % (dec_val['_class']['model'], e)) print("Added %d, Errors %d" % (count, errors)) f.close() ```
[ { "content": "Here is the source code:\n```python\n# Protocol Buffers - Google's data interchange format\n# Copyright 2008 Google Inc. All rights reserved.\n# http://code.google.com/p/protobuf/\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that...
[ { "content": "Here is the source code:\n<|memory_start|>```python\n# Protocol Buffers - Google's data interchange format\n# Copyright 2008 Google Inc. All rights reserved.\n# http://code.google.com/p/protobuf/\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitt...
```python # Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import unicode_literals """Contains metaclasses used to create protocol service and service stub classes from ServiceDescriptor objects at runtime. The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to inject all useful functionality into the classes output by the protocol compiler at compile-time. """ __author__ = 'petar@google.com (Petar Petrov)' class GeneratedServiceType(type): """Metaclass for service classes created at runtime from ServiceDescriptors. Implementations for all methods described in the Service class are added here by this class. We also create properties to allow getting/setting all fields in the protocol message. The protocol compiler currently uses this metaclass to create protocol service classes at runtime. Clients can also manually create their own classes at runtime, as in this example: mydescriptor = ServiceDescriptor(.....) MyProtoService=GeneratedServiceType('MyProtoService',(service.Service,),{'DESCRIPTOR':mydescriptor}) myservice_instance = MyProtoService() ... """ _DESCRIPTOR_KEY = 'DESCRIPTOR' def __init__(cls, name, bases, dictionary): """Creates a message service class. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type. """ # Don't do anything if this class doesn't have a descriptor. This happens # when a service class is subclassed. if GeneratedServiceType._DESCRIPTOR_KEY not in dictionary: return descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY] service_builder = _ServiceBuilder(descriptor) service_builder.BuildService(cls) class GeneratedServiceStubType(GeneratedServiceType): """Metaclass for service stubs created at runtime from ServiceDescriptors. This class has similar responsibilities as GeneratedServiceType, except that it creates the service stub classes. """ _DESCRIPTOR_KEY = 'DESCRIPTOR' def __init__(cls, name, bases, dictionary): """Creates a message service stub class. Args: name: Name of the class (ignored, here). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type. """ super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary) # Don't do anything if this class doesn't have a descriptor. This happens # when a service stub is subclassed. if GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary: return descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY] service_stub_builder = _ServiceStubBuilder(descriptor) service_stub_builder.BuildServiceStub(cls) class _ServiceBuilder(object): """This class constructs a protocol service class using a service descriptor. Given a service descriptor, this class constructs a class that represents the specified service descriptor. One service builder instance constructs exactly one service class. That means all instances of that class share the same builder. """ def __init__(self, service_descriptor): """Initializes an instance of the service class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the service class. """ self.descriptor = service_descriptor def BuildService(self, cls): """Constructs the service class. Args: cls: The class that will be constructed. """ # CallMethod needs to operate with an instance of the Service class. This # internal wrapper function exists only to be able to pass the service # instance to the method that does the real CallMethod work. def _WrapCallMethod(srvc, method_descriptor, rpc_controller, request, callback): return self._CallMethod(srvc, method_descriptor, rpc_controller, request, callback) self.cls = cls cls.CallMethod = _WrapCallMethod cls.GetDescriptor = staticmethod(lambda: self.descriptor) cls.GetDescriptor.__doc__ = "Returns the service descriptor." cls.GetRequestClass = self._GetRequestClass cls.GetResponseClass = self._GetResponseClass for method in self.descriptor.methods: setattr(cls, method.name, self._GenerateNonImplementedMethod(method)) def _CallMethod(self, srvc, method_descriptor, rpc_controller, request, callback): """Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method's execution. request: Request protocol message. callback: A callback to invoke after the method has completed. """ if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'CallMethod() given method descriptor for wrong service type.') method = getattr(srvc, method_descriptor.name) return method(rpc_controller, request, callback) def _GetRequestClass(self, method_descriptor): """Returns the class of the request protocol message. Args: method_descriptor: Descriptor of the method for which to return the request protocol message class. Returns: A class that represents the input protocol message of the specified method. """ if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'GetRequestClass() given method descriptor for wrong service type.') return method_descriptor.input_type._concrete_class def _GetResponseClass(self, method_descriptor): """Returns the class of the response protocol message. Args: method_descriptor: Descriptor of the method for which to return the response protocol message class. Returns: A class that represents the output protocol message of the specified method. """ if method_descriptor.containing_service != self.descriptor: raise RuntimeError( 'GetResponseClass() given method descriptor for wrong service type.') return method_descriptor.output_type._concrete_class def _GenerateNonImplementedMethod(self, method): """Generates and returns a method that can be set for a service methods. Args: method: Descriptor of the service method for which a method is to be generated. Returns: A method that can be added to the service class. """ return lambda inst, rpc_controller, request, callback: ( self._NonImplementedMethod(method.name, rpc_controller, callback)) def _NonImplementedMethod(self, method_name, rpc_controller, callback): """The body of all methods in the generated service class. Args: method_name: Name of the method being executed. rpc_controller: RPC controller used to execute this method. callback: A callback which will be invoked when the method finishes. """ rpc_controller.SetFailed('Method %s not implemented.' % method_name) callback(None) class _ServiceStubBuilder(object): """Constructs a protocol service stub class using a service descriptor. Given a service descriptor, this class constructs a suitable stub class. A stub is just a type-safe wrapper around an RpcChannel which emulates a local implementation of the service. One service stub builder instance constructs exactly one class. It means all instances of that class share the same service stub builder. """ def __init__(self, service_descriptor): """Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class. """ self.descriptor = service_descriptor def BuildServiceStub(self, cls): """Constructs the stub class. Args: cls: The class that will be constructed. """ def _ServiceStubInit(stub, rpc_channel): stub.rpc_channel = rpc_channel self.cls = cls cls.__init__ = _ServiceStubInit for method in self.descriptor.methods: setattr(cls, method.name, self._GenerateStubMethod(method)) def _GenerateStubMethod(self, method): return (lambda inst, rpc_controller, request, callback=None: self._StubMethod(inst, method, rpc_controller, request, callback)) def _StubMethod(self, stub, method_descriptor, rpc_controller, request, callback): """The body of all service methods in the generated stub class. Args: stub: Stub instance. method_descriptor: Descriptor of the invoked method. rpc_controller: Rpc controller to execute the method. request: Request protocol message. callback: A callback to execute when the method finishes. Returns: Response message (in case of blocking call). """ return stub.rpc_channel.CallMethod( method_descriptor, rpc_controller, request, method_descriptor.output_type._concrete_class, callback) ```
[ { "content": "Recreate the original code text:\n```python\n#!/usr/bin/env python\n# Test finding storage pool source of 'netfs' type\n\nfrom xml.dom import minidom\n\nimport libvirt\nfrom libvirt import libvirtError\n\nfrom src import sharedmod\nfrom utils import utils\n\nrequired_params = ('sourcehost',)\nopti...
[ { "content": "Recreate the original code text:\n<|memory_start|>```python\n#!/usr/bin/env python\n# Test finding storage pool source of 'netfs' type\n\nfrom xml.dom import minidom\n\nimport libvirt\nfrom libvirt import libvirtError\n\nfrom src import sharedmod\nfrom utils import utils\n\nrequired_params = ('sou...
```python #!/usr/bin/env python # Test finding storage pool source of 'netfs' type from xml.dom import minidom import libvirt from libvirt import libvirtError from src import sharedmod from utils import utils required_params = ('sourcehost',) optional_params = {'xml' : 'xmls/netfs_pool_source.xml', } def check_pool_sources(host, xmlstr): """check the netfs sources with command: showmount --no-headers -e HOSTNAME """ source_val = [] doc = minidom.parseString(xmlstr) for diskTag in doc.getElementsByTagName("source"): device_element = diskTag.getElementsByTagName("dir")[0] attr = device_element.getAttributeNode('path') path_val = attr.nodeValue source_val.append(path_val) logger.debug("pool source info list is: %s" % source_val) cmd = "showmount --no-headers -e %s | awk -F' ' '{print $1}'" % host ret, path_list = utils.exec_cmd(cmd, shell=True) logger.debug("showmount command output list is: %s" % path_list) if source_val == path_list: logger.info("source list matched with showmount command output") return 0 else: logger.error("source list did not match with showmount command output") return 1 def find_netfs_pool_sources(params): """Find netfs type storage pool sources from xml""" global logger logger = params['logger'] sourcehost = params['sourcehost'] xmlstr = params['xml'] conn = sharedmod.libvirtobj['conn'] try: logger.debug("storage source spec xml:\n%s" % xmlstr) logger.info("find pool sources of netfs type") source_xml = conn.findStoragePoolSources('netfs', xmlstr, 0) logger.info("pool sources xml description is:\n %s" % source_xml) ret = check_pool_sources(sourcehost, source_xml) if ret: logger.error("pool sources check failed") return 1 else: logger.info("pool sources check succeed") except libvirtError, e: logger.error("libvirt call failed: " + str(e)) return 1 return 0 ```
[ { "content": "Repeat the full code snippet:\n```python\n# Copyright 2021 The Cirq Developers\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# https://www.apache.org/lic...
[ { "content": "Repeat the full code snippet:\n<|memory_start|>```python\n# Copyright 2021 The Cirq Developers\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# https://ww...
```python # Copyright 2021 The Cirq Developers # # 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 # # https://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. """Batteries-included class for Cirq's built-in simulators.""" import abc import collections from typing import ( Any, Dict, Iterator, List, Tuple, TYPE_CHECKING, cast, Generic, Type, Sequence, Optional, ) import numpy as np from cirq import circuits, ops, protocols, study, value, devices from cirq.sim import ActOnArgsContainer from cirq.sim.operation_target import OperationTarget from cirq.sim.simulator import ( TStepResult, TSimulationTrialResult, TSimulatorState, TActOnArgs, SimulatesIntermediateState, SimulatesSamples, check_all_resolved, split_into_matching_protocol_then_general, ) if TYPE_CHECKING: import cirq class SimulatorBase( Generic[TStepResult, TSimulationTrialResult, TSimulatorState, TActOnArgs], SimulatesIntermediateState[TStepResult, TSimulationTrialResult, TSimulatorState, TActOnArgs], SimulatesSamples, metaclass=abc.ABCMeta, ): """A base class for the built-in simulators. Most implementors of this interface should implement the `_create_partial_act_on_args` and `_create_step_result` methods. The first one creates the simulator's quantum state representation at the beginning of the simulation. The second creates the step result emitted after each `Moment` in the simulation. Iteration in the subclass is handled by the `_core_iterator` implementation here, which handles moment stepping, application of operations, measurement collection, and creation of noise. Simulators with more advanced needs can override the implementation if necessary. Sampling is handled by the implementation of `_run`. This implementation iterates the circuit to create a final step result, and samples that result when possible. If not possible, due to noise or classical probabilities on a state vector, the implementation attempts to fully iterate the unitary prefix once, then only repeat the non-unitary suffix from copies of the state obtained by the prefix. If more advanced functionality is required, then the `_run` method can be overridden. Note that state here refers to simulator state, which is not necessarily a state vector. The included simulators and corresponding states are state vector, density matrix, Clifford, and MPS. Each of these use the default `_core_iterator` and `_run` methods. """ def __init__( self, *, dtype: Type[np.number] = np.complex64, noise: 'cirq.NOISE_MODEL_LIKE' = None, seed: 'cirq.RANDOM_STATE_OR_SEED_LIKE' = None, ignore_measurement_results: bool = False, split_untangled_states: bool = False, ): """Initializes the simulator. Args: dtype: The `numpy.dtype` used by the simulation. noise: A noise model to apply while simulating. seed: The random seed to use for this simulator. ignore_measurement_results: If True, then the simulation will treat measurement as dephasing instead of collapsing process. This is only applicable to simulators that can model dephasing. split_untangled_states: If True, optimizes simulation by running unentangled qubit sets independently and merging those states at the end. """ self._dtype = dtype self._prng = value.parse_random_state(seed) self.noise = devices.NoiseModel.from_noise_model_like(noise) self._ignore_measurement_results = ignore_measurement_results self._split_untangled_states = split_untangled_states @abc.abstractmethod def _create_partial_act_on_args( self, initial_state: Any, qubits: Sequence['cirq.Qid'], logs: Dict[str, Any], ) -> TActOnArgs: """Creates an instance of the TActOnArgs class for the simulator. It represents the supplied qubits initialized to the provided state. Args: initial_state: The initial state to represent. An integer state is understood to be a pure state. Other state representations are simulator-dependent. qubits: The sequence of qubits to represent. logs: The structure to hold measurement logs. A single instance should be shared among all ActOnArgs within the simulation. """ @abc.abstractmethod def _create_step_result( self, sim_state: TActOnArgs, qubit_map: Dict['cirq.Qid', int], ) -> TStepResult: """This method should be implemented to create a step result. Args: sim_state: The TActOnArgs for this trial. qubit_map: Determines the canonical ordering of the qubits. This is often used in specifying the initial state, i.e. the ordering of the computational basis states. Returns: The StepResult. """ def _can_be_in_run_prefix(self, val: Any): """Determines what should be put in the prefix in `_run` The `_run` method has an optimization that reduces repetition by splitting the circuit into a prefix that is pure with respect to the state representation, and only executing that once per sample set. For state vectors, any unitary operation is pure, and we make this the default here. For density matrices, any non-measurement operation can be represented wholely in the matrix, and thus this method is overridden there to enable greater optimization there. Custom simulators can override this method appropriately. Args: val: An operation or noise model to test for purity within the state representation. Returns: A boolean representing whether the value can be added to the `_run` prefix.""" return protocols.has_unitary(val) def _core_iterator( self, circuit: circuits.Circuit, sim_state: OperationTarget[TActOnArgs], all_measurements_are_terminal: bool = False, ) -> Iterator[TStepResult]: """Standard iterator over StepResult from Moments of a Circuit. Args: circuit: The circuit to simulate. sim_state: The initial args for the simulation. The form of this state depends on the simulation implementation. See documentation of the implementing class for details. Yields: StepResults from simulating a Moment of the Circuit. """ if len(circuit) == 0: step_state = sim_state.create_merged_state() yield self._create_step_result(step_state, step_state.qubit_map) return noisy_moments = self.noise.noisy_moments(circuit, sorted(circuit.all_qubits())) measured: Dict[Tuple['cirq.Qid', ...], bool] = collections.defaultdict(bool) for moment in noisy_moments: for op in ops.flatten_to_ops(moment): try: # TODO: support more general measurements. # Github issue: https://github.com/quantumlib/Cirq/issues/3566 # Preprocess measurements if all_measurements_are_terminal and measured[op.qubits]: continue if isinstance(op.gate, ops.MeasurementGate): measured[op.qubits] = True if all_measurements_are_terminal: continue if self._ignore_measurement_results: op = ops.phase_damp(1).on(*op.qubits) # Simulate the operation sim_state.apply_operation(op) except TypeError: raise TypeError(f"{self.__class__.__name__} doesn't support {op!r}") step_state = sim_state.create_merged_state() yield self._create_step_result(step_state, step_state.qubit_map) step_state.log_of_measurement_results.clear() def _run( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int ) -> Dict[str, np.ndarray]: """See definition in `cirq.SimulatesSamples`.""" if self._ignore_measurement_results: raise ValueError("run() is not supported when ignore_measurement_results = True") param_resolver = param_resolver or study.ParamResolver({}) resolved_circuit = protocols.resolve_parameters(circuit, param_resolver) check_all_resolved(resolved_circuit) qubits = tuple(sorted(resolved_circuit.all_qubits())) act_on_args = self._create_act_on_args(0, qubits) prefix, general_suffix = ( split_into_matching_protocol_then_general(resolved_circuit, self._can_be_in_run_prefix) if self._can_be_in_run_prefix(self.noise) else (resolved_circuit[0:0], resolved_circuit) ) step_result = None for step_result in self._core_iterator( circuit=prefix, sim_state=act_on_args, ): pass general_ops = list(general_suffix.all_operations()) if all(isinstance(op.gate, ops.MeasurementGate) for op in general_ops): for step_result in self._core_iterator( circuit=general_suffix, sim_state=act_on_args, all_measurements_are_terminal=True, ): pass assert step_result is not None measurement_ops = [cast(ops.GateOperation, op) for op in general_ops] return step_result.sample_measurement_ops(measurement_ops, repetitions, seed=self._prng) measurements: Dict[str, List[np.ndarray]] = {} for i in range(repetitions): all_step_results = self._core_iterator( general_suffix, sim_state=act_on_args.copy() if i < repetitions - 1 else act_on_args, ) for step_result in all_step_results: for k, v in step_result.measurements.items(): if k not in measurements: measurements[k] = [] measurements[k].append(np.array(v, dtype=np.uint8)) return {k: np.array(v) for k, v in measurements.items()} def _create_act_on_args( self, initial_state: Any, qubits: Sequence['cirq.Qid'], ) -> OperationTarget[TActOnArgs]: if isinstance(initial_state, OperationTarget): return initial_state log: Dict[str, Any] = {} if self._split_untangled_states: args_map: Dict[Optional['cirq.Qid'], TActOnArgs] = {} if isinstance(initial_state, int): for q in reversed(qubits): args_map[q] = self._create_partial_act_on_args( initial_state=initial_state % q.dimension, qubits=[q], logs=log, ) initial_state = int(initial_state / q.dimension) else: args = self._create_partial_act_on_args( initial_state=initial_state, qubits=qubits, logs=log, ) for q in qubits: args_map[q] = args args_map[None] = self._create_partial_act_on_args(0, (), log) return ActOnArgsContainer(args_map, qubits, self._split_untangled_states, log) else: return self._create_partial_act_on_args( initial_state=initial_state, qubits=qubits, logs=log, ) ```
[ { "content": "```python\n#!/usr/bin/env python\nimport messagebird\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True)\nparser.add_argument('--callID', help='identifier for the call', type=str, required=True)\...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\nimport messagebird\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True)\nparser.add_argument('--callID', help='identifier for the call', type=str,...
```python #!/usr/bin/env python import messagebird import argparse parser = argparse.ArgumentParser() parser.add_argument('--accessKey', help='access key for MessageBird API', type=str, required=True) parser.add_argument('--callID', help='identifier for the call', type=str, required=True) parser.add_argument('--legID', help='identifier for the leg object you wish to list the recordings for', type=str, required=True) parser.add_argument('--recordingID', help='identifier for the recording', type=str, required=True) args = vars(parser.parse_args()) try: client = messagebird.Client(args['accessKey']) voiceRecording = client.voice_recording_view(args['callID'], args['legID'], args['recordingID']) # Print the object information. print('The following information was returned as a Voice Recording object:') print(voiceRecording) except messagebird.client.ErrorException as e: print('An error occured while requesting a Message object:') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) print(' parameter : %s\n' % error.parameter) ```
[ { "content": "Repeat the code precisely as written (spacing intact):\n```python\nimport logging, os, re\nfrom autotest_lib.client.common_lib import error\nfrom autotest_lib.client.bin import utils, os_dep\nfrom autotest_lib.client.virt import virt_utils\nfrom autotest_lib.client.virt import virt_env_process\n\n...
[ { "content": "Repeat the code precisely as written (spacing intact):\n<|memory_start|>```python\nimport logging, os, re\nfrom autotest_lib.client.common_lib import error\nfrom autotest_lib.client.bin import utils, os_dep\nfrom autotest_lib.client.virt import virt_utils\nfrom autotest_lib.client.virt import virt...
```python import logging, os, re from autotest_lib.client.common_lib import error from autotest_lib.client.bin import utils, os_dep from autotest_lib.client.virt import virt_utils from autotest_lib.client.virt import virt_env_process class NFSCorruptConfig(object): """ This class sets up nfs_corrupt test environment. """ def __init__(self, test, params): self.nfs_dir = os.path.join(test.tmpdir, "nfs_dir") self.mnt_dir = os.path.join(test.tmpdir, "mnt_dir") self.chk_re = params.get("nfs_stat_chk_re", "running") cmd_list = self._get_service_cmds() self.start_cmd = cmd_list[0] self.stop_cmd = cmd_list[1] self.restart_cmd = cmd_list[2] self.status_cmd = cmd_list[3] @error.context_aware def _get_service_cmds(self): """ Figure out the commands used to control the NFS service. """ error.context("Finding out appropriate commands to handle NFS service") service = os_dep.command("service") try: systemctl = os_dep.command("systemctl") except ValueError: systemctl = None if systemctl is not None: init_script = "/etc/init.d/nfs" service_file = "/lib/systemd/system/nfs-server.service" if os.path.isfile(init_script): service_name = "nfs" elif os.path.isfile(service_file): service_name = "nfs-server" else: raise error.TestError("Files %s and %s absent, don't know " "how to set up NFS for this host" % (init_script, service_file)) start_cmd = "%s start %s.service" % (systemctl, service_name) stop_cmd = "%s stop %s.service" % (systemctl, service_name) restart_cmd = "%s restart %s.service" % (systemctl, service_name) status_cmd = "%s status %s.service" % (systemctl, service_name) else: start_cmd = "%s nfs start" % service stop_cmd = "%s nfs stop" % service restart_cmd = "%s nfs restart" % service status_cmd = "%s nfs status" % service return [start_cmd, stop_cmd, restart_cmd, status_cmd] @error.context_aware def setup(self, force_start=False): """ Setup test NFS share. @param force_start: Whether to make NFS service start anyway. """ error.context("Setting up test NFS share") for d in [self.nfs_dir, self.mnt_dir]: try: os.makedirs(d) except OSError: pass if force_start: self.start_service() else: if not self.is_service_active(): self.start_service() utils.run("exportfs localhost:%s -o rw,no_root_squash" % self.nfs_dir) utils.run("mount localhost:%s %s -o rw,soft,timeo=1,retrans=1,vers=3" % (self.nfs_dir, self.mnt_dir)) @error.context_aware def cleanup(self, force_stop=False): error.context("Cleaning up test NFS share") utils.run("umount %s" % self.mnt_dir) utils.run("exportfs -u localhost:%s" % self.nfs_dir) if force_stop: self.stop_service() def start_service(self): """ Starts the NFS server. """ utils.run(self.start_cmd) def stop_service(self): """ Stops the NFS server. """ utils.run(self.stop_cmd) def restart_service(self): """ Restarts the NFS server. """ utils.run(self.restart_cmd) def is_service_active(self): """ Verifies whether the NFS server is running or not. @param chk_re: Regular expression that tells whether NFS is running or not. """ status = utils.system_output(self.status_cmd, ignore_status=True) if re.findall(self.chk_re, status): return True else: return False @error.context_aware def run_nfs_corrupt(test, params, env): """ Test if VM paused when image NFS shutdown, the drive option 'werror' should be stop, the drive option 'cache' should be none. 1) Setup NFS service on host 2) Boot up a VM using another disk on NFS server and write the disk by dd 3) Check if VM status is 'running' 4) Reject NFS connection on host 5) Check if VM status is 'paused' 6) Accept NFS connection on host and continue VM by monitor command 7) Check if VM status is 'running' @param test: kvm test object. @param params: Dictionary with the test parameters. @param env: Dictionary with test environment. """ def get_nfs_devname(params, session): """ Get the possbile name of nfs storage dev name in guest. @param params: Test params dictionary. @param session: An SSH session object. """ image1_type = params.object_params("image1").get("drive_format") stg_type = params.object_params("stg").get("drive_format") cmd = "" # Seems we can get correct 'stg' devname even if the 'stg' image # has a different type from main image (we call it 'image1' in # config file) with these 'if' sentences. if image1_type == stg_type: cmd = "ls /dev/[hsv]d[a-z]" elif stg_type == "virtio": cmd = "ls /dev/vd[a-z]" else: cmd = "ls /dev/[sh]d[a-z]" cmd += " | tail -n 1" return session.cmd_output(cmd) def check_vm_status(vm, status): """ Check if VM has the given status or not. @param vm: VM object. @param status: String with desired status. @return: True if VM status matches our desired status. @return: False if VM status does not match our desired status. """ try: vm.verify_status(status) except: return False else: return True config = NFSCorruptConfig(test, params) config.setup() params["image_name_stg"] = os.path.join(config.mnt_dir, 'nfs_corrupt') params["force_create_image_stg"] = "yes" params["create_image_stg"] = "yes" stg_params = params.object_params("stg") virt_env_process.preprocess_image(test, stg_params) vm = env.get_vm(params["main_vm"]) vm.create(params=params) session = vm.wait_for_login(timeout=int(params.get("login_timeout", 360))) nfs_devname = get_nfs_devname(params, session) # Write disk on NFS server write_disk_cmd = "dd if=/dev/urandom of=%s" % nfs_devname logging.info("Write disk on NFS server, cmd: %s" % write_disk_cmd) session.sendline(write_disk_cmd) try: # Read some command output, it will timeout session.read_up_to_prompt(timeout=30) except: pass try: error.context("Make sure guest is running before test") vm.resume() vm.verify_status("running") try: cmd = "iptables" cmd += " -t filter" cmd += " -A INPUT" cmd += " -s localhost" cmd += " -m state" cmd += " --state NEW" cmd += " -p tcp" cmd += " --dport 2049" cmd += " -j REJECT" error.context("Reject NFS connection on host") utils.system(cmd) error.context("Check if VM status is 'paused'") if not virt_utils.wait_for( lambda: check_vm_status(vm, "paused"), int(params.get('wait_paused_timeout', 120))): raise error.TestError("Guest is not paused after stop NFS") finally: error.context("Accept NFS connection on host") cmd = "iptables" cmd += " -t filter" cmd += " -D INPUT" cmd += " -s localhost" cmd += " -m state" cmd += " --state NEW" cmd += " -p tcp" cmd += " --dport 2049" cmd += " -j REJECT" utils.system(cmd) error.context("Continue guest") vm.resume() error.context("Check if VM status is 'running'") if not virt_utils.wait_for(lambda: check_vm_status(vm, "running"), 20): raise error.TestError("Guest does not restore to 'running' status") finally: session.close() vm.destroy(gracefully=True) config.cleanup() ```
[ { "content": "Here is the code content:\n```python\n#!/usr/bin/env python\n\n\"\"\"\nCopyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)\nSee the file 'doc/COPYING' for copying permission\n\"\"\"\n\nimport time\n\nfrom lib.core.common import clearConsoleLine\nfrom lib.core.common import dataToStdout\...
[ { "content": "Here is the code content:\n<|memory_start|>```python\n#!/usr/bin/env python\n\n\"\"\"\nCopyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)\nSee the file 'doc/COPYING' for copying permission\n\"\"\"\n\nimport time\n\nfrom lib.core.common import clearConsoleLine\nfrom lib.core.common impo...
```python #!/usr/bin/env python """ Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import time from lib.core.common import clearConsoleLine from lib.core.common import dataToStdout from lib.core.common import filterListValue from lib.core.common import getFileItems from lib.core.common import Backend from lib.core.common import getPageWordSet from lib.core.common import hashDBWrite from lib.core.common import randomInt from lib.core.common import randomStr from lib.core.common import readInput from lib.core.common import safeStringFormat from lib.core.common import safeSQLIdentificatorNaming from lib.core.common import unsafeSQLIdentificatorNaming from lib.core.data import conf from lib.core.data import kb from lib.core.data import logger from lib.core.enums import DBMS from lib.core.enums import HASHDB_KEYS from lib.core.enums import PAYLOAD from lib.core.exception import SqlmapDataException from lib.core.exception import SqlmapMissingMandatoryOptionException from lib.core.settings import BRUTE_COLUMN_EXISTS_TEMPLATE from lib.core.settings import BRUTE_TABLE_EXISTS_TEMPLATE from lib.core.settings import METADB_SUFFIX from lib.core.threads import getCurrentThreadData from lib.core.threads import runThreads from lib.request import inject def _addPageTextWords(): wordsList = [] infoMsg = "adding words used on web page to the check list" logger.info(infoMsg) pageWords = getPageWordSet(kb.originalPage) for word in pageWords: word = word.lower() if len(word) > 2 and not word[0].isdigit() and word not in wordsList: wordsList.append(word) return wordsList def tableExists(tableFile, regex=None): if kb.tableExistsChoice is None and not any(_ for _ in kb.injection.data if _ not in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED)) and not conf.direct: warnMsg = "it's not recommended to use '%s' and/or '%s' " % (PAYLOAD.SQLINJECTION[PAYLOAD.TECHNIQUE.TIME], PAYLOAD.SQLINJECTION[PAYLOAD.TECHNIQUE.STACKED]) warnMsg += "for common table existence check" logger.warn(warnMsg) message = "are you sure you want to continue? [y/N] " test = readInput(message, default="N") kb.tableExistsChoice = test[0] in ("y", "Y") if not kb.tableExistsChoice: return None result = inject.checkBooleanExpression("%s" % safeStringFormat(BRUTE_TABLE_EXISTS_TEMPLATE, (randomInt(1), randomStr()))) if conf.db and Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): conf.db = conf.db.upper() if result: errMsg = "can't use table existence check because of detected invalid results " errMsg += "(most likely caused by inability of the used injection " errMsg += "to distinguish erroneous results)" raise SqlmapDataException(errMsg) tables = getFileItems(tableFile, lowercase=Backend.getIdentifiedDbms() in (DBMS.ACCESS,), unique=True) infoMsg = "checking table existence using items from '%s'" % tableFile logger.info(infoMsg) tables.extend(_addPageTextWords()) tables = filterListValue(tables, regex) threadData = getCurrentThreadData() threadData.shared.count = 0 threadData.shared.limit = len(tables) threadData.shared.value = [] threadData.shared.unique = set() def tableExistsThread(): threadData = getCurrentThreadData() while kb.threadContinue: kb.locks.count.acquire() if threadData.shared.count < threadData.shared.limit: table = safeSQLIdentificatorNaming(tables[threadData.shared.count], True) threadData.shared.count += 1 kb.locks.count.release() else: kb.locks.count.release() break if conf.db and METADB_SUFFIX not in conf.db and Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD): fullTableName = "%s.%s" % (conf.db, table) else: fullTableName = table result = inject.checkBooleanExpression("%s" % safeStringFormat(BRUTE_TABLE_EXISTS_TEMPLATE, (randomInt(1), fullTableName))) kb.locks.io.acquire() if result and table.lower() not in threadData.shared.unique: threadData.shared.value.append(table) threadData.shared.unique.add(table.lower()) if conf.verbose in (1, 2) and not hasattr(conf, "api"): clearConsoleLine(True) infoMsg = "[%s] [INFO] retrieved: %s\n" % (time.strftime("%X"), unsafeSQLIdentificatorNaming(table)) dataToStdout(infoMsg, True) if conf.verbose in (1, 2): status = '%d/%d items (%d%%)' % (threadData.shared.count, threadData.shared.limit, round(100.0 * threadData.shared.count / threadData.shared.limit)) dataToStdout("\r[%s] [INFO] tried %s" % (time.strftime("%X"), status), True) kb.locks.io.release() try: runThreads(conf.threads, tableExistsThread, threadChoice=True) except KeyboardInterrupt: warnMsg = "user aborted during table existence " warnMsg += "check. sqlmap will display partial output" logger.warn(warnMsg) clearConsoleLine(True) dataToStdout("\n") if not threadData.shared.value: warnMsg = "no table(s) found" logger.warn(warnMsg) else: for item in threadData.shared.value: if conf.db not in kb.data.cachedTables: kb.data.cachedTables[conf.db] = [item] else: kb.data.cachedTables[conf.db].append(item) for _ in ((conf.db, item) for item in threadData.shared.value): if _ not in kb.brute.tables: kb.brute.tables.append(_) hashDBWrite(HASHDB_KEYS.KB_BRUTE_TABLES, kb.brute.tables, True) return kb.data.cachedTables def columnExists(columnFile, regex=None): if kb.columnExistsChoice is None and not any(_ for _ in kb.injection.data if _ not in (PAYLOAD.TECHNIQUE.TIME, PAYLOAD.TECHNIQUE.STACKED)) and not conf.direct: warnMsg = "it's not recommended to use '%s' and/or '%s' " % (PAYLOAD.SQLINJECTION[PAYLOAD.TECHNIQUE.TIME], PAYLOAD.SQLINJECTION[PAYLOAD.TECHNIQUE.STACKED]) warnMsg += "for common column existence check" logger.warn(warnMsg) message = "are you sure you want to continue? [y/N] " test = readInput(message, default="N") kb.columnExistsChoice = test[0] in ("y", "Y") if not kb.columnExistsChoice: return None if not conf.tbl: errMsg = "missing table parameter" raise SqlmapMissingMandatoryOptionException(errMsg) if conf.db and Backend.getIdentifiedDbms() in (DBMS.ORACLE, DBMS.DB2): conf.db = conf.db.upper() result = inject.checkBooleanExpression(safeStringFormat(BRUTE_COLUMN_EXISTS_TEMPLATE, (randomStr(), randomStr()))) if result: errMsg = "can't use column existence check because of detected invalid results " errMsg += "(most likely caused by inability of the used injection " errMsg += "to distinguish erroneous results)" raise SqlmapDataException(errMsg) infoMsg = "checking column existence using items from '%s'" % columnFile logger.info(infoMsg) columns = getFileItems(columnFile, unique=True) columns.extend(_addPageTextWords()) columns = filterListValue(columns, regex) table = safeSQLIdentificatorNaming(conf.tbl, True) if conf.db and METADB_SUFFIX not in conf.db and Backend.getIdentifiedDbms() not in (DBMS.SQLITE, DBMS.ACCESS, DBMS.FIREBIRD): table = "%s.%s" % (safeSQLIdentificatorNaming(conf.db), table) kb.threadContinue = True kb.bruteMode = True threadData = getCurrentThreadData() threadData.shared.count = 0 threadData.shared.limit = len(columns) threadData.shared.value = [] def columnExistsThread(): threadData = getCurrentThreadData() while kb.threadContinue: kb.locks.count.acquire() if threadData.shared.count < threadData.shared.limit: column = safeSQLIdentificatorNaming(columns[threadData.shared.count]) threadData.shared.count += 1 kb.locks.count.release() else: kb.locks.count.release() break result = inject.checkBooleanExpression(safeStringFormat(BRUTE_COLUMN_EXISTS_TEMPLATE, (column, table))) kb.locks.io.acquire() if result: threadData.shared.value.append(column) if conf.verbose in (1, 2) and not hasattr(conf, "api"): clearConsoleLine(True) infoMsg = "[%s] [INFO] retrieved: %s\n" % (time.strftime("%X"), unsafeSQLIdentificatorNaming(column)) dataToStdout(infoMsg, True) if conf.verbose in (1, 2): status = "%d/%d items (%d%%)" % (threadData.shared.count, threadData.shared.limit, round(100.0 * threadData.shared.count / threadData.shared.limit)) dataToStdout("\r[%s] [INFO] tried %s" % (time.strftime("%X"), status), True) kb.locks.io.release() try: runThreads(conf.threads, columnExistsThread, threadChoice=True) except KeyboardInterrupt: warnMsg = "user aborted during column existence " warnMsg += "check. sqlmap will display partial output" logger.warn(warnMsg) clearConsoleLine(True) dataToStdout("\n") if not threadData.shared.value: warnMsg = "no column(s) found" logger.warn(warnMsg) else: columns = {} for column in threadData.shared.value: if Backend.getIdentifiedDbms() in (DBMS.MYSQL,): result = not inject.checkBooleanExpression("%s" % safeStringFormat("EXISTS(SELECT %s FROM %s WHERE %s REGEXP '[^0-9]')", (column, table, column))) else: result = inject.checkBooleanExpression("%s" % safeStringFormat("EXISTS(SELECT %s FROM %s WHERE ROUND(%s)=ROUND(%s))", (column, table, column, column))) if result: columns[column] = "numeric" else: columns[column] = "non-numeric" kb.data.cachedColumns[conf.db] = {conf.tbl: columns} for _ in map(lambda x: (conf.db, conf.tbl, x[0], x[1]), columns.items()): if _ not in kb.brute.columns: kb.brute.columns.append(_) hashDBWrite(HASHDB_KEYS.KB_BRUTE_COLUMNS, kb.brute.columns, True) return kb.data.cachedColumns ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\n\n# Copyright(C) 2012 Romain Bignon\n#\n# This file is part of weboob.\n#\n# weboob is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either ver...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n# Copyright(C) 2012 Romain Bignon\n#\n# This file is part of weboob.\n#\n# weboob is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Founda...
```python # -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob 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. # # weboob 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 weboob. If not, see <http://www.gnu.org/licenses/>. import urllib from weboob.tools.json import json from weboob.tools.browser import BaseBrowser from weboob.capabilities.housing import Query from .pages import SearchResultsPage, HousingPage __all__ = ['PapBrowser'] class PapBrowser(BaseBrowser): PROTOCOL = 'http' DOMAIN = 'www.pap.fr' ENCODING = 'utf-8' PAGES = { 'http://www.pap.fr/annonce/.*': SearchResultsPage, 'http://www.pap.fr/annonces/.*': HousingPage, } def search_geo(self, pattern): fp = self.openurl(self.buildurl('http://www.pap.fr/index/ac-geo', q=pattern.encode('utf-8'))) return json.load(fp) TYPES = {Query.TYPE_RENT: 'location', Query.TYPE_SALE: 'vente', } def search_housings(self, type, cities, nb_rooms, area_min, area_max, cost_min, cost_max): data = {'geo_objets_ids': ','.join(cities), 'surface[min]': area_min or '', 'surface[max]': area_max or '', 'prix[min]': cost_min or '', 'prix[max]': cost_max or '', 'produit': self.TYPES.get(type, 'location'), 'recherche': 1, 'nb_resultats_par_page': 40, 'submit': 'rechercher', 'typesbien[]': 'appartement', } if nb_rooms: data['nb_pieces[min]'] = nb_rooms data['nb_pieces[max]'] = nb_rooms self.location('/annonce/', urllib.urlencode(data)) assert self.is_on_page(SearchResultsPage) return self.page.iter_housings() def get_housing(self, housing): self.location('/annonces/%s' % urllib.quote(housing)) assert self.is_on_page(HousingPage) return self.page.get_housing() ```
[ { "content": "Repeat the code precisely as written (spacing intact):\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 li...
[ { "content": "Repeat the code precisely as written (spacing intact):\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 pro...
```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 typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class ExpressRouteCrossConnectionsOperations: """ExpressRouteCrossConnectionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2020_04_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list( self, **kwargs ) -> AsyncIterable["_models.ExpressRouteCrossConnectionListResult"]: """Retrieves all the ExpressRouteCrossConnections in a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExpressRouteCrossConnectionListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnectionListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnectionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteCrossConnections'} # type: ignore def list_by_resource_group( self, resource_group_name: str, **kwargs ) -> AsyncIterable["_models.ExpressRouteCrossConnectionListResult"]: """Retrieves all the ExpressRouteCrossConnections in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ExpressRouteCrossConnectionListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnectionListResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_resource_group.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnectionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections'} # type: ignore async def get( self, resource_group_name: str, cross_connection_name: str, **kwargs ) -> "_models.ExpressRouteCrossConnection": """Gets details about the specified ExpressRouteCrossConnection. :param resource_group_name: The name of the resource group (peering location of the circuit). :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection (service key of the circuit). :type cross_connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteCrossConnection, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, cross_connection_name: str, parameters: "_models.ExpressRouteCrossConnection", **kwargs ) -> "_models.ExpressRouteCrossConnection": cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(parameters, 'ExpressRouteCrossConnection') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, cross_connection_name: str, parameters: "_models.ExpressRouteCrossConnection", **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCrossConnection"]: """Update the specified ExpressRouteCrossConnection. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param parameters: Parameters supplied to the update express route crossConnection operation. :type parameters: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCrossConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, parameters=parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def update_tags( self, resource_group_name: str, cross_connection_name: str, cross_connection_parameters: "_models.TagsObject", **kwargs ) -> "_models.ExpressRouteCrossConnection": """Updates an express route cross connection tags. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the cross connection. :type cross_connection_name: str :param cross_connection_parameters: Parameters supplied to update express route cross connection tags. :type cross_connection_parameters: ~azure.mgmt.network.v2020_04_01.models.TagsObject :keyword callable cls: A custom type or function that will be passed the direct response :return: ExpressRouteCrossConnection, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update_tags.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(cross_connection_parameters, 'TagsObject') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('ExpressRouteCrossConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update_tags.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}'} # type: ignore async def _list_arp_table_initial( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> Optional["_models.ExpressRouteCircuitsArpTableListResult"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExpressRouteCircuitsArpTableListResult"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self._list_arp_table_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ExpressRouteCircuitsArpTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _list_arp_table_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/arpTables/{devicePath}'} # type: ignore async def begin_list_arp_table( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCircuitsArpTableListResult"]: """Gets the currently advertised ARP table associated with the express route cross connection in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param peering_name: The name of the peering. :type peering_name: str :param device_path: The path of the device. :type device_path: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCircuitsArpTableListResult or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitsArpTableListResult] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCircuitsArpTableListResult"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._list_arp_table_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, peering_name=peering_name, device_path=device_path, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCircuitsArpTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_list_arp_table.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/arpTables/{devicePath}'} # type: ignore async def _list_routes_table_summary_initial( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> Optional["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self._list_routes_table_summary_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ExpressRouteCrossConnectionsRoutesTableSummaryListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _list_routes_table_summary_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTablesSummary/{devicePath}'} # type: ignore async def begin_list_routes_table_summary( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"]: """Gets the route table summary associated with the express route cross connection in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param peering_name: The name of the peering. :type peering_name: str :param device_path: The path of the device. :type device_path: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCrossConnectionsRoutesTableSummaryListResult or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCrossConnectionsRoutesTableSummaryListResult"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._list_routes_table_summary_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, peering_name=peering_name, device_path=device_path, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCrossConnectionsRoutesTableSummaryListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_list_routes_table_summary.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTablesSummary/{devicePath}'} # type: ignore async def _list_routes_table_initial( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> Optional["_models.ExpressRouteCircuitsRoutesTableListResult"]: cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.ExpressRouteCircuitsRoutesTableListResult"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2020-04-01" accept = "application/json" # Construct URL url = self._list_routes_table_initial.metadata['url'] # type: ignore path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ExpressRouteCircuitsRoutesTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _list_routes_table_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTables/{devicePath}'} # type: ignore async def begin_list_routes_table( self, resource_group_name: str, cross_connection_name: str, peering_name: str, device_path: str, **kwargs ) -> AsyncLROPoller["_models.ExpressRouteCircuitsRoutesTableListResult"]: """Gets the currently advertised routes table associated with the express route cross connection in a resource group. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param cross_connection_name: The name of the ExpressRouteCrossConnection. :type cross_connection_name: str :param peering_name: The name of the peering. :type peering_name: str :param device_path: The path of the device. :type device_path: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: Pass in True if you'd like the AsyncARMPolling polling method, False for no polling, or your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either ExpressRouteCircuitsRoutesTableListResult or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_04_01.models.ExpressRouteCircuitsRoutesTableListResult] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteCircuitsRoutesTableListResult"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._list_routes_table_initial( resource_group_name=resource_group_name, cross_connection_name=cross_connection_name, peering_name=peering_name, device_path=device_path, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('ExpressRouteCircuitsRoutesTableListResult', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'crossConnectionName': self._serialize.url("cross_connection_name", cross_connection_name, 'str'), 'peeringName': self._serialize.url("peering_name", peering_name, 'str'), 'devicePath': self._serialize.url("device_path", device_path, 'str'), 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_list_routes_table.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/expressRouteCrossConnections/{crossConnectionName}/peerings/{peeringName}/routeTables/{devicePath}'} # type: ignore ```
[ { "content": "Provide a verbatim copy of the code:\n```python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCommon type definitions and constants for edx-dl\n\nThe classes in this module represent the structure of courses in edX. The\nstructure is:\n\n* A Course contains Sections\n* Each Section contains Subsections\n* ...
[ { "content": "Provide a verbatim copy of the code:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCommon type definitions and constants for edx-dl\n\nThe classes in this module represent the structure of courses in edX. The\nstructure is:\n\n* A Course contains Sections\n* Each Section contains...
```python # -*- coding: utf-8 -*- """ Common type definitions and constants for edx-dl The classes in this module represent the structure of courses in edX. The structure is: * A Course contains Sections * Each Section contains Subsections * Each Subsection contains Units Notice that we don't represent the full tree structure for both performance and UX reasons: Course -> [Section] -> [SubSection] -> [Unit] -> [Video] In the script the data structures used are: 1. The data structures to represent the course information: Course, Section->[SubSection] 2. The data structures to represent the chosen courses and sections: selections = {Course, [Section]} 3. The data structure of all the downloable resources which represent each subsection via its URL and the of resources who can be extracted from the Units it contains: all_units = {Subsection.url: [Unit]} 4. The units can contain multiple videos: Unit -> [Video] """ class Course(object): """ Course class represents course information. """ def __init__(self, id, name, url, state): """ @param id: The id of a course in edX is composed by the path {organization}/{course_number}/{course_run} @type id: str or None @param name: Name of the course. The name is taken from course page h3 header. @type name: str @param url: URL of the course. @type url: str or None @param state: State of the course. One of the following values: * 'Not yet' * 'Started' @type state: str """ self.id = id self.name = name self.url = url self.state = state class Section(object): """ Representation of a section of the course. """ def __init__(self, position, name, url, subsections): """ @param position: Integer position of the section in the list of sections. Starts at 1. @type position: int @param name: Name of the section. @type name: str @param url: URL of the section. None when section contains no subsections. @type url: str or None @param subsections: List of subsections. @type subsections: [SubSection] """ self.position = position self.name = name self.url = url self.subsections = subsections class SubSection(object): """ Representation of a subsection in a section. """ def __init__(self, position, name, url): """ @param position: Integer position of the subsection in the subsection list. Starts at 1. @type position: int @param name: Name of the subsection. @type name: str @param url: URL of the subsection. @type url: str """ self.position = position self.name = name self.url = url class Unit(object): """ Representation of a single unit of the course. """ def __init__(self, videos, resources_urls): """ @param videos: List of videos present in the unit. @type videos: [Video] @param resources_urls: List of additional resources that are come along with the unit. Resources include files with certain extensions and youtube links. @type resources_urls: [str] """ self.videos = videos self.resources_urls = resources_urls class Video(object): """ Representation of a single video. """ def __init__(self, video_youtube_url, available_subs_url, sub_template_url, mp4_urls): """ @param video_youtube_url: Youtube link (if any). @type video_youtube_url: str or None @param available_subs_url: URL to the available subtitles. @type available_subs_url: str @param sub_template_url: ??? @type sub_template_url: str @param mp4_urls: List of URLs to mp4 video files. @type mp4_urls: [str] """ self.video_youtube_url = video_youtube_url self.available_subs_url = available_subs_url self.sub_template_url = sub_template_url self.mp4_urls = mp4_urls YOUTUBE_DL_CMD = ['youtube-dl', '--ignore-config'] DEFAULT_CACHE_FILENAME = 'edx-dl.cache' ```
[ { "content": "Recreate the entire code block with identical formatting:\n```python\n\"\"\"\nHelper functions, OS agnostic\n\n@author: Roy Nielsen\n\"\"\"\n\n#--- Native python libraries\nimport re\nimport os\nimport sys\nimport time\nimport ctypes\nimport traceback\nfrom subprocess import Popen, STDOUT, PIPE\nt...
[ { "content": "Recreate the entire code block with identical formatting:\n<|memory_start|>```python\n\"\"\"\nHelper functions, OS agnostic\n\n@author: Roy Nielsen\n\"\"\"\n\n#--- Native python libraries\nimport re\nimport os\nimport sys\nimport time\nimport ctypes\nimport traceback\nfrom subprocess import Popen,...
```python """ Helper functions, OS agnostic @author: Roy Nielsen """ #--- Native python libraries import re import os import sys import time import ctypes import traceback from subprocess import Popen, STDOUT, PIPE try: import termios except: pass #--- non-native python libraries in this source tree from . loggers import CyLogger from . loggers import LogPriority as lp from . run_commands import RunWith logger = CyLogger() run = RunWith(logger) def getOsFamily(): '''Get the os name from the "uname -s" command @author: Roy Nielsen ''' operatingsystemfamily = sys.platform return operatingsystemfamily ########################################################################### class FoundException(Exception) : '''Exeption to raise when the condition is met in a for/while Accompanying code (in collect_for_hostmaster.py) derived from example in "Rapid GUI Programming with Python and QT" pgs 66 - 71, by Mark Summerfeild For more examples on python user defined exceptions: http://docs.python.org/2/tutorial/errors.html ''' pass ############################################################################## def get_console_user(): '''Get the user that owns the console on the Mac. This user is the user that is logged in to the GUI. ''' user = False cmd = ["/usr/bin/stat", "-f", "'%Su'", "/dev/console"] try: retval = Popen(cmd, stdout=PIPE, stderr=STDOUT).communicate()[0] space_stripped = str(retval).strip() quote_stripped = str(space_stripped).strip("'") except Exception as err: logger.log(lp.VERBOSE, "Exception trying to get the console user...") logger.log(lp.VERBOSE, "Associated exception: " + str(err)) logger.log(lp.WARNING, traceback.format_exc()) logger.log(lp.WARNING, str(err)) raise err else: """ LANL's environment has chosen the regex below as a valid match for usernames on the network. """ if re.match("^[A-Za-z][A-Za-z1-9_]+$", quote_stripped): user = str(quote_stripped) logger.log(lp.VERBOSE, "user: " + str(user)) return user ########################################################################### def is_valid_pn(random_pn=0) : '''Validate that the property number is seven digits. @author: Roy Nielsen :param random_pn: (Default value = 0) ''' retval = True # Need to check for 7 decimal places if not re.match("^\d\d\d\d\d\d\d$", str(random_pn)): logger.log(lp.VERBOSE, "PN is not valid...") retval = False else: logger.log(lp.VERBOSE, "PN \"" + str(random_pn) + "\" is valid") return retval ########################################################################### def get_darwin_mac() : '''Get the mac address and place it in net_hw_addr Future METHOD: Use the "ifconfig" command - look for the "active" interface - collect "interface", "mac", "ipaddr" to return. PATH to ifconfig may be specific to the Mac. Description: Runs the networksetup -listallhardwareports, processing the output to get the network interface mac address. Specific to the Mac. @author: Roy Nielsen ''' found = 0 output = Popen(["/usr/sbin/networksetup", "-listallhardwareports"], stdout=PIPE, stderr=STDOUT).communicate()[0] try : for line in output.split("\n") : match_hw_addr = re.compile \ ("^Ethernet Address:\s+(\w+:\w+:\w+:\w+:\w+:\w+)\s*$") if re.match("^Device:\s+(\w+)\s*$", line) : found = 1 if re.match \ ("^Ethernet Address:\s+(\w+:\w+:\w+:\w+:\w+:\w+)\s*$", \ line) and found == 1 : raise FoundException except FoundException : hw_addr = match_hw_addr.search(line) net_hw_addr = hw_addr.group(1) # net_hw_addr except Exception as err: logger.log(lp.VERBOSE, "Error attempting to acquire MAC address...") logger.log(lp.VERBOSE, "Exception: " + str(err)) raise err else : net_hw_addr = "No MAC addr found" logger.log(lp.VERBOSE, "No MAC address found") return net_hw_addr ########################################################################### def is_laptop(): '''Determine if the machine this is currently running on is a laptop @author: Roy Nielsen ''' isThisALaptop = False cmd = ["/usr/sbin/system_profiler", "SPHardwareDataType"] retval, reterr = Popen(cmd, stdout=PIPE, stderr=PIPE).communicate() if not reterr : if retval : for line in retval.split("\n") : if re.match("^\s+Model Name:", line) : if re.search("[bB]ook", line) : isThisALaptop = True break else : logger.log(lp.VERBOSE, "Error processing system_profiler output...") else : logger.log(lp.VERBOSE, "Error processing system_profiler output: " + str(reterr)) return isThisALaptop ########################################################################### def touch(filename=""): '''Python implementation of the touch command.. :param filename: (Default value = "") ''' if re.match("^\s*$", filename) : logger.log(lp.INFO, "Cannot touch a file without a filename....") else : try: os.utime(filename, None) except: try : open(filename, 'a').close() except Exception as err : logger.log(lp.INFO, "Cannot open to touch: " + str(filename)) ########################################################################### def installFdeUser(myusername="", mypassword="") : '''Create an input plist for the fdesetup command to enable a user in the filevault login screen @author: Roy Nielsen :param myusername: (Default value = "") :param mypassword: (Default value = "") ''' success = False logger.log(lp.DEBUG, "Starting installFdeUser...") if re.match("^\s*$", myusername) : logger.log(lp.INFO, "Empty username: '" + str(myusername) + "'") elif re.match("^\s*$", mypassword) : logger.log(lp.INFO, "Empty password: '" + str(mypassword) + "'") if re.match("^\s*$", myusername) or re.match("^\s*$", mypassword) : logger.log(lp.INFO, "in buildInputPlist -- cannot build the plist with an empty username or password...") return success plist = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + \ "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" + \ "<plist version=\"1.0\">\n" + \ "\t<dict>\n" + \ "\t\t<key>Username</key>\n" + \ "\t\t<string>" + str(myusername) + "</string>\n" + \ "\t\t<key>Password</key>\n" + \ "\t\t<string>" + str(mypassword) + "</string>\n" + \ "\t</dict>\n</plist>" ##### # Do the fdesetup command cmd = ["/usr/bin/fdesetup", "enable", "-outputplist", "-inputplist"] logger.log(lp.DEBUG, "Command: " + str(cmd)) proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) (retval, reterr) = proc.communicate(plist + "\n") logger.log(lp.DEBUG, "retval: " + str(retval)) logger.log(lp.DEBUG, "reterr: " + str(reterr)) if not reterr: success = True logger.log(lp.DEBUG, "Installed an Fde User...") return success ########################################################################### def removeFdeUser(myusername=""): '''Remove a user from the FDE login screen @author: Roy Nielsen :param myusername: (Default value = "") ''' success = False if re.match("^\s+$", myusername) or not myusername: logger.log(lp.INFO, "Empty username: '" + str(myusername) + "'") return success cmd = ["/usr/bin/fdesetup", "remove", myusername] run.setCommand(cmd) run.communicate() if not run.getStderr(): success = True return success ############################################################################ def touch(filename=""): '''Python implementation of the touch command.. :param filename: (Default value = "") ''' if re.match("^\s*$", filename) : logger.log(lp.INFO, "Cannot touch a file without a filename....") else : try: os.utime(filename, None) except: try : open(filename, 'a').close() except Exception as err : logger.log(lp.INFO, "Cannot open to touch: " + str(filename)) ########################################################################### def getecho (fileDescriptor): '''This returns the terminal echo mode. This returns True if echo is on or False if echo is off. Child applications that are expecting you to enter a password often set ECHO False. See waitnoecho(). Borrowed from pexpect - acceptable to license :param fileDescriptor: ''' attr = termios.tcgetattr(fileDescriptor) if attr[3] & termios.ECHO: return True return False ############################################################################ def waitnoecho (fileDescriptor, timeout=3): '''This waits until the terminal ECHO flag is set False. This returns True if the echo mode is off. This returns False if the ECHO flag was not set False before the timeout. This can be used to detect when the child is waiting for a password. Usually a child application will turn off echo mode when it is waiting for the user to enter a password. For example, instead of expecting the "password:" prompt you can wait for the child to set ECHO off:: see below in runAsWithSudo If timeout is None or negative, then this method to block forever until ECHO flag is False. Borrowed from pexpect - acceptable to license :param fileDescriptor: :param timeout: (Default value = 3) ''' if timeout is not None and timeout > 0: end_time = time.time() + timeout while True: if not getecho(fileDescriptor): return True if timeout < 0 and timeout is not None: return False if timeout is not None: timeout = end_time - time.time() time.sleep(0.1) ########################################################################### def isSaneFilePath(filepath): '''Check for a good file path in the passed in string. @author: Roy Nielsen :param filepath: ''' sane = False if filepath and isinstance(filepath, str): if re.match("^[A-Za-z0-9_\-/\.]*", filepath): sane = True return sane ########################################################################### ```
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n```python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nfrom mock import Mock\nfrom mock imp...
[ { "content": "Write out the code verbatim, preserving indentation and whitespace:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nfrom mock import Moc...
```python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from mock import Mock from mock import patch from squirrel.common.unittest import TestCase from squirrel.launcher.squirrel_dev import run as run_dev from squirrel.launcher.squirrel_prod import run as run_prod from squirrel.services.config import Config class TestEntryPoint(TestCase): @patch("squirrel.services.serve_backend.app", new=Mock()) @patch("squirrel.launcher.common.initializeConfig", new=Mock()) @patch("squirrel.launcher.common.setupLogger", new=Mock()) @patch("squirrel.launcher.common.loadPlugins", new=Mock()) @patch("squirrel.launcher.common.createWorkdirs", new=Mock()) def testRunProd(self): Config().unload() Config({ 'frontend': { 'root_fullpath': 'full/path', 'port': '1234', }, 'crawlers': {}, }) self.assertEqual(Config().frontend.root_fullpath, "full/path") run_prod() @patch("squirrel.services.serve_backend.app", new=Mock()) @patch("squirrel.launcher.common.initializeConfig", new=Mock()) @patch("squirrel.launcher.common.setupLogger", new=Mock()) @patch("squirrel.launcher.common.loadPlugins", new=Mock()) @patch("squirrel.launcher.common.createWorkdirs", new=Mock()) def testRunDev(self): Config().unload() Config({ 'frontend': { 'root_fullpath': 'full/path', 'port': '1234', }, 'crawlers': {}, }) self.assertEqual(Config().frontend.root_fullpath, "full/path") run_dev() ```
[ { "content": "Recreate the entire code block with identical formatting:\n```python\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2011 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in c...
[ { "content": "Recreate the entire code block with identical formatting:\n<|memory_start|>```python\n# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n# Copyright 2011 OpenStack Foundation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this ...
```python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2011 OpenStack Foundation. # 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. # This is a modified version of what was in oslo-incubator lockutils.py from # commit 5039a610355e5265fb9fbd1f4023e8160750f32e but this one does not depend # on oslo.cfg or the very large oslo-incubator oslo logging module (which also # pulls in oslo.cfg) and is reduced to only what taskflow currently wants to # use from that code. import errno import logging import os import threading import time from taskflow.utils import misc LOG = logging.getLogger(__name__) WAIT_TIME = 0.01 def locked(*args, **kwargs): """A decorator that looks for a given attribute (typically a lock or a list of locks) and before executing the decorated function uses the given lock or list of locks as a context manager, automatically releasing on exit. """ def decorator(f): attr_name = kwargs.get('lock', '_lock') @misc.wraps(f) def wrapper(*args, **kwargs): lock = getattr(args[0], attr_name) if isinstance(lock, (tuple, list)): lock = MultiLock(locks=list(lock)) with lock: return f(*args, **kwargs) return wrapper # This is needed to handle when the decorator has args or the decorator # doesn't have args, python is rather weird here... if kwargs or not args: return decorator else: if len(args) == 1: return decorator(args[0]) else: return decorator class MultiLock(object): """A class which can attempt to obtain many locks at once and release said locks when exiting. Useful as a context manager around many locks (instead of having to nest said individual context managers). """ def __init__(self, locks): assert len(locks) > 0, "Zero locks requested" self._locks = locks self._locked = [False] * len(locks) def __enter__(self): def is_locked(lock): # NOTE(harlowja): the threading2 lock doesn't seem to have this # attribute, so thats why we are checking it existing first. if hasattr(lock, 'locked'): return lock.locked() return False for i in range(0, len(self._locked)): if self._locked[i] or is_locked(self._locks[i]): raise threading.ThreadError("Lock %s not previously released" % (i + 1)) self._locked[i] = False for (i, lock) in enumerate(self._locks): self._locked[i] = lock.acquire() def __exit__(self, type, value, traceback): for (i, locked) in enumerate(self._locked): try: if locked: self._locks[i].release() self._locked[i] = False except threading.ThreadError: LOG.exception("Unable to release lock %s", i + 1) class _InterProcessLock(object): """Lock implementation which allows multiple locks, working around issues like bugs.debian.org/cgi-bin/bugreport.cgi?bug=632857 and does not require any cleanup. Since the lock is always held on a file descriptor rather than outside of the process, the lock gets dropped automatically if the process crashes, even if __exit__ is not executed. There are no guarantees regarding usage by multiple green threads in a single process here. This lock works only between processes. Note these locks are released when the descriptor is closed, so it's not safe to close the file descriptor while another green thread holds the lock. Just opening and closing the lock file can break synchronisation, so lock files must be accessed only using this abstraction. """ def __init__(self, name): self._lockfile = None self._fname = name @property def path(self): return self._fname def __enter__(self): self._lockfile = open(self.path, 'w') while True: try: # Using non-blocking locks since green threads are not # patched to deal with blocking locking calls. # Also upon reading the MSDN docs for locking(), it seems # to have a laughable 10 attempts "blocking" mechanism. self.trylock() return self except IOError as e: if e.errno in (errno.EACCES, errno.EAGAIN): time.sleep(WAIT_TIME) else: raise def __exit__(self, exc_type, exc_val, exc_tb): try: self.unlock() self._lockfile.close() except IOError: LOG.exception("Could not release the acquired lock `%s`", self.path) def trylock(self): raise NotImplementedError() def unlock(self): raise NotImplementedError() class _WindowsLock(_InterProcessLock): def trylock(self): msvcrt.locking(self._lockfile.fileno(), msvcrt.LK_NBLCK, 1) def unlock(self): msvcrt.locking(self._lockfile.fileno(), msvcrt.LK_UNLCK, 1) class _PosixLock(_InterProcessLock): def trylock(self): fcntl.lockf(self._lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB) def unlock(self): fcntl.lockf(self._lockfile, fcntl.LOCK_UN) if os.name == 'nt': import msvcrt InterProcessLock = _WindowsLock else: import fcntl InterProcessLock = _PosixLock ```
[ { "content": "```python\n# -*- coding: utf-8 -*-\n'''\t\nforgetting_curve.py\nThis program aims at generating a plan for memorizing\nvocabularies according to the Forgetting Curve.\n\nCopyright (c) 2015 Libao Jin\nLicence: unknown\n'''\n\nimport math\nimport itertools\n\n__author__ = 'Libao Jin'\n__date__ = 'Ju...
[ { "content": "<|memory_start|>```python\n# -*- coding: utf-8 -*-\n'''\t\nforgetting_curve.py\nThis program aims at generating a plan for memorizing\nvocabularies according to the Forgetting Curve.\n\nCopyright (c) 2015 Libao Jin\nLicence: unknown\n'''\n\nimport math\nimport itertools\n\n__author__ = 'Libao Jin'...
```python # -*- coding: utf-8 -*- ''' forgetting_curve.py This program aims at generating a plan for memorizing vocabularies according to the Forgetting Curve. Copyright (c) 2015 Libao Jin Licence: unknown ''' import math import itertools __author__ = 'Libao Jin' __date__ = 'July 03, 2015' def listGroup(lists, numberOfNewListsPerDay, numberOfListGroups): ''' to devide a list into groups of sublists ''' listGroup = range(numberOfListGroups) listGroups = [] for i in listGroup: listGroups.append(lists[numberOfNewListsPerDay*(i):numberOfNewListsPerDay*(i+1)]) return listGroups def acuSum(numbers): ''' accummulate summation over a list of numbers. ''' for i,e in enumerate(numbers): if i == 0: numbers[i] = e else: numbers[i] = e + numbers[i-1] return numbers def mergeLists(lists): ''' merge sublists of a list into one list. ''' mergedList = itertools.chain(*lists) return mergedList def genTasks(listGroups, forgetLaw, days): ''' generate/make a table of arrangment of lists. ''' Tasks = [[] for i in range(days)] for i,e in enumerate(listGroups): for j in forgetLaw: Tasks[i+j].append(e) return Tasks def genBoundedTasks(listGroups, forgetLaw, limit): ''' generate/make a table of arrangment of lists which is more scientific. ''' Tasks = [[] for i in range(200)] k = 0 for i,e in enumerate(listGroups): for j in forgetLaw: #print(len(Tasks[i+j+k])) #print(Tasks[i+j+k]) while len(Tasks[i+j+k]) >= limit: k += 1 Tasks[i+j+k].append(e) return Tasks def memo_list(): numberOfLists = 40 numberOfNewListsPerDay = 10 numberOfListGroups = math.ceil(numberOfLists / numberOfNewListsPerDay) forgetLawBasic = [0, 1, 2, 4, 7, 15] forgetLaw = acuSum(forgetLawBasic) days = numberOfListGroups + forgetLaw[-1] lists = list(range(1, numberOfLists+1, 1)) listGroups = listGroup(lists, numberOfNewListsPerDay, numberOfListGroups) limitNumberOfListsPerDay = 2 Tasks2 = genTasks(listGroups, forgetLaw, days) Tasks = genBoundedTasks(listGroups, forgetLaw, limitNumberOfListsPerDay) timetable = 'timetable.txt' f = open(timetable, 'w+', encoding = 'utf-8') print(len(Tasks)) for i in Tasks: ml = list(itertools.chain(*i)) print(ml) for j,e in enumerate(ml): if j < len(ml)-1: f.write(str(e)) f.write(', ') else: f.write(str(e)) f.write('\n') f.close() if __name__ == '__main__': memo_list() ```
[ { "content": "Repeat the code exactly:\n```python\n#!/usr/bin/env python3.2\n#\n# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012\n# and Voyager Internet Ltd, New Zealand, 2012-2013\n#\n# This file is part of py-magcode-core.\n#\n# Py-magcode-core is free software: you can redis...
[ { "content": "Repeat the code exactly:\n<|memory_start|>```python\n#!/usr/bin/env python3.2\n#\n# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012\n# and Voyager Internet Ltd, New Zealand, 2012-2013\n#\n# This file is part of py-magcode-core.\n#\n# Py-magcode-core is free softwar...
```python #!/usr/bin/env python3.2 # # Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012 # and Voyager Internet Ltd, New Zealand, 2012-2013 # # This file is part of py-magcode-core. # # Py-magcode-core is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Py-magcode-core is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with py-magcode-core. If not, see <http://www.gnu.org/licenses/>. # """ Module for ZoneDataUtil mix in class for zone_engine Split out so that changes can be seen more easily """ import re from copy import copy from sqlalchemy.exc import IntegrityError from sqlalchemy.orm.exc import NoResultFound from magcode.core.globals_ import * from magcode.core.database import sql_types from dms.globals_ import * from dms.exceptions import * from dms.auto_ptr_util import check_auto_ptr_privilege from dms.dns import RRTYPE_SOA from dms.dns import RRTYPE_NS from dms.dns import RRTYPE_A from dms.dns import RRTYPE_AAAA from dms.dns import RRTYPE_CNAME from dms.dns import RRTYPE_MX from dms.dns import RRTYPE_SRV from dms.dns import RRTYPE_PTR from dms.dns import RROP_DELETE from dms.dns import RROP_UPDATE_RRTYPE from dms.dns import RROP_ADD from dms.dns import RROP_PTR_UPDATE from dms.dns import RROP_PTR_UPDATE_FORCE from dms.dns import validate_zi_hostname from dms.dns import validate_zi_ttl from dms.dns import is_inet_hostname from dms.dns import label_from_address from dms.dns import new_zone_soa_serial import dms.database.zone_cfg as zone_cfg from dms.database.zone_sm import exec_zonesm from dms.database.zone_sm import ZoneSMDoRefresh from dms.database.zone_sm import ZoneSM from dms.database.reverse_network import ReverseNetwork from dms.database.zone_instance import ZoneInstance from dms.database.rr_comment import RRComment from dms.database.resource_record import data_to_rr from dms.database.resource_record import RR_PTR from dms.database.resource_record import ResourceRecord from dms.database.reference import find_reference from dms.database.zi_update import ZiUpdate from dms.database.update_group import new_update_group class DataTools(object): """ Container class for methods and runtime data for consistency checking code """ def __init__(self, db_session, zone_sm, zi_cname_flag=False): """ Initialise runtime data """ self.db_session = db_session self.zone_sm = zone_sm self.name = zone_sm.name self.zi_cname_flag = zi_cname_flag self.zi_rr_data = {} self.auto_ptr_data = [] self.apex_comment = None def check_rr_consistency(self, rrs, rr, rr_data, update_group): """ Check that RR can be consistently added to zone """ # Skip for any RROP_DELETE if update_group and rr.update_op and rr.update_op == RROP_DELETE: return if (not update_group or not rr.update_op or rr.update_op != RROP_UPDATE_RRTYPE): # Duplicate Record check if rr in rrs: raise DuplicateRecordInZone(self.name, rr_data) # Can't add another SOA if there is one there already if rr.type_ == RRTYPE_SOA: num_soa = len([r for r in rrs if r.type_ == RRTYPE_SOA]) if num_soa: raise ZoneAlreadyHasSOARecord(self.name, rr_data) # CNAME addition check if rr.type_ == RRTYPE_CNAME: self.zi_cname_flag = True # anti-CNAME addition check if self.zi_cname_flag: # Find any cnames with rr label and barf num_lbls = len([ r for r in rrs if (r.type_ == RRTYPE_CNAME and r.label == rr.label)]) # Check that we are not updating an existing CNAME if (num_lbls and update_group and rr.update_op and rr.update_op == RROP_UPDATE_RRTYPE and rr.type_ == RRTYPE_CNAME): num_lbls = 0 if num_lbls: raise ZoneCNAMEExists(self.name, rr_data) def check_zi_consistency(self, rrs): """ Check consistency of zone instance """ # CNAME check rr_cnames = [r for r in rrs if r.type_ == RRTYPE_CNAME] for rr in rr_cnames: clash = len([ r for r in rrs if (r.label == rr.label and r.type_ != RRTYPE_CNAME)]) if clash: raise ZoneCNAMELabelExists(self.name, self.zi_rr_data[str(rr)]) # Check NS MX and SRV records point to actual A # and AAAA records if they are in zone # (Bind Option check-integrity) # NS rr_nss = [r for r in rrs if r.type_ == RRTYPE_NS and r.label != '@'] for rr in rr_nss: if not rr.rdata.endswith('.'): target_hosts = [r for r in rrs if r.label == rr.rdata] if not len(target_hosts): raise ZoneCheckIntegrityNoGlue(self.name, self.zi_rr_data[str(rr)], rr.rdata) # MX rr_mxs = [r for r in rrs if r.type_ == RRTYPE_MX] for rr in rr_mxs: if not rr.rdata.endswith('.'): rdata = rr.rdata.split() target_hosts = [r for r in rrs if r.label == rdata[1]] if not len(target_hosts): raise ZoneCheckIntegrityNoGlue(self.name, self.zi_rr_data[str(rr)], rdata[1]) #SRV rr_srvs = [r for r in rrs if r.type_ == RRTYPE_SRV] for rr in rr_srvs: if not rr.rdata.endswith('.'): rdata = rr.rdata.split() target_hosts = [r for r in rrs if r.label == rdata[3]] if not len(target_hosts): raise ZoneCheckIntegrityNoGlue(self.name, self.zi_rr_data[str(rr)], rdata[3]) # If NS records are part of the zone, no point in doing # sanity checks as client will not be sending any SOAs if self.zone_sm.use_apex_ns: return # Check that zi has 1 SOA, and that its for the apex '@' rr_soas = [r for r in rrs if r.type_ == RRTYPE_SOA] if not rr_soas: raise ZoneHasNoSOARecord(self.name) if len(rr_soas) > 1: raise ZoneAlreadyHasSOARecord(self.name, self.zi_rr_data[str(rr_soas[1])]) if rr_soas[0].label != '@': raise ZoneSOARecordNotAtApex(self.name, self.zi_rr_data[str(rr_soas[0])]) # Check that apex has at least 1 NS record rr_nss = [r for r in rrs if r.type_ == RRTYPE_NS and r.label == '@'] if not rr_nss: raise ZoneHasNoNSRecord(self.name, self.zi_rr_data[str(rr_soas[0])]) def put_zi_rr_data(self, key, rr_data): """ Store rr_data for later use """ self.zi_rr_data[key] = rr_data def get_auto_ptr_data(self): """ Return auto_ptr_data """ return self.auto_ptr_data def handle_auto_ptr_data(self, rr, rr_data): """ Handle auto reverse IP functionality. This is brief to quickly come up with a list of candidates that can be filtered for netblock reverse zone later on. """ # We only look at IP address records if (rr.type_ != RRTYPE_A and rr.type_ != RRTYPE_AAAA): return # We ignore DELETE update_ops, as algorithm will ignore that if (rr.update_op and rr.update_op == RROP_DELETE): return # Use the dnspython rewritten rdata to make sure that IPv6 # addresses are uniquely written. hostname = rr.label + '.' + self.name if rr.label != '@' else self.name # Force reverse is once only, and not saved to DB, track_reverse is # force reverse all the time force_reverse = False if rr_data.get('force_reverse'): force_reverse = True if rr_data['force_reverse'] else False if rr_data.get('track_reverse'): force_reverse = True if rr_data['track_reverse'] else force_reverse disable = False if rr_data.get('disable'): disable = True if rr_data['disable'] else False zone_ref = self.zone_sm.reference zone_ref_str = zone_ref.reference if zone_ref else None self.auto_ptr_data.append({ 'address': rr.rdata, 'disable': disable, 'force_reverse': force_reverse, 'hostname': hostname, 'reference': zone_ref_str}) def check_reference_string(self, ref_str): """ Check that the supplied reference string is complete """ if not re.match(r'^[\-_a-zA-Z0-9.@]+$', ref_str): error_msg = "can only contain characters '-_a-zA-Z0-9.@'" raise ReferenceFormatError(ref_str, error_msg) if not re.match(r'^[0-9a-zA-Z][\-_a-zA-Z0-9.@]*$', ref_str): error_msg = "must start with 'a-zA-Z0-9'" raise ReferenceFormatError(ref_str, error_msg) if len(ref_str) > 1024: error_msg = "too long, must be <= 1024." raise ReferenceFormatError(ref_str, error_msg) def check_extra_data_privilege(self, rr_data, admin_privilege, helpdesk_privilege): """ Check privilege for use of extra data items to do with auto reverse IP setting and pyparsing error finformation """ if (not admin_privilege): if (rr_data.get('lock_ptr')): raise AdminPrivilegeNeeded(self.name, rr_data, 'lock_ptr') rr_data.pop('lock_ptr', None) if (not admin_privilege and not helpdesk_privilege): if rr_data.get('reference'): raise HelpdeskPrivilegeNeeded(self.name, rr_data, 'reference') rr_data.pop('reference', None) def add_comment(self, top_comment, comment=None, tag=None, **kwargs): """ Add a new comment or apex_comment """ # Don't do anything unless 'comment' is supplied! if not comment and not top_comment: return None db_session = self.db_session # Deal with Apex comment - special, even set text to default # if none! if (top_comment or tag == settings['apex_rr_tag']): if self.zone_sm.use_apex_ns: # If Apex done by global config, update routines # will create an appropriate Apex comment return None if not comment: comment = settings['apex_comment_template'] % self.name tag = settings['apex_rr_tag'] # Create a new comment rr_comment = RRComment(comment=comment, tag=tag) db_session.add(rr_comment) # Need to flush to get a new id from database db_session.flush() if (rr_comment.tag == settings['apex_rr_tag']): self.apex_comment = rr_comment return rr_comment.id_ def get_apex_comment(self): """ Return Apex Comment """ return self.apex_comment def rr_data_create_comments(self, zi_data, zone_ttl, creating_real_zi=True): """ Common code for creating comments, and creating comment IDs """ # Get comment IDs created and established. rr_group_data = zi_data.get('rr_groups') for rr_group in rr_group_data: rr_groups_index = rr_group_data.index(rr_group) top_comment = creating_real_zi and rr_groups_index == 0 comment_group_id = self.add_comment(top_comment, **rr_group) rr_group['comment_group_id'] = comment_group_id for rr_data in rr_group['rrs']: # get rr_groups_index and rrs_index for error handling rr_data['rrs_index'] = rr_group['rrs'].index(rr_data) rr_data['rr_groups_index'] = rr_groups_index # Handle comment IDs rr_data['comment_rr_id'] = self.add_comment(False, **rr_data) rr_data['comment_group_id'] = comment_group_id # Following needed to initialise dnspython RRs correctly rr_data['zone_ttl'] = zone_ttl self.rr_group_data = rr_group_data zi_data.pop('rr_groups', None) def add_rrs(self, rrs_func, add_rr_func, admin_privilege, helpdesk_privilege, update_group=None): """ Add RR to data base Note use of rrs_func so that list of rrs is always refreshed in function. Can be supplied by using a no argument lambda function. This is so that in the case of a full ZI, rrs can be added to it, which is different to the case of incremental updates, where the list of RRs is constructed, and the rrs just added directly to the resource records table. """ db_session = self.db_session for rr_group in self.rr_group_data: for rr_data in rr_group['rrs']: # Remove unneeded keys from rr_data rr_data.pop('comment', None) rr_data.pop('zone_id', None) # Check privilege self.check_extra_data_privilege(rr_data, admin_privilege, helpdesk_privilege) rr = data_to_rr(self.name, rr_data) self.check_rr_consistency(rrs_func(), rr, rr_data, update_group) # Store rr_data for zi consistency checks self.put_zi_rr_data(str(rr), rr_data) # Add rr to SQLAlchemy data structures db_session.add(rr) # Sort out RR reference part of the data structure rr_ref_str = rr_data.get('reference') if rr_ref_str: self.check_reference_string(rr_ref_str) rr_ref = find_reference(db_session, rr_ref_str) rr.ref_id = rr_ref.id_ if rr_ref else None rr.reference = rr_ref # Sort out update_group if given if update_group: update_group.update_ops.append(rr) add_rr_func(rr) self.handle_auto_ptr_data(rr, rr_data) class PseudoZi(ZiUpdate): """ Dummy ZI class so that ZiUpdate operations can do a trial run, so that incremental updates can be consistency checked by zi checking code. """ def __init__(self, db_session, zi): # make sure ZiUpdate runs in trial mode ZiUpdate.__init__(self, db_session=db_session, trial_run=True) # Copy rrs list so that changes do not trigger SQAlchemy self.rrs = [] for rr in zi.rrs: rr_type = sql_types[type(rr).__name__] new_rr = rr_type(label=rr.label, domain=zi.zone.name, ttl=rr.ttl, zone_ttl=rr.zone_ttl, rdata=rr.rdata, lock_ptr=rr.lock_ptr, disable=rr.disable, track_reverse=rr.track_reverse) self.rrs.append(new_rr) def add_rr(self, rr): """ Add RR to rrs list """ self.rrs.append(rr) def remove_rr(self, rr): """ Remove rr from rrs list """ self.rrs.remove(rr) class ZoneDataUtil(object): """ Mix in class for ZoneEngine, containing _data_to_zi and _data_to_incr functions """ def _data_to_zi(self, name, zi_data, change_by, normalize_ttls=False, admin_privilege=False, helpdesk_privilege=False): """ Construct a new ZI, RRS and comments, from zone_data. """ def set_missing_zi_data(): """ Set missing fields in supplied zi_data to prevent problems """ # Set ZI Zone ttl if not already set if 'zone_ttl' not in zi_data: zi_data['zone_ttl'] = zone_ttl # Set other SOA values in zi_data from defaults # if they are not there. soa_ttl can be None for field in ['soa_mname', 'soa_rname', 'soa_refresh', 'soa_retry', 'soa_expire', 'soa_minimum']: if not zi_data.get(field): zi_data[field] = zone_cfg.get_row_exc(db_session, field, sg=zone_sm.sg) # We always update serial number on zone udpdate/publish # but it is nicer and probably less troublesome to replace # an existing serial number that may be out there if not zi_data.get('soa_serial'): if zone_sm.soa_serial: zi_data['soa_serial'] = zone_sm.soa_serial else: # Obviously a new zone zi_data['soa_serial'] = new_zone_soa_serial(db_session) def check_zi_data(): """ Check incoming zi_data attributes for correctness """ for field in ['soa_mname', 'soa_rname']: validate_zi_hostname(name, field, zi_data[field]) for field in ['soa_refresh', 'soa_retry', 'soa_expire', 'soa_minimum', 'soa_ttl', 'zone_ttl']: if field == 'soa_ttl' and not zi_data.get(field): # SOA TTL can be None continue validate_zi_ttl(name, field, zi_data[field]) for field in ['soa_serial']: if field == 'soa_serial' and zi_data.get(field, None) == None: # SOA serial can be None continue # Check incoming data type of soa_serial if not isinstance(zi_data['soa_serial'], int): raise SOASerialTypeError(name) if not ( 0 < zi_data['soa_serial'] <= (2**32-1)): # RFC 2136 Section 4.2 AO serial cannot be zero raise SOASerialRangeError(name) # Function start db_session = self.db_session # Get zone_sm to get zone ID etc zone_sm = self._get_zone_sm(name) zone_id = zone_sm.id_ # initialise data and zone consistency checking data_tools = DataTools(db_session, zone_sm) # Sort out a candidate value for zone_ttl so that RRs can be created zone_ttl = zi_data.get('zone_ttl', zone_cfg.get_row_exc(db_session, 'zone_ttl', sg=zone_sm.sg)) zone_ttl_supplied = 'zone_ttl' in zi_data # Create comments, and set up comment IDs, and stuff for handlng # RR Groups zi_data structures data_tools.rr_data_create_comments(zi_data, zone_ttl) # Deal with ZI data problems, and supply defaults if missing set_missing_zi_data() check_zi_data() # This constructor call sets attributes in zi as well! zi = ZoneInstance(change_by=change_by, **zi_data) db_session.add(zi) apex_comment = data_tools.get_apex_comment() if apex_comment: zi.add_apex_comment(apex_comment) # Get zi.id_ zi.zone_id from database db_session.flush() # Add RRs to zi # Note use of lambda so that list of rrs is always refreshed in # function data_tools.add_rrs(lambda :zi.rrs, zi.add_rr, admin_privilege, helpdesk_privilege) # tie zi into data_structures zone_sm.all_zis.append(zi) zi.zone = zone_sm db_session.flush() # Normalise TTLs here if normalize_ttls and zone_ttl_supplied: zi.normalize_ttls() # Update SOA and NS records - can't hurt to do it here # This also cleans out any incoming apex NS records if # client should not be setting them. zi.update_apex(db_session) # Update Zone TTLs for clean initialisation zi.update_zone_ttls() db_session.flush() # Check zone consistency. Do this here as Apex RRs need to be complete. data_tools.check_zi_consistency(zi.rrs) return zi, data_tools.get_auto_ptr_data() def _data_to_update(self, name, update_data, update_type, change_by, admin_privilege=False, helpdesk_privilege=False): """ Construct an update group for a zone, from supplied RRS and comments. Functional equivalent of _data_to_zi() above, but for incremental updates """ # Function start db_session = self.db_session # Check that update_type is supplied if not update_type: raise UpdateTypeRequired(name) # Get zone_sm to get zone ID etc zone_sm = self._get_zone_sm(name) zone_id = zone_sm.id_ # See if incremental updates are enabled for zone before queuing any if not zone_sm.inc_updates: raise IncrementalUpdatesDisabled(name) # Don't queue updates for a disabled zone if zone_sm.is_disabled(): raise ZoneDisabled(name) # Privilege check for no apex zones - admin only if not zone_sm.use_apex_ns and not admin_privilege: raise ZoneAdminPrivilegeNeeded(name) # Use candidate ZI as it always is available. zi is published zi zi = self._get_zi(zone_sm.zi_candidate_id) if not zi: raise ZiNotFound(name, zone_sm.zi_candidate_id) # Get value of zone_ttl so that RRs can be created zone_ttl = zi.zone_ttl # Create RRs list from published ZI pzi = PseudoZi(db_session, zi) # initialise data and zone consistency checking zi_cname_flag = False if len([r for r in pzi.rrs if r.type_ == RRTYPE_CNAME]): zi_cname_flag = True data_tools = DataTools(db_session, zone_sm, zi_cname_flag) # Create comments, and set up comment IDs, and stuff for handlng # RR Groups zi_data structures data_tools.rr_data_create_comments(update_data, zone_ttl, creating_real_zi=False) try: # Create new update_group update_group = new_update_group(db_session, update_type, zone_sm, change_by) except IntegrityError as exc: raise UpdateTypeAlreadyQueued(name, update_type) # Add RRs to DB and operate on Pseudo ZI data_tools.add_rrs(lambda :pzi.rrs, pzi.trial_op_rr, admin_privilege, helpdesk_privilege, update_group=update_group) data_tools.check_zi_consistency(pzi.rrs) # Get all data out to DB, and ids etc established. db_session.flush() # Refresh zone to implement updates exec_zonesm(zone_sm, ZoneSMDoRefresh) # Return auto update info return data_tools.get_auto_ptr_data() def _queue_auto_ptr_data(self, auto_ptr_data): """ Queue auto PTR data as incremental updates against respective reverse zones. """ if not auto_ptr_data: return if not len(auto_ptr_data): return if not settings['auto_reverse']: return db_session = self.db_session # Create new update_group ug_dict = {} auto_ptr_privilege_flag = False for ptr_data in auto_ptr_data: # Ignore addresses we don't have reverse zone for query = db_session.query(ZoneSM)\ .join(ReverseNetwork)\ .filter(":address <<= reverse_networks.network")\ .params(address = ptr_data['address']) query = ZoneSM.query_is_not_deleted(query) query = ZoneSM.query_inc_updates(query) query = query.order_by(ReverseNetwork.network.desc())\ .limit(1) try: zone_sm = query.one() except NoResultFound: continue # Ignore invalid host names if not is_inet_hostname(ptr_data['hostname'], absolute=True, wildcard=False): log_error("Hostname '%s' is not a valid hostname." % ptr_data['hostname']) continue # Determine proposed update operation update_op = RROP_PTR_UPDATE_FORCE if ptr_data['force_reverse'] \ else RROP_PTR_UPDATE # Execute privilege checks ahead of time to save unnecessary churn # Better than needlessly going through whole rigamorole of # incremental update processing later on for no effect #1 See if old PTR exists to retrieve any RR reference # Both following also used lower down when generating RR_PTR label = label_from_address(ptr_data['address']) rr_ref = find_reference(db_session, ptr_data['reference'], raise_exc=False) # query for old record - this generates one select # Optimization - if check has previously suceeded, don't check # again as this is all checked further in if not auto_ptr_privilege_flag: qlabel= label[:label.rfind(zone_sm.name)-1] query = db_session.query(ResourceRecord)\ .filter(ResourceRecord.label == qlabel)\ .filter(ResourceRecord.zi_id == zone_sm.zi_candidate_id)\ .filter(ResourceRecord.disable == False)\ .filter(ResourceRecord.type_ == RRTYPE_PTR) old_rrs = query.all() old_rr = old_rrs[0] if len(old_rrs) else None # Check that we can proceed, only if check has not succeded yet if not check_auto_ptr_privilege(rr_ref, self.sectag, zone_sm, old_rr): if old_rr: log_debug("Zone '%s' - can't replace '%s' PTR" " as neither" " sectags '%s' vs '%s'" " references '%s' vs '%s'/'%s' (old PTR/rev zone)" "match ," " or values not given." % (zone_sm.name, old_rr.label, self.sectag.sectag, settings['admin_sectag'], rr_ref, old_rr.reference, zone_sm.reference)) else: log_debug("Zone '%s' - can't add '%s' PTR as neither" " sectags '%s' vs '%s'" " references '%s' vs '%s' (rev zone) match," " or values not given." % (zone_sm.name, qlabel, self.sectag.sectag, settings['admin_sectag'], rr_ref, zone_sm.reference)) continue auto_ptr_privilege_flag = True # Create a new update group if zone has not been seen before. try: update_group, zone_ttl = ug_dict.get(zone_sm) except (ValueError, TypeError): # Obtain reverse zone_ttl so PTR rrs can be created # Use candidate ZI as it always is available. # zi is published zi zi = self._get_zi(zone_sm.zi_candidate_id) if not zi: log_error("Zone '%s': does not have candidate zi." % zone_sm.name) continue zone_ttl = zi.zone_ttl update_group = new_update_group(db_session, None, zone_sm, None, ptr_only=True, sectag=self.sectag.sectag) ug_dict[zone_sm] = (update_group, zone_ttl) # Allocate RR_PTR update record rr = RR_PTR(label=label, zone_ttl=zone_ttl, rdata=ptr_data['hostname'], disable=ptr_data['disable'], domain=zone_sm.name, update_op=update_op) rr.ref_id = rr_ref.id_ if rr_ref else None rr.reference = rr_ref # Chain on RR_PTR update record update_group.update_ops.append(rr) # Flush everything to disk db_session.flush() # Issue zone refreshes to implement PTR changes for zone_sm in ug_dict: if zone_sm.is_disabled(): continue exec_zonesm(zone_sm, ZoneSMDoRefresh) # Make sure everything is committed db_session.commit() ```
[ { "content": "```python\nfrom collections import Counter\nfrom itertools import chain, combinations\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.http import urlquote\nfrom django.template.response import TemplateResponse\n\nfrom us_ignite.apps.models impor...
[ { "content": "<|memory_start|>```python\nfrom collections import Counter\nfrom itertools import chain, combinations\n\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.http import urlquote\nfrom django.template.response import TemplateResponse\n\nfrom us_ignite.a...
```python from collections import Counter from itertools import chain, combinations from django.conf import settings from django.core.urlresolvers import reverse from django.utils.http import urlquote from django.template.response import TemplateResponse from us_ignite.apps.models import Application, Domain from us_ignite.actionclusters.models import ActionCluster, Domain as ACDomain from us_ignite.common.response import json_response def _get_domain(label): domain = Domain.objects.get(name__exact=label) return domain.slug def _get_ac_domain(label): domain = ACDomain.objects.get(name__exact=label) return domain.slug URLS = { 'app_stage': ('app_list_stage', Application.get_stage_id), 'app_domain': ('app_list_domain', _get_domain), 'ac_stage': ('actioncluster_list_stage', ActionCluster.get_stage_id), 'ac_domain': ('actioncluster_list_domain', _get_ac_domain) } def _get_search_url(name, label): if name in URLS: slug, function = URLS[name] args = [function(label)] if function else [] path = reverse(slug, args=args) else: path = '%s?q=%s' % (reverse('search'), urlquote(label)) return u'%s%s' % (settings.SITE_URL, path) def get_chart_data(counter, name): chart_data = [] for i, (key, value) in enumerate(counter.items()): chart_data.append({ 'label': key, 'value': value, 'id': '%s-%s' % (name, i), 'url': _get_search_url(name, key), }) return chart_data def get_app_stats(display = 0): if display == 0: app_list = Application.objects.select_related('app_domain').all() else: app_list = Application.objects.select_related('app_domain').filter(status=display) domain_list = [] stage_list = [] feature_list = [] for app in app_list: if app.domain: domain_list.append(app.domain.name) stage_list.append(app.get_stage_display()) feature_list += [f.name for f in app.features.all()] stats = { 'total': len(app_list), 'domain': get_chart_data(Counter(domain_list), 'app_domain'), 'stage': get_chart_data(Counter(stage_list), 'app_stage'), 'feature': get_chart_data(Counter(feature_list), 'feature'), } return stats def get_actioncluster_stats(display = 0): if display == 0: ac_list = ActionCluster.objects.select_related('ac_domain').all() else: ac_list = ActionCluster.objects.select_related('ac_domain').filter(status=display) domain_list = [] stage_list = [] feature_list = [] for ac in ac_list: if ac.domain: domain_list.append(ac.domain.name) stage_list.append(ac.get_stage_display()) feature_list += [f.name for f in ac.features.all()] stats = { 'total': len(ac_list), 'domain': get_chart_data(Counter(domain_list), 'ac_domain'), 'stage': get_chart_data(Counter(stage_list), 'ac_stage'), 'feature': get_chart_data(Counter(feature_list), 'feature'), } return stats def get_hub_stats(): stats = {} return stats def visual_list(request): context = { 'apps': get_app_stats(1), 'hubs': get_hub_stats(), } return TemplateResponse(request, 'visualize/object_list.html', context) def visual_json(request): def in_dictlist((key, value), my_dictlist): for this in my_dictlist: if this[key] == value: return this return {} apps = get_app_stats(1) acs = get_actioncluster_stats(1) stages = list(chain(apps.get('stage'), acs.get('stage'))) domains = list(chain(apps.get('domain'), acs.get('domain'))) features = list(chain(apps.get('feature'), acs.get('feature'))) new_stages = [] new_domains = [] new_features = [] stage_label = [] for stage in stages: if stage['label'] not in stage_label: stage_label.append(stage['label']) domain_label = [] for domain in domains: if domain['label'] not in domain_label: domain_label.append(domain['label']) feature_label = [] for feature in features: if feature['label'] not in feature_label: feature_label.append(feature['label']) for label in stage_label: new_stages.append(in_dictlist(('label', label), stages)) for label in domain_label: new_domains.append(in_dictlist(('label', label), domains)) for label in feature_label: new_features.append(in_dictlist(('label', label), features)) get_status = { 'domain': new_domains, 'total': apps.get('total') + acs.get('total'), 'feature': new_features, 'stage': new_stages } context = { 'apps': get_status } return json_response(context, callback='chart.render') ```
[ { "content": "```python\n#!/usr/bin/env python\nfrom __future__ import division, print_function\nimport os\nfrom math import log\nfrom collections import namedtuple, OrderedDict, deque\nimport time\nimport threading\nimport json\nimport gc\ntry:\n from Queue import Queue\nexcept ImportError:\n from queue ...
[ { "content": "<|memory_start|>```python\n#!/usr/bin/env python\nfrom __future__ import division, print_function\nimport os\nfrom math import log\nfrom collections import namedtuple, OrderedDict, deque\nimport time\nimport threading\nimport json\nimport gc\ntry:\n from Queue import Queue\nexcept ImportError:\...
```python #!/usr/bin/env python from __future__ import division, print_function import os from math import log from collections import namedtuple, OrderedDict, deque import time import threading import json import gc try: from Queue import Queue except ImportError: from queue import Queue import io import logging from fractions import Fraction import numpy from PIL import Image import pyexiv2 from picamera import PiCamera from scipy.signal import convolve, gaussian, savgol_coeffs from exposure import lens logger = logging.getLogger("camera") import signal try: import colors as _colors except ImportError: logger.warning("Colors module not available, using slow Python implementation") colors = None else: colors = _colors.Flatfield("flatfield.txt") sRGB = _colors.SRGB() ExpoRedBlue = namedtuple("ExpoRedBlue", ("ev", "red", "blue")) GainRedBlue = namedtuple("GainRedBlue", ("red", "blue")) class SavGol(object): "Class for Savitsky-Golay filtering" def __init__(self, order=2): "select the order of the filter" self.order = order self.cache = {} #len, filter def __call__(self, lst): "filter a list. the last having the more weight" l = len(lst) if l%2 == 0: lst = numpy.array(lst[1:]) l -= 1 else: lst = numpy.array(lst) if len(lst) < self.order: return lst[-1] if l not in self.cache: self.cache[l] = savgol_coeffs(l, self.order, pos=0) return numpy.dot(lst, self.cache[l]) savgol0 = SavGol(0) savgol1 = SavGol(1) class Frame(object): """This class holds one image""" BINNING = 1 INDEX = 0 semclass = threading.Semaphore() # YUV conversion matrix from ITU-R BT.601 version (SDTV) # Y U V YUV2RGB = numpy.array([[1.164, 0.000, 1.596], # R [1.164, -0.392, -0.813], # G [1.164, 2.017, 0.000]]).T # B def __init__(self, data): "Constructor" self.timestamp = time.time() with self.semclass: self.index = self.INDEX self.__class__.INDEX += 1 self.data = data self.camera_meta = {} self.gravity = None self.position = None self.servo_status = None self.sem = threading.Semaphore() self._yuv = None self._rgb = None self._histograms = None def __repr__(self): return "Frame #%04i"%self.index def get_date_time(self): return time.strftime("%Y-%m-%d-%Hh%Mm%Ss", time.localtime(self.timestamp)) @property def yuv(self): """Retrieve the YUV array, binned 2x2 or not depending on the BINNING class attribute""" if self._yuv is None: with self.sem: if self._yuv is None: resolution = self.camera_meta.get("resolution", (640, 480)) if colors: yuv = _colors.yuv420_to_yuv(self.data, resolution)[0] else: width, height = resolution fwidth = (width + 31) & ~(31) fheight = (height + 15) & ~ (15) ylen = fwidth * fheight uvlen = ylen // 4 ary = numpy.frombuffer(self.data, dtype=numpy.uint8) if self.BINNING == 2: Y_full = (ary[:ylen]).astype(numpy.int16) Y_full.shape = (fheight, fwidth) Y = (Y_full[::2, ::2] + Y_full[::2, 1::2] + Y_full[1::2, ::2] + Y_full[1::2, 1::2]) // 4 U = ary[ylen: - uvlen].reshape((fheight // 2, fwidth // 2)) V = ary[-uvlen:].reshape((fheight // 2, fwidth // 2)) yuv = numpy.dstack((Y.astype(numpy.uint8), U, V))[:height // 2, :width // 2, :] else: # Reshape the values into two dimensions, and double the size of the # U and V values (which only have quarter resolution in YUV4:2:0) Y = (ary[:ylen]).reshape((fheight, fwidth)) U = (ary[ylen: - uvlen]).reshape((fheight // 2, fwidth // 2)).repeat(2, axis=0).repeat(2, axis=1) V = (ary[-uvlen:]).reshape((fheight // 2, fwidth // 2)).repeat(2, axis=0).repeat(2, axis=1) # Stack the channels together and crop to the actual resolution yuv = numpy.dstack((Y, U, V))[:height, :width, :] self._yuv = yuv return self._yuv @property def rgb(self): """retrieve the image a RGB array. Takes 13s""" if self._rgb is None: if colors is None: YUV = self.yuv.astype(numpy.int16) with self.sem: if self._rgb is None: if colors: resolution = self.camera_meta.get("resolution", (640, 480)) self._rgb, self._histograms = colors.yuv420_to_rgb16(self.data, resolution) else: YUV[:, :, 0] = YUV[:, :, 0] - 16 # Offset Y by 16 YUV[:, :, 1:] = YUV[:, :, 1:] - 128 # Offset UV by 128 # Calculate the dot product with the matrix to produce RGB output, # clamp the results to byte range and convert to bytes self._rgb = (YUV.dot(self.YUV2RGB)*257.0).clip(0, 65535).astype(numpy.uint16) return self._rgb @property def histograms(self): """Calculate the 4 histograms with Y,R,G,B""" if self._histograms is None: if colors is None: histograms = numpy.zeros((4, 256), numpy.int32) histograms[0] = numpy.bincount(self.yuv[:, :, 0].ravel(), minlength=256) histograms[1] = numpy.bincount(self.rgb[:, :, 0].ravel(), minlength=256) histograms[2] = numpy.bincount(self.rgb[:, :, 1].ravel(), minlength=256) histograms[3] = numpy.bincount(self.rgb[:, :, 2].ravel(), minlength=256) self._histograms = histograms else: rgb = self.rgb return self._histograms @classmethod def load(cls, fname): """load the raw data on one side and the header on the other""" with open(fname) as f: new = cls(f.read()) jf = fname[:-3] + "json" if os.path.exists(jf): with open(jf) as f: new.camera_meta = json.load(f) if "index" in new.camera_meta: new.index = new.camera_meta["index"] return new def save(self): "Save the data as YUV raw data" fname = self.get_date_time()+".yuv" with open(fname, "w") as f: f.write(self.data) fname = self.get_date_time()+".json" comments = OrderedDict((("index", self.index),)) if self.position: comments["pan"] = self.position.pan comments["tilt"] = self.position.tilt if self.gravity: comments["gx"] = self.gravity.x comments["gy"] = self.gravity.y comments["gz"] = self.gravity.z comments.update(self.camera_meta) with open(fname, "w") as f: f.write(json.dumps(comments, indent=4)) logger.info("Saved YUV raw data %i %s", self.index, fname) class StreamingOutput(object): """This class handles the stream, it re-cycles a BytesIO and provides frames""" def __init__(self, size): """Constructor :param size: size of an image in bytes. For YUV, it is 1.5x the number of pixel of the padded image. """ self.size = size self.frame = None self.buffer = io.BytesIO() self.condition = threading.Condition() def write(self, buf): res = self.buffer.write(buf) if self.buffer.tell() >= self.size: #image complete self.buffer.truncate(self.size) # New frame, copy the existing buffer's content and notify all # clients it's available with self.condition: self.frame = Frame(self.buffer.getvalue()) self.condition.notify_all() self.buffer.seek(0) else: print("Incomplete buffer of %i bytes"%self.buffer.tell()) return res class Camera(threading.Thread): "A class for acquiring continusly images..." def __init__(self, resolution=(3280, 2464), framerate=1, sensor_mode=3, avg_ev=21, avg_wb=31, histo_ev=None, wb_red=None, wb_blue=None, quit_event=None, queue=None, config_queue=None): """This thread handles the camera """ threading.Thread.__init__(self, name="Camera") signal.signal(signal.SIGINT, self.quit) self.quit_event = quit_event or threading.Event() self._can_record = threading.Event() self._done_recording = threading.Event() self._done_recording.set() self._can_record.set() self.queue = queue or Queue() self.config_queue = config_queue or Queue() self.avg_ev = avg_ev self.avg_wb = avg_wb self.histo_ev = histo_ev or [] self.wb_red = wb_red or [] self.wb_blue = wb_blue or [] raw_size = (((resolution[0]+31)& ~(31))*((resolution[1]+15)& ~(15))*3//2) self.stream = StreamingOutput(raw_size) self.camera = PiCamera(resolution=resolution, framerate=framerate, sensor_mode=sensor_mode) def __del__(self): self.camera = self.stream = None def quit(self, *arg, **kwarg): "quit the main loop and end the thread" self.quit_event.set() def pause(self, wait=True): "pause the recording, wait for the current value to be acquired" self._can_record.clear() if wait: self._done_recording.wait() def resume(self): "resume the recording" self._can_record.set() def get_config(self): config = OrderedDict([("resolution", tuple(self.camera.resolution)), ("framerate", float(self.camera.framerate)), ("sensor_mode", self.camera.sensor_mode), ("avg_ev", self.avg_ev), ("avg_wb", self.avg_wb), ("hist_ev", self.histo_ev), ("wb_red", self.wb_red), ("wb_blue", self.wb_blue)]) return config def set_config(self, dico): self.camera.resolution = dico.get("resolution", self.camera.resolution) self.camera.framerate = dico.get("framerate", self.camera.framerate) self.camera.sensor_mode = dico.get("sensor_mode", self.camera.sensor_mode) self.wb_red = dico.get("wb_red", self.wb_red) self.wb_blue = dico.get("wb_blue", self.wb_blue) self.histo_ev = dico.get("histo_ev", self.histo_ev) self.avg_ev = dico.get("avg_ev", self.avg_ev) self.avg_wb = dico.get("avg_wb", self.avg_wb) def set_analysis(self, do_analysis): if do_analysis: self.camera.awb_mode = "off" # "auto" self.camera.exposure_mode = "off" #night" #"auto" else: self.camera.awb_mode = "auto" self.camera.exposure_mode = "auto" def get_metadata(self): metadata = {"iso": float(self.camera.iso), "analog_gain": float(self.camera.analog_gain), "awb_gains": [float(i) for i in self.camera.awb_gains], "digital_gain": float(self.camera.digital_gain), "exposure_compensation": float(self.camera.exposure_compensation), "exposure_speed": float(self.camera.exposure_speed), "exposure_mode": self.camera.exposure_mode, "framerate": float(self.camera.framerate), "revision": self.camera.revision, "shutter_speed": float(self.camera.shutter_speed), "aperture": lens.aperture, "resolution": self.camera.resolution} if metadata['revision'] == "imx219": metadata['iso_calc'] = 54.347826086956516 * metadata["analog_gain"] * metadata["digital_gain"] else: metadata['iso_calc'] = 100.0 * metadata["analog_gain"] * metadata["digital_gain"] return metadata def warm_up(self, delay=10): "warm up the camera" logger.info("warming up the camera for %ss",delay) framerate = self.camera.framerate self.camera.awb_mode = "auto" self.camera.exposure_mode = "auto" self.camera.framerate = 10 for i in range(delay): rg, bg = self.camera.awb_gains rg = float(rg) bg = float(bg) if rg == 0.0: rg = 1.0 if bg == 0.0: bg = 1.0 self.wb_red.append(rg) self.wb_blue.append(bg) time.sleep(1) self.camera.framerate = framerate def run(self): "main thread activity" #self.camera.awb_mode = "off" # "auto" #self.camera.exposure_mode = "off" #night" #"auto" self._done_recording.clear() for foo in self.camera.capture_continuous(self.stream, format='yuv'): self._done_recording.set() if self.stream.frame is not None: frame = self.stream.frame logger.debug("Acquired %s", frame) frame.camera_meta = self.get_metadata() self.queue.put(frame) else: logger.info("No frame acquired") if self.quit_event.is_set(): break # update the camera settings if needed: # Disabled for now at trajlaps level if not self.config_queue.empty(): while not self.config_queue.empty(): evrb = self.config_queue.get() if evrb.red: self.wb_red.append(evrb.red) self.wb_blue.append(evrb.blue) if evrb.ev: self.histo_ev.append(evrb.ev) self.config_queue.task_done() self.update_expo() self._can_record.wait() self._done_recording.clear() self.camera.close() def update_expo(self): """This method updates the white balance, exposure time and gain according to the history """ #return #disabled for now if len(self.wb_red) * len(self.wb_blue) == 0: return if len(self.wb_red) > self.avg_wb: self.wb_red = self.wb_red[-self.avg_wb:] self.wb_blue = self.wb_blue[-self.avg_wb:] if len(self.histo_ev) > self.avg_ev: self.histo_ev = self.histo_ev[-self.avg_ev:] self.camera.awb_gains = (savgol0(self.wb_red), savgol0(self.wb_blue)) ev = savgol1(self.histo_ev) speed = lens.calc_speed(ev) #if self.camera.revision == "imx219": # speed *= 1.84 framerate = float(self.camera.framerate) logger.info("Update speed: %s %s",speed,framerate) if speed > framerate: self.camera.shutter_speed = int(1000000. / framerate / speed) self.camera.iso = 100 elif speed > framerate * 2: self.camera.shutter_speed = int(2000000. / framerate / speed) self.camera.iso = 200 elif speed > framerate * 4: self.camera.shutter_speed = int(4000000. / framerate / speed) self.camera.iso = 400 else: self.camera.shutter_speed = min(int(8000000. / framerate / speed), int(1000000/framerate)) self.camera.iso = 800 # #TODO: how to change framerate ? maybe start with low class Saver(threading.Thread): "This thread is in charge of saving the frames arriving from the queue on the disk" def __init__(self, folder="/mnt", queue=None, quit_event=None): threading.Thread.__init__(self, name="Saver") self.queue = queue or Queue() self.quit_event = quit_event or threading.Signal() self.folder = os.path.abspath(folder) if not os.path.exists(self.folder): logger.warning("Creating folder %s", self.folder) os.makedirs(self.folder) def run(self): while not self.quit_event.is_set(): t0 = time.time() frames = self.queue.get() if frames: frame = frames.pop() if not frame: continue comments = OrderedDict((("index", frame.index), ("summed", 1))) exposure_speed = frame.camera_meta.get("exposure_speed", 1) RGB16 = frame.rgb if exposure_speed > 62000.0: #1/16 seconde #2e5/frame.camera_meta.get("framerate"): while frames: other = frames.pop() #merge in linear RGB space summed, over = sRGB.sum(RGB16, other.rgb) if over: break else: RGB16 = summed comments["summed"] += 1 exposure_speed += other.camera_meta.get("exposure_speed", 1) frames = None gc.collect() name = os.path.join(self.folder, frame.get_date_time()+".jpg") logger.info("Save frame #%i as %s sum of %i", frame.index, name, comments["summed"]) rgb8 = sRGB.compress(RGB16) Image.fromarray(rgb8).save(name, quality=90, optimize=True, progressive=True) exif = pyexiv2.ImageMetadata(name) exif.read() speed = Fraction(int(exposure_speed), 1000000) iso = int(frame.camera_meta.get("iso_calc")) exif["Exif.Photo.FNumber"] = Fraction(int(frame.camera_meta.get("aperture") * 100), 100) exif["Exif.Photo.ExposureTime"] = speed exif["Exif.Photo.ISOSpeedRatings"] = iso if frame.position: comments["pan"] = frame.position.pan comments["tilt"] = frame.position.tilt if frame.gravity: comments["gx"] = frame.gravity.x comments["gy"] = frame.gravity.y comments["gz"] = frame.gravity.z comments.update(frame.camera_meta) if frame.servo_status: comments.update(frame.servo_status) exif.comment = json.dumps(comments) exif.write(preserve_timestamps=True) self.queue.task_done() logger.info("Saving of frame #%i took %.3fs, sum of %s", frame.index, time.time() - t0, comments["summed"]) class Analyzer(threading.Thread): "This thread is in charge of analyzing the image and suggesting new exposure value and white balance" def __init__(self, frame_queue=None, config_queue=None, quit_event=None): threading.Thread.__init__(self, name="Analyzer") self.queue = frame_queue or Queue() self.output_queue = config_queue or Queue() self.quit_event = quit_event or threading.Signal() #self.history = [] #self.max_size = 100 #i = numpy.arange(40) #j = 0.5 ** (0.25 * i) #k = ((j + 0.099) / 1.099) ** (1 / 0.45) * (235 - 16) + 16 #m2 = j < 0.018 #k[m2] = (235-16) / 4.5 * j[m2] + 16 #kr = numpy.round(k).astype(int) #self.ukr = numpy.concatenate(([0], numpy.sort(numpy.unique(kr)), [256])) #start = -0.25*(self.ukr.size-1)+0.5 #self.delta_expo = numpy.arange(start, 0.5, 0.25) #self.g19_2 = gaussian(19, 2) #self.g19_2 /= self.g19_2.sum() def run(self): """This executed in a thread""" target_rgb = 5e-4 # pixels at 99.5% should be white while not self.quit_event.is_set(): frame = self.queue.get() t0 = time.time() ev = oldev = lens.calc_EV(1000000/frame.camera_meta.get("exposure_speed", 1), iso=frame.camera_meta.get("iso_calc",100)) histo = frame.histograms if 1: #for exposure calculation: ylin = histo[0] ymax = numpy.where(ylin)[0][-1] #logger.info("ymax: %s", ymax) if ymax>1000: logger.debug("exposition %s is correct to over %s", ev, ymax) cs = ylin.cumsum() lim = 16 lo_light = cs[lim-1] hi_light = cs[-1] - cs[-lim] if hi_light > lo_light: #over exposed if lo_light == 0: ev += 1 else: log(1.0 * hi_light/lo_light, 2) logger.info("image is over-exposed, let's shrink %s %s eV: %s->%s", lo_light, hi_light, oldev, ev) else: ev += log(1.0 * ymax / ylin.size, 2) logger.info("image is under exposed, let's boost it %s eV: %s->%s", ymax, oldev, ev) if 1: #Calculation of the corrected white-balance csr = numpy.cumsum(histo[1]) csg = numpy.cumsum(histo[2]) csb = numpy.cumsum(histo[3]) if (csr[-1] != csg[-1]) or (csg[-1] != csb[-1]): logger.error("Different number of pixel in chanels R, G and B: %s", histo.sum(axis=-1)) pos = csr[-1] * (1.0 - target_rgb) try: pos_r = numpy.where(csr >= pos)[0][0] pos_g = numpy.where(csg >= pos)[0][0] pos_b = numpy.where(csb >= pos)[0][0] except IndexError as e: logger.error("no awb %s, exposure to low ",e) #self.queue.task_done() #continue pos_r = numpy.where(histo[1])[0][-1] pos_g = numpy.where(histo[2])[0][-1] pos_b = numpy.where(histo[3])[0][-1] rg, bg = frame.camera_meta.get("awb_gains", (1.0, 1.0)) if rg == 0.0: rg = 1.0 if bg == 0.0: bg = 1.0 try: red_gain = 1.0 * rg * pos_g / pos_r blue_gain = 1.0 * bg * pos_g / pos_b logger.info("Update Red: %s -> %s Blue %s -> %s r%s g%s b%s", rg, red_gain, bg, blue_gain, pos_r, pos_g, pos_b) #awb = GainRedBlue(min(8, max(0.125, red_gain)), min(8, max(0.125, blue_gain))) except ZeroDivisionError: logger.error("pos_r %s, pos_g %s, pos_b %s, rg %s, bg %s", pos_r, pos_g, pos_b, rg, bg) red_gain = rg blue_gain = bg #awb = GainRedBlue(rg, bg) else: red_gain = None blue_gain = None now = time.time() awb = ExpoRedBlue(ev, min(8, max(0.125, red_gain)), min(8, max(0.125, blue_gain))) self.output_queue.put(awb) self.queue.task_done() logger.info("Analysis of frame #%i took: %.3fs, delay since acquisition: %.3fs", frame.index, now-t0, now-frame.timestamp) ```
[ { "content": "Reconstruct the code exactly:\n```python\n# -*- coding: utf-8 -*-\nfrom freezegun import freeze_time\n\nfrom odoo.addons.account.tests.common import AccountTestInvoicingCommon\nfrom odoo.tests.common import Form\nfrom odoo.tests import tagged\n\n\n@tagged('post_install', '-at_install')\nclass Test...
[ { "content": "Reconstruct the code exactly:\n<|memory_start|>```python\n# -*- coding: utf-8 -*-\nfrom freezegun import freeze_time\n\nfrom odoo.addons.account.tests.common import AccountTestInvoicingCommon\nfrom odoo.tests.common import Form\nfrom odoo.tests import tagged\n\n\n@tagged('post_install', '-at_insta...
```python # -*- coding: utf-8 -*- from freezegun import freeze_time from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests.common import Form from odoo.tests import tagged @tagged('post_install', '-at_install') class TestReconciliationMatchingRules(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) ################# # Company setup # ################# cls.currency_data_2 = cls.setup_multi_currency_data({ 'name': 'Dark Chocolate Coin', 'symbol': '🍫', 'currency_unit_label': 'Dark Choco', 'currency_subunit_label': 'Dark Cacao Powder', }, rate2016=10.0, rate2017=20.0) cls.company = cls.company_data['company'] cls.account_pay = cls.company_data['default_account_payable'] cls.current_assets_account = cls.env['account.account'].search([ ('user_type_id', '=', cls.env.ref('account.data_account_type_current_assets').id), ('company_id', '=', cls.company.id)], limit=1) cls.bank_journal = cls.env['account.journal'].search([('type', '=', 'bank'), ('company_id', '=', cls.company.id)], limit=1) cls.cash_journal = cls.env['account.journal'].search([('type', '=', 'cash'), ('company_id', '=', cls.company.id)], limit=1) cls.tax21 = cls.env['account.tax'].create({ 'name': '21%', 'type_tax_use': 'purchase', 'amount': 21, }) cls.tax12 = cls.env['account.tax'].create({ 'name': '12%', 'type_tax_use': 'purchase', 'amount': 12, }) cls.partner_1 = cls.env['res.partner'].create({'name': 'partner_1', 'company_id': cls.company.id}) cls.partner_2 = cls.env['res.partner'].create({'name': 'partner_2', 'company_id': cls.company.id}) cls.partner_3 = cls.env['res.partner'].create({'name': 'partner_3', 'company_id': cls.company.id}) ############### # Rules setup # ############### cls.rule_1 = cls.env['account.reconcile.model'].create({ 'name': 'Invoices Matching Rule', 'sequence': '1', 'rule_type': 'invoice_matching', 'auto_reconcile': False, 'match_nature': 'both', 'match_same_currency': True, 'match_total_amount': True, 'match_total_amount_param': 100, 'match_partner': True, 'match_partner_ids': [(6, 0, (cls.partner_1 + cls.partner_2 + cls.partner_3).ids)], 'company_id': cls.company.id, 'line_ids': [(0, 0, {'account_id': cls.current_assets_account.id})], }) cls.rule_2 = cls.env['account.reconcile.model'].create({ 'name': 'write-off model', 'rule_type': 'writeoff_suggestion', 'match_partner': True, 'match_partner_ids': [], 'line_ids': [(0, 0, {'account_id': cls.current_assets_account.id})], }) ################## # Invoices setup # ################## cls.invoice_line_1 = cls._create_invoice_line(100, cls.partner_1, 'out_invoice') cls.invoice_line_2 = cls._create_invoice_line(200, cls.partner_1, 'out_invoice') cls.invoice_line_3 = cls._create_invoice_line(300, cls.partner_1, 'in_refund', name="RBILL/2019/09/0013") cls.invoice_line_4 = cls._create_invoice_line(1000, cls.partner_2, 'in_invoice') cls.invoice_line_5 = cls._create_invoice_line(600, cls.partner_3, 'out_invoice') cls.invoice_line_6 = cls._create_invoice_line(600, cls.partner_3, 'out_invoice', ref="RF12 3456") cls.invoice_line_7 = cls._create_invoice_line(200, cls.partner_3, 'out_invoice', pay_reference="RF12 3456") #################### # Statements setup # #################### # TODO : account_number, partner_name, transaction_type, narration invoice_number = cls.invoice_line_1.move_id.name cls.bank_st, cls.bank_st_2, cls.cash_st = cls.env['account.bank.statement'].create([ { 'name': 'test bank journal', 'journal_id': cls.bank_journal.id, 'line_ids': [ (0, 0, { 'payment_ref': 'invoice %s-%s-%s' % tuple(invoice_number.split('/')[1:]), 'partner_id': cls.partner_1.id, 'amount': 100, 'sequence': 1, }), (0, 0, { 'payment_ref': 'xxxxx', 'partner_id': cls.partner_1.id, 'amount': 600, 'sequence': 2, }), ], }, { 'name': 'second test bank journal', 'journal_id': cls.bank_journal.id, 'line_ids': [ (0, 0, { 'payment_ref': 'nawak', 'narration': 'Communication: RF12 3456', 'partner_id': cls.partner_3.id, 'amount': 600, 'sequence': 1, }), (0, 0, { 'payment_ref': 'RF12 3456', 'partner_id': cls.partner_3.id, 'amount': 600, 'sequence': 2, }), (0, 0, { 'payment_ref': 'baaaaah', 'ref': 'RF12 3456', 'partner_id': cls.partner_3.id, 'amount': 600, 'sequence': 2, }), ], }, { 'name': 'test cash journal', 'journal_id': cls.cash_journal.id, 'line_ids': [ (0, 0, { 'payment_ref': 'yyyyy', 'partner_id': cls.partner_2.id, 'amount': -1000, 'sequence': 1, }), ], } ]) cls.bank_line_1, cls.bank_line_2 = cls.bank_st.line_ids cls.bank_line_3, cls.bank_line_4, cls.bank_line_5 = cls.bank_st_2.line_ids cls.cash_line_1 = cls.cash_st.line_ids cls._post_statements(cls) @classmethod def _create_invoice_line(cls, amount, partner, type, currency=None, pay_reference=None, ref=None, name=None): ''' Create an invoice on the fly.''' invoice_form = Form(cls.env['account.move'].with_context(default_move_type=type, default_invoice_date='2019-09-01', default_date='2019-09-01')) invoice_form.partner_id = partner if currency: invoice_form.currency_id = currency if pay_reference: invoice_form.payment_reference = pay_reference if ref: invoice_form.ref = ref if name: invoice_form.name = name with invoice_form.invoice_line_ids.new() as invoice_line_form: invoice_line_form.name = 'xxxx' invoice_line_form.quantity = 1 invoice_line_form.price_unit = amount invoice_line_form.tax_ids.clear() invoice = invoice_form.save() invoice.action_post() lines = invoice.line_ids return lines.filtered(lambda l: l.account_id.user_type_id.type in ('receivable', 'payable')) def _post_statements(self): self.bank_st.balance_end_real = self.bank_st.balance_end self.bank_st_2.balance_end_real = self.bank_st_2.balance_end self.cash_st.balance_end_real = self.cash_st.balance_end (self.bank_st + self.bank_st_2 + self.cash_st).button_post() def _check_statement_matching(self, rules, expected_values, statements=None): if statements is None: statements = self.bank_st + self.cash_st statement_lines = statements.mapped('line_ids').sorted() matching_values = rules._apply_rules(statement_lines, None) for st_line_id, values in matching_values.items(): values.pop('reconciled_lines', None) values.pop('write_off_vals', None) self.assertDictEqual(values, expected_values[st_line_id]) def test_matching_fields(self): # Check without restriction. self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) def test_matching_fields_match_text_location(self): self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = False self.rule_1.match_text_location_note = False self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = False self.rule_1.match_text_location_note = True self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = True self.rule_1.match_text_location_note = False self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = True self.rule_1.match_text_location_note = True self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = False self.rule_1.match_text_location_reference = False self.rule_1.match_text_location_note = False self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) def test_matching_fields_match_journal_ids(self): self.rule_1.match_journal_ids |= self.cash_st.journal_id self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_journal_ids |= self.bank_st.journal_id + self.cash_st.journal_id def test_matching_fields_match_nature(self): self.rule_1.match_nature = 'amount_received' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': []}, }) self.rule_1.match_nature = 'amount_paid' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_nature = 'both' def test_matching_fields_match_amount(self): self.rule_1.match_amount = 'lower' self.rule_1.match_amount_max = 150 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': []}, }) self.rule_1.match_amount = 'greater' self.rule_1.match_amount_min = 200 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_1.id, self.invoice_line_2.id, self.invoice_line_3.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_amount = 'between' self.rule_1.match_amount_min = 200 self.rule_1.match_amount_max = 800 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_1.id, self.invoice_line_2.id, self.invoice_line_3.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': []}, }) self.rule_1.match_amount = False def test_matching_fields_match_label(self): self.rule_1.match_label = 'contains' self.rule_1.match_label_param = 'yyyyy' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_label = 'not_contains' self.rule_1.match_label_param = 'xxxxx' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_label = 'match_regex' self.rule_1.match_label_param = 'xxxxx|yyyyy' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_1.id, self.invoice_line_2.id, self.invoice_line_3.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_label = False def test_matching_fields_match_total_amount(self): # Check match_total_amount: line amount >= total residual amount. self.rule_1.match_total_amount_param = 90.0 self.bank_line_1.amount += 5 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'status': 'write_off', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_total_amount_param = 100.0 self.bank_line_1.amount -= 5 # Check match_total_amount: line amount <= total residual amount. self.rule_1.match_total_amount_param = 90.0 self.bank_line_1.amount -= 5 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'status': 'write_off', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_total_amount_param = 100.0 self.bank_line_1.amount += 5 def test_matching_fields_match_partner_category_ids(self): test_category = self.env['res.partner.category'].create({'name': 'Consulting Services'}) self.partner_2.category_id = test_category self.rule_1.match_partner_category_ids |= test_category self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_partner_category_ids = False def test_mixin_rules(self): ''' Test usage of rules together.''' # rule_1 is used before rule_2. self.rule_1.sequence = 1 self.rule_2.sequence = 2 self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) # rule_2 is used before rule_1. self.rule_1.sequence = 2 self.rule_2.sequence = 1 self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.cash_line_1.partner_id}, }) # rule_2 is used before rule_1 but only on partner_1. self.rule_2.match_partner_ids |= self.partner_1 self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) def test_auto_reconcile(self): ''' Test auto reconciliation.''' self.bank_line_1.amount += 5 self.rule_1.sequence = 2 self.rule_1.auto_reconcile = True self.rule_1.match_total_amount_param = 90 self.rule_2.sequence = 1 self.rule_2.match_partner_ids |= self.partner_2 self.rule_2.auto_reconcile = True self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'reconciled', 'partner': self.cash_line_1.partner_id}, }) # Check first line has been well reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 105.0, 'credit': 0.0}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 5.0}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 100.0}, ]) # Check second line has been well reconciled. self.assertRecordValues(self.cash_line_1.line_ids, [ {'partner_id': self.partner_2.id, 'debit': 0.0, 'credit': 1000.0}, {'partner_id': self.partner_2.id, 'debit': 1000.0, 'credit': 0.0}, ]) def test_larger_invoice_auto_reconcile(self): ''' Test auto reconciliation with an invoice with larger amount than the statement line's, for rules without write-offs.''' self.bank_line_1.amount = 40 self.invoice_line_1.move_id.payment_reference = self.bank_line_1.payment_ref self.rule_1.sequence = 2 self.rule_1.auto_reconcile = True self.rule_1.line_ids = [(5, 0, 0)] self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, statements=self.bank_st) # Check first line has been well reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 40.0, 'credit': 0.0}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 40.0}, ]) self.assertEqual(self.invoice_line_1.amount_residual, 60.0, "The invoice should have been partially reconciled") def test_auto_reconcile_with_tax(self): ''' Test auto reconciliation with a tax amount included in the bank statement line''' self.rule_1.write({ 'auto_reconcile': True, 'rule_type': 'writeoff_suggestion', 'line_ids': [(1, self.rule_1.line_ids.id, { 'amount': 50, 'force_tax_included': True, 'tax_ids': [(6, 0, self.tax21.ids)], }), (0, 0, { 'amount': 100, 'force_tax_included': False, 'tax_ids': [(6, 0, self.tax12.ids)], 'account_id': self.current_assets_account.id, })] }) self.bank_line_1.amount = -121 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_2.partner_id}, }, statements=self.bank_st) # Check first line has been well reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 121.0, 'tax_ids': [], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 7.26, 'tax_ids': [], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 50.0, 'credit': 0.0, 'tax_ids': [self.tax21.id], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 10.5, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.tax21.id}, {'partner_id': self.partner_1.id, 'debit': 60.5, 'credit': 0.0, 'tax_ids': [self.tax12.id], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 7.26, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.tax12.id}, ]) def test_reverted_move_matching(self): partner = self.partner_1 AccountMove = self.env['account.move'] move = AccountMove.create({ 'journal_id': self.bank_journal.id, 'line_ids': [ (0, 0, { 'account_id': self.account_pay.id, 'partner_id': partner.id, 'name': 'One of these days', 'debit': 10, }), (0, 0, { 'account_id': self.bank_journal.payment_credit_account_id.id, 'partner_id': partner.id, 'name': 'I\'m gonna cut you into little pieces', 'credit': 10, }) ], }) payment_bnk_line = move.line_ids.filtered(lambda l: l.account_id == self.bank_journal.payment_credit_account_id) move.action_post() move_reversed = move._reverse_moves() self.assertTrue(move_reversed.exists()) self.bank_line_1.write({ 'payment_ref': '8', 'partner_id': partner.id, 'amount': -10, }) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [payment_bnk_line.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, statements=self.bank_st) def test_match_different_currencies(self): partner = self.env['res.partner'].create({'name': 'Bernard Gagnant'}) self.rule_1.write({'match_partner_ids': [(6, 0, partner.ids)], 'match_same_currency': False}) currency_inv = self.env.ref('base.EUR') currency_statement = self.env.ref('base.JPY') currency_statement.active = True invoice_line = self._create_invoice_line(100, partner, 'out_invoice', currency=currency_inv) self.bank_line_1.write({'partner_id': partner.id, 'foreign_currency_id': currency_statement.id, 'amount_currency': 100, 'payment_ref': 'test'}) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': invoice_line.ids, 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, statements=self.bank_st) def test_invoice_matching_rule_no_partner(self): """ Tests that a statement line without any partner can be matched to the right invoice if they have the same payment reference. """ self.invoice_line_1.move_id.write({'payment_reference': 'Tournicoti66'}) self.bank_line_1.write({ 'payment_ref': 'Tournicoti66', 'partner_id': None, 'amount': 95, }) self.rule_1.write({ 'line_ids': [(5, 0, 0)], 'match_partner': False, 'match_label': 'contains', 'match_label_param': 'Tournicoti', # So that we only match what we want to test }) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) def test_inv_matching_rule_auto_rec_no_partner_with_writeoff(self): self.invoice_line_1.move_id.write({'payment_reference': 'doudlidou355'}) self.bank_line_1.write({ 'payment_ref': 'doudlidou355', 'partner_id': None, 'amount': 95, }) self.rule_1.write({ 'match_partner': False, 'match_label': 'contains', 'match_label_param': 'doudlidou', # So that we only match what we want to test 'match_total_amount_param': 90, 'auto_reconcile': True, }) # Check bank reconciliation self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id, 'status': 'reconciled'}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) # Check invoice line has been fully reconciled, with a write-off. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 95.0, 'credit': 0.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 5.0, 'credit': 0.0, 'account_id': self.current_assets_account.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 100.0, 'account_id': self.invoice_line_1.account_id.id, 'reconciled': True}, ]) self.assertEqual(self.invoice_line_1.amount_residual, 0.0, "The invoice should have been fully reconciled") def test_partner_mapping_rule(self): self.bank_line_1.write({'partner_id': None, 'payment_ref': 'toto42', 'narration': None}) self.bank_line_2.write({'partner_id': None}) # Do the test for both rule 1 and 2, so that we check invoice matching and write-off rules for rule in (self.rule_1 + self.rule_2): # To cope for minor differences in rule results matching_amls = rule.rule_type == 'invoice_matching' and self.invoice_line_1.ids or [] result_status = rule.rule_type == 'writeoff_suggestion' and {'status': 'write_off'} or {} match_result = {**result_status, 'aml_ids': matching_amls, 'model': rule, 'partner': self.partner_1} no_match_result = {'aml_ids': []} # Without mapping, there should be no match self._check_statement_matching(rule, { self.bank_line_1.id: no_match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) # We add some mapping for payment reference to rule_1 rule.write({ 'partner_mapping_line_ids': [(0, 0, { 'partner_id': self.partner_1.id, 'payment_ref_regex': 'toto.*', })] }) # bank_line_1 should now match self._check_statement_matching(rule, { self.bank_line_1.id: match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) # If we now add a narration regex to the same mapping line, nothing should match rule.partner_mapping_line_ids.write({'narration_regex': ".*coincoin"}) self.bank_line_1.write({'narration': None}) # Reset from possible previous iteration self._check_statement_matching(rule, { self.bank_line_1.id: no_match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) # If we set the narration so that it matches the new mapping criterium, line_1 matches self.bank_line_1.write({'narration': "42coincoin"}) self._check_statement_matching(rule, { self.bank_line_1.id: match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) def test_partner_name_in_communication(self): self.invoice_line_1.partner_id.write({'name': "Archibald Haddock"}) self.bank_line_1.write({'partner_id': None, 'payment_ref': '1234//HADDOCK-Archibald'}) self.bank_line_2.write({'partner_id': None}) self.rule_1.write({'match_partner': False}) # bank_line_1 should match, as its communication contains the invoice's partner name self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) def test_partner_name_with_regexp_chars(self): self.invoice_line_1.partner_id.write({'name': "Archibald + Haddock"}) self.bank_line_1.write({'partner_id': None, 'payment_ref': '1234//HADDOCK+Archibald'}) self.bank_line_2.write({'partner_id': None}) self.rule_1.write({'match_partner': False}) # The query should still work self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) def test_match_multi_currencies(self): ''' Ensure the matching of candidates is made using the right statement line currency. In this test, the value of the statement line is 100 USD = 300 GOL = 900 DAR and we want to match two journal items of: - 100 USD = 200 GOL (= 600 DAR from the statement line point of view) - 14 USD = 280 DAR Both journal items should be suggested to the user because they represents 98% of the statement line amount (DAR). ''' partner = self.env['res.partner'].create({'name': 'Bernard Perdant'}) journal = self.env['account.journal'].create({ 'name': 'test_match_multi_currencies', 'code': 'xxxx', 'type': 'bank', 'currency_id': self.currency_data['currency'].id, }) matching_rule = self.env['account.reconcile.model'].create({ 'name': 'test_match_multi_currencies', 'rule_type': 'invoice_matching', 'match_partner': True, 'match_partner_ids': [(6, 0, partner.ids)], 'match_total_amount': True, 'match_total_amount_param': 95.0, 'match_same_currency': False, 'company_id': self.company_data['company'].id, }) statement = self.env['account.bank.statement'].create({ 'name': 'test_match_multi_currencies', 'journal_id': journal.id, 'line_ids': [ (0, 0, { 'journal_id': journal.id, 'date': '2016-01-01', 'payment_ref': 'line', 'partner_id': partner.id, 'foreign_currency_id': self.currency_data_2['currency'].id, 'amount': 300.0, # Rate is 3 GOL = 1 USD in 2016. 'amount_currency': 900.0, # Rate is 10 DAR = 1 USD in 2016 but the rate used by the bank is 9:1. }), ], }) statement_line = statement.line_ids statement.button_post() move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'journal_id': self.company_data['default_journal_sale'].id, 'line_ids': [ # Rate is 2 GOL = 1 USD in 2017. # The statement line will consider this line equivalent to 600 DAR. (0, 0, { 'account_id': self.company_data['default_account_receivable'].id, 'partner_id': partner.id, 'currency_id': self.currency_data['currency'].id, 'debit': 100.0, 'credit': 0.0, 'amount_currency': 200.0, }), # Rate is 20 GOL = 1 USD in 2017. (0, 0, { 'account_id': self.company_data['default_account_receivable'].id, 'partner_id': partner.id, 'currency_id': self.currency_data_2['currency'].id, 'debit': 14.0, 'credit': 0.0, 'amount_currency': 280.0, }), # Line to balance the journal entry: (0, 0, { 'account_id': self.company_data['default_account_revenue'].id, 'debit': 0.0, 'credit': 114.0, }), ], }) move.action_post() move_line_1 = move.line_ids.filtered(lambda line: line.debit == 100.0) move_line_2 = move.line_ids.filtered(lambda line: line.debit == 14.0) with freeze_time('2017-01-01'): self._check_statement_matching(matching_rule, { statement_line.id: {'aml_ids': (move_line_1 + move_line_2).ids, 'model': matching_rule, 'partner': statement_line.partner_id} }, statements=statement) def test_inv_matching_with_write_off(self): self.rule_1.match_total_amount_param = 90 self.bank_st.line_ids[1].unlink() # We don't need this one here statement_line = self.bank_st.line_ids[0] statement_line.write({ 'payment_ref': self.invoice_line_1.move_id.payment_reference, 'amount': 90, }) # Test the invoice-matching part self._check_statement_matching(self.rule_1, { statement_line.id: {'aml_ids': self.invoice_line_1.ids, 'model': self.rule_1, 'partner': self.invoice_line_1.partner_id, 'status': 'write_off'}, }, self.bank_st) # Test the write-off part expected_write_off = { 'balance': 10, 'currency_id': False, 'reconcile_model_id': self.rule_1.id, 'account_id': self.current_assets_account.id, } matching_result = self.rule_1._apply_rules(statement_line) self.assertEqual(len(matching_result[statement_line.id].get('write_off_vals', [])), 1, "Exactly one write-off line should be proposed.") full_write_off_dict = matching_result[statement_line.id]['write_off_vals'][0] to_compare = { key: full_write_off_dict[key] for key in expected_write_off.keys() } self.assertDictEqual(expected_write_off, to_compare) def test_inv_matching_with_write_off_autoreconcile(self): self.bank_line_1.amount = 95 self.rule_1.sequence = 2 self.rule_1.auto_reconcile = True self.rule_1.match_total_amount_param = 90 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, statements=self.bank_st) # Check first line has been properly reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 95.0, 'credit': 0.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 5.0, 'credit': 0.0, 'account_id': self.current_assets_account.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 100.0, 'account_id': self.invoice_line_1.account_id.id, 'reconciled': True}, ]) self.assertEqual(self.invoice_line_1.amount_residual, 0.0, "The invoice should have been fully reconciled") def test_avoid_amount_matching_bypass(self): """ By the default, if the label of statement lines exactly matches a payment reference, it bypasses any kind of amount verification. This is annoying in some setups, so a config parameter was introduced to handle that. """ self.env['ir.config_parameter'].set_param('account.disable_rec_models_bypass', '1') self.rule_1.match_total_amount_param = 90 second_inv_matching_rule = self.env['account.reconcile.model'].create({ 'name': 'Invoices Matching Rule', 'sequence': 2, 'rule_type': 'invoice_matching', 'auto_reconcile': False, 'match_nature': 'both', 'match_same_currency': False, 'match_total_amount': False, 'match_partner': True, 'company_id': self.company.id, }) self.bank_line_1.write({ 'payment_ref': self.invoice_line_1.move_id.payment_reference, 'amount': 99, }) self.bank_line_2.write({ 'payment_ref': self.invoice_line_2.move_id.payment_reference, 'amount': 1, }) self._check_statement_matching(self.rule_1 + second_inv_matching_rule, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'status': 'write_off', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [self.invoice_line_2.id], 'model': second_inv_matching_rule, 'partner': self.bank_line_2.partner_id} }, statements=self.bank_st) ```
[ { "content": "Return the code exactly, with no changes:\n```python\nfrom argparse import ArgumentParser\nimport os\nimport sys\n\nimport django\nfrom django.conf import settings\n\nfrom coverage import Coverage\nfrom termcolor import colored\n\nTESTS_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file...
[ { "content": "Return the code exactly, with no changes:\n<|memory_start|>```python\nfrom argparse import ArgumentParser\nimport os\nimport sys\n\nimport django\nfrom django.conf import settings\n\nfrom coverage import Coverage\nfrom termcolor import colored\n\nTESTS_ROOT = os.path.abspath(os.path.dirname(os.pat...
```python from argparse import ArgumentParser import os import sys import django from django.conf import settings from coverage import Coverage from termcolor import colored TESTS_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) TESTS_THRESHOLD = 100 def main(): parser = ArgumentParser(description='Run the dj-stripe Test Suite.') parser.add_argument("--skip-utc", action="store_true", help="Skip any tests that require the system timezone to be in UTC.") parser.add_argument("--no-coverage", action="store_true", help="Disable checking for 100% code coverage (Not advised).") parser.add_argument("--no-pep8", action="store_true", help="Disable checking for pep8 errors (Not advised).") args = parser.parse_args() run_test_suite(args) def run_test_suite(args): skip_utc = args.skip_utc enable_coverage = not args.no_coverage enable_pep8 = not args.no_pep8 if enable_coverage: cov = Coverage(config_file=True) cov.erase() cov.start() settings.configure( DJSTRIPE_TESTS_SKIP_UTC=skip_utc, TIME_ZONE='America/Los_Angeles', DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "djstripe", "USER": "", "PASSWORD": "", "HOST": "", "PORT": "", }, }, ROOT_URLCONF="tests.test_urls", INSTALLED_APPS=[ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.sites", "jsonfield", "djstripe", "tests", "tests.apps.testapp" ], MIDDLEWARE_CLASSES=( "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware" ), SITE_ID=1, STRIPE_PUBLIC_KEY=os.environ.get("STRIPE_PUBLIC_KEY", ""), STRIPE_SECRET_KEY=os.environ.get("STRIPE_SECRET_KEY", ""), DJSTRIPE_PLANS={ "test0": { "stripe_plan_id": "test_id_0", "name": "Test Plan 0", "description": "A test plan", "price": 1000, # $10.00 "currency": "usd", "interval": "month" }, "test": { "stripe_plan_id": "test_id", "name": "Test Plan 1", "description": "Another test plan", "price": 2500, # $25.00 "currency": "usd", "interval": "month" }, "test2": { "stripe_plan_id": "test_id_2", "name": "Test Plan 2", "description": "Yet Another test plan", "price": 5000, # $50.00 "currency": "usd", "interval": "month" }, "test_deletion": { "stripe_plan_id": "test_id_3", "name": "Test Plan 3", "description": "Test plan for deletion.", "price": 5000, # $50.00 "currency": "usd", "interval": "month" }, "test_trial": { "stripe_plan_id": "test_id_4", "name": "Test Plan 4", "description": "Test plan for trails.", "price": 7000, # $70.00 "currency": "usd", "interval": "month", "trial_period_days": 7 }, "unidentified_test_plan": { "name": "Unidentified Test Plan", "description": "A test plan with no ID.", "price": 2500, # $25.00 "currency": "usd", "interval": "month" } }, DJSTRIPE_PLAN_HIERARCHY = { "bronze": { "level": 1, "plans": [ "test0", "test", ] }, "silver": { "level": 2, "plans": [ "test2", "test_deletion", ] }, "gold": { "level": 3, "plans": [ "test_trial", "unidentified_test_plan", ] }, }, DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=( "(admin)", "test_url_name", "testapp_namespaced:test_url_namespaced", ), ) # Avoid AppRegistryNotReady exception # http://stackoverflow.com/questions/24793351/django-appregistrynotready if hasattr(django, "setup"): django.setup() # Announce the test suite sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"])) sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"])) sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"])) # Announce test run sys.stdout.write(colored(text="Step 1: Running unit tests.\n\n", color="yellow", attrs=["bold"])) # Hack to reset the global argv before nose has a chance to grab it # http://stackoverflow.com/a/1718407/1834570 args = sys.argv[1:] sys.argv = sys.argv[0:1] from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner(verbosity=1) failures = test_runner.run_tests(["."]) if failures: sys.exit(failures) if enable_coverage: # Announce coverage run sys.stdout.write(colored(text="\nStep 2: Generating coverage results.\n\n", color="yellow", attrs=["bold"])) cov.stop() percentage = round(cov.report(show_missing=True), 2) cov.html_report(directory='cover') cov.save() if percentage < TESTS_THRESHOLD: sys.stderr.write(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " + "WAS {old}%, IS NOW {new}%.\n\n".format(old=TESTS_THRESHOLD, new=percentage), color="red", attrs=["bold"])) sys.exit(1) else: # Announce disabled coverage run sys.stdout.write(colored(text="\nStep 2: Generating coverage results [SKIPPED].", color="yellow", attrs=["bold"])) if enable_pep8: # Announce flake8 run sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors.\n\n", color="yellow", attrs=["bold"])) print("pep8 errors:") print("----------------------------------------------------------------------") from subprocess import call flake_result = call(["flake8", ".", "--count"]) if flake_result != 0: sys.stderr.write("pep8 errors detected.\n") sys.stderr.write(colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n\n", color="red", attrs=["bold"])) sys.exit(flake_result) else: print("None") else: # Announce disabled coverage run sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors [SKIPPED].\n", color="yellow", attrs=["bold"])) # Announce success if enable_coverage and enable_pep8: sys.stdout.write(colored(text="\nTests completed successfully with no errors. Congrats!\n", color="green", attrs=["bold"])) else: sys.stdout.write(colored(text="\nTests completed successfully, but some step(s) were skipped!\n", color="green", attrs=["bold"])) sys.stdout.write(colored(text="Don't push without running the skipped step(s).\n", color="red", attrs=["bold"])) if __name__ == "__main__": main() ```