max_stars_repo_path
stringlengths
6
149
max_stars_repo_name
stringclasses
629 values
max_stars_count
int64
2.02k
191k
id
stringlengths
3
8
content
stringlengths
15
158k
violations
stringclasses
51 values
bugs
stringclasses
11 values
duplicated_lines_density
stringclasses
46 values
cognitive_complexity
stringclasses
117 values
vulnerabilities
stringclasses
3 values
code_smells
stringclasses
50 values
sqale_rating
stringclasses
4 values
security_hotspots
stringclasses
17 values
complexity
stringclasses
112 values
issues
listlengths
0
100
__index_level_0__
int64
2
13.3k
src/python/grpcio_tests/tests/unit/_cython/_server_test.py
warlock135/grpc
36,552
8047522
# Copyright 2017 gRPC 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. """Test servers at the level of the Cython API.""" import threading import time import unittest from grpc._cython import cygrpc class Test(unittest.TestCase): def test_lonely_server(self): server_call_completion_queue = cygrpc.CompletionQueue() server_shutdown_completion_queue = cygrpc.CompletionQueue() server = cygrpc.Server(None, False) server.register_completion_queue(server_call_completion_queue) server.register_completion_queue(server_shutdown_completion_queue) port = server.add_http2_port(b'[::]:0') server.start() server_request_call_tag = 'server_request_call_tag' server_request_call_start_batch_result = server.request_call( server_call_completion_queue, server_call_completion_queue, server_request_call_tag) time.sleep(4) server_shutdown_tag = 'server_shutdown_tag' server_shutdown_result = server.shutdown( server_shutdown_completion_queue, server_shutdown_tag) server_request_call_event = server_call_completion_queue.poll() server_shutdown_event = server_shutdown_completion_queue.poll() if __name__ == '__main__': unittest.main(verbosity=2)
5
0
0.0
1
0
5
1.0
0
2
[ { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 31, "message": "Remove the unused local variable \"port\".", "textRange": { "endLine": 31, "endOffset": 12, "startLine": 31, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 35, "message": "Remove the unused local variable \"server_request_call_start_batch_result\".", "textRange": { "endLine": 35, "endOffset": 46, "startLine": 35, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 42, "message": "Remove the unused local variable \"server_shutdown_result\".", "textRange": { "endLine": 42, "endOffset": 30, "startLine": 42, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 44, "message": "Remove the unused local variable \"server_request_call_event\".", "textRange": { "endLine": 44, "endOffset": 33, "startLine": 44, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 45, "message": "Remove the unused local variable \"server_shutdown_event\".", "textRange": { "endLine": 45, "endOffset": 29, "startLine": 45, "startOffset": 8 }, "type": "CODE_SMELL" } ]
4,926
desktop/core/ext-py/nose-1.3.7/examples/plugin/plug.py
kokosing/hue
5,079
3381786
<filename>desktop/core/ext-py/nose-1.3.7/examples/plugin/plug.py from nose.plugins import Plugin class ExamplePlugin(Plugin): pass
null
null
null
null
null
null
null
null
null
[]
2,918
tests/db_functions/math/test_log.py
Lord-Elrond/django
61,676
140063
<reponame>Lord-Elrond/django import math from decimal import Decimal from django.db.models.functions import Log from django.test import TestCase from ..models import DecimalModel, FloatModel, IntegerModel class LogTests(TestCase): def test_null(self): IntegerModel.objects.create(big=100) obj = IntegerModel.objects.annotate( null_log_small=Log('small', 'normal'), null_log_normal=Log('normal', 'big'), null_log_big=Log('big', 'normal'), ).first() self.assertIsNone(obj.null_log_small) self.assertIsNone(obj.null_log_normal) self.assertIsNone(obj.null_log_big) def test_decimal(self): DecimalModel.objects.create(n1=Decimal('12.9'), n2=Decimal('3.6')) obj = DecimalModel.objects.annotate(n_log=Log('n1', 'n2')).first() self.assertIsInstance(obj.n_log, Decimal) self.assertAlmostEqual(obj.n_log, Decimal(math.log(obj.n2, obj.n1))) def test_float(self): FloatModel.objects.create(f1=2.0, f2=4.0) obj = FloatModel.objects.annotate(f_log=Log('f1', 'f2')).first() self.assertIsInstance(obj.f_log, float) self.assertAlmostEqual(obj.f_log, math.log(obj.f2, obj.f1)) def test_integer(self): IntegerModel.objects.create(small=4, normal=8, big=2) obj = IntegerModel.objects.annotate( small_log=Log('small', 'big'), normal_log=Log('normal', 'big'), big_log=Log('big', 'big'), ).first() self.assertIsInstance(obj.small_log, float) self.assertIsInstance(obj.normal_log, float) self.assertIsInstance(obj.big_log, float) self.assertAlmostEqual(obj.small_log, math.log(obj.big, obj.small)) self.assertAlmostEqual(obj.normal_log, math.log(obj.big, obj.normal)) self.assertAlmostEqual(obj.big_log, math.log(obj.big, obj.big))
0
0
0.0
0
0
0
1.0
0
4
[]
863
sklearn/gaussian_process/tests/_mini_sequence_kernel.py
MaiRajborirug/scikit-learn
50,961
91634
from sklearn.gaussian_process.kernels import Kernel, Hyperparameter from sklearn.gaussian_process.kernels import GenericKernelMixin from sklearn.gaussian_process.kernels import StationaryKernelMixin import numpy as np from sklearn.base import clone class MiniSeqKernel(GenericKernelMixin, StationaryKernelMixin, Kernel): """ A minimal (but valid) convolutional kernel for sequences of variable length. """ def __init__(self, baseline_similarity=0.5, baseline_similarity_bounds=(1e-5, 1)): self.baseline_similarity = baseline_similarity self.baseline_similarity_bounds = baseline_similarity_bounds @property def hyperparameter_baseline_similarity(self): return Hyperparameter( "baseline_similarity", "numeric", self.baseline_similarity_bounds ) def _f(self, s1, s2): return sum( [1.0 if c1 == c2 else self.baseline_similarity for c1 in s1 for c2 in s2] ) def _g(self, s1, s2): return sum([0.0 if c1 == c2 else 1.0 for c1 in s1 for c2 in s2]) def __call__(self, X, Y=None, eval_gradient=False): if Y is None: Y = X if eval_gradient: return ( np.array([[self._f(x, y) for y in Y] for x in X]), np.array([[[self._g(x, y)] for y in Y] for x in X]), ) else: return np.array([[self._f(x, y) for y in Y] for x in X]) def diag(self, X): return np.array([self._f(x, x) for x in X]) def clone_with_theta(self, theta): cloned = clone(self) cloned.theta = theta return cloned
3
0
0.0
5
0
3
1.0
0
11
[ { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 32, "message": "Rename this parameter \"X\" to match the regular expression ^[_a-z][a-z0-9_]*$.", "textRange": { "endLine": 32, "endOffset": 24, "startLine": 32, "startOffset": 23 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 32, "message": "Rename this parameter \"Y\" to match the regular expression ^[_a-z][a-z0-9_]*$.", "textRange": { "endLine": 32, "endOffset": 27, "startLine": 32, "startOffset": 26 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 44, "message": "Rename this parameter \"X\" to match the regular expression ^[_a-z][a-z0-9_]*$.", "textRange": { "endLine": 44, "endOffset": 20, "startLine": 44, "startOffset": 19 }, "type": "CODE_SMELL" } ]
585
python/tvm/relay/op/vm/vm.py
XiaoSong9905/tvm
4,640
11348370
# 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. # pylint: disable=no-else-return,invalid-name,len-as-condition,too-many-nested-blocks """Dialect operators for Relay VM.""" from . import _ffi_api def shape_of(expr): """Invoke a function to get the shape of a tensor. Parameters ---------- expr : tvm.relay.Expr The expr used to evaluate its tensor shape. Returns ------- result : tvm.relay.Expr The expression with the evaluated tensor shape. """ return _ffi_api.shape_of(expr) def invoke_tvm_op(func, inputs, outputs): """Call a primitive function with the TVM operator calling convention. Parameters ---------- func : tvm.relay.Expr The input expr. inputs : tvm.relay.Expr A tuple of the inputs to pass to the TVM function. outputs : tvm.relay.Expr A tuple of the outputs to pass to the TVM function. Returns ------- result : tvm.relay.Expr The invoke_tvm_op call node. """ return _ffi_api.invoke_tvm_op(func, inputs, outputs) def shape_func(func, inputs, outputs, is_inputs): """Invoke the shape function of the passed function. Parameters ---------- func : tvm.relay.Expr The primitive function from which to compute the shape function. inputs : tvm.relay.Tuple The tupled inputs. outputs : tvm.relay.Tuple The tupled outputs. is_inputs : List[bool] A boolean list indicating whether the shape function should expect shape or input at each position. Returns ------- result : tvm.relay.Expr The shape function expression. """ return _ffi_api.shape_func(func, inputs, outputs, is_inputs) def reshape_tensor(data, shape, newshape): """Invoke the VM ReshapeTensor instruction. Parameters ---------- data : tvm.relay.Expr The input data. shape : tvm.relay.Expr The newshape tensor. newshape : List[tvm.ir.PrimExpr] The new shape. """ return _ffi_api.reshape_tensor(data, shape, newshape)
0
0
0.0
0
0
0
1.0
0
4
[]
7,172
tests/sanic/conftest.py
TheVinhLuong102/Strawberry
2,062
11458546
<gh_stars>1000+ import pytest from .app import create_app @pytest.fixture def sanic_client(): yield create_app()
null
null
null
null
null
null
null
null
null
[]
9,616
libs/boxes/roi.py
wesen/FastMaskRCNN
3,509
11339840
<gh_stars>1000+ from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim def roi_align(feat, boxes): """Given features and boxes, This function crops feature """ return def roi_cropping(feat, boxes, clses, anchors, spatial_scale=1.0/16): """This function computes final rpn boxes And crops areas from the incoming features """ return
8
0
0.0
0
0
8
2.0
0
2
[ { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 10, "message": "Remove the unused function parameter \"feat\".", "textRange": { "endLine": 10, "endOffset": 18, "startLine": 10, "startOffset": 14 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 10, "message": "Remove the unused function parameter \"boxes\".", "textRange": { "endLine": 10, "endOffset": 25, "startLine": 10, "startOffset": 20 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 12, "message": "Remove this redundant return.", "textRange": { "endLine": 12, "endOffset": 8, "startLine": 12, "startOffset": 2 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 14, "message": "Remove the unused function parameter \"feat\".", "textRange": { "endLine": 14, "endOffset": 21, "startLine": 14, "startOffset": 17 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 14, "message": "Remove the unused function parameter \"clses\".", "textRange": { "endLine": 14, "endOffset": 35, "startLine": 14, "startOffset": 30 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 14, "message": "Remove the unused function parameter \"anchors\".", "textRange": { "endLine": 14, "endOffset": 44, "startLine": 14, "startOffset": 37 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 14, "message": "Remove the unused function parameter \"spatial_scale\".", "textRange": { "endLine": 14, "endOffset": 66, "startLine": 14, "startOffset": 46 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 18, "message": "Remove this redundant return.", "textRange": { "endLine": 18, "endOffset": 8, "startLine": 18, "startOffset": 2 }, "type": "CODE_SMELL" } ]
7,121
desktop/core/ext-py/repoze.who-2.3/repoze/who/plugins/auth_tkt.py
kokosing/hue
5,079
1667072
import datetime from codecs import utf_8_decode from codecs import utf_8_encode import hashlib import os import time from wsgiref.handlers import _monthname # Locale-independent, RFC-2616 from wsgiref.handlers import _weekdayname # Locale-independent, RFC-2616 try: from urllib.parse import urlencode, parse_qsl except ImportError: from urllib import urlencode from urlparse import parse_qsl from zope.interface import implementer from repoze.who.interfaces import IIdentifier from repoze.who.interfaces import IAuthenticator from repoze.who._compat import get_cookies import repoze.who._auth_tkt as auth_tkt from repoze.who._compat import STRING_TYPES _UTCNOW = None # unit tests can replace def _utcnow(): #pragma NO COVERAGE if _UTCNOW is not None: return _UTCNOW return datetime.datetime.utcnow() @implementer(IIdentifier, IAuthenticator) class AuthTktCookiePlugin(object): userid_typename = 'userid_type' userid_type_decoders = {'int': int, 'unicode': lambda x: utf_8_decode(x)[0], } userid_type_encoders = {int: ('int', str), } try: userid_type_encoders[long] = ('int', str) except NameError: #pragma NO COVER Python >= 3.0 pass try: userid_type_encoders[unicode] = ('unicode', lambda x: utf_8_encode(x)[0]) except NameError: #pragma NO COVER Python >= 3.0 pass def __init__(self, secret, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, userid_checker=None, digest_algo=auth_tkt.DEFAULT_DIGEST): self.secret = secret self.cookie_name = cookie_name self.include_ip = include_ip self.secure = secure if timeout and ( (not reissue_time) or (reissue_time > timeout) ): raise ValueError('When timeout is specified, reissue_time must ' 'be set to a lower value') self.timeout = timeout self.reissue_time = reissue_time self.userid_checker = userid_checker self.digest_algo = digest_algo # IIdentifier def identify(self, environ): cookies = get_cookies(environ) cookie = cookies.get(self.cookie_name) if cookie is None or not cookie.value: return None if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' try: timestamp, userid, tokens, user_data = auth_tkt.parse_ticket( self.secret, cookie.value, remote_addr, self.digest_algo) except auth_tkt.BadTicket: return None if self.timeout and ( (timestamp + self.timeout) < time.time() ): return None user_data_dict = dict(parse_qsl(user_data)) userid_type = user_data_dict.get(self.userid_typename) if userid_type: decoder = self.userid_type_decoders.get(userid_type) if decoder: userid = decoder(userid) environ['REMOTE_USER_TOKENS'] = tokens environ['REMOTE_USER_DATA'] = user_data environ['AUTH_TYPE'] = 'cookie' identity = {} identity['timestamp'] = timestamp identity['repoze.who.plugins.auth_tkt.userid'] = userid identity['tokens'] = tokens identity['userdata'] = user_data_dict return identity # IIdentifier def forget(self, environ, identity): # return a set of expires Set-Cookie headers return self._get_cookies(environ, 'INVALID', 0) # IIdentifier def remember(self, environ, identity): if self.include_ip: remote_addr = environ['REMOTE_ADDR'] else: remote_addr = '0.0.0.0' cookies = get_cookies(environ) old_cookie = cookies.get(self.cookie_name) existing = cookies.get(self.cookie_name) old_cookie_value = getattr(existing, 'value', None) max_age = identity.get('max_age', None) timestamp, userid, tokens, userdata = None, '', (), '' if old_cookie_value: try: timestamp,userid,tokens,userdata = auth_tkt.parse_ticket( self.secret, old_cookie_value, remote_addr, self.digest_algo) except auth_tkt.BadTicket: pass tokens = tuple(tokens) who_userid = identity['repoze.who.userid'] who_tokens = tuple(identity.get('tokens', ())) who_userdata_dict = identity.get('userdata', {}) encoding_data = self.userid_type_encoders.get(type(who_userid)) if encoding_data: encoding, encoder = encoding_data who_userid = encoder(who_userid) who_userdata_dict[self.userid_typename] = encoding who_userdata = urlencode(who_userdata_dict) old_data = (userid, tokens, userdata) new_data = (who_userid, who_tokens, who_userdata) if old_data != new_data or (self.reissue_time and ( (timestamp + self.reissue_time) < time.time() )): ticket = auth_tkt.AuthTicket( self.secret, who_userid, remote_addr, tokens=who_tokens, user_data=who_userdata, cookie_name=self.cookie_name, secure=self.secure, digest_algo=self.digest_algo) new_cookie_value = ticket.cookie_value() if old_cookie_value != new_cookie_value: # return a set of Set-Cookie headers return self._get_cookies(environ, new_cookie_value, max_age) # IAuthenticator def authenticate(self, environ, identity): userid = identity.get('repoze.who.plugins.auth_tkt.userid') if userid is None: return None if self.userid_checker and not self.userid_checker(userid): return None identity['repoze.who.userid'] = userid return userid def _get_cookies(self, environ, value, max_age=None): if max_age is not None: max_age = int(max_age) later = _utcnow() + datetime.timedelta(seconds=max_age) # Wdy, DD-Mon-YY HH:MM:SS GMT expires = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( _weekdayname[later.weekday()], later.day, _monthname[later.month], later.year, later.hour, later.minute, later.second, ) # the Expires header is *required* at least for IE7 (IE7 does # not respect Max-Age) max_age = "; Max-Age=%s; Expires=%s" % (max_age, expires) else: max_age = '' secure = '' if self.secure: secure = '; secure; HttpOnly' cur_domain = environ.get('HTTP_HOST', environ.get('SERVER_NAME')) cur_domain = cur_domain.split(':')[0] # drop port wild_domain = '.' + cur_domain cookies = [ ('Set-Cookie', '%s="%s"; Path=/%s%s' % ( self.cookie_name, value, max_age, secure)), ('Set-Cookie', '%s="%s"; Path=/; Domain=%s%s%s' % ( self.cookie_name, value, cur_domain, max_age, secure)), ('Set-Cookie', '%s="%s"; Path=/; Domain=%s%s%s' % ( self.cookie_name, value, wild_domain, max_age, secure)) ] return cookies def __repr__(self): return '<%s %s>' % (self.__class__.__name__, id(self)) #pragma NO COVERAGE def _bool(value): if isinstance(value, STRING_TYPES): return value.lower() in ('yes', 'true', '1') return value def make_plugin(secret=None, secretfile=None, cookie_name='auth_tkt', secure=False, include_ip=False, timeout=None, reissue_time=None, userid_checker=None, digest_algo=auth_tkt.DEFAULT_DIGEST, ): from repoze.who.utils import resolveDotted if (secret is None and secretfile is None): raise ValueError("One of 'secret' or 'secretfile' must not be None.") if (secret is not None and secretfile is not None): raise ValueError("Specify only one of 'secret' or 'secretfile'.") if secretfile: secretfile = os.path.abspath(os.path.expanduser(secretfile)) if not os.path.exists(secretfile): raise ValueError("No such 'secretfile': %s" % secretfile) with open(secretfile) as f: secret = f.read().strip() if timeout: timeout = int(timeout) if reissue_time: reissue_time = int(reissue_time) if userid_checker is not None: userid_checker = resolveDotted(userid_checker) if isinstance(digest_algo, str): try: digest_algo = getattr(hashlib, digest_algo) except AttributeError: raise ValueError("No such 'digest_algo': %s" % digest_algo) plugin = AuthTktCookiePlugin(secret, cookie_name, _bool(secure), _bool(include_ip), timeout, reissue_time, userid_checker, digest_algo, ) return plugin
3
0
0.0
48
0
3
1.0
0
44
[ { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 106, "message": "Remove the unused function parameter \"identity\".", "textRange": { "endLine": 106, "endOffset": 38, "startLine": 106, "startOffset": 30 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 118, "message": "Remove the unused local variable \"old_cookie\".", "textRange": { "endLine": 118, "endOffset": 18, "startLine": 118, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 167, "message": "Remove the unused function parameter \"environ\".", "textRange": { "endLine": 167, "endOffset": 34, "startLine": 167, "startOffset": 27 }, "type": "CODE_SMELL" } ]
1,454
bokeh/server/django/__init__.py
g-parki/bokeh
15,193
6771486
<filename>bokeh/server/django/__init__.py # Bokeh imports from bokeh.util.dependencies import import_required # Bokeh imports from .apps import DjangoBokehConfig from .routing import autoload, directory, document from .static import static_extensions import_required("django", "django is required by bokeh.server.django") import_required("channels", "The package channels is required by bokeh.server.django and must be installed") default_app_config = "bokeh.server.django.DjangoBokehConfig"
0
0
0.0
0
0
0
1.0
0
0
[]
9,179
packages/python/plotly/plotly/tests/test_optional/test_px/test_colors.py
mastermind88/plotly.py
11,750
4327666
<gh_stars>1000+ import plotly.express as px def test_reversed_colorscale(): fig1 = px.scatter( x=[1, 2], y=[2, 3], color=[3, 4], color_continuous_scale="plasma_r" ) fig2 = px.scatter(x=[1, 2], y=[2, 3], color=[3, 4], color_continuous_scale="plasma") colors1 = [val[1] for val in fig1.layout.coloraxis.colorscale] colors2 = [val[1] for val in fig2.layout.coloraxis.colorscale] assert colors1 == colors2[::-1] fig1 = px.scatter( x=[1, 2], y=[2, 3], color=[3, 4], color_continuous_scale=px.colors.sequential.Plasma, ) fig2 = px.scatter( x=[1, 2], y=[2, 3], color=[3, 4], color_continuous_scale=px.colors.sequential.Plasma_r, ) colors1 = [val[1] for val in fig1.layout.coloraxis.colorscale] colors2 = [val[1] for val in fig2.layout.coloraxis.colorscale] assert colors1 == colors2[::-1]
0
0
0.0
0
0
0
1.0
0
1
[]
13,235
apps/opencv_stitching_tool/opencv_stitching/image_handler.py
nowireless/opencv
56,632
11523688
<reponame>nowireless/opencv import cv2 as cv from .megapix_downscaler import MegapixDownscaler from .stitching_error import StitchingError class ImageHandler: DEFAULT_MEDIUM_MEGAPIX = 0.6 DEFAULT_LOW_MEGAPIX = 0.1 DEFAULT_FINAL_MEGAPIX = -1 def __init__(self, medium_megapix=DEFAULT_MEDIUM_MEGAPIX, low_megapix=DEFAULT_LOW_MEGAPIX, final_megapix=DEFAULT_FINAL_MEGAPIX): if medium_megapix < low_megapix: raise StitchingError("Medium resolution megapix need to be " "greater or equal than low resolution " "megapix") self.medium_scaler = MegapixDownscaler(medium_megapix) self.low_scaler = MegapixDownscaler(low_megapix) self.final_scaler = MegapixDownscaler(final_megapix) self.scales_set = False self.img_names = [] self.img_sizes = [] def set_img_names(self, img_names): self.img_names = img_names def resize_to_medium_resolution(self): return self.read_and_resize_imgs(self.medium_scaler) def resize_to_low_resolution(self, medium_imgs=None): if medium_imgs and self.scales_set: return self.resize_medium_to_low(medium_imgs) return self.read_and_resize_imgs(self.low_scaler) def resize_to_final_resolution(self): return self.read_and_resize_imgs(self.final_scaler) def read_and_resize_imgs(self, scaler): for img, size in self.input_images(): yield self.resize_img_by_scaler(scaler, size, img) def resize_medium_to_low(self, medium_imgs): for img, size in zip(medium_imgs, self.img_sizes): yield self.resize_img_by_scaler(self.low_scaler, size, img) @staticmethod def resize_img_by_scaler(scaler, size, img): desired_size = scaler.get_scaled_img_size(size) return cv.resize(img, desired_size, interpolation=cv.INTER_LINEAR_EXACT) def input_images(self): self.img_sizes = [] for name in self.img_names: img = self.read_image(name) size = self.get_image_size(img) self.img_sizes.append(size) self.set_scaler_scales() yield img, size @staticmethod def get_image_size(img): """(width, height)""" return (img.shape[1], img.shape[0]) @staticmethod def read_image(img_name): img = cv.imread(img_name) if img is None: raise StitchingError("Cannot read image " + img_name) return img def set_scaler_scales(self): if not self.scales_set: first_img_size = self.img_sizes[0] self.medium_scaler.set_scale_by_img_size(first_img_size) self.low_scaler.set_scale_by_img_size(first_img_size) self.final_scaler.set_scale_by_img_size(first_img_size) self.scales_set = True def get_medium_to_final_ratio(self): return self.final_scaler.scale / self.medium_scaler.scale def get_medium_to_low_ratio(self): return self.low_scaler.scale / self.medium_scaler.scale def get_final_to_low_ratio(self): return self.low_scaler.scale / self.final_scaler.scale
0
0
0.0
8
0
0
1.0
0
23
[]
9,912
poem/cv_mim/pipelines.py
DionysisChristopoulos/google-research
23,901
11274825
# 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. """Implements pipeline utility functions.""" import math import tensorflow as tf from poem.core import common from poem.core import input_generator from poem.core import keypoint_utils from poem.core import tfe_input_layer def create_dataset_from_tables( input_table_patterns, batch_sizes, num_instances_per_record, shuffle=False, num_epochs=None, drop_remainder=False, keypoint_names_3d=None, keypoint_names_2d=None, feature_dim=None, num_classes=None, num_frames=None, shuffle_buffer_size=4096, num_shards=1, shard_index=None, common_module=common, dataset_class=tf.data.TFRecordDataset, input_example_parser_creator=tfe_input_layer.create_tfe_parser, seed=None): """Reads data from tf.Example table. Note that this function mainly duplicates `read_batch_from_tfe_tables` in `v1.pipeline_utils.py` for compatible with tf2. IMPORTANT: We assume that 2D keypoints from the input have been normalized by image size. No normalization is expected and no denormalization will be performed for both 2D and 3D keypoints. Args: input_table_patterns: A list of strings for the paths or pattern to input tables. batch_sizes: A list of integers for the batch sizes to read from each table. num_instances_per_record: An integer for the number of instances per tf.Example record. shuffle: A boolean for whether to shuffle batch. num_epochs: An integer for the number of epochs to read. Use `None` to read indefinitely. drop_remainder: A boolean for whether to drop remainder batch. keypoint_names_3d: A list of strings for 3D keypoint names to read (coordinates). Use None to skip reading 2D keypoints. keypoint_names_2d: A list of strings for 2D keypoint names to read (coordinates and scores). Use None to skip reading 2D keypoints. feature_dim: An integer for size of pre-computed feature vectors. Use None to skip reading feature vectors. num_classes: An integer for total number of classification label classes to read labels for. Use None to skip reading class labels. num_frames: An integer for the number of frames per object each example has. Use None to skip adding the frame dimension. shuffle_buffer_size: An integer for the buffer size used for shuffling. A large buffer size benefits shuffling quality. num_shards: An integer for the number of shards to divide the dataset. This is useful to distributed training. See `tf.data.Dataset.shard` for details. shard_index: An integer for the shard index to use. This is useful to distributed training, and should usually be set to the id of a synchronized worker. See `tf.data.Dataset.shard` for details. Note this must be specified if `num_shards` is greater than 1. common_module: A Python module that defines common constants. dataset_class: A dataset class to use. Must match input table type. input_example_parser_creator: A function handle for creating parser function. seed: An integer for random seed. Returns: A tf.data.Dataset object. """ parser_kwargs = { 'num_objects': num_instances_per_record, } if keypoint_names_3d: parser_kwargs.update({ 'keypoint_names_3d': keypoint_names_3d, 'include_keypoint_scores_3d': False, }) if keypoint_names_2d: parser_kwargs.update({ 'keypoint_names_2d': keypoint_names_2d, 'include_keypoint_scores_2d': True, }) if feature_dim: parser_kwargs.update({ 'feature_dim': feature_dim, }) if num_classes: parser_kwargs.update({ 'num_classes': num_classes, }) if num_frames: parser_kwargs.update({ 'sequence_length': num_frames, }) parser_fn = input_example_parser_creator( common_module=common_module, **parser_kwargs) dataset = tfe_input_layer.read_batch_from_tables( input_table_patterns, batch_sizes=batch_sizes, drop_remainder=drop_remainder, num_epochs=num_epochs, num_shards=num_shards, shard_index=shard_index, shuffle=shuffle, shuffle_buffer_size=shuffle_buffer_size, seed=seed, dataset_class=dataset_class, parser_fn=parser_fn) return dataset def create_model_input(inputs, model_input_keypoint_type, keypoint_profile_2d=None, keypoint_profile_3d=None, normalize_keypoints_2d=True, min_keypoint_score_2d=-1.0, azimuth_range=(-math.pi, math.pi), elevation_range=(-math.pi / 6.0, math.pi / 6.0), roll_range=(-math.pi / 6.0, math.pi / 6.0), seed=None): """Creates model input features (2D keypoints) from input keypoints. Note that this function mainly duplicates `create_model_input` in `v1.input_generator.py` for compatible with tf2. IMPORTANT: We assume that 2D keypoints from the inputs have been normalized by image size. This function will reads image sizes from the input and denormalize the 2D keypoints with them. No normalization is expected and no denormalization will be performed for 3D keypoints. Args: inputs: A dictionary for tensor inputs. model_input_keypoint_type: An enum string for model input keypoint type. See `MODEL_INPUT_KEYPOINT_TYPE_*` for supported values. keypoint_profile_2d: A KeypointProfile2D object for input 2D keypoints. Required for normalizing 2D keypoints. Also required when 3D-to-2D projection is involved. keypoint_profile_3d: A KeypointProfile3D object for input 3D keypoints. Only used when 3D-to-2D projection is involved. normalize_keypoints_2d: A boolean for whether to normalize 2D keypoints at the end. min_keypoint_score_2d: A float for the minimum score to consider a 2D keypoint as invalid. azimuth_range: A tuple for minimum and maximum azimuth angles to randomly rotate 3D keypoints with. elevation_range: A tuple for minimum and maximum elevation angles to randomly rotate 3D keypoints with. roll_range: A tuple for minimum and maximum roll angles to randomly rotate 3D keypoints with. seed: An integer for random seed. Returns: features: A tensor for input features. Shape = [..., feature_dim]. side_outputs: A dictionary for side outputs, which includes `offset_points_2d` (shape = [..., 1, 2]) and `scale_distances_2d` (shape = [..., 1, 1]) if `normalize_keypoints_2d` is True. """ keypoints_2d = keypoint_utils.denormalize_points_by_image_size( inputs[common.KEY_KEYPOINTS_2D], image_sizes=inputs[common.KEY_IMAGE_SIZES]) keypoint_scores_2d = inputs[common.KEY_KEYPOINT_SCORES_2D] if min_keypoint_score_2d < 0.0: keypoint_masks_2d = tf.ones_like(keypoint_scores_2d, dtype=tf.float32) else: keypoint_masks_2d = tf.cast( tf.math.greater_equal(keypoint_scores_2d, min_keypoint_score_2d), dtype=tf.float32) keypoints_3d = inputs.get(common.KEY_KEYPOINTS_3D, None) features, side_outputs = input_generator.create_model_input( keypoints_2d, keypoint_masks_2d, keypoints_3d, model_input_keypoint_type, normalize_keypoints_2d=normalize_keypoints_2d, keypoint_profile_2d=keypoint_profile_2d, keypoint_profile_3d=keypoint_profile_3d, azimuth_range=azimuth_range, elevation_range=elevation_range, roll_range=roll_range, seed=seed) # IMPORTANT: It is better not to modify `inputs` in TF2. Instead, we save # results in the `side_outputs` for further computation. side_outputs.update({ common.KEY_KEYPOINTS_2D: keypoints_2d, common.KEY_KEYPOINT_MASKS_2D: keypoint_masks_2d }) return features, side_outputs
1
0
0.0
7
0
1
1.0
0
8
[ { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 29, "message": "Function \"create_dataset_from_tables\" has 18 parameters, which is greater than the 13 authorized.", "textRange": { "endLine": 46, "endOffset": 13, "startLine": 29, "startOffset": 4 }, "type": "CODE_SMELL" } ]
6,733
torch_geometric/nn/acts.py
NucciTheBoss/pytorch_geometric
12,651
178744
<reponame>NucciTheBoss/pytorch_geometric<gh_stars>1000+ def swish(x): return x * x.sigmoid()
0
0
0.0
0
0
0
1.0
0
1
[]
1,099
recipes/Python/578535_lndirpy_short_pythversiBSDX11_lndir/recipe-578535.py
tdiprima/code
2,023
4071122
#!/usr/bin/env python ################################################################################ # # # Copyright (c) 2013, Mike 'Fuzzy' Partin <<EMAIL>> # # All rights reserved. # # # # Redistribution and use in source and binary forms, with or without # # modification, are permitted provided that the following conditions are met: # # # # 1. Redistributions of source code must retain the above copyright notice, # # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # # this list of conditions and the following disclaimer in the documentation # # and/or other materials provided with the distribution. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. # # # # The views and conclusions contained in the software and documentation are # # those of the authors and should not be interpreted as representing official # # policies, either expressed or implied, of the FreeBSD Project. # # # ################################################################################ ################################################################################ ### Module imports ### ################################################################################ # Stdlib import os import re import sys import types ################################################################################ ### Main logic and argument handling ### ################################################################################ try: if __name__ == '__main__': ### check to see that all args are present on the command line ############################################################## if len(sys.argv) < 3: print("Usage: %s <src>/ <dst>/" % sys.argv[0]) sys.exit(1) else: ### check to see that source and destination targets exist ########################################################## for i in [str(sys.argv[1]), str(sys.argv[2])]: if not os.path.isdir(i): raise OSError("ERROR: %s is not a valid directory." % i) ### Setup some convenience src = str(sys.argv[1]) dst = str(sys.argv[2]) src_b = None if len(sys.argv) == 4: src_b = sys.argv[3] if src_b == None: if src[-1:] == '/': src_b = os.path.basename(src[:-1]) else: src_b = os.path.basename(src) ### start walking the source target ################################### dirs_c = 0 # counter for dires file_c = 0 # counter for files for root, dirs, files in os.walk(src): for i in files: os.symlink('%s/%s' % (root, i), '%s%s/%s' % (dst, re.sub(src, '', root), i)) file_c += 1 for i in dirs: try: os.mkdir('%s%s/%s' % (dst, re.sub(src, '', root), i)) except OSError: pass dirs_c += 1 sys.stdout.write('> %-53s %6d dirs %6d files\r' % ( src_b[:52], # basename of src dirs_c, # Dir count file_c)) # File count sys.stdout.flush() sys.stdout.write('> %-53s %6d dirs %6d files\n' % ( src_b[:52], # basename of src dirs_c, # Dir count file_c)) # File count sys.stdout.flush() except OSError as msg: print(msg) sys.exit(0)
1
0
0.0
39
0
1
1.0
0
10
[ { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 74, "message": "Use `endswith` here.", "textRange": { "endLine": 74, "endOffset": 26, "startLine": 74, "startOffset": 11 }, "type": "CODE_SMELL" } ]
12,834
tests/components/image_processing/test_init.py
MrDelik/core
30,023
6472508
<reponame>MrDelik/core<gh_stars>1000+ """The tests for the image_processing component.""" from unittest.mock import PropertyMock, patch import pytest import homeassistant.components.http as http import homeassistant.components.image_processing as ip from homeassistant.const import ATTR_ENTITY_PICTURE from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component from tests.common import assert_setup_component, async_capture_events from tests.components.image_processing import common @pytest.fixture def aiohttp_unused_port(loop, aiohttp_unused_port, socket_enabled): """Return aiohttp_unused_port and allow opening sockets.""" return aiohttp_unused_port def get_url(hass): """Return camera url.""" state = hass.states.get("camera.demo_camera") return f"{hass.config.internal_url}{state.attributes.get(ATTR_ENTITY_PICTURE)}" async def setup_image_processing(hass, aiohttp_unused_port): """Set up things to be run when tests are started.""" await async_setup_component( hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: aiohttp_unused_port()}}, ) config = {ip.DOMAIN: {"platform": "test"}, "camera": {"platform": "demo"}} await async_setup_component(hass, ip.DOMAIN, config) await hass.async_block_till_done() async def setup_image_processing_alpr(hass): """Set up things to be run when tests are started.""" config = {ip.DOMAIN: {"platform": "demo"}, "camera": {"platform": "demo"}} await async_setup_component(hass, ip.DOMAIN, config) await hass.async_block_till_done() return async_capture_events(hass, "image_processing.found_plate") async def setup_image_processing_face(hass): """Set up things to be run when tests are started.""" config = {ip.DOMAIN: {"platform": "demo"}, "camera": {"platform": "demo"}} await async_setup_component(hass, ip.DOMAIN, config) await hass.async_block_till_done() return async_capture_events(hass, "image_processing.detect_face") async def test_setup_component(hass): """Set up demo platform on image_process component.""" config = {ip.DOMAIN: {"platform": "demo"}} with assert_setup_component(1, ip.DOMAIN): assert await async_setup_component(hass, ip.DOMAIN, config) async def test_setup_component_with_service(hass): """Set up demo platform on image_process component test service.""" config = {ip.DOMAIN: {"platform": "demo"}} with assert_setup_component(1, ip.DOMAIN): assert await async_setup_component(hass, ip.DOMAIN, config) assert hass.services.has_service(ip.DOMAIN, "scan") @patch( "homeassistant.components.demo.camera.Path.read_bytes", return_value=b"Test", ) async def test_get_image_from_camera( mock_camera_read, hass, aiohttp_unused_port, enable_custom_integrations ): """Grab an image from camera entity.""" await setup_image_processing(hass, aiohttp_unused_port) common.async_scan(hass, entity_id="image_processing.test") await hass.async_block_till_done() state = hass.states.get("image_processing.test") assert mock_camera_read.called assert state.state == "1" assert state.attributes["image"] == b"Test" @patch( "homeassistant.components.camera.async_get_image", side_effect=HomeAssistantError(), ) async def test_get_image_without_exists_camera( mock_image, hass, aiohttp_unused_port, enable_custom_integrations ): """Try to get image without exists camera.""" await setup_image_processing(hass, aiohttp_unused_port) hass.states.async_remove("camera.demo_camera") common.async_scan(hass, entity_id="image_processing.test") await hass.async_block_till_done() state = hass.states.get("image_processing.test") assert mock_image.called assert state.state == "0" async def test_alpr_event_single_call(hass, aioclient_mock): """Set up and scan a picture and test plates from event.""" alpr_events = await setup_image_processing_alpr(hass) aioclient_mock.get(get_url(hass), content=b"image") common.async_scan(hass, entity_id="image_processing.demo_alpr") await hass.async_block_till_done() state = hass.states.get("image_processing.demo_alpr") assert len(alpr_events) == 4 assert state.state == "AC3829" event_data = [ event.data for event in alpr_events if event.data.get("plate") == "AC3829" ] assert len(event_data) == 1 assert event_data[0]["plate"] == "AC3829" assert event_data[0]["confidence"] == 98.3 assert event_data[0]["entity_id"] == "image_processing.demo_alpr" async def test_alpr_event_double_call(hass, aioclient_mock): """Set up and scan a picture and test plates from event.""" alpr_events = await setup_image_processing_alpr(hass) aioclient_mock.get(get_url(hass), content=b"image") common.async_scan(hass, entity_id="image_processing.demo_alpr") common.async_scan(hass, entity_id="image_processing.demo_alpr") await hass.async_block_till_done() state = hass.states.get("image_processing.demo_alpr") assert len(alpr_events) == 4 assert state.state == "AC3829" event_data = [ event.data for event in alpr_events if event.data.get("plate") == "AC3829" ] assert len(event_data) == 1 assert event_data[0]["plate"] == "AC3829" assert event_data[0]["confidence"] == 98.3 assert event_data[0]["entity_id"] == "image_processing.demo_alpr" @patch( "homeassistant.components.demo.image_processing.DemoImageProcessingAlpr.confidence", new_callable=PropertyMock(return_value=95), ) async def test_alpr_event_single_call_confidence(confidence_mock, hass, aioclient_mock): """Set up and scan a picture and test plates from event.""" alpr_events = await setup_image_processing_alpr(hass) aioclient_mock.get(get_url(hass), content=b"image") common.async_scan(hass, entity_id="image_processing.demo_alpr") await hass.async_block_till_done() state = hass.states.get("image_processing.demo_alpr") assert len(alpr_events) == 2 assert state.state == "AC3829" event_data = [ event.data for event in alpr_events if event.data.get("plate") == "AC3829" ] assert len(event_data) == 1 assert event_data[0]["plate"] == "AC3829" assert event_data[0]["confidence"] == 98.3 assert event_data[0]["entity_id"] == "image_processing.demo_alpr" async def test_face_event_call(hass, aioclient_mock): """Set up and scan a picture and test faces from event.""" face_events = await setup_image_processing_face(hass) aioclient_mock.get(get_url(hass), content=b"image") common.async_scan(hass, entity_id="image_processing.demo_face") await hass.async_block_till_done() state = hass.states.get("image_processing.demo_face") assert len(face_events) == 2 assert state.state == "Hans" assert state.attributes["total_faces"] == 4 event_data = [ event.data for event in face_events if event.data.get("name") == "Hans" ] assert len(event_data) == 1 assert event_data[0]["name"] == "Hans" assert event_data[0]["confidence"] == 98.34 assert event_data[0]["gender"] == "male" assert event_data[0]["entity_id"] == "image_processing.demo_face" @patch( "homeassistant.components.demo.image_processing." "DemoImageProcessingFace.confidence", new_callable=PropertyMock(return_value=None), ) async def test_face_event_call_no_confidence(mock_config, hass, aioclient_mock): """Set up and scan a picture and test faces from event.""" face_events = await setup_image_processing_face(hass) aioclient_mock.get(get_url(hass), content=b"image") common.async_scan(hass, entity_id="image_processing.demo_face") await hass.async_block_till_done() state = hass.states.get("image_processing.demo_face") assert len(face_events) == 3 assert state.state == "4" assert state.attributes["total_faces"] == 4 event_data = [ event.data for event in face_events if event.data.get("name") == "Hans" ] assert len(event_data) == 1 assert event_data[0]["name"] == "Hans" assert event_data[0]["confidence"] == 98.34 assert event_data[0]["gender"] == "male" assert event_data[0]["entity_id"] == "image_processing.demo_face"
8
5
0.0
0
0
3
1.0
0
19
[ { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 90, "message": "Define a constant instead of duplicating this literal \"image_processing.test\" 4 times.", "textRange": { "endLine": 90, "endOffset": 61, "startLine": 90, "startOffset": 38 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 126, "message": "Define a constant instead of duplicating this literal \"image_processing.demo_alpr\" 10 times.", "textRange": { "endLine": 126, "endOffset": 66, "startLine": 126, "startOffset": 38 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "RELIABILITY" } ], "line": 139, "message": "Do not perform equality checks with floating point values.", "textRange": { "endLine": 139, "endOffset": 46, "startLine": 139, "startOffset": 11 }, "type": "BUG" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "RELIABILITY" } ], "line": 162, "message": "Do not perform equality checks with floating point values.", "textRange": { "endLine": 162, "endOffset": 46, "startLine": 162, "startOffset": 11 }, "type": "BUG" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "RELIABILITY" } ], "line": 188, "message": "Do not perform equality checks with floating point values.", "textRange": { "endLine": 188, "endOffset": 46, "startLine": 188, "startOffset": 11 }, "type": "BUG" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 197, "message": "Define a constant instead of duplicating this literal \"image_processing.demo_face\" 6 times.", "textRange": { "endLine": 197, "endOffset": 66, "startLine": 197, "startOffset": 38 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "RELIABILITY" } ], "line": 211, "message": "Do not perform equality checks with floating point values.", "textRange": { "endLine": 211, "endOffset": 47, "startLine": 211, "startOffset": 11 }, "type": "BUG" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "RELIABILITY" } ], "line": 240, "message": "Do not perform equality checks with floating point values.", "textRange": { "endLine": 240, "endOffset": 47, "startLine": 240, "startOffset": 11 }, "type": "BUG" } ]
4,150
pipenv/patched/piptools/repositories/__init__.py
Enzime/pipenv
18,636
9671823
<gh_stars>1000+ # flake8: noqa from .local import LocalRequirementsRepository from .pypi import PyPIRepository
0
0
0.0
0
0
0
1.0
0
0
[]
5,906
torch/autograd/profiler.py
xiaohanhuang/pytorch
60,067
11457937
<gh_stars>1000+ from torch.autograd.profiler_util import ( EventList, FunctionEvent, MemRecordsAcc, MEMORY_EVENT_NAME, _filter_name, _filter_stack_entry, _rewrite_name ) from torch.autograd import ( DeviceType, ProfilerActivity, ProfilerConfig, ProfilerState, kineto_available, _ProfilerResult, _disable_profiler, _enable_profiler, _prepare_profiler, _supported_activities ) import torch import torch.cuda from torch.futures import Future from typing import Any, Dict, List, Optional from warnings import warn try: # Available in Python >= 3.2 from contextlib import ContextDecorator except ImportError: import functools class ContextDecorator(object): # type: ignore[no-redef] def __enter__(self): raise NotImplementedError def __exit__(self, exc_type, exc_val, exc_tb): raise NotImplementedError def __call__(self, func): @functools.wraps(func) def wrapped(*args, **kwargs): with self: return func(*args, **kwargs) return wrapped class profile(object): """Context manager that manages autograd profiler state and holds a summary of results. Under the hood it just records events of functions being executed in C++ and exposes those events to Python. You can wrap any code into it and it will only report runtime of PyTorch functions. Note: profiler is thread local and is automatically propagated into the async tasks Args: enabled (bool, optional): Setting this to False makes this context manager a no-op. use_cuda (bool, optional): Enables timing of CUDA events as well using the cudaEvent API. Adds approximately 4us of overhead to each tensor operation. record_shapes (bool, optional): If shapes recording is set, information about input dimensions will be collected. This allows one to see which dimensions have been used under the hood and further group by them using prof.key_averages(group_by_input_shape=True). Please note that shape recording might skew your profiling data. It is recommended to use separate runs with and without shape recording to validate the timing. Most likely the skew will be negligible for bottom most events (in a case of nested function calls). But for higher level functions the total self cpu time might be artificially increased because of the shape collection. with_flops (bool, optional): If with_flops is set, the profiler will estimate the FLOPs (floating point operations) value using the operator's input shape. This allows one to estimate the hardware performance. Currently, this option only works for the matrix multiplication and 2D convolution operators. profile_memory (bool, optional): track tensor memory allocation/deallocation. with_stack (bool, optional): record source information (file and line number) for the ops. with_modules (bool): record module hierarchy (including function names) corresponding to the callstack of the op. e.g. If module A's forward call's module B's forward which contains an aten::add op, then aten::add's module hierarchy is A.B Note that this support exist, at the moment, only for TorchScript models and not eager mode models. use_kineto (bool, optional): experimental, enable profiling with Kineto profiler. use_cpu (bool, optional): profile CPU events; setting to ``False`` requires ``use_kineto=True`` and can be used to lower the overhead for GPU-only profiling. .. warning: Enabling memory profiling or source attribution incurs additional profiler overhead .. warning: This context managers should not be called recursively, i.e. no nested instances are allowed .. warning: Due to some CUDA multiprocessing limitations (multiprocessing-cuda-note_), one cannot use the profiler with ``use_cuda = True`` to benchmark DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading, please use ``use_cuda = False`` or ``num_workers = 0``. Example: >>> x = torch.randn((1, 1), requires_grad=True) >>> with torch.autograd.profiler.profile() as prof: >>> for _ in range(100): # any normal python code, really! >>> y = x ** 2 >> y.backward() >>> # NOTE: some columns were removed for brevity >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) ----------------------------------- --------------- --------------- --------------- Name Self CPU total CPU time avg Number of Calls ----------------------------------- --------------- --------------- --------------- mul 32.048ms 32.048ms 200 pow 27.041ms 27.041ms 200 PowBackward0 9.727ms 55.483ms 100 torch::autograd::AccumulateGrad 9.148ms 9.148ms 100 torch::autograd::GraphRoot 691.816us 691.816us 100 ----------------------------------- --------------- --------------- --------------- """ def __init__( self, enabled=True, *, use_cuda=False, record_shapes=False, with_flops=False, profile_memory=False, with_stack=False, with_modules=False, use_kineto=False, use_cpu=True): self.enabled: bool = enabled if not self.enabled: return self.use_cuda = use_cuda self.function_events: Optional[EventList] = None self.entered = False self.record_shapes = record_shapes self.with_flops = with_flops self.record_shapes |= self.with_flops self.profile_memory = profile_memory self.with_stack = with_stack self.with_modules = with_modules self.use_cpu = use_cpu self.kineto_results: Optional[_ProfilerResult] = None if not self.use_cpu: assert use_kineto, \ "Device-only events supported only with Kineto (use_kineto=True)" if self.use_cuda and not torch.cuda.is_available(): warn("CUDA is not available, disabling CUDA profiling") self.use_cuda = False self.kineto_activities = set() if self.use_cpu: self.kineto_activities.add(ProfilerActivity.CPU) self.profiler_kind = ProfilerState.KINETO if self.use_cuda: if (not use_kineto or ProfilerActivity.CUDA not in _supported_activities()): assert self.use_cpu, "Legacy CUDA profiling requires use_cpu=True" self.profiler_kind = ProfilerState.KINETO_GPU_FALLBACK else: self.kineto_activities.add(ProfilerActivity.CUDA) assert len(self.kineto_activities) > 0, \ "No activities specified for the profiler" def config(self): return ProfilerConfig( self.profiler_kind, self.record_shapes, self.profile_memory, self.with_stack, self.with_flops, self.with_modules) def __enter__(self): if not self.enabled: return if self.entered: raise RuntimeError("Profiler context manager is not reentrant") self._prepare_trace() self._start_trace() return self def _prepare_trace(self): self.entered = True _prepare_profiler(self.config(), self.kineto_activities) def _start_trace(self): self.entered = True _enable_profiler(self.config(), self.kineto_activities) def __exit__(self, exc_type, exc_val, exc_tb): if not self.enabled: return if self.use_cuda: torch.cuda.synchronize() self.kineto_results = _disable_profiler() parsed_results = self._parse_kineto_results(self.kineto_results) self.function_events = EventList( parsed_results, use_cuda=self.use_cuda, profile_memory=self.profile_memory, with_flops=self.with_flops) self.function_events._build_tree() return False def __repr__(self): if self.function_events is None: return '<unfinished torch.autograd.profile>' return repr(self.function_events) def __str__(self): if self.function_events is None: return '<unfinished torch.autograd.profile>' return str(self.function_events) def _check_finish(self): if self.function_events is None: raise RuntimeError("Profiler didn't finish running") def table(self, sort_by=None, row_limit=100, max_src_column_width=75, header=None, top_level_events_only=False): self._check_finish() assert self.function_events is not None return self.function_events.table( sort_by=sort_by, row_limit=row_limit, max_src_column_width=max_src_column_width, header=header, top_level_events_only=top_level_events_only ) table.__doc__ = EventList.table.__doc__ def export_chrome_trace(self, path): self._check_finish() if kineto_available(): self.kineto_results.save(path) # type: ignore[union-attr] else: return self.function_events.export_chrome_trace(path) # type: ignore[union-attr] export_chrome_trace.__doc__ = EventList.export_chrome_trace.__doc__ def export_stacks(self, path: str, metric: str = "self_cpu_time_total"): self._check_finish() assert self.function_events is not None, "Expected profiling results" assert self.with_stack, "export_stacks() requires with_stack=True" return self.function_events.export_stacks(path, metric) def key_averages(self, group_by_input_shape=False, group_by_stack_n=0): self._check_finish() assert self.function_events is not None, "Expected profiling results" return self.function_events.key_averages(group_by_input_shape, group_by_stack_n) key_averages.__doc__ = EventList.key_averages.__doc__ def total_average(self): self._check_finish() assert self.function_events is not None, "Expected profiling results" return self.function_events.total_average() total_average.__doc__ = EventList.total_average.__doc__ @property def self_cpu_time_total(self): """ Returns total time spent on CPU obtained as a sum of all self times across all the events. """ self._check_finish() assert self.function_events is not None return self.function_events.self_cpu_time_total def _parse_kineto_results(self, result): # result.events() has most of the events - PyTorch op-level and device-level events trace_start_us = result.trace_start_us() mem_records = [[evt, False] for evt in result.events() if evt.name() == MEMORY_EVENT_NAME] mem_records_acc = MemRecordsAcc(mem_records) def _cpu_memory_usage(mem_record): return mem_record.nbytes() if \ mem_record.device_type() in [DeviceType.CPU, DeviceType.MKLDNN, DeviceType.IDEEP] \ else 0 def _cuda_memory_usage(mem_record): return mem_record.nbytes() if \ mem_record.device_type() in [DeviceType.CUDA, DeviceType.HIP] \ else 0 # Create and return FunctionEvent list function_events = [] cuda_corr_map: Dict[int, List[FunctionEvent]] = {} max_evt_id = 0 for kineto_event in result.events(): if _filter_name(kineto_event.name()): continue rel_start_us = kineto_event.start_us() - trace_start_us rel_end_us = rel_start_us + kineto_event.duration_us() abs_end_us = kineto_event.start_us() + kineto_event.duration_us() cpu_memory_usage = 0 cuda_memory_usage = 0 if kineto_event.device_type() == DeviceType.CPU: # find the corresponding memory allocation events for mem_record in mem_records_acc.in_interval(kineto_event.start_us(), abs_end_us): cpu_memory_usage += _cpu_memory_usage(mem_record[0]) cuda_memory_usage += _cuda_memory_usage(mem_record[0]) mem_record[1] = True is_async = kineto_event.is_async() or ( kineto_event.start_thread_id() != kineto_event.end_thread_id() ) fe = FunctionEvent( id=kineto_event.correlation_id(), name=_rewrite_name(name=kineto_event.name(), with_wildcard=True), trace_name=_rewrite_name(name=kineto_event.name(), with_wildcard=False), thread=kineto_event.start_thread_id(), start_us=rel_start_us, end_us=rel_end_us, fwd_thread=kineto_event.fwd_thread_id(), input_shapes=kineto_event.shapes(), stack=[entry for entry in kineto_event.stack() if _filter_stack_entry(entry)], scope=kineto_event.scope(), cpu_memory_usage=cpu_memory_usage, cuda_memory_usage=cuda_memory_usage, is_async=is_async, sequence_nr=kineto_event.sequence_nr(), device_type=kineto_event.device_type(), device_index=kineto_event.device_index(), flops=kineto_event.flops(), ) max_evt_id = fe.id if fe.id > max_evt_id else max_evt_id if fe.device_type == DeviceType.CPU and not fe.is_async: # Check if we have CUDA time as a fallback cuda_time = kineto_event.cuda_elapsed_us() if cuda_time > 0: fe.append_kernel( fe.name, fe.device_index, cuda_time) fe.is_legacy = True function_events.append(fe) corr_id = kineto_event.linked_correlation_id() if corr_id > 0: if corr_id not in cuda_corr_map: cuda_corr_map[corr_id] = [] cuda_corr_map[corr_id].append(fe) # associate CUDA kernels and CUDA runtime (CPU) with CPU events for fe in function_events: if (fe.device_type == DeviceType.CPU and not fe.is_async and fe.id in cuda_corr_map): for f_evt in cuda_corr_map[fe.id]: if f_evt.device_type == DeviceType.CUDA: fe.append_kernel( f_evt.name, f_evt.device_index, f_evt.time_range.end - f_evt.time_range.start) elif f_evt.device_type == DeviceType.CPU: # make sure that 'thread' of a CPU Kineto (e.g. CUDA Runtime) event is associated # with the 'thread' of the corresponding linked PyTorch event to properly track # parents and children f_evt.thread = fe.thread # output top-level memory events for mem_record in mem_records: if not mem_record[1]: rel_start_us = mem_record[0].start_us() - trace_start_us max_evt_id += 1 fe = FunctionEvent( id=max_evt_id, name=MEMORY_EVENT_NAME, trace_name=None, # not outputting in the trace thread=mem_record[0].start_thread_id(), start_us=rel_start_us, end_us=rel_start_us, # no duration fwd_thread=mem_record[0].start_thread_id(), input_shapes=[], stack=[], scope=0, # RecordScope::FUNCTION cpu_memory_usage=_cpu_memory_usage(mem_record[0]), cuda_memory_usage=_cuda_memory_usage(mem_record[0]), is_async=False, sequence_nr=-1, device_type=DeviceType.CPU, device_index=0, ) function_events.append(fe) function_events.sort(key=lambda evt: [evt.time_range.start, -evt.time_range.end]) return function_events class record_function(ContextDecorator): """Context manager/function decorator that adds a label to a block of Python code (or function) when running autograd profiler. It is useful when tracing the code profile. Args: name (str): Label assigned to the block of code. node_id (int): ID of node, for distributed profiling. Unset in non-distributed cases. Example: >>> x = torch.randn((1, 1), requires_grad=True) >>> with torch.autograd.profiler.profile() as prof: ... y = x ** 2 ... with torch.autograd.profiler.record_function("label-z"): # label the block ... z = y ** 3 ... y.backward() ... >>> # NOTE: some columns were removed for brevity >>> print(prof.key_averages().table(sort_by="self_cpu_time_total")) ----------------------------------- --------------- --------------- --------------- Name Self CPU total % CPU time avg Number of Calls ----------------------------------- --------------- --------------- --------------- pow 60.77% 47.470us 3 mul 21.73% 25.465us 2 PowBackward0 12.03% 121.891us 1 torch::autograd::AccumulateGrad 2.70% 6.324us 1 label-z 2.13% 12.421us 1 torch::autograd::GraphRoot 0.64% 1.503us 1 ----------------------------------- --------------- --------------- --------------- Self CPU time total: 234.344us CUDA time total: 0.000us """ def __init__(self, name: str, args: Optional[str] = None): self.name: str = name self.args: Optional[str] = args # Whether or not we should run record function's end callbacks when exiting. self.run_callbacks_on_exit: bool = True # Stores underlying RecordFunction as a tensor. TODO: move to custom # class (https://github.com/pytorch/pytorch/issues/35026). self.handle: torch.Tensor = torch.zeros(1) def __enter__(self): self.handle = torch.ops.profiler._record_function_enter(self.name, self.args) return self def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any): if self.run_callbacks_on_exit: torch.ops.profiler._record_function_exit(self.handle) def _call_end_callbacks_on_future(self, fut: Future[Any]) -> Future[Any]: """ _call_end_callbacks_on_future is meant to be used for profiling async calls that return a future. Calling this function will extend recording beyond this scope, until the future is satisfied. It is useful for profiling the end to end time of asynchronous calls. This function should only be called once to attach the callback onto the future, and will throw if called multiple times. Args: fut: (torch._C.Future): future for which to schedule callback for. Returns: A future that completes with the value of the passed in future when the profiling callbacks have ran. """ # Throw if we have already attached a callback onto the future. if not self.run_callbacks_on_exit: raise RuntimeError("_call_end_callbacks_on_future can only be called once.") # We are scheduling to run this RecordFunction's end callbacks when the # passed in future completes, so don't run end callbacks on exit. self.run_callbacks_on_exit = False profiled_future = torch.ops.profiler._call_end_callbacks_on_jit_fut(self.handle, fut) return profiled_future class emit_nvtx(object): """Context manager that makes every autograd operation emit an NVTX range. It is useful when running the program under nvprof:: nvprof --profile-from-start off -o trace_name.prof -- <regular command here> Unfortunately, there's no way to force nvprof to flush the data it collected to disk, so for CUDA profiling one has to use this context manager to annotate nvprof traces and wait for the process to exit before inspecting them. Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or :func:`torch.autograd.profiler.load_nvprof` can load the results for inspection e.g. in Python REPL. .. warning: This context manager should not be called recursively, i.e. at most one instance should be enabled at any given time. Args: enabled (bool, optional, default=True): Setting ``enabled=False`` makes this context manager a no-op. Default: ``True``. record_shapes (bool, optional, default=False): If ``record_shapes=True``, the nvtx range wrapping each autograd op will append information about the sizes of Tensor arguments received by that op, in the following format: ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]`` Non-tensor arguments will be represented by ``[]``. Arguments will be listed in the order they are received by the backend op. Please note that this order may not match the order in which those arguments were passed on the Python side. Also note that shape recording may increase the overhead of nvtx range creation. Example: >>> with torch.cuda.profiler.profile(): ... model(x) # Warmup CUDA memory allocator and profiler ... with torch.autograd.profiler.emit_nvtx(): ... model(x) **Forward-backward correlation** When viewing a profile created using :class:`emit_nvtx` in the Nvidia Visual Profiler, correlating each backward-pass op with the corresponding forward-pass op can be difficult. To ease this task, :class:`emit_nvtx` appends sequence number information to the ranges it generates. During the forward pass, each function range is decorated with ``seq=<N>``. ``seq`` is a running counter, incremented each time a new backward Function object is created and stashed for backward. Thus, the ``seq=<N>`` annotation associated with each forward function range tells you that if a backward Function object is created by this forward function, the backward object will receive sequence number N. During the backward pass, the top-level range wrapping each C++ backward Function's ``apply()`` call is decorated with ``stashed seq=<M>``. ``M`` is the sequence number that the backward object was created with. By comparing ``stashed seq`` numbers in backward with ``seq`` numbers in forward, you can track down which forward op created each backward Function. Any functions executed during the backward pass are also decorated with ``seq=<N>``. During default backward (with ``create_graph=False``) this information is irrelevant, and in fact, ``N`` may simply be 0 for all such functions. Only the top-level ranges associated with backward Function objects' ``apply()`` methods are useful, as a way to correlate these Function objects with the earlier forward pass. **Double-backward** If, on the other hand, a backward pass with ``create_graph=True`` is underway (in other words, if you are setting up for a double-backward), each function's execution during backward is given a nonzero, useful ``seq=<N>``. Those functions may themselves create Function objects to be executed later during double-backward, just as the original functions in the forward pass did. The relationship between backward and double-backward is conceptually the same as the relationship between forward and backward: The functions still emit current-sequence-number-tagged ranges, the Function objects they create still stash those sequence numbers, and during the eventual double-backward, the Function objects' ``apply()`` ranges are still tagged with ``stashed seq`` numbers, which can be compared to `seq` numbers from the backward pass. .. warning: The sequence number is thread-local, and some forward functions don't create an associated backward Function object (instead delegating that to sub-functions further down the call chain). For these reasons, the correspondence of stashed sequence numbers in backward Function ``apply()`` ranges with `seq` numbers in forward-pass ranges is not guaranteed to be 1 to 1. The sequence numbers alone may not be enough to fully disambiguate which forward function created which backward Function object. You may need to make a judgment based on analytic knowledge of what the expected correspondence should be. """ def __init__(self, enabled=True, record_shapes=False): self.enabled = enabled self.entered = False self.record_shapes = record_shapes def __enter__(self): if not self.enabled: return if self.entered: raise RuntimeError("NVTX annotation context manager is not reentrant") self.entered = True torch.cuda.synchronize() _enable_profiler( ProfilerConfig( ProfilerState.NVTX, self.record_shapes, False, False, False, False), set() ) return self def __exit__(self, exc_type, exc_val, exc_tb): if not self.enabled: return torch.cuda.synchronize() _disable_profiler() return False def load_nvprof(path): """Opens an nvprof trace file and parses autograd annotations. Args: path (str): path to nvprof trace """ return EventList(parse_nvprof_trace(path)) class EnforceUnique(object): """Raises an error if a key is seen more than once.""" def __init__(self): self.seen = set() def see(self, *key): if key in self.seen: raise RuntimeError('duplicate key: ' + str(key)) self.seen.add(key) def parse_nvprof_trace(path): import sqlite3 conn = sqlite3.connect(path) conn.row_factory = sqlite3.Row # Parse strings table strings = {} for r in conn.execute("SELECT _id_ as id, value FROM StringTable"): strings[r["id"]] = torch._C._demangle(r["value"]) # First, find all functions and create FunctionEvents for them marker_query = """ SELECT start.id AS marker_id, start.name, start.timestamp AS start_time, end.timestamp AS end_time FROM CUPTI_ACTIVITY_KIND_MARKER AS start INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end ON start.id = end.id WHERE start.name != 0 AND end.name = 0 """ functions = [] functions_map = {} unique = EnforceUnique() for row in conn.execute(marker_query): unique.see(row['marker_id']) evt = FunctionEvent(id=row['marker_id'], node_id=0, # missing a node_id when calling FunctionEvent. This is just to ensure # that pytorch doesn't crash when creating a FunctionEvent() object name=strings[row['name']], start_us=row['start_time'], end_us=row['end_time'], thread=0) # TODO: find in sqlite database functions.append(evt) functions_map[evt.id] = evt # Now, correlate all kernels with FunctionEvents kernel_query = """ SELECT start.id AS marker_id, start.name, start.timestamp, end.timestamp, runtime._id_ AS runtime_id, runtime.cbid, runtime.start AS runtime_start, runtime.end AS runtime_end, kernel.start AS kernel_start, kernel.end AS kernel_end, kernel.name AS kernel_name FROM CUPTI_ACTIVITY_KIND_MARKER AS start INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end ON start.id = end.id INNER JOIN CUPTI_ACTIVITY_KIND_RUNTIME as runtime ON (start.timestamp < runtime.start AND runtime.end < end.timestamp) INNER JOIN CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL AS kernel ON kernel.correlationId = runtime.correlationId """ unique = EnforceUnique() for row in conn.execute(kernel_query): unique.see(row['marker_id'], row['runtime_id']) # 211 is cudaKernelLaunch for cuda >= 9.2 assert (row['cbid'] == 211) evt = functions_map[row['marker_id']] evt.append_kernel(row['kernel_name'], 0, row['kernel_end'] - row['kernel_start']) functions.sort(key=lambda evt: evt.time_range.start) return functions
null
null
null
null
null
null
null
null
null
[]
9,615
tests/validation/tests/v1_api/test_deployment.py
ursinnDev/rancher_rancher
18,697
9768808
from .common import * # NOQA import pytest namespace = {"client": None, "ns": None} def test_namespace_create(): template = read_yaml_from_resource_dir("namespace.yaml") template["metadata"]["name"] = random_test_name() client = namespace["client"] res = client.create_namespace(template) # validate the namespace is created ns = client.by_id_namespace(res.id) assert ns.id == res.id # delete the namespace at the end client.delete(ns) def test_deployment(): client = namespace["client"] ns = namespace["ns"] template = read_json_from_resource_dir("deployment_1.json") name = random_name() # set name template["metadata"]["name"] = name # set namespace template["metadata"]["namespace"] = ns.id # set container image and name template["spec"]["template"]["spec"]["containers"][0]["image"] = TEST_IMAGE_V1 template["spec"]["template"]["spec"]["containers"][0]["name"] = name # set label and selector label_value = "apps.deployment-{}-{}".format(ns.id, name) labels = template["spec"]["template"]["metadata"]["labels"] labels["workload.user.cattle.io/workloadselector"] = label_value matches = template["spec"]["selector"]["matchLabels"] matches["workload.user.cattle.io/workloadselector"] = label_value deployment = client.create_apps_deployment(template) deployment = validate_deployment(client, deployment) # scale up to 5 pods deployment.spec.replicas = 5 deployment = client.update(deployment, deployment) deployment = validate_deployment(client, deployment) client.delete(deployment) def validate_deployment(client, deployment): # wait for the deployment to be active wait_for(lambda: client.reload(deployment).metadata.state.name == "active", timeout_message="time out waiting for deployment to be ready") res = client.reload(deployment) name = res["metadata"]["name"] namespace = res["metadata"]["namespace"] replicas = res["spec"]["replicas"] # Rancher Dashboard gets pods by passing the label selector target_label = 'workload.user.cattle.io/workloadselector=apps.deployment-{}-{}' pods = client.list_pod( labelSelector=target_label.format(namespace, name)) assert "data" in pods.keys(), "failed to get pods" assert len(pods.data) == replicas, "failed to get the right number of pods" for pod in pods.data: assert pod.metadata.state.name == "running" return res @pytest.fixture(scope='module', autouse="True") def create_client(request): client = get_cluster_client_for_token_v1() template = read_yaml_from_resource_dir("namespace.yaml") template["metadata"]["name"] = random_test_name() ns = client.create_namespace(template) namespace["client"] = client namespace["ns"] = ns def fin(): client.delete(namespace["ns"]) request.addfinalizer(fin)
null
null
null
null
null
null
null
null
null
[]
6,232
tests/components/motion_blinds/__init__.py
tbarbette/core
30,023
8241861
<reponame>tbarbette/core """Tests for the Motion Blinds integration."""
0
0
0.0
0
0
0
1.0
0
0
[]
9,202
posthog/settings/cloud.py
dorucioclea/posthog
7,409
9633711
# Overridden in posthog-cloud import sys from posthog.settings.utils import get_from_env, print_warning, str_to_bool # Early exit to avoid issues with cloud not being properly included if get_from_env("MULTI_TENANCY", False, type_cast=str_to_bool): print_warning(("️Environment variable MULTI_TENANCY is set, but cloud settings have not been included",)) sys.exit("[ERROR] Stopping Django server…\n")
null
null
null
null
null
null
null
null
null
[]
5,668
xirl/xirl/evaluators/reward_visualizer.py
xxdreck/google-research
23,901
10173439
# 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. """Reward visualizer.""" from .base import Evaluator from .base import EvaluatorOutput import matplotlib.pyplot as plt import numpy as np from scipy.spatial.distance import cdist class RewardVisualizer(Evaluator): """Distance to goal state visualizer.""" def __init__(self, distance, num_plots): """Constructor. Args: distance: The distance metric to use when calculating nearest-neighbours. num_plots: The number of reward plots to display. Raises: ValueError: If the distance metric is invalid. """ super().__init__(inter_class=False) if distance not in ["sqeuclidean", "cosine"]: raise ValueError( "{} is not a supported distance metric.".format(distance)) # For plotting, we don't want to display squared euclidean distances so we # will override to `euclidean` if it was selected. if distance == "sqeuclidean": distance = "euclidean" self.distance = distance self.num_plots = num_plots def _gen_reward_plot(self, rewards): """Create a pyplot plot and save to buffer.""" fig, axes = plt.subplots(1, len(rewards), figsize=(6.4 * len(rewards), 4.8)) if len(rewards) == 1: axes = [axes] for i, rew in enumerate(rewards): axes[i].plot(rew) fig.text(0.5, 0.04, "Timestep", ha="center") fig.text(0.04, 0.5, "Reward", va="center", rotation="vertical") fig.canvas.draw() img_arr = np.array(fig.canvas.renderer.buffer_rgba())[:, :, :3] plt.close() return img_arr def _compute_goal_emb(self, embs): """Compute the mean of all last frame embeddings.""" goal_emb = [emb[-1, :] for emb in embs] goal_emb = np.stack(goal_emb, axis=0) goal_emb = np.mean(goal_emb, axis=0, keepdims=True) return goal_emb def evaluate(self, outs): embs = [o.embs for o in outs] goal_emb = self._compute_goal_emb(embs) # Make sure we sample only as many as are available. num_plots = min(len(embs), self.num_plots) rand_idxs = np.random.choice( np.arange(len(embs)), size=num_plots, replace=False) # Compute rewards as distances to the goal embedding. rewards = [] for idx in rand_idxs: emb = embs[idx] dists = cdist(emb, goal_emb, self.distance) rewards.append(-dists) image = self._gen_reward_plot(rewards) return EvaluatorOutput(image=image)
null
null
null
null
null
null
null
null
null
[]
11,923
python/paddle/fluid/tests/unittests/test_conv2d_transpose_op_depthwise_conv.py
zmxdream/Paddle
17,085
10185976
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import print_function import unittest import numpy as np import paddle paddle.enable_static() import paddle.fluid.core as core import paddle.fluid as fluid from op_test import OpTest from test_conv2d_transpose_op import TestConv2DTransposeOp class TestDepthwiseConvTranspose(TestConv2DTransposeOp): def init_test_case(self): self.pad = [1, 1] self.stride = [1, 1] self.dilations = [1, 1] self.input_size = [1, 8, 4, 4] # NCHW self.groups = 8 assert np.mod(self.input_size[1], self.groups) == 0 f_c = self.input_size[1] // self.groups self.filter_size = [self.input_size[1], f_c, 4, 4] self.op_type = "depthwise_conv2d_transpose" class TestDepthwiseConvTransposeAsymmetricPad(TestConv2DTransposeOp): def init_test_case(self): self.pad = [1, 1, 1, 2] self.stride = [1, 1] self.dilations = [1, 1] self.input_size = [1, 8, 4, 4] # NCHW self.groups = 8 assert np.mod(self.input_size[1], self.groups) == 0 f_c = self.input_size[1] // self.groups self.filter_size = [self.input_size[1], f_c, 3, 3] self.op_type = "depthwise_conv2d_transpose" self.data_format = 'NCHW' class TestDepthwiseConvTransposeSAMEPad(TestConv2DTransposeOp): def init_test_case(self): self.stride = [1, 1] self.dilations = [1, 1] self.input_size = [1, 8, 4, 4] # NHWC self.groups = 8 assert np.mod(self.input_size[1], self.groups) == 0 f_c = self.input_size[1] // self.groups self.filter_size = [self.input_size[1], f_c, 3, 3] self.op_type = "depthwise_conv2d_transpose" self.padding_algorithm = 'SAME' class TestDepthwiseConvTransposeVALIDPad(TestConv2DTransposeOp): def init_test_case(self): self.stride = [1, 1] self.dilations = [1, 1] self.input_size = [1, 8, 4, 4] # NHWC self.groups = 8 assert np.mod(self.input_size[1], self.groups) == 0 f_c = self.input_size[1] // self.groups self.filter_size = [self.input_size[1], f_c, 3, 3] self.op_type = "depthwise_conv2d_transpose" self.padding_algorithm = 'VALID' class TestDepthwiseConvTranspose_NHWC_3x3kernel(TestConv2DTransposeOp): def init_test_case(self): self.pad = [1, 1] self.stride = [1, 1] self.dilations = [1, 1] self.input_size = [1, 4, 4, 8] # NHWC self.groups = 8 assert np.mod(self.input_size[3], self.groups) == 0 f_c = self.input_size[3] // self.groups self.filter_size = [self.input_size[3], f_c, 3, 3] self.op_type = "depthwise_conv2d_transpose" self.data_format = 'NHWC' if __name__ == '__main__': unittest.main()
null
null
null
null
null
null
null
null
null
[]
12,003
homeassistant/components/unifiprotect/light.py
liangleslie/core
30,023
515251
<gh_stars>1000+ """This component provides Lights for UniFi Protect.""" from __future__ import annotations import logging from typing import Any from pyunifiprotect.data import Light from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode, LightEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN from .data import ProtectData from .entity import ProtectDeviceEntity _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up lights for UniFi Protect integration.""" data: ProtectData = hass.data[DOMAIN][entry.entry_id] entities = [ ProtectLight( data, device, ) for device in data.api.bootstrap.lights.values() ] if not entities: return async_add_entities(entities) def unifi_brightness_to_hass(value: int) -> int: """Convert unifi brightness 1..6 to hass format 0..255.""" return min(255, round((value / 6) * 255)) def hass_to_unifi_brightness(value: int) -> int: """Convert hass brightness 0..255 to unifi 1..6 scale.""" return max(1, round((value / 255) * 6)) class ProtectLight(ProtectDeviceEntity, LightEntity): """A Ubiquiti UniFi Protect Light Entity.""" device: Light _attr_icon = "mdi:spotlight-beam" _attr_color_mode = ColorMode.BRIGHTNESS _attr_supported_color_modes = {ColorMode.BRIGHTNESS} @callback def _async_update_device_from_protect(self) -> None: super()._async_update_device_from_protect() self._attr_is_on = self.device.is_light_on self._attr_brightness = unifi_brightness_to_hass( self.device.light_device_settings.led_level ) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the light on.""" hass_brightness = kwargs.get(ATTR_BRIGHTNESS, self.brightness) unifi_brightness = hass_to_unifi_brightness(hass_brightness) _LOGGER.debug("Turning on light with brightness %s", unifi_brightness) await self.device.set_light(True, unifi_brightness) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" _LOGGER.debug("Turning off light") await self.device.set_light(False)
0
0
0.0
1
0
0
1.0
0
7
[]
10,391
tests_django/test_settings.py
gugux289/chatterbot
13,200
10102852
<gh_stars>1000+ """ Django settings for when tests are run. """ import os from chatterbot import constants DEBUG = True BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'fake-key' INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'chatterbot.ext.django_chatterbot', 'tests_django', ] CHATTERBOT = { 'name': 'Test Django ChatterBot', 'logic_adapters': [ { 'import_path': 'chatterbot.logic.BestMatch', }, { 'import_path': 'chatterbot.logic.MathematicalEvaluation', } ], 'storage_adapter': 'chatterbot.storage.DjangoStorageAdapter', 'django_app_name': constants.DEFAULT_DJANGO_APP_NAME, 'initialize': False } MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Using the MD5 password hasher improves test performance PASSWORD_HASHERS = ( 'django.contrib.auth.hashers.MD5PasswordHasher', ) USE_TZ = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, }
null
null
null
null
null
null
null
null
null
[]
11,633
configs/paa/paa_r50_fpn_1.5x_coco.py
evgps/mmdetection_trashcan
20,190
11287256
<gh_stars>1000+ _base_ = './paa_r50_fpn_1x_coco.py' lr_config = dict(step=[12, 16]) runner = dict(type='EpochBasedRunner', max_epochs=18)
null
null
null
null
null
null
null
null
null
[]
6,811
homeassistant/components/fastdotcom/sensor.py
MrDelik/core
30,023
405011
<reponame>MrDelik/core """Support for Fast.com internet speed testing sensor.""" from __future__ import annotations from typing import Any from homeassistant.components.sensor import SensorEntity from homeassistant.const import DATA_RATE_MEGABITS_PER_SECOND from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import DATA_UPDATED, DOMAIN as FASTDOTCOM_DOMAIN ICON = "mdi:speedometer" async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Fast.com sensor.""" async_add_entities([SpeedtestSensor(hass.data[FASTDOTCOM_DOMAIN])]) class SpeedtestSensor(RestoreEntity, SensorEntity): """Implementation of a FAst.com sensor.""" _attr_name = "Fast.com Download" _attr_native_unit_of_measurement = DATA_RATE_MEGABITS_PER_SECOND _attr_icon = ICON _attr_should_poll = False _attr_native_value = None def __init__(self, speedtest_data: dict[str, Any]) -> None: """Initialize the sensor.""" self._speedtest_data = speedtest_data async def async_added_to_hass(self) -> None: """Handle entity which will be added.""" await super().async_added_to_hass() self.async_on_remove( async_dispatcher_connect( self.hass, DATA_UPDATED, self._schedule_immediate_update ) ) if not (state := await self.async_get_last_state()): return self._attr_native_value = state.state def update(self) -> None: """Get the latest data and update the states.""" if (data := self._speedtest_data.data) is None: # type: ignore[attr-defined] return self._attr_native_value = data["download"] @callback def _schedule_immediate_update(self) -> None: self.async_schedule_update_ha_state(True)
null
null
null
null
null
null
null
null
null
[]
10,193
tests/nlu/featurizers/test_regex_featurizer.py
Next-Trends/rasa
3,603
6565391
<gh_stars>1000+ from typing import Text, List, Any, Tuple, Callable, Dict, Optional import dataclasses import numpy as np import pytest from rasa.engine.graph import ExecutionContext from rasa.engine.storage.resource import Resource from rasa.engine.storage.storage import ModelStorage from rasa.nlu.featurizers.sparse_featurizer.regex_featurizer import RegexFeaturizer from rasa.shared.nlu.training_data.training_data import TrainingData from rasa.shared.nlu.training_data.message import Message from rasa.nlu.tokenizers.whitespace_tokenizer import WhitespaceTokenizer from rasa.nlu.constants import SPACY_DOCS, TOKENS_NAMES from rasa.shared.nlu.constants import TEXT, INTENT, RESPONSE from rasa.nlu.tokenizers.spacy_tokenizer import SpacyTokenizer @pytest.fixture() def resource() -> Resource: return Resource("regex_featurizer") @pytest.fixture() def create_featurizer( default_model_storage: ModelStorage, default_execution_context: ExecutionContext, resource: Resource, ) -> Callable[..., RegexFeaturizer]: def inner( config: Dict[Text, Any] = None, known_patterns: Optional[List[Dict[Text, Any]]] = None, ) -> RegexFeaturizer: config = config or {} return RegexFeaturizer( {**RegexFeaturizer.get_default_config(), **config}, default_model_storage, resource, default_execution_context, known_patterns, ) return inner @pytest.mark.parametrize( "sentence, expected_sequence_features, expected_sentence_features," "labeled_tokens", [ ( "hey how are you today", [ [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], ], [0.0, 1.0, 0.0], [0], ), ( "hey 456 how are you", [ [0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], ], [1.0, 1.0, 0.0], [1, 0], ), ( "blah balh random eh", [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [0.0, 0.0, 0.0], [], ), ( "a 1 digit number", [[0.0, 0.0, 0.0], [1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [1.0, 0.0, 1.0], [1, 1], ), ], ) def test_regex_featurizer( sentence: Text, expected_sequence_features: List[float], expected_sentence_features: List[float], labeled_tokens: List[int], spacy_nlp: Any, create_featurizer: Callable[..., RegexFeaturizer], spacy_tokenizer: SpacyTokenizer, ): patterns = [ {"pattern": "[0-9]+", "name": "number", "usage": "intent"}, {"pattern": "\\bhey*", "name": "hello", "usage": "intent"}, {"pattern": "[0-1]+", "name": "binary", "usage": "intent"}, ] ftr = create_featurizer(known_patterns=patterns) # adds tokens to the message message = Message(data={TEXT: sentence, RESPONSE: sentence}) message.set(SPACY_DOCS[TEXT], spacy_nlp(sentence)) spacy_tokenizer.process([message]) sequence_features, sentence_features = ftr._features_for_patterns(message, TEXT) assert np.allclose( sequence_features.toarray(), expected_sequence_features, atol=1e-10 ) assert np.allclose( sentence_features.toarray(), expected_sentence_features, atol=1e-10 ) # the tokenizer should have added tokens assert len(message.get(TOKENS_NAMES[TEXT], [])) > 0 # the number of regex matches on each token should match for i, token in enumerate(message.get(TOKENS_NAMES[TEXT])): token_matches = token.get("pattern").values() num_matches = sum(token_matches) assert num_matches == labeled_tokens.count(i) @pytest.mark.parametrize( "sentence, tokens, expected_sequence_features, expected_sentence_features," "labeled_tokens", [ ( "明天上海的天气怎么样?", [("明天", 0), ("上海", 2), ("的", 4), ("天气", 5), ("怎么样", 7), ("?", 10)], [[0.0, 1.0], [1.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], [1.0, 1.0], [0.0, 1.0], ), ( "北京的天气如何?", [("北京", 0), ("的", 2), ("天气", 3), ("如何", 5), ("?", 7)], [[1.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], [1.0, 0.0], [0.0], ), ( "昨天和今天的天气都不错", [("昨天", 0), ("和", 2), ("今天", 3), ("的", 5), ("天气", 6), ("都", 8), ("不错", 9)], [ [0.0, 1.0], [0.0, 0.0], [0.0, 1.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], ], [0.0, 1.0], [0.0, 2.0], ), ( "后天呢?", [("后天", 0), ("呢", 2), ("?", 3)], [[0.0, 1.0], [0.0, 0.0], [0.0, 0.0]], [0.0, 1.0], [0.0], ), ], ) def test_lookup_tables_without_use_word_boundaries( sentence: Text, tokens: List[Tuple[Text, float]], expected_sequence_features: List[float], expected_sentence_features: List[float], labeled_tokens: List[float], create_featurizer: Callable[..., RegexFeaturizer], ): from rasa.nlu.tokenizers.tokenizer import Token lookups = [ {"name": "cites", "elements": ["北京", "上海", "广州", "深圳", "杭州"]}, {"name": "dates", "elements": ["昨天", "今天", "明天", "后天"]}, ] ftr = create_featurizer({"use_word_boundaries": False}) training_data = TrainingData() training_data.lookup_tables = lookups ftr.train(training_data) # adds tokens to the message message = Message(data={TEXT: sentence}) message.set(TOKENS_NAMES[TEXT], [Token(word, start) for (word, start) in tokens]) sequence_features, sentence_features = ftr._features_for_patterns(message, TEXT) assert np.allclose( sequence_features.toarray(), expected_sequence_features, atol=1e-10 ) assert np.allclose( sentence_features.toarray(), expected_sentence_features, atol=1e-10 ) # the number of regex matches on each token should match for i, token in enumerate(message.get(TOKENS_NAMES[TEXT])): token_matches = token.get("pattern").values() num_matches = sum(token_matches) assert num_matches == labeled_tokens.count(i) @pytest.mark.parametrize( "sentence, expected_sequence_features, expected_sentence_features, " "labeled_tokens", [ ( "lemonade and mapo tofu", [[1.0, 0.0], [0.0, 0.0], [0.0, 1.0], [0.0, 1.0]], [1.0, 1.0], [0.0, 2.0, 3.0], ), ( "a cup of tea", [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [1.0, 0.0]], [1.0, 0.0], [3.0], ), ( "Is burrito my favorite food?", [[0.0, 0.0], [0.0, 1.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], [0.0, 1.0], [1.0], ), ("I want club?mate", [[0.0, 0.0], [0.0, 0.0], [1.0, 0.0]], [1.0, 0.0], [2.0]), ], ) def test_lookup_tables( sentence: Text, expected_sequence_features: List[float], expected_sentence_features: List[float], labeled_tokens: List[float], spacy_nlp: Any, spacy_tokenizer: SpacyTokenizer, create_featurizer: Callable[..., RegexFeaturizer], ): lookups = [ { "name": "drinks", "elements": ["mojito", "lemonade", "sweet berry wine", "tea", "club?mate"], }, {"name": "plates", "elements": "data/test/lookup_tables/plates.txt"}, ] ftr = create_featurizer() training_data = TrainingData() training_data.lookup_tables = lookups ftr.train(training_data) ftr.process_training_data(training_data) # adds tokens to the message message = Message(data={TEXT: sentence}) message.set("text_spacy_doc", spacy_nlp(sentence)) spacy_tokenizer.process([message]) sequence_features, sentence_features = ftr._features_for_patterns(message, TEXT) assert np.allclose( sequence_features.toarray(), expected_sequence_features, atol=1e-10 ) assert np.allclose( sentence_features.toarray(), expected_sentence_features, atol=1e-10 ) # the tokenizer should have added tokens assert len(message.get(TOKENS_NAMES[TEXT], [])) > 0 # the number of regex matches on each token should match for i, token in enumerate(message.get(TOKENS_NAMES[TEXT])): token_matches = token.get("pattern").values() num_matches = sum(token_matches) assert num_matches == labeled_tokens.count(i) @pytest.mark.parametrize( "sentence, expected_sequence_features, expected_sentence_features", [ ("hey how are you today", [0.0, 1.0, 0.0], [0.0, 1.0, 0.0]), ("hey 456 how are you", [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]), ("blah balh random eh", [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]), ("a 1 digit number", [0.0, 0.0, 0.0], [1.0, 0.0, 1.0]), ], ) def test_regex_featurizer_no_sequence( sentence: Text, expected_sequence_features: List[float], expected_sentence_features: List[float], spacy_nlp: Any, create_featurizer: Callable[..., RegexFeaturizer], spacy_tokenizer: SpacyTokenizer, ): patterns = [ {"pattern": "[0-9]+", "name": "number", "usage": "intent"}, {"pattern": "\\bhey*", "name": "hello", "usage": "intent"}, {"pattern": "[0-1]+", "name": "binary", "usage": "intent"}, ] ftr = create_featurizer(known_patterns=patterns) # adds tokens to the message message = Message(data={TEXT: sentence}) message.set(SPACY_DOCS[TEXT], spacy_nlp(sentence)) spacy_tokenizer.process([message]) sequence_features, sentence_features = ftr._features_for_patterns(message, TEXT) assert np.allclose( sequence_features.toarray()[0], expected_sequence_features, atol=1e-10 ) assert np.allclose( sentence_features.toarray()[-1], expected_sentence_features, atol=1e-10 ) def test_regex_featurizer_train( create_featurizer: Callable[..., RegexFeaturizer], whitespace_tokenizer: WhitespaceTokenizer, ): patterns = [ {"pattern": "[0-9]+", "name": "number", "usage": "intent"}, {"pattern": "\\bhey*", "name": "hello", "usage": "intent"}, {"pattern": "[0-1]+", "name": "binary", "usage": "intent"}, ] featurizer = create_featurizer() sentence = "hey how are you today 19.12.2019 ?" message = Message(data={TEXT: sentence}) message.set(RESPONSE, sentence) message.set(INTENT, "intent") whitespace_tokenizer.process_training_data(TrainingData([message])) training_data = TrainingData([message], regex_features=patterns) featurizer.train(training_data) featurizer.process_training_data(training_data) expected = np.array([0, 1, 0]) expected_cls = np.array([1, 1, 1]) seq_vecs, sen_vec = message.get_sparse_features(TEXT, []) if seq_vecs: seq_vecs = seq_vecs.features if sen_vec: sen_vec = sen_vec.features assert (6, 3) == seq_vecs.shape assert (1, 3) == sen_vec.shape assert np.all(seq_vecs.toarray()[0] == expected) assert np.all(sen_vec.toarray()[-1] == expected_cls) seq_vecs, sen_vec = message.get_sparse_features(RESPONSE, []) if seq_vecs: seq_vecs = seq_vecs.features if sen_vec: sen_vec = sen_vec.features assert (6, 3) == seq_vecs.shape assert (1, 3) == sen_vec.shape assert np.all(seq_vecs.toarray()[0] == expected) assert np.all(sen_vec.toarray()[-1] == expected_cls) seq_vecs, sen_vec = message.get_sparse_features(INTENT, []) if seq_vecs: seq_vecs = seq_vecs.features if sen_vec: sen_vec = sen_vec.features assert seq_vecs is None assert sen_vec is None @pytest.mark.parametrize( "sentence, expected_sequence_features, expected_sentence_features," "case_sensitive", [ ("Hey How are you today", [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], True), ("Hey How are you today", [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], False), ("Hey 456 How are you", [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], True), ("Hey 456 How are you", [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], False), ], ) def test_regex_featurizer_case_sensitive( sentence: Text, expected_sequence_features: List[float], expected_sentence_features: List[float], case_sensitive: bool, spacy_nlp: Any, create_featurizer: Callable[..., RegexFeaturizer], spacy_tokenizer: SpacyTokenizer, ): patterns = [ {"pattern": "[0-9]+", "name": "number", "usage": "intent"}, {"pattern": "\\bhey*", "name": "hello", "usage": "intent"}, {"pattern": "[0-1]+", "name": "binary", "usage": "intent"}, ] ftr = create_featurizer({"case_sensitive": case_sensitive}, known_patterns=patterns) # adds tokens to the message message = Message(data={TEXT: sentence}) message.set(SPACY_DOCS[TEXT], spacy_nlp(sentence)) spacy_tokenizer.process([message]) sequence_features, sentence_features = ftr._features_for_patterns(message, TEXT) assert np.allclose( sequence_features.toarray()[0], expected_sequence_features, atol=1e-10 ) assert np.allclose( sentence_features.toarray()[-1], expected_sentence_features, atol=1e-10 ) @pytest.mark.parametrize( "sentence, expected_sequence_features, expected_sentence_features," "labeled_tokens, use_word_boundaries", [ ("how are you", [[1.0], [0.0], [0.0]], [1.0], [0.0], True), ("how are you", [[1.0], [0.0], [0.0]], [1.0], [0.0], False), ("Take a shower", [[0.0], [0.0], [0.0]], [0.0], [], True), ("Take a shower", [[0.0], [0.0], [1.0]], [1.0], [2.0], False), ("What a show", [[0.0], [0.0], [0.0]], [0.0], [], True), ("What a show", [[0.0], [0.0], [1.0]], [1.0], [2.0], False), ("The wolf howled", [[0.0], [0.0], [0.0]], [0.0], [], True), ("The wolf howled", [[0.0], [0.0], [1.0]], [1.0], [2.0], False), ], ) def test_lookup_with_and_without_boundaries( sentence: Text, expected_sequence_features: List[List[float]], expected_sentence_features: List[float], labeled_tokens: List[float], use_word_boundaries: bool, spacy_nlp: Any, create_featurizer: Callable[..., RegexFeaturizer], spacy_tokenizer: SpacyTokenizer, ): ftr = create_featurizer({"use_word_boundaries": use_word_boundaries}) training_data = TrainingData() # we use lookups because the "use_word_boundaries" flag is only used when # producing patterns from lookup tables lookups = [{"name": "how", "elements": ["how"]}] training_data.lookup_tables = lookups ftr.train(training_data) # adds tokens to the message message = Message(data={TEXT: sentence}) message.set(SPACY_DOCS[TEXT], spacy_nlp(sentence)) spacy_tokenizer.process([message]) (sequence_features, sentence_features) = ftr._features_for_patterns(message, TEXT) sequence_features = sequence_features.toarray() sentence_features = sentence_features.toarray() num_of_patterns = sum([len(lookup["elements"]) for lookup in lookups]) assert sequence_features.shape == ( len(message.get(TOKENS_NAMES[TEXT])), num_of_patterns, ) num_of_lookup_tables = len(lookups) assert sentence_features.shape == (num_of_lookup_tables, num_of_patterns) # sequence_features should be {0,1} for each token: 1 if match, 0 if not assert np.allclose(sequence_features, expected_sequence_features, atol=1e-10) # sentence_features should be {0,1} for each lookup table: 1 if sentence # contains match from that table, 0 if not assert np.allclose(sentence_features, expected_sentence_features, atol=1e-10) # the tokenizer should have added tokens assert len(message.get(TOKENS_NAMES[TEXT], [])) > 0 # the number of regex matches on each token should match for i, token in enumerate(message.get(TOKENS_NAMES[TEXT])): token_matches = token.get("pattern").values() num_matches = sum(token_matches) # labeled_tokens should list the token(s) which match a pattern assert num_matches == labeled_tokens.count(i) def test_persist_load_for_finetuning( create_featurizer: Callable[..., RegexFeaturizer], default_model_storage: ModelStorage, default_execution_context: ExecutionContext, resource: Resource, whitespace_tokenizer: WhitespaceTokenizer, ): patterns = [ {"pattern": "[0-9]+", "name": "number", "usage": "intent"}, {"pattern": "\\bhey*", "name": "hello", "usage": "intent"}, {"pattern": "[0-1]+", "name": "binary", "usage": "intent"}, ] featurizer = create_featurizer() sentence = "hey how are you today 19.12.2019 ?" message = Message(data={TEXT: sentence}) message.set(RESPONSE, sentence) message.set(INTENT, "intent") training_data = TrainingData([message], regex_features=patterns) whitespace_tokenizer.process_training_data(training_data) featurizer.train(training_data) loaded_featurizer = RegexFeaturizer.load( RegexFeaturizer.get_default_config(), default_model_storage, resource, dataclasses.replace(default_execution_context, is_finetuning=True), ) # Test component loaded in finetune mode and also with # same patterns as before and vocabulary statistics assert loaded_featurizer.known_patterns == featurizer.known_patterns assert loaded_featurizer.finetune_mode new_lookups = [{"name": "plates", "elements": "data/test/lookup_tables/plates.txt"}] training_data = TrainingData() training_data.lookup_tables = new_lookups loaded_featurizer.train(training_data) # Test merging of a new pattern to an already trained component. assert len(loaded_featurizer.known_patterns) == 4 def test_vocabulary_expand_for_finetuning( create_featurizer: Callable[..., RegexFeaturizer], default_model_storage: ModelStorage, resource: Resource, default_execution_context: ExecutionContext, whitespace_tokenizer: WhitespaceTokenizer, ): patterns = [ {"pattern": "[0-9]+", "name": "number", "usage": "intent"}, {"pattern": "\\bhey*", "name": "hello", "usage": "intent"}, ] featurizer = create_featurizer() sentence = "hey hey 2020" message = Message(data={TEXT: sentence}) message.set(RESPONSE, sentence) message.set(INTENT, "intent") training_data = TrainingData([message], regex_features=patterns) whitespace_tokenizer.process_training_data(training_data) featurizer.train(training_data) featurizer.process_training_data(training_data) # Test featurization of message expected = np.array([1, 0]) expected_cls = np.array([1, 1]) seq_vecs, sen_vec = message.get_sparse_features(TEXT, []) if seq_vecs: seq_vecs = seq_vecs.features if sen_vec: sen_vec = sen_vec.features assert (3, 2) == seq_vecs.shape assert (1, 2) == sen_vec.shape assert np.all(seq_vecs.toarray()[0] == expected) assert np.all(sen_vec.toarray()[-1] == expected_cls) loaded_featurizer = RegexFeaturizer.load( RegexFeaturizer.get_default_config(), default_model_storage, resource, dataclasses.replace(default_execution_context, is_finetuning=True), ) new_patterns = [ {"pattern": "\\btoday*", "name": "day", "usage": "intent"}, {"pattern": "\\bhey+", "name": "hello", "usage": "intent"}, ] new_sentence = "hey today" message = Message(data={TEXT: new_sentence}) message.set(RESPONSE, new_sentence) message.set(INTENT, "intent") new_training_data = TrainingData([message], regex_features=patterns + new_patterns) whitespace_tokenizer.process_training_data(new_training_data) loaded_featurizer.train(new_training_data) loaded_featurizer.process_training_data(new_training_data) # Test featurization of message, this time for the extra pattern as well. expected_token_1 = np.array([1, 0, 0]) expected_token_2 = np.array([0, 0, 1]) expected_cls = np.array([1, 0, 1]) seq_vecs, sen_vec = message.get_sparse_features(TEXT, []) if seq_vecs: seq_vecs = seq_vecs.features if sen_vec: sen_vec = sen_vec.features assert (2, 3) == seq_vecs.shape assert (1, 3) == sen_vec.shape assert np.all(seq_vecs.toarray()[0] == expected_token_1) assert np.all(seq_vecs.toarray()[1] == expected_token_2) assert np.all(sen_vec.toarray()[-1] == expected_cls) # let's check if the order of patterns is preserved for old_index, pattern in enumerate(featurizer.known_patterns): assert pattern["name"] == loaded_featurizer.known_patterns[old_index]["name"] # we also modified a pattern, check if that is correctly modified pattern_to_check = [ pattern for pattern in loaded_featurizer.known_patterns if pattern["name"] == "hello" ] assert pattern_to_check == [new_patterns[1]]
null
null
null
null
null
null
null
null
null
[]
4,471
tests/components/eafm/__init__.py
tbarbette/core
30,023
3327514
"""Tests for eafm."""
0
0
0.0
0
0
0
1.0
0
0
[]
2,608
OpenCorePkg/Debug/Scripts/gdb_uefi.py
CEOALT1/RefindPlusUDK
10,125
11351705
<gh_stars>1000+ """ Allows loading TianoCore symbols into a GDB session attached to EFI Firmware. This is how it works: build GdbSyms - it's a dummy binary that contains the relevant symbols needed to find and load image symbols. $ gdb /path/to/GdbSyms.dll (gdb) target remote .... (gdb) source Scripts/gdb_uefi.py (gdb) reload-uefi -o /path/to/GdbSyms.dll N.B: it was noticed that GDB for certain targets behaves strangely when run without any binary - like assuming a certain physical address space size and endianness. To avoid this madness and seing strange bugs, make sure to pass /path/to/GdbSyms.dll when starting gdb. The -o option should be used if you've debugging EFI, where the PE images were converted from MACH-O or ELF binaries. """ import array import getopt import binascii import re import sys import os import subprocess import sys sys.path.append(os.path.dirname(__file__)) from common_uefi import * __license__ = "BSD" __version = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Works" if sys.version_info > (3,): long = int class ReloadUefi (gdb.Command): """Reload UEFI symbols""" # # Various constants. # EINVAL = 0xffffffff CV_NB10 = 0x3031424E CV_RSDS = 0x53445352 CV_MTOC = 0x434F544D DOS_MAGIC = 0x5A4D PE32PLUS_MAGIC = 0x20b EST_SIGNATURE = 0x5453595320494249 DEBUG_GUID = [0x49152E77, 0x1ADA, 0x4764, [0xB7,0xA2,0x7A,0xFE, 0xFE,0xD9,0x5E, 0x8B]] DEBUG_IS_UPDATING = 0x1 # # If the images were built as ELF/MACH-O and then converted to PE, # then the base address needs to be offset by PE headers. # offset_by_headers = False def __init__ (self): super (ReloadUefi, self).__init__ ("reload-uefi", gdb.COMMAND_OBSCURE) # # Returns gdb.Type for a type. # def type (self, typename): return gdb.lookup_type (typename) # # Returns gdb.Type for a pointer to a type. # def ptype (self, typename): return gdb.lookup_type (typename).pointer () # # Computes CRC32 on an array of data. # def crc32 (self, data): return binascii.crc32 (data) & 0xFFFFFFFF # # Sets a field in a struct to a value, i.e. # value->field_name = data. # # Newer Py bindings to Gdb provide access to the inferior # memory, but not all, so have to do it this awkward way. # def set_field (self, value, field_name, data): gdb.execute ("set *(%s *) 0x%x = 0x%x" % \ (str (value[field_name].type), \ long (value[field_name].address), data)) # # Returns data backing a gdb.Value as an array. # Same comment as above regarding newer Py bindings... # def value_data (self, value, bytes=0): value_address = gdb.Value (value.address) array_t = self.ptype ('UINT8') value_array = value_address.cast (array_t) if bytes == 0: bytes = value.type.sizeof data = array.array ('B') for i in range (0, bytes): data.append (value_array[i]) return data # # Locates the EFI_SYSTEM_TABLE as per UEFI spec 17.4. # Returns base address or -1. # def search_est (self): address = 0 estp_t = self.ptype ('EFI_SYSTEM_TABLE_POINTER') while True: try: estp = gdb.Value(address).cast(estp_t) if estp['Signature'] == self.EST_SIGNATURE: oldcrc = long(estp['Crc32']) self.set_field (estp, 'Crc32', 0) newcrc = self.crc32 (self.value_data (estp.dereference (), 0)) self.set_field (estp, 'Crc32', long(oldcrc)) if newcrc == oldcrc: print('EFI_SYSTEM_TABLE_POINTER @ 0x%x' % address) return estp['EfiSystemTableBase'] except gdb.MemoryError: pass address += 4 * 2**20 if address >= 2**32: return self.EINVAL # # Searches for a vendor-specific configuration table (in EST), # given a vendor-specific table GUID. GUID is a list like - # [32-bit, 16-bit, 16-bit, [8 bytes]] # def search_config (self, cfg_table, count, guid): index = 0 while index != count: cfg_entry = cfg_table[index]['VendorGuid'] if cfg_entry['Data1'] == guid[0] and \ cfg_entry['Data2'] == guid[1] and \ cfg_entry['Data3'] == guid[2] and \ self.value_data (cfg_entry['Data4']).tolist () == guid[3]: return cfg_table[index]['VendorTable'] index = index + 1 return gdb.Value(self.EINVAL) # # Returns offset of a field within structure. Useful # for getting container of a structure. # def offsetof (self, typename, field): t = gdb.Value (0).cast (self.ptype (typename)) return long(t[field].address) # # Returns sizeof of a type. # def sizeof (self, typename): return self.type (typename).sizeof # # Returns the EFI_IMAGE_NT_HEADERS32 pointer, given # an ImageBase address as a gdb.Value. # def pe_headers (self, imagebase): dosh_t = self.ptype ('EFI_IMAGE_DOS_HEADER') head_t = self.ptype ('EFI_IMAGE_OPTIONAL_HEADER_UNION') dosh = imagebase.cast (dosh_t) h_addr = long(imagebase) if dosh['e_magic'] == self.DOS_MAGIC: h_addr = h_addr + long(dosh['e_lfanew']) return gdb.Value(h_addr).cast (head_t) # # Returns a dictionary with PE sections. # def pe_sections (self, opt, file, imagebase): sect_t = self.ptype ('EFI_IMAGE_SECTION_HEADER') sections = (opt.address + 1).cast (sect_t) sects = {} for i in range (file['NumberOfSections']): name = UefiMisc.parse_utf8 (sections[i]['Name']) addr = long(sections[i]['VirtualAddress']) if name != '': sects[name] = addr return sects # # Returns True if pe_headers refer to a PE32+ image. # def pe_is_64 (self, pe_headers): if pe_headers['Pe32']['OptionalHeader']['Magic'] == self.PE32PLUS_MAGIC: return True return False # # Returns the PE fileheader. # def pe_file (self, pe): if self.pe_is_64 (pe): return pe['Pe32Plus']['FileHeader'] else: return pe['Pe32']['FileHeader'] # # Returns the PE (not so) optional header. # def pe_optional (self, pe): if self.pe_is_64 (pe): return pe['Pe32Plus']['OptionalHeader'] else: return pe['Pe32']['OptionalHeader'] # # Returns the symbol file name for a PE image. # def pe_parse_debug (self, pe): opt = self.pe_optional (pe) debug_dir_entry = opt['DataDirectory'][6] dep = debug_dir_entry['VirtualAddress'] + opt['ImageBase'] dep = dep.cast (self.ptype ('EFI_IMAGE_DEBUG_DIRECTORY_ENTRY')) cvp = dep.dereference ()['RVA'] + opt['ImageBase'] cvv = cvp.cast(self.ptype ('UINT32')).dereference () if cvv == self.CV_NB10: return cvp + self.sizeof('EFI_IMAGE_DEBUG_CODEVIEW_NB10_ENTRY') elif cvv == self.CV_RSDS: return cvp + self.sizeof('EFI_IMAGE_DEBUG_CODEVIEW_RSDS_ENTRY') elif cvv == self.CV_MTOC: return cvp + self.sizeof('EFI_IMAGE_DEBUG_CODEVIEW_MTOC_ENTRY') return gdb.Value(self.EINVAL) # # Prepares gdb symbol load command with proper section information. # Currently supports Mach-O and single-section files. # # TODO: Proper ELF support. # def get_sym_cmd (self, file, orgbase, sections, macho, fallack_base): cmd = 'add-symbol-file %s' % file # Fallback case, no sections, just load .text. if not sections.get('.text') or not sections.get('.data'): cmd += ' 0x%x' % (fallack_base) return cmd cmd += ' 0x%x' % (long(orgbase) + sections['.text']) if not macho or not os.path.exists(file): # Another fallback, try to load data at least. cmd += ' -s .data 0x%x' % (long(orgbase) + sections['.data']) return cmd # 1. Parse Mach-O. # FIXME: We should not rely on otool really. commands = subprocess.check_output(['otool', '-l', file]) try: lines = commands.decode('utf-8').split('\n') except: lines = commands.split('\n') in_sect = False machsections = {} for line in lines: line = line.strip() if line.startswith('Section'): in_sect = True sectname = None segname = None elif in_sect: if line.startswith('sectname'): sectname = line.split()[1] elif line.startswith('segname'): segname = line.split()[1] elif line.startswith('addr'): machsections[segname + '.' + sectname] = long(line.split()[1], base=16) in_sect = False # 2. Convert section names to gdb sections. mapping = { '__TEXT.__cstring': '.cstring', '__TEXT.__const': '.const', '__TEXT.__ustring': '__TEXT.__ustring', '__DATA.__const': '.const_data', '__DATA.__data': '.data', '__DATA.__bss': '.bss', '__DATA.__common': '__DATA.__common', # FIXME: These should not be loadable, but gdb still loads them :/ # '__DWARF.__apple_names': '__DWARF.__apple_names', # '__DWARF.__apple_namespac': '__DWARF.__apple_namespac', # '__DWARF.__apple_types': '__DWARF.__apple_types', # '__DWARF.__apple_objc': '__DWARF.__apple_objc', } # 3. Rebase. for entry in mapping: if machsections.get(entry): cmd += ' -s %s 0x%x' % (mapping[entry], long(orgbase) + machsections[entry]) return cmd # # Parses an EFI_LOADED_IMAGE_PROTOCOL, figuring out the symbol file name. # This file name is then appended to list of loaded symbols. # # TODO: Support TE images. # def parse_image (self, image, syms): orgbase = base = image['ImageBase'] pe = self.pe_headers (base) opt = self.pe_optional (pe) file = self.pe_file (pe) sym_name = self.pe_parse_debug (pe) sections = self.pe_sections (opt, file, base) # For ELF and Mach-O-derived images... if self.offset_by_headers: base = base + opt['SizeOfHeaders'] if sym_name != self.EINVAL: sym_name = sym_name.cast (self.ptype('CHAR8')).string () sym_name_dbg = re.sub(r"\.dll$", ".debug", sym_name) macho = False if os.path.isdir(sym_name + '.dSYM'): sym_name += '.dSYM/Contents/Resources/DWARF/' + os.path.basename(sym_name) macho = True elif sym_name_dbg != sym_name and os.path.exists(sym_name_dbg): # TODO: implement .elf handling. sym_name = sym_name_dbg syms.append (self.get_sym_cmd (sym_name, long(orgbase), sections, macho, long(base))) # # Parses table EFI_DEBUG_IMAGE_INFO structures, builds # a list of add-symbol-file commands, and reloads debugger # symbols. # def parse_edii (self, edii, count): index = 0 syms = [] print ("Found {} images...".format(count)) while index != count: entry = edii[index] if entry['ImageInfoType'].dereference () == 1: entry = entry['NormalImage'] self.parse_image(entry['LoadedImageProtocolInstance'], syms) else: print ("Skipping unknown EFI_DEBUG_IMAGE_INFO (Type 0x%x)" % \ entry['ImageInfoType'].dereference ()) index = index + 1 gdb.execute ("symbol-file") print ("Loading new symbols...") for sym in syms: try: gdb.execute (sym) except (gdb.error) as err: print ('Failed: %s' % err) # # Parses EFI_DEBUG_IMAGE_INFO_TABLE_HEADER, in order to load # image symbols. # def parse_dh (self, dh): dh_t = self.ptype ('EFI_DEBUG_IMAGE_INFO_TABLE_HEADER') dh = dh.cast (dh_t) print ("DebugImageInfoTable @ 0x%x, 0x%x entries" % \ (long (dh['EfiDebugImageInfoTable']), dh['TableSize'])) if dh['UpdateStatus'] & self.DEBUG_IS_UPDATING: print ("EfiDebugImageInfoTable update in progress, retry later") return self.parse_edii (dh['EfiDebugImageInfoTable'], dh['TableSize']) # # Parses EFI_SYSTEM_TABLE, in order to load image symbols. # def parse_est (self, est): est_t = self.ptype ('EFI_SYSTEM_TABLE') est = est.cast (est_t) print ("Connected to %s (Rev. 0x%x)" % \ (UefiMisc.parse_utf16 (est['FirmwareVendor']), \ long (est['FirmwareRevision']))) print ("ConfigurationTable @ 0x%x, 0x%x entries" % \ (long (est['ConfigurationTable']), est['NumberOfTableEntries'])) dh = self.search_config(est['ConfigurationTable'], est['NumberOfTableEntries'], self.DEBUG_GUID) if dh == self.EINVAL: print ("No EFI_DEBUG_IMAGE_INFO_TABLE_HEADER") return self.parse_dh (dh) # # Usage information. # def usage (self): print ("Usage: reload-uefi [-o] [/path/to/GdbSyms.dll]") # # Handler for reload-uefi. # def invoke (self, arg, from_tty): args = arg.split(' ') try: opts, args = getopt.getopt(args, "o", ["offset-by-headers"]) except (getopt.GetoptError) as err: self.usage () return for opt, arg in opts: if opt == "-o": self.offset_by_headers = True if len(args) >= 1 and args[0] != '': gdb.execute ("symbol-file") gdb.execute ("symbol-file %s" % args[0]) else: # FIXME: gdb.objfiles () loses files after symbol-file execution, # so we have to extract GdbSymbs.dll manually. lines = gdb.execute ("info files", to_string=True).split('\n') for line in lines: m = re.search("`([^']+)'", line) if m: gdb.execute ("symbol-file") gdb.execute ("symbol-file %s" % m.group(1)) break est = self.search_est () if est == self.EINVAL: print ("No EFI_SYSTEM_TABLE...") return print ("EFI_SYSTEM_TABLE @ 0x%x" % est) self.parse_est (est) class UefiStringPrinter: def __init__(self, val): self.val = val def to_string (self): if not self.val: return "NULL" return 'L"' + UefiMisc.parse_utf16(self.val) + '"' class UefiEfiStatusPrinter: def __init__(self, val): self.val = val def to_string (self): return UefiMisc.parse_status(self.val, True) class UefiReturnStatusPrinter: def __init__(self, val): self.val = val def to_string (self): return UefiMisc.parse_status(self.val, False) class UefiGuidPrinter: def __init__(self, val): self.val = val def to_string (self): return UefiMisc.parse_guid(self.val) def lookup_uefi_type (val): if str(val.type) == 'const CHAR16 *' or str(val.type) == 'CHAR16 *': return UefiStringPrinter(val) elif str(val.type) == 'EFI_STATUS': return UefiEfiStatusPrinter(val) elif str(val.type) == 'RETURN_STATUS': return UefiReturnStatusPrinter(val) elif str(val.type) == 'GUID' or str(val.type) == 'EFI_GUID': return UefiGuidPrinter(val) return None ReloadUefi () gdb.pretty_printers.append (lookup_uefi_type)
12
0
0.0
81
0
12
1.0
0
80
[ { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 35, "message": "Import only needed names or import the module and then use its members.", "textRange": { "endLine": 35, "endOffset": 25, "startLine": 35, "startOffset": 0 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 119, "message": "Rename this variable; it shadows a builtin.", "textRange": { "endLine": 119, "endOffset": 17, "startLine": 119, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 266, "message": "Complete the task associated to this \"TODO\" comment.", "textRange": { "endLine": 266, "endOffset": 31, "startLine": 266, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 268, "message": "Refactor this function to reduce its Cognitive Complexity from 17 to the 15 allowed.", "textRange": { "endLine": 268, "endOffset": 19, "startLine": 268, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 272, "message": "Define a constant instead of duplicating this literal '.data' 3 times.", "textRange": { "endLine": 272, "endOffset": 64, "startLine": 272, "startOffset": 57 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 284, "message": "Take the required action to fix the issue indicated by this \"FIXME\" comment.", "textRange": { "endLine": 284, "endOffset": 52, "startLine": 284, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 288, "message": "Specify an exception class to catch or reraise the exception", "textRange": { "endLine": 288, "endOffset": 14, "startLine": 288, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 316, "message": "Take the required action to fix the issue indicated by this \"FIXME\" comment.", "textRange": { "endLine": 316, "endOffset": 78, "startLine": 316, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 334, "message": "Complete the task associated to this \"TODO\" comment.", "textRange": { "endLine": 334, "endOffset": 30, "startLine": 334, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 356, "message": "Complete the task associated to this \"TODO\" comment.", "textRange": { "endLine": 356, "endOffset": 48, "startLine": 356, "startOffset": 16 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 437, "message": "Remove the unused local variable \"err\".", "textRange": { "endLine": 437, "endOffset": 42, "startLine": 437, "startOffset": 39 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 448, "message": "Take the required action to fix the issue indicated by this \"FIXME\" comment.", "textRange": { "endLine": 448, "endOffset": 77, "startLine": 448, "startOffset": 12 }, "type": "CODE_SMELL" } ]
7,187
code/2.7/7_decorators_args.py
suqi/suqi-interpy-zh
6,594
10218124
from functools import wraps def logit(logfile='out.log'): def logging_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + ' was called' print log_string with open(logfile, 'a') as opened_file: opened_file.write(log_string + '\n') return func(*args, **kwargs) return wrapped_function return logging_decorator @logit() def myfunc1(): pass @logit(logfile='func2.log') def myfunc2(): pass def main(): myfunc1() myfunc2() if __name__ == '__main__': main()
null
null
null
null
null
null
null
null
null
[]
12,178
tests/integration/test_disabled_access_control_improvements/test_row_policy.py
mrk-andreev/ClickHouse
8,629
9674883
import os import pytest from helpers.cluster import ClickHouseCluster from helpers.test_tools import TSV cluster = ClickHouseCluster(__file__) node = cluster.add_instance( "node", main_configs=["configs/config.d/disable_access_control_improvements.xml"], user_configs=[ "configs/users.d/row_policy.xml", "configs/users.d/another_user.xml", ], ) def copy_policy_xml(local_file_name): script_dir = os.path.dirname(os.path.realpath(__file__)) node.copy_file_to_container( os.path.join(script_dir, local_file_name), "/etc/clickhouse-server/users.d/row_policy.xml", ) node.query("SYSTEM RELOAD CONFIG") @pytest.fixture(scope="module", autouse=True) def started_cluster(): try: cluster.start() node.query( """ CREATE DATABASE mydb; CREATE TABLE mydb.filtered_table1 (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.filtered_table1 values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.table (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.table values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.filtered_table2 (a UInt8, b UInt8, c UInt8, d UInt8) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.filtered_table2 values (0, 0, 0, 0), (1, 2, 3, 4), (4, 3, 2, 1), (0, 0, 6, 0); CREATE TABLE mydb.filtered_table3 (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.filtered_table3 values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.`.filtered_table4` (a UInt8, b UInt8, c UInt16 ALIAS a + b) ENGINE MergeTree ORDER BY a; INSERT INTO mydb.`.filtered_table4` values (0, 0), (0, 1), (1, 0), (1, 1); CREATE TABLE mydb.local (a UInt8, b UInt8) ENGINE MergeTree ORDER BY a; """ ) node.query("INSERT INTO mydb.local values (2, 0), (2, 1), (1, 0), (1, 1)") yield cluster finally: cluster.shutdown() @pytest.fixture(autouse=True) def reset_policies(): try: yield finally: copy_policy_xml("normal_filters.xml") node.query("DROP POLICY IF EXISTS pA, pB ON mydb.filtered_table1") def test_introspection(): policies = [ [ "another ON mydb.filtered_table1", "another", "mydb", "filtered_table1", "6068883a-0e9d-f802-7e22-0144f8e66d3c", "users.xml", "1", 0, 0, "['another']", "[]", ], [ "another ON mydb.filtered_table2", "another", "mydb", "filtered_table2", "c019e957-c60b-d54e-cc52-7c90dac5fb01", "users.xml", "1", 0, 0, "['another']", "[]", ], [ "another ON mydb.filtered_table3", "another", "mydb", "filtered_table3", "4cb080d0-44e8-dbef-6026-346655143628", "users.xml", "1", 0, 0, "['another']", "[]", ], [ "another ON mydb.local", "another", "mydb", "local", "5b23c389-7e18-06bf-a6bc-dd1afbbc0a97", "users.xml", "a = 1", 0, 0, "['another']", "[]", ], [ "default ON mydb.filtered_table1", "default", "mydb", "filtered_table1", "9e8a8f62-4965-2b5e-8599-57c7b99b3549", "users.xml", "a = 1", 0, 0, "['default']", "[]", ], [ "default ON mydb.filtered_table2", "default", "mydb", "filtered_table2", "cffae79d-b9bf-a2ef-b798-019c18470b25", "users.xml", "a + b < 1 or c - d > 5", 0, 0, "['default']", "[]", ], [ "default ON mydb.filtered_table3", "default", "mydb", "filtered_table3", "12fc5cef-e3da-3940-ec79-d8be3911f42b", "users.xml", "c = 1", 0, 0, "['default']", "[]", ], [ "default ON mydb.local", "default", "mydb", "local", "cdacaeb5-1d97-f99d-2bb0-4574f290629c", "users.xml", "1", 0, 0, "['default']", "[]", ], ] assert node.query( "SELECT * from system.row_policies ORDER BY short_name, database, table" ) == TSV(policies) def test_dcl_introspection(): assert node.query("SHOW POLICIES") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", "default ON mydb.local", ] ) assert node.query("SHOW POLICIES ON mydb.filtered_table1") == TSV( ["another", "default"] ) assert node.query("SHOW POLICIES ON mydb.local") == TSV(["another", "default"]) assert node.query("SHOW POLICIES ON mydb.*") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "another ON mydb.local", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", "default ON mydb.local", ] ) assert node.query("SHOW POLICIES default") == TSV( [ "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", "default ON mydb.local", ] ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.local") == "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default\n" ) assert node.query("SHOW CREATE POLICY default") == TSV( [ "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default", "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default", "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default", ] ) assert node.query("SHOW CREATE POLICIES ON mydb.filtered_table1") == TSV( [ "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another", "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", ] ) assert node.query("SHOW CREATE POLICIES ON mydb.*") == TSV( [ "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 TO another", "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default", "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default", "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default", ] ) assert node.query("SHOW CREATE POLICIES") == TSV( [ "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 TO another", "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 TO another", "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default", "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default", "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default", "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default", ] ) expected_access = ( "CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another\n" "CREATE ROW POLICY another ON mydb.filtered_table2 FOR SELECT USING 1 TO another\n" "CREATE ROW POLICY another ON mydb.filtered_table3 FOR SELECT USING 1 TO another\n" "CREATE ROW POLICY another ON mydb.local FOR SELECT USING a = 1 TO another\n" "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default\n" "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default\n" "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default\n" "CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default\n" ) assert expected_access in node.query("SHOW ACCESS") copy_policy_xml("all_rows.xml") assert node.query("SHOW POLICIES") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", ] ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING 1 TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING 1 TO default\n" ) copy_policy_xml("no_rows.xml") assert node.query("SHOW POLICIES") == TSV( [ "another ON mydb.filtered_table1", "another ON mydb.filtered_table2", "another ON mydb.filtered_table3", "default ON mydb.filtered_table1", "default ON mydb.filtered_table2", "default ON mydb.filtered_table3", ] ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table1") == "CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING NULL TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table2") == "CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING NULL TO default\n" ) assert ( node.query("SHOW CREATE POLICY default ON mydb.filtered_table3") == "CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING NULL TO default\n" ) copy_policy_xml("no_filters.xml") assert node.query("SHOW POLICIES") == "" def test_dcl_management(): copy_policy_xml("no_filters.xml") assert node.query("SHOW POLICIES") == "" node.query("CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a<b") assert node.query("SELECT * FROM mydb.filtered_table1") == "" assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pA\n" node.query("ALTER POLICY pA ON mydb.filtered_table1 TO default") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[0, 1]]) assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pA\n" node.query("ALTER POLICY pA ON mydb.filtered_table1 FOR SELECT USING a>b") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]]) node.query("ALTER POLICY pA ON mydb.filtered_table1 RENAME TO pB") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0]]) assert node.query("SHOW POLICIES ON mydb.filtered_table1") == "pB\n" assert ( node.query("SHOW CREATE POLICY pB ON mydb.filtered_table1") == "CREATE ROW POLICY pB ON mydb.filtered_table1 FOR SELECT USING a > b TO default\n" ) node.query("DROP POLICY pB ON mydb.filtered_table1") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV( [[0, 0], [0, 1], [1, 0], [1, 1]] ) assert node.query("SHOW POLICIES") == "" def test_dcl_users_with_policies_from_users_xml(): node.query("CREATE USER X") node.query("GRANT SELECT ON mydb.filtered_table1 TO X") assert node.query("SELECT * FROM mydb.filtered_table1") == TSV([[1, 0], [1, 1]]) assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == "" node.query("DROP USER X") def test_some_users_without_policies(): copy_policy_xml("no_filters.xml") assert node.query("SHOW POLICIES") == "" node.query("CREATE USER X, Y") node.query("GRANT SELECT ON mydb.filtered_table1 TO X, Y") # permissive a >= b for X, none for Y node.query( "CREATE POLICY pA ON mydb.filtered_table1 FOR SELECT USING a >= b AS permissive TO X" ) assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == TSV( [[0, 0], [1, 0], [1, 1]] ) assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" # restrictive a >=b for X, none for Y node.query("ALTER POLICY pA ON mydb.filtered_table1 AS restrictive") assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == "" assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" # permissive a >= b for X, restrictive a <= b for X, none for Y node.query("ALTER POLICY pA ON mydb.filtered_table1 AS permissive") node.query( "CREATE POLICY pB ON mydb.filtered_table1 FOR SELECT USING a <= b AS restrictive TO X" ) assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == TSV( [[0, 0], [1, 1]] ) assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" # permissive a >= b for X, restrictive a <= b for Y node.query("ALTER POLICY pB ON mydb.filtered_table1 TO Y") assert node.query("SELECT * FROM mydb.filtered_table1", user="X") == TSV( [[0, 0], [1, 0], [1, 1]] ) assert node.query("SELECT * FROM mydb.filtered_table1", user="Y") == "" node.query("DROP POLICY pA, pB ON mydb.filtered_table1") node.query("DROP USER X, Y")
23
0
0.0
0
0
23
1.0
0
8
[ { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 74, "message": "Define a constant instead of duplicating this literal \"another ON mydb.filtered_table1\" 5 times.", "textRange": { "endLine": 74, "endOffset": 45, "startLine": 74, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 79, "message": "Define a constant instead of duplicating this literal \"users.xml\" 8 times.", "textRange": { "endLine": 79, "endOffset": 23, "startLine": 79, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 83, "message": "Define a constant instead of duplicating this literal \"['another']\" 4 times.", "textRange": { "endLine": 83, "endOffset": 25, "startLine": 83, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 87, "message": "Define a constant instead of duplicating this literal \"another ON mydb.filtered_table2\" 5 times.", "textRange": { "endLine": 87, "endOffset": 45, "startLine": 87, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 100, "message": "Define a constant instead of duplicating this literal \"another ON mydb.filtered_table3\" 5 times.", "textRange": { "endLine": 100, "endOffset": 45, "startLine": 100, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 113, "message": "Define a constant instead of duplicating this literal \"another ON mydb.local\" 3 times.", "textRange": { "endLine": 113, "endOffset": 35, "startLine": 113, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 126, "message": "Define a constant instead of duplicating this literal \"default ON mydb.filtered_table1\" 6 times.", "textRange": { "endLine": 126, "endOffset": 45, "startLine": 126, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 135, "message": "Define a constant instead of duplicating this literal \"['default']\" 4 times.", "textRange": { "endLine": 135, "endOffset": 25, "startLine": 135, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 139, "message": "Define a constant instead of duplicating this literal \"default ON mydb.filtered_table2\" 6 times.", "textRange": { "endLine": 139, "endOffset": 45, "startLine": 139, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 152, "message": "Define a constant instead of duplicating this literal \"default ON mydb.filtered_table3\" 6 times.", "textRange": { "endLine": 152, "endOffset": 45, "startLine": 152, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 165, "message": "Define a constant instead of duplicating this literal \"default ON mydb.local\" 4 times.", "textRange": { "endLine": 165, "endOffset": 35, "startLine": 165, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 184, "message": "Define a constant instead of duplicating this literal \"SHOW POLICIES\" 7 times.", "textRange": { "endLine": 184, "endOffset": 37, "startLine": 184, "startOffset": 22 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 197, "message": "Define a constant instead of duplicating this literal \"SHOW POLICIES ON mydb.filtered_table1\" 4 times.", "textRange": { "endLine": 197, "endOffset": 61, "startLine": 197, "startOffset": 22 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 223, "message": "Define a constant instead of duplicating this literal \"SHOW CREATE POLICY default ON mydb.filtered_table1\" 3 times.", "textRange": { "endLine": 223, "endOffset": 71, "startLine": 223, "startOffset": 19 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 227, "message": "Define a constant instead of duplicating this literal \"SHOW CREATE POLICY default ON mydb.filtered_table2\" 3 times.", "textRange": { "endLine": 227, "endOffset": 71, "startLine": 227, "startOffset": 19 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 231, "message": "Define a constant instead of duplicating this literal \"SHOW CREATE POLICY default ON mydb.filtered_table3\" 3 times.", "textRange": { "endLine": 231, "endOffset": 71, "startLine": 231, "startOffset": 19 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 241, "message": "Define a constant instead of duplicating this literal \"CREATE ROW POLICY default ON mydb.filtered_table1 FOR SELECT USING a = 1 TO default\" 4 times.", "textRange": { "endLine": 241, "endOffset": 97, "startLine": 241, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 242, "message": "Define a constant instead of duplicating this literal \"CREATE ROW POLICY default ON mydb.filtered_table2 FOR SELECT USING ((a + b) < 1) OR ((c - d) > 5) TO default\" 3 times.", "textRange": { "endLine": 242, "endOffset": 122, "startLine": 242, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 243, "message": "Define a constant instead of duplicating this literal \"CREATE ROW POLICY default ON mydb.filtered_table3 FOR SELECT USING c = 1 TO default\" 3 times.", "textRange": { "endLine": 243, "endOffset": 97, "startLine": 243, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 244, "message": "Define a constant instead of duplicating this literal \"CREATE ROW POLICY default ON mydb.local FOR SELECT USING 1 TO default\" 3 times.", "textRange": { "endLine": 244, "endOffset": 83, "startLine": 244, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 249, "message": "Define a constant instead of duplicating this literal \"CREATE ROW POLICY another ON mydb.filtered_table1 FOR SELECT USING 1 TO another\" 3 times.", "textRange": { "endLine": 249, "endOffset": 93, "startLine": 249, "startOffset": 12 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 338, "message": "Define a constant instead of duplicating this literal \"no_filters.xml\" 3 times.", "textRange": { "endLine": 338, "endOffset": 36, "startLine": 338, "startOffset": 20 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 347, "message": "Define a constant instead of duplicating this literal \"SELECT * FROM mydb.filtered_table1\" 15 times.", "textRange": { "endLine": 347, "endOffset": 58, "startLine": 347, "startOffset": 22 }, "type": "CODE_SMELL" } ]
5,922
recipes/Python/576505_Sudoku_solvercreator/recipe-576505.py
tdiprima/code
2,023
515289
<reponame>tdiprima/code<gh_stars>1000+ #!/usr/bin/python # TODO: Make solve function faster!!! Have it check for singles, doubles, # triples, and quads both naked and hidden from random import random def rand(lst): "returns a random element in list or integer" if type(lst)==type([]): return lst[int(random()*len(lst))] elif type(lst)==type(0): return int(random()*lst) else: raise Exception,"don't know what do do with type %s!!!"%type(lst) def reorder(lst): "reorders a list to a random order" ret=[] for item in lst: ret.insert(rand(len(ret)),item) return ret def row(row,puzzle): return puzzle[row*9:row*9+9] def col(col,puzzle): ret=[] for i in range(9): ret.append(row(i,puzzle)[col]) return ret def box(box,puzzle): x=box%3 if box<3: y=0 elif box<6: y=1 else: y=2 ret=[] for i in range(3): ret.extend(row(y*3+i,puzzle)[x*3:x*3+3]) return ret def remaining(wcb): ret=[] for i in range(1,10): if not i in wcb: ret.append(i) return reorder(ret) # does not significantly slow program # and allows for generation of random puzzles def coordToBox(x,y): box=0 if x<3: pass elif x<6: box+=1 else: box+=2 if y<3: pass elif y<6: box+=3 else: box+=6 return box def coordToLinear(x,y): return y*9+x def linearToCoord(index): y=8 for i in range(9): if index<i*9: y-=1 x=index%9 return x,y def possible(x,y,puzzle): if not puzzle[coordToLinear(x,y)]==0: return [puzzle[coordToLinear(x,y)]] imp=[] imp.extend(row(y,puzzle)) imp.extend(col(x,puzzle)) imp.extend(box(coordToBox(x,y),puzzle)) return remaining(imp) def printPuzzle(puzzle): string=((((("%s "*3)+"| ")*2+("%s "*3)+"\n")*3+"------|-------|------\n")*3)[:-22]+"\n" text=(string%tuple(puzzle)).replace("0","_") print text, return text def check(x,y,puzzle): for i in range(9): if not i==y and len(possible(x,i,puzzle))==0: return False if not i==x and len(possible(i,y,puzzle))==0: return False box_x,box_y=linearToCoord(coordToBox(x,y)) for i in range(box_x,box_x+3): if i==x: break for j in range(box_y,box_y+3): if j==y: break if len(possible(i,j,puzzle))==0: return False return True def solve(puzzle,start=0): # TODO: Make this function faster!!! if start==81: return [puzzle[:]] ret=[] x,y=linearToCoord(start) possibilities=possible(x,y,puzzle) if len(possibilities)==0: return for possibility in possibilities: p=puzzle[:] p[coordToLinear(x,y)]=possibility x,y=linearToCoord(start) if not check(x,y,puzzle): continue solved=solve(p,start+1) if solved: ret.extend(solved) if 1<len(ret): # there is more than one puzzle return ret # enough already!!! return ret def solve_no_check_for_dups(puzzle,start=0): "This solver function does not check for multiple solutions." if start==81: return puzzle[:] x,y=linearToCoord(start) possibilities=possible(x,y,puzzle) if len(possibilities)==0: return for possibility in possibilities: p=puzzle[:] p[coordToLinear(x,y)]=possibility x,y=linearToCoord(start) if not check(x,y,puzzle): continue solved=solve_no_check_for_dups(p,start+1) if solved: return solved return [] def generate(sym=True,goodness=0): # goodness=0 means evil if sym: RANGE=41 else: RANGE=81 puzzle=[0]*81 soln=solve_no_check_for_dups(puzzle) puzzle=soln[:] spaces=range(RANGE) for i in range(RANGE-goodness): space=spaces.pop(rand(len(spaces))) puzzle[space]=0 if sym: puzzle[80-space]=0 if 1<len(solve(puzzle)): puzzle[space]=soln[space] if sym: puzzle[80-space]=soln[80-space] return puzzle #puzzle=[] #for i in range(9): # puzzle.extend(map(int,raw_input().split())) try: import psyco psyco.full() except ImportError: print "You do not have psyco installed. The program will run slower." if __name__=="__main__": #puzzle=generate() #printPuzzle(puzzle) #soln=solve(puzzle) #printPuzzle(soln[0]) #if 1<len(soln): # print "More than one solution!!!" #puzzle=generate(sym=False) #printPuzzle(puzzle) #soln=solve(puzzle) #printPuzzle(soln[0]) #if 1<len(soln): # print "More than one solution!!!" from time import sleep while True: puzzle=generate(sym=False) text=printPuzzle(puzzle) f=open("./sudoku","a") f.write(text) f.close() sleep(180)
19
0
0.0
71
0
19
1.0
2
55
[ { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 3, "message": "Complete the task associated to this \"TODO\" comment.", "textRange": { "endLine": 3, "endOffset": 73, "startLine": 3, "startOffset": 0 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 15, "message": "Replace this generic exception class with a more specific one.", "textRange": { "endLine": 15, "endOffset": 17, "startLine": 15, "startOffset": 8 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 49, "message": "Use the opposite operator (\"not in\") instead.", "textRange": { "endLine": 49, "endOffset": 17, "startLine": 49, "startOffset": 5 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 54, "message": "Rename function \"coordToBox\" to match the regular expression ^[a-z_][a-z0-9_]*$.", "textRange": { "endLine": 54, "endOffset": 14, "startLine": 54, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 57, "message": "Either remove or fill this block of code.", "textRange": { "endLine": 57, "endOffset": 6, "startLine": 57, "startOffset": 2 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 63, "message": "Either remove or fill this block of code.", "textRange": { "endLine": 63, "endOffset": 6, "startLine": 63, "startOffset": 2 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 70, "message": "Rename function \"coordToLinear\" to match the regular expression ^[a-z_][a-z0-9_]*$.", "textRange": { "endLine": 70, "endOffset": 17, "startLine": 70, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 73, "message": "Rename function \"linearToCoord\" to match the regular expression ^[a-z_][a-z0-9_]*$.", "textRange": { "endLine": 73, "endOffset": 17, "startLine": 73, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 82, "message": "Use the opposite operator (\"!=\") instead.", "textRange": { "endLine": 82, "endOffset": 37, "startLine": 82, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 90, "message": "Rename function \"printPuzzle\" to match the regular expression ^[a-z_][a-z0-9_]*$.", "textRange": { "endLine": 90, "endOffset": 15, "startLine": 90, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 93, "message": "Replace print statement by built-in function.", "textRange": { "endLine": 93, "endOffset": 6, "startLine": 93, "startOffset": 1 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "HIGH", "softwareQuality": "MAINTAINABILITY" } ], "line": 96, "message": "Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed.", "textRange": { "endLine": 96, "endOffset": 9, "startLine": 96, "startOffset": 4 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 98, "message": "Use the opposite operator (\"!=\") instead.", "textRange": { "endLine": 98, "endOffset": 13, "startLine": 98, "startOffset": 5 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 100, "message": "Use the opposite operator (\"!=\") instead.", "textRange": { "endLine": 100, "endOffset": 13, "startLine": 100, "startOffset": 5 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 113, "message": "Complete the task associated to this \"TODO\" comment.", "textRange": { "endLine": 113, "endOffset": 63, "startLine": 113, "startOffset": 27 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "LOW", "softwareQuality": "MAINTAINABILITY" } ], "line": 162, "message": "Remove the unused local variable \"i\".", "textRange": { "endLine": 162, "endOffset": 6, "startLine": 162, "startOffset": 5 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 173, "message": "Remove this commented out code.", "textRange": { "endLine": 173, "endOffset": 10, "startLine": 173, "startOffset": 0 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 181, "message": "Replace print statement by built-in function.", "textRange": { "endLine": 181, "endOffset": 6, "startLine": 181, "startOffset": 1 }, "type": "CODE_SMELL" }, { "impacts": [ { "severity": "MEDIUM", "softwareQuality": "MAINTAINABILITY" } ], "line": 184, "message": "Remove this commented out code.", "textRange": { "endLine": 184, "endOffset": 19, "startLine": 184, "startOffset": 1 }, "type": "CODE_SMELL" } ]
10,392
algorithms/tree/traversal/__init__.py
Heart-throb-Rajnish/algorithms
22,426
3220141
<reponame>Heart-throb-Rajnish/algorithms<filename>algorithms/tree/traversal/__init__.py<gh_stars>1000+ from .preorder import * from .postorder import * from .inorder import *
null
null
null
null
null
null
null
null
null
[]
2,144

No dataset card yet

Downloads last month
5