hexsha
stringlengths
40
40
size
int64
2
1.02M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
1.02M
avg_line_length
float64
1
417k
max_line_length
int64
1
987k
alphanum_fraction
float64
0
1
content_no_comment
stringlengths
0
1.01M
is_comment_constant_removed
bool
1 class
is_sharp_comment_removed
bool
1 class
1c39ba30cf076499676c885c32fc3bc7af869d8a
2,261
py
Python
scripts/hunter/tracer.py
Duroktar/Wolf
c192d5c27eb2098e440f7726eb1bff40ed004db5
[ "Apache-2.0" ]
105
2018-02-07T22:07:47.000Z
2022-03-31T18:16:47.000Z
scripts/hunter/tracer.py
Duroktar/Wolf
c192d5c27eb2098e440f7726eb1bff40ed004db5
[ "Apache-2.0" ]
57
2018-02-07T23:07:41.000Z
2021-11-21T17:14:06.000Z
scripts/hunter/tracer.py
MalcomnM/Fox
f41e59305c1fb4c008f5e0d712e291525c2b39f2
[ "Apache-2.0" ]
10
2018-02-24T23:44:51.000Z
2022-03-02T07:52:27.000Z
from __future__ import absolute_import import sys import threading from .event import Event class Tracer(object): """ Trace object. """ def __init__(self, threading_support=False): self._handler = None self._previous = None self._threading_previous = None self.threading_support = threading_support self.depth = 0 self.calls = 0 @property def handler(self): return self._handler @property def previous(self): return self._previous def __repr__(self): return '<hunter.tracer.Tracer at 0x%x: threading_support=%s, %s%s%s%s>' % ( id(self), self.threading_support, '<stopped>' if self._handler is None else 'handler=', '' if self._handler is None else repr(self._handler), '' if self._previous is None else ', previous=', '' if self._previous is None else repr(self._previous), ) def __call__(self, frame, kind, arg): """ The settrace function. .. note:: This always returns self (drills down) - as opposed to only drilling down when predicate(event) is True because it might match further inside. """ if self._handler is not None: self._handler(Event(frame, kind, arg, self)) if kind == 'call': self.depth += 1 self.calls += 1 elif kind == 'return': self.depth -= 1 return self def trace(self, predicate): self._handler = predicate if self.threading_support: self._threading_previous = getattr(threading, '_trace_hook', None) threading.settrace(self) self._previous = sys.gettrace() sys.settrace(self) return self def stop(self): if self._handler is not None: sys.settrace(self._previous) self._handler = self._previous = None if self.threading_support: threading.settrace(self._threading_previous) self._threading_previous = None def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop()
27.573171
115
0.57939
from __future__ import absolute_import import sys import threading from .event import Event class Tracer(object): def __init__(self, threading_support=False): self._handler = None self._previous = None self._threading_previous = None self.threading_support = threading_support self.depth = 0 self.calls = 0 @property def handler(self): return self._handler @property def previous(self): return self._previous def __repr__(self): return '<hunter.tracer.Tracer at 0x%x: threading_support=%s, %s%s%s%s>' % ( id(self), self.threading_support, '<stopped>' if self._handler is None else 'handler=', '' if self._handler is None else repr(self._handler), '' if self._previous is None else ', previous=', '' if self._previous is None else repr(self._previous), ) def __call__(self, frame, kind, arg): if self._handler is not None: self._handler(Event(frame, kind, arg, self)) if kind == 'call': self.depth += 1 self.calls += 1 elif kind == 'return': self.depth -= 1 return self def trace(self, predicate): self._handler = predicate if self.threading_support: self._threading_previous = getattr(threading, '_trace_hook', None) threading.settrace(self) self._previous = sys.gettrace() sys.settrace(self) return self def stop(self): if self._handler is not None: sys.settrace(self._previous) self._handler = self._previous = None if self.threading_support: threading.settrace(self._threading_previous) self._threading_previous = None def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.stop()
true
true
1c39ba66fa608550e4cccc018cb87aabc2527ad6
1,705
py
Python
tests/test_utils.py
suganthsundar/melano
8e9dd57d3ce9945b18e64da6b0df30811018fbf0
[ "MIT" ]
null
null
null
tests/test_utils.py
suganthsundar/melano
8e9dd57d3ce9945b18e64da6b0df30811018fbf0
[ "MIT" ]
null
null
null
tests/test_utils.py
suganthsundar/melano
8e9dd57d3ce9945b18e64da6b0df30811018fbf0
[ "MIT" ]
null
null
null
import nose from melano.utils import (sort, group_by, count) def test_utils_sort_single_key(): items = [dict(x=1), dict(x=4), dict(x=2)] sorted_items = sort(items, 'x') nose.tools.assert_list_equal(sorted_items, [dict(x=1), dict(x=2), dict(x=4)]) def test_utils_sort_multiple_keys(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] sorted_items = sort(items, 'x', 'y') nose.tools.assert_list_equal(sorted_items, [dict(x=1, y=2), dict(x=1, y=5), dict(x=2, y=3), dict(x=4, y=2)]) def test_utils_group_by_single_key(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] expected = [ {'items': [{'x': 1, 'y': 5}, {'x': 1, 'y': 2}], 'x': 1}, {'items': [{'x': 2, 'y': 3}], 'x': 2}, {'items': [{'x': 4, 'y': 2}], 'x': 4} ] group_items = group_by(items, 'x') nose.tools.assert_list_equal(group_items, expected) def test_utils_group_by_multiple_keys(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] expected = [ {'items': [{'x': 1, 'y': 2}], 'x': 1, 'y': 2}, {'items': [{'x': 1, 'y': 5}], 'x': 1, 'y': 5}, {'items': [{'x': 2, 'y': 3}], 'x': 2, 'y': 3}, {'items': [{'x': 4, 'y': 2}], 'x': 4, 'y': 2} ] group_items = group_by(items, 'x', 'y') nose.tools.assert_list_equal(group_items, expected) def test_utils_count_single_key(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] expected = [ {'count': 2, 'x': 1}, {'count': 1, 'x': 2}, {'count': 1, 'x': 4} ] group_items = count(items, 'x') nose.tools.assert_list_equal(group_items, expected)
34.1
112
0.524927
import nose from melano.utils import (sort, group_by, count) def test_utils_sort_single_key(): items = [dict(x=1), dict(x=4), dict(x=2)] sorted_items = sort(items, 'x') nose.tools.assert_list_equal(sorted_items, [dict(x=1), dict(x=2), dict(x=4)]) def test_utils_sort_multiple_keys(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] sorted_items = sort(items, 'x', 'y') nose.tools.assert_list_equal(sorted_items, [dict(x=1, y=2), dict(x=1, y=5), dict(x=2, y=3), dict(x=4, y=2)]) def test_utils_group_by_single_key(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] expected = [ {'items': [{'x': 1, 'y': 5}, {'x': 1, 'y': 2}], 'x': 1}, {'items': [{'x': 2, 'y': 3}], 'x': 2}, {'items': [{'x': 4, 'y': 2}], 'x': 4} ] group_items = group_by(items, 'x') nose.tools.assert_list_equal(group_items, expected) def test_utils_group_by_multiple_keys(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] expected = [ {'items': [{'x': 1, 'y': 2}], 'x': 1, 'y': 2}, {'items': [{'x': 1, 'y': 5}], 'x': 1, 'y': 5}, {'items': [{'x': 2, 'y': 3}], 'x': 2, 'y': 3}, {'items': [{'x': 4, 'y': 2}], 'x': 4, 'y': 2} ] group_items = group_by(items, 'x', 'y') nose.tools.assert_list_equal(group_items, expected) def test_utils_count_single_key(): items = [dict(x=1, y=5), dict(x=4, y=2), dict(x=2, y=3), dict(x=1, y=2)] expected = [ {'count': 2, 'x': 1}, {'count': 1, 'x': 2}, {'count': 1, 'x': 4} ] group_items = count(items, 'x') nose.tools.assert_list_equal(group_items, expected)
true
true
1c39bb0fc92c8274504c4a01918fd5834b1290c6
1,576
py
Python
bindings/python/examples/feature_example.py
beckgom/wav2letter
69ea72b2ea553d2792fa8a702ebe84fdb6b6f372
[ "BSD-3-Clause" ]
1
2019-06-25T03:29:55.000Z
2019-06-25T03:29:55.000Z
bindings/python/examples/feature_example.py
beckgom/wav2letter
69ea72b2ea553d2792fa8a702ebe84fdb6b6f372
[ "BSD-3-Clause" ]
null
null
null
bindings/python/examples/feature_example.py
beckgom/wav2letter
69ea72b2ea553d2792fa8a702ebe84fdb6b6f372
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python3 # adapted from wav2letter/src/feature/test/MfccTest.cpp import itertools as it import os import sys from wav2letter.feature import FeatureParams, Mfcc if len(sys.argv) != 2: print(f"usage: {sys.argv[0]} feature_test_data_path", file=sys.stderr) print(" (usually: <wav2letter_root>/src/feature/test/data)", file=sys.stderr) sys.exit(1) data_path = sys.argv[1] def load_data(filename): path = os.path.join(data_path, filename) path = os.path.abspath(path) with open(path) as f: return [float(x) for x in it.chain.from_iterable(line.split() for line in f)] wavinput = load_data("sa1.dat") htkfeat = load_data("sa1-mfcc.htk") assert len(wavinput) > 0 assert len(htkfeat) > 0 params = FeatureParams() params.samplingFreq = 16000 params.lowFreqFilterbank = 0 params.highFreqFilterbank = 8000 params.zeroMeanFrame = True params.numFilterbankChans = 20 params.numCepstralCoeffs = 13 params.useEnergy = False params.zeroMeanFrame = False params.usePower = False mfcc = Mfcc(params) feat = mfcc.apply(wavinput) assert len(feat) == len(htkfeat) assert len(feat) % 39 == 0 numframes = len(feat) // 39 featcopy = feat.copy() for f in range(numframes): for i in range(1, 39): feat[f * 39 + i - 1] = feat[f * 39 + i] feat[f * 39 + 12] = featcopy[f * 39 + 0] feat[f * 39 + 25] = featcopy[f * 39 + 13] feat[f * 39 + 38] = featcopy[f * 39 + 26] differences = [abs(x[0] - x[1]) for x in zip(feat, htkfeat)] print(f"max_diff={max(differences)}") print(f"avg_diff={sum(differences)/len(differences)}")
25.836066
85
0.687183
import itertools as it import os import sys from wav2letter.feature import FeatureParams, Mfcc if len(sys.argv) != 2: print(f"usage: {sys.argv[0]} feature_test_data_path", file=sys.stderr) print(" (usually: <wav2letter_root>/src/feature/test/data)", file=sys.stderr) sys.exit(1) data_path = sys.argv[1] def load_data(filename): path = os.path.join(data_path, filename) path = os.path.abspath(path) with open(path) as f: return [float(x) for x in it.chain.from_iterable(line.split() for line in f)] wavinput = load_data("sa1.dat") htkfeat = load_data("sa1-mfcc.htk") assert len(wavinput) > 0 assert len(htkfeat) > 0 params = FeatureParams() params.samplingFreq = 16000 params.lowFreqFilterbank = 0 params.highFreqFilterbank = 8000 params.zeroMeanFrame = True params.numFilterbankChans = 20 params.numCepstralCoeffs = 13 params.useEnergy = False params.zeroMeanFrame = False params.usePower = False mfcc = Mfcc(params) feat = mfcc.apply(wavinput) assert len(feat) == len(htkfeat) assert len(feat) % 39 == 0 numframes = len(feat) // 39 featcopy = feat.copy() for f in range(numframes): for i in range(1, 39): feat[f * 39 + i - 1] = feat[f * 39 + i] feat[f * 39 + 12] = featcopy[f * 39 + 0] feat[f * 39 + 25] = featcopy[f * 39 + 13] feat[f * 39 + 38] = featcopy[f * 39 + 26] differences = [abs(x[0] - x[1]) for x in zip(feat, htkfeat)] print(f"max_diff={max(differences)}") print(f"avg_diff={sum(differences)/len(differences)}")
true
true
1c39bb129b8916d3543e06f71819bd1661e4a778
592
py
Python
gumroad_clone/products/migrations/0003_auto_20211223_1608.py
AlexanderTCHK/gumroad-clone
39654243e581b918569772e410196557f71f6591
[ "MIT" ]
1
2022-01-22T13:43:30.000Z
2022-01-22T13:43:30.000Z
gumroad_clone/products/migrations/0003_auto_20211223_1608.py
AlexanderTCHK/gumroad-clone
39654243e581b918569772e410196557f71f6591
[ "MIT" ]
null
null
null
gumroad_clone/products/migrations/0003_auto_20211223_1608.py
AlexanderTCHK/gumroad-clone
39654243e581b918569772e410196557f71f6591
[ "MIT" ]
null
null
null
# Generated by Django 3.1.14 on 2021-12-23 10:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0002_product_user'), ] operations = [ migrations.AddField( model_name='product', name='active', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='product', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), ]
24.666667
108
0.592905
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0002_product_user'), ] operations = [ migrations.AddField( model_name='product', name='active', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='product', name='id', field=models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), ]
true
true
1c39bbc1bd2d09912707a6984ef94b6d42f347b5
1,397
py
Python
src/litedesk/lib/airwatch/device.py
litedesk/litedesk-lib-airwatch
19c47a50d606f966497a6e24fd892bca1bf11354
[ "Apache-2.0" ]
1
2016-12-22T07:10:45.000Z
2016-12-22T07:10:45.000Z
src/litedesk/lib/airwatch/device.py
litedesk/litedesk-lib-airwatch
19c47a50d606f966497a6e24fd892bca1bf11354
[ "Apache-2.0" ]
null
null
null
src/litedesk/lib/airwatch/device.py
litedesk/litedesk-lib-airwatch
19c47a50d606f966497a6e24fd892bca1bf11354
[ "Apache-2.0" ]
null
null
null
# Copyright 2014, Deutsche Telekom AG - Laboratories (T-Labs) # # 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 base import BaseObject from app import App class Device(BaseObject): @classmethod def search(cls, client, **kwargs): endpoint = 'mdm/devices/search' response = client.call_api('GET', endpoint, params=kwargs) response.raise_for_status() try: return [ cls(client, **attrs) for attrs in response.json().get('Devices') ] except: return [] @property def installed_apps(self): endpoint = 'mdm/devices/udid/{0}/apps'.format(self.Udid) response = self._client.call_api('GET', endpoint) response.raise_for_status() return [ App(self._client, **attrs) for attrs in response.json().get('DeviceApps') ]
32.488372
74
0.652112
from base import BaseObject from app import App class Device(BaseObject): @classmethod def search(cls, client, **kwargs): endpoint = 'mdm/devices/search' response = client.call_api('GET', endpoint, params=kwargs) response.raise_for_status() try: return [ cls(client, **attrs) for attrs in response.json().get('Devices') ] except: return [] @property def installed_apps(self): endpoint = 'mdm/devices/udid/{0}/apps'.format(self.Udid) response = self._client.call_api('GET', endpoint) response.raise_for_status() return [ App(self._client, **attrs) for attrs in response.json().get('DeviceApps') ]
true
true
1c39bc31e2a7c8c1b35471d80affab37545856b8
2,134
py
Python
phonenumbers/data/region_BH.py
ayushgoel/FixGoogleContacts
e49e58db6718bef8f95b6f767241605441c7fe41
[ "MIT" ]
2
2019-02-22T05:27:22.000Z
2020-12-30T19:33:18.000Z
phonenumbers/data/region_BH.py
ayushgoel/FixGoogleContacts
e49e58db6718bef8f95b6f767241605441c7fe41
[ "MIT" ]
null
null
null
phonenumbers/data/region_BH.py
ayushgoel/FixGoogleContacts
e49e58db6718bef8f95b6f767241605441c7fe41
[ "MIT" ]
null
null
null
"""Auto-generated file, do not edit by hand. BH metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_BH = PhoneMetadata(id='BH', country_code=973, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[136-9]\\d{7}', possible_number_pattern='\\d{8}'), fixed_line=PhoneNumberDesc(national_number_pattern='(?:1(?:3[3-6]|6[0156]|7\\d)\\d|6(?:1[16]\\d|6(?:0\\d|3[12]|44)|9(?:69|9[6-9]))|77\\d{2})\\d{4}', possible_number_pattern='\\d{8}', example_number='17001234'), mobile=PhoneNumberDesc(national_number_pattern='(?:3(?:[1-4679]\\d|5[035]|8[348])\\d|6(?:1[16]\\d|3(?:00|33|6[16])|500|6(?:[069]\\d|3[03-9]|44|88)|9(?:69|9[6-9]))|77\\d{2})\\d{4}', possible_number_pattern='\\d{8}', example_number='36001234'), toll_free=PhoneNumberDesc(national_number_pattern='80\\d{6}', possible_number_pattern='\\d{8}', example_number='80123456'), premium_rate=PhoneNumberDesc(national_number_pattern='(?:87|9[014578])\\d{6}', possible_number_pattern='\\d{8}', example_number='90123456'), shared_cost=PhoneNumberDesc(national_number_pattern='84\\d{6}', possible_number_pattern='\\d{8}', example_number='84123456'), personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), uan=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), emergency=PhoneNumberDesc(national_number_pattern='999', possible_number_pattern='\\d{3}', example_number='999'), voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), short_code=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), standard_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), number_format=[NumberFormat(pattern='(\\d{4})(\\d{4})', format='\\1 \\2')])
101.619048
246
0.741799
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_BH = PhoneMetadata(id='BH', country_code=973, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[136-9]\\d{7}', possible_number_pattern='\\d{8}'), fixed_line=PhoneNumberDesc(national_number_pattern='(?:1(?:3[3-6]|6[0156]|7\\d)\\d|6(?:1[16]\\d|6(?:0\\d|3[12]|44)|9(?:69|9[6-9]))|77\\d{2})\\d{4}', possible_number_pattern='\\d{8}', example_number='17001234'), mobile=PhoneNumberDesc(national_number_pattern='(?:3(?:[1-4679]\\d|5[035]|8[348])\\d|6(?:1[16]\\d|3(?:00|33|6[16])|500|6(?:[069]\\d|3[03-9]|44|88)|9(?:69|9[6-9]))|77\\d{2})\\d{4}', possible_number_pattern='\\d{8}', example_number='36001234'), toll_free=PhoneNumberDesc(national_number_pattern='80\\d{6}', possible_number_pattern='\\d{8}', example_number='80123456'), premium_rate=PhoneNumberDesc(national_number_pattern='(?:87|9[014578])\\d{6}', possible_number_pattern='\\d{8}', example_number='90123456'), shared_cost=PhoneNumberDesc(national_number_pattern='84\\d{6}', possible_number_pattern='\\d{8}', example_number='84123456'), personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), uan=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), emergency=PhoneNumberDesc(national_number_pattern='999', possible_number_pattern='\\d{3}', example_number='999'), voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), short_code=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), standard_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), number_format=[NumberFormat(pattern='(\\d{4})(\\d{4})', format='\\1 \\2')])
true
true
1c39bc742127d4a9e7c8c6db4eb2ca4162e43bb9
5,727
py
Python
pontoon/sync/tests/__init__.py
nanopony/pontoon
ebd342922d04df2dfbbce23ac5a15ee1e71d50fe
[ "BSD-3-Clause" ]
null
null
null
pontoon/sync/tests/__init__.py
nanopony/pontoon
ebd342922d04df2dfbbce23ac5a15ee1e71d50fe
[ "BSD-3-Clause" ]
null
null
null
pontoon/sync/tests/__init__.py
nanopony/pontoon
ebd342922d04df2dfbbce23ac5a15ee1e71d50fe
[ "BSD-3-Clause" ]
null
null
null
import os.path import factory from mock import patch, PropertyMock from pontoon.base.models import Project from pontoon.base.tests import ( EntityFactory, LocaleFactory, ProjectFactory, RepositoryFactory, ResourceFactory, TestCase, TranslationFactory, ) from pontoon.base.utils import aware_datetime from pontoon.sync.changeset import ChangeSet from pontoon.sync.models import ProjectSyncLog, RepositorySyncLog, SyncLog from pontoon.sync.vcs.models import VCSEntity, VCSProject, VCSResource, VCSTranslation FAKE_CHECKOUT_PATH = os.path.join(os.path.dirname(__file__), 'fake-checkout') class VCSEntityFactory(factory.Factory): resource = None key = 'key' string = 'string' string_plural = '' comments = factory.List([]) source = factory.List([]) order = factory.Sequence(lambda n: n) class Meta: model = VCSEntity class VCSTranslationFactory(factory.Factory): key = factory.Sequence(lambda n: 'key-{0}'.format(n)) strings = factory.Dict({}) comments = factory.List([]) fuzzy = False class Meta: model = VCSTranslation class SyncLogFactory(factory.DjangoModelFactory): class Meta: model = SyncLog class ProjectSyncLogFactory(factory.DjangoModelFactory): sync_log = factory.SubFactory(SyncLogFactory) project = factory.SubFactory(ProjectFactory) class Meta: model = ProjectSyncLog class RepositorySyncLogFactory(factory.DjangoModelFactory): project_sync_log = factory.SubFactory(ProjectSyncLogFactory) repository = factory.SubFactory(RepositoryFactory) class Meta: model = RepositorySyncLog class FakeCheckoutTestCase(TestCase): """Parent class for tests that use the fake l10n repo checkout.""" def setUp(self): self.now = aware_datetime(1970, 1, 1) timezone_patch = patch('pontoon.sync.tasks.timezone') self.mock_timezone = timezone_patch.start() self.addCleanup(timezone_patch.stop) self.mock_timezone.now.return_value = self.now self.translated_locale = LocaleFactory.create(code='translated-locale') self.inactive_locale = LocaleFactory.create(code='inactive-locale') self.repository = RepositoryFactory() self.db_project = ProjectFactory.create( name='db-project', locales=[self.translated_locale], repositories=[self.repository] ) self.main_db_resource = ResourceFactory.create( project=self.db_project, path='main.lang', format='lang' ) self.other_db_resource = ResourceFactory.create( project=self.db_project, path='other.lang', format='lang' ) self.missing_db_resource = ResourceFactory.create( project=self.db_project, path='missing.lang', format='lang' ) self.main_db_entity = EntityFactory.create( resource=self.main_db_resource, string='Source String', key='Source String', obsolete=False ) self.other_db_entity = EntityFactory.create( resource=self.other_db_resource, string='Other Source String', key='Other Source String', obsolete=False ) self.main_db_translation = TranslationFactory.create( entity=self.main_db_entity, plural_form=None, locale=self.translated_locale, string='Translated String', date=aware_datetime(1970, 1, 1), approved=True, extra={'tags': []} ) # Load paths from the fake locale directory. checkout_path_patch = patch.object( Project, 'checkout_path', new_callable=PropertyMock, return_value=FAKE_CHECKOUT_PATH ) checkout_path_patch.start() self.addCleanup(checkout_path_patch.stop) vcs_changed_files = { self.main_db_resource.path: [self.translated_locale], self.other_db_resource.path: [self.translated_locale], self.missing_db_resource.path: [self.translated_locale], } changed_files_patch = patch.object( VCSProject, 'changed_files', new_callable=PropertyMock, return_value=vcs_changed_files ) changed_files_patch.start() self.addCleanup(changed_files_patch.stop) source_repository = patch.object( Project, 'source_repository', new_callable=PropertyMock, return_value=self.db_project.repositories.all()[0] ) source_repository.start() self.addCleanup(source_repository.stop) self.vcs_project = VCSProject(self.db_project) self.main_vcs_resource = self.vcs_project.resources[self.main_db_resource.path] self.other_vcs_resource = self.vcs_project.resources[self.other_db_resource.path] self.missing_vcs_resource = self.vcs_project.resources[self.missing_db_resource.path] self.main_vcs_entity = self.main_vcs_resource.entities['Source String'] self.main_vcs_translation = self.main_vcs_entity.translations['translated-locale'] # Mock VCSResource.save() for each resource to avoid altering # the filesystem. resource_save_patch = patch.object(VCSResource, 'save') resource_save_patch.start() self.addCleanup(resource_save_patch.stop) self.changeset = ChangeSet( self.db_project, self.vcs_project, aware_datetime(1970, 1, 1), self.translated_locale, )
31.994413
93
0.654618
import os.path import factory from mock import patch, PropertyMock from pontoon.base.models import Project from pontoon.base.tests import ( EntityFactory, LocaleFactory, ProjectFactory, RepositoryFactory, ResourceFactory, TestCase, TranslationFactory, ) from pontoon.base.utils import aware_datetime from pontoon.sync.changeset import ChangeSet from pontoon.sync.models import ProjectSyncLog, RepositorySyncLog, SyncLog from pontoon.sync.vcs.models import VCSEntity, VCSProject, VCSResource, VCSTranslation FAKE_CHECKOUT_PATH = os.path.join(os.path.dirname(__file__), 'fake-checkout') class VCSEntityFactory(factory.Factory): resource = None key = 'key' string = 'string' string_plural = '' comments = factory.List([]) source = factory.List([]) order = factory.Sequence(lambda n: n) class Meta: model = VCSEntity class VCSTranslationFactory(factory.Factory): key = factory.Sequence(lambda n: 'key-{0}'.format(n)) strings = factory.Dict({}) comments = factory.List([]) fuzzy = False class Meta: model = VCSTranslation class SyncLogFactory(factory.DjangoModelFactory): class Meta: model = SyncLog class ProjectSyncLogFactory(factory.DjangoModelFactory): sync_log = factory.SubFactory(SyncLogFactory) project = factory.SubFactory(ProjectFactory) class Meta: model = ProjectSyncLog class RepositorySyncLogFactory(factory.DjangoModelFactory): project_sync_log = factory.SubFactory(ProjectSyncLogFactory) repository = factory.SubFactory(RepositoryFactory) class Meta: model = RepositorySyncLog class FakeCheckoutTestCase(TestCase): def setUp(self): self.now = aware_datetime(1970, 1, 1) timezone_patch = patch('pontoon.sync.tasks.timezone') self.mock_timezone = timezone_patch.start() self.addCleanup(timezone_patch.stop) self.mock_timezone.now.return_value = self.now self.translated_locale = LocaleFactory.create(code='translated-locale') self.inactive_locale = LocaleFactory.create(code='inactive-locale') self.repository = RepositoryFactory() self.db_project = ProjectFactory.create( name='db-project', locales=[self.translated_locale], repositories=[self.repository] ) self.main_db_resource = ResourceFactory.create( project=self.db_project, path='main.lang', format='lang' ) self.other_db_resource = ResourceFactory.create( project=self.db_project, path='other.lang', format='lang' ) self.missing_db_resource = ResourceFactory.create( project=self.db_project, path='missing.lang', format='lang' ) self.main_db_entity = EntityFactory.create( resource=self.main_db_resource, string='Source String', key='Source String', obsolete=False ) self.other_db_entity = EntityFactory.create( resource=self.other_db_resource, string='Other Source String', key='Other Source String', obsolete=False ) self.main_db_translation = TranslationFactory.create( entity=self.main_db_entity, plural_form=None, locale=self.translated_locale, string='Translated String', date=aware_datetime(1970, 1, 1), approved=True, extra={'tags': []} ) checkout_path_patch = patch.object( Project, 'checkout_path', new_callable=PropertyMock, return_value=FAKE_CHECKOUT_PATH ) checkout_path_patch.start() self.addCleanup(checkout_path_patch.stop) vcs_changed_files = { self.main_db_resource.path: [self.translated_locale], self.other_db_resource.path: [self.translated_locale], self.missing_db_resource.path: [self.translated_locale], } changed_files_patch = patch.object( VCSProject, 'changed_files', new_callable=PropertyMock, return_value=vcs_changed_files ) changed_files_patch.start() self.addCleanup(changed_files_patch.stop) source_repository = patch.object( Project, 'source_repository', new_callable=PropertyMock, return_value=self.db_project.repositories.all()[0] ) source_repository.start() self.addCleanup(source_repository.stop) self.vcs_project = VCSProject(self.db_project) self.main_vcs_resource = self.vcs_project.resources[self.main_db_resource.path] self.other_vcs_resource = self.vcs_project.resources[self.other_db_resource.path] self.missing_vcs_resource = self.vcs_project.resources[self.missing_db_resource.path] self.main_vcs_entity = self.main_vcs_resource.entities['Source String'] self.main_vcs_translation = self.main_vcs_entity.translations['translated-locale'] resource_save_patch = patch.object(VCSResource, 'save') resource_save_patch.start() self.addCleanup(resource_save_patch.stop) self.changeset = ChangeSet( self.db_project, self.vcs_project, aware_datetime(1970, 1, 1), self.translated_locale, )
true
true
1c39bd85b12944df9e3e4d4650fe72b4a9c113d5
211
py
Python
Trivia.py
Plumbob/PythonDemos
fb008651ad72e5f07ded5da44a04ab996571fb4d
[ "Unlicense" ]
null
null
null
Trivia.py
Plumbob/PythonDemos
fb008651ad72e5f07ded5da44a04ab996571fb4d
[ "Unlicense" ]
null
null
null
Trivia.py
Plumbob/PythonDemos
fb008651ad72e5f07ded5da44a04ab996571fb4d
[ "Unlicense" ]
null
null
null
def even_evens(some_list): """ Give a list 'some_list', return a list of only the even numbers from the even indices of 'some_list'. """ return [x for x in some_list[::2] if x % 2 == 0]
17.583333
76
0.606635
def even_evens(some_list): return [x for x in some_list[::2] if x % 2 == 0]
true
true
1c39bdaabf85888bdde2272e24f9b639e4b3bc26
4,042
py
Python
digits/download_data/cifar10.py
dcmartin/digits
4a16aef47226413eba232e268049678816281c7d
[ "BSD-3-Clause" ]
1
2021-01-25T01:06:25.000Z
2021-01-25T01:06:25.000Z
digits/download_data/cifar10.py
dcmartin/digits
4a16aef47226413eba232e268049678816281c7d
[ "BSD-3-Clause" ]
null
null
null
digits/download_data/cifar10.py
dcmartin/digits
4a16aef47226413eba232e268049678816281c7d
[ "BSD-3-Clause" ]
null
null
null
# Copyright (c) 2015-2017, NVIDIA CORPORATION. All rights reserved. import pickle import os import tarfile import PIL.Image from .downloader import DataDownloader class Cifar10Downloader(DataDownloader): """ See details about the CIFAR10 dataset here: http://www.cs.toronto.edu/~kriz/cifar.html """ def urlList(self): return [ 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', ] def uncompressData(self): filename = 'cifar-10-python.tar.gz' filepath = os.path.join(self.outdir, filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename if not os.path.exists(os.path.join(self.outdir, 'cifar-10-batches-py')): print("Uncompressing file=%s ..." % filename) with tarfile.open(filepath) as tf: tf.extractall(self.outdir) def processData(self): label_filename = 'batches.meta' label_filepath = os.path.join(self.outdir, 'cifar-10-batches-py', label_filename) with open(label_filepath, 'rb') as infile: pickleObj = pickle.load(infile) label_names = pickleObj['label_names'] for phase in 'train', 'test': dirname = os.path.join(self.outdir, phase) self.mkdir(dirname, clean=True) with open(os.path.join(dirname, 'labels.txt'), 'w') as outfile: for name in label_names: outfile.write('%s\n' % name) for filename, phase in [ ('data_batch_1', 'train'), ('data_batch_2', 'train'), ('data_batch_3', 'train'), ('data_batch_4', 'train'), ('data_batch_5', 'train'), ('test_batch', 'test'), ]: filepath = os.path.join(self.outdir, 'cifar-10-batches-py', filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename self.__extractData(filepath, phase, label_names) def __extractData(self, input_file, phase, label_names): """ Read a pickle file at input_file and output images Arguments: input_file -- the input pickle file phase -- train or test label_names -- a list of strings """ print('Extracting images file=%s ...' % input_file) # Read the pickle file with open(input_file, 'rb') as infile: pickleObj = pickle.load(infile) # print('Batch -', pickleObj['batch_label']) data = pickleObj['data'] assert data.shape == (10000, 3072), 'Expected data.shape to be (10000, 3072), not %s' % (data.shape,) count = data.shape[0] labels = pickleObj['labels'] assert len(labels) == count, 'Expected len(labels) to be %d, not %d' % (count, len(labels)) filenames = pickleObj['filenames'] assert len(filenames) == count, 'Expected len(filenames) to be %d, not %d' % (count, len(filenames)) data = data.reshape((10000, 3, 32, 32)) data = data.transpose((0, 2, 3, 1)) output_dir = os.path.join(self.outdir, phase) self.mkdir(output_dir) with open(os.path.join(output_dir, '%s.txt' % phase), 'a') as outfile: for index, image in enumerate(data): # Create the directory dirname = os.path.join(output_dir, label_names[labels[index]]) if not os.path.exists(dirname): os.makedirs(dirname) # Get the filename filename = filenames[index] ext = os.path.splitext(filename)[1][1:].lower() if ext != self.file_extension: filename = '%s.%s' % (os.path.splitext(filename)[0], self.file_extension) filename = os.path.join(dirname, filename) # Save the image PIL.Image.fromarray(image).save(filename) outfile.write('%s %s\n' % (filename, labels[index]))
38.495238
113
0.567293
import pickle import os import tarfile import PIL.Image from .downloader import DataDownloader class Cifar10Downloader(DataDownloader): def urlList(self): return [ 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', ] def uncompressData(self): filename = 'cifar-10-python.tar.gz' filepath = os.path.join(self.outdir, filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename if not os.path.exists(os.path.join(self.outdir, 'cifar-10-batches-py')): print("Uncompressing file=%s ..." % filename) with tarfile.open(filepath) as tf: tf.extractall(self.outdir) def processData(self): label_filename = 'batches.meta' label_filepath = os.path.join(self.outdir, 'cifar-10-batches-py', label_filename) with open(label_filepath, 'rb') as infile: pickleObj = pickle.load(infile) label_names = pickleObj['label_names'] for phase in 'train', 'test': dirname = os.path.join(self.outdir, phase) self.mkdir(dirname, clean=True) with open(os.path.join(dirname, 'labels.txt'), 'w') as outfile: for name in label_names: outfile.write('%s\n' % name) for filename, phase in [ ('data_batch_1', 'train'), ('data_batch_2', 'train'), ('data_batch_3', 'train'), ('data_batch_4', 'train'), ('data_batch_5', 'train'), ('test_batch', 'test'), ]: filepath = os.path.join(self.outdir, 'cifar-10-batches-py', filename) assert os.path.exists(filepath), 'Expected "%s" to exist' % filename self.__extractData(filepath, phase, label_names) def __extractData(self, input_file, phase, label_names): print('Extracting images file=%s ...' % input_file) with open(input_file, 'rb') as infile: pickleObj = pickle.load(infile) data = pickleObj['data'] assert data.shape == (10000, 3072), 'Expected data.shape to be (10000, 3072), not %s' % (data.shape,) count = data.shape[0] labels = pickleObj['labels'] assert len(labels) == count, 'Expected len(labels) to be %d, not %d' % (count, len(labels)) filenames = pickleObj['filenames'] assert len(filenames) == count, 'Expected len(filenames) to be %d, not %d' % (count, len(filenames)) data = data.reshape((10000, 3, 32, 32)) data = data.transpose((0, 2, 3, 1)) output_dir = os.path.join(self.outdir, phase) self.mkdir(output_dir) with open(os.path.join(output_dir, '%s.txt' % phase), 'a') as outfile: for index, image in enumerate(data): dirname = os.path.join(output_dir, label_names[labels[index]]) if not os.path.exists(dirname): os.makedirs(dirname) filename = filenames[index] ext = os.path.splitext(filename)[1][1:].lower() if ext != self.file_extension: filename = '%s.%s' % (os.path.splitext(filename)[0], self.file_extension) filename = os.path.join(dirname, filename) PIL.Image.fromarray(image).save(filename) outfile.write('%s %s\n' % (filename, labels[index]))
true
true
1c39bf2d260753f05acf235e773635b503489f9b
328
py
Python
core/urls.py
adankro/Mood-sensing-app
9fe77a04c506d6bfb5f77cbd5c68d02a69758570
[ "MIT" ]
null
null
null
core/urls.py
adankro/Mood-sensing-app
9fe77a04c506d6bfb5f77cbd5c68d02a69758570
[ "MIT" ]
14
2020-02-11T23:12:48.000Z
2022-03-11T23:29:00.000Z
core/urls.py
adankro/Mood-sensing-app
9fe77a04c506d6bfb5f77cbd5c68d02a69758570
[ "MIT" ]
1
2020-07-06T03:29:57.000Z
2020-07-06T03:29:57.000Z
from django.urls import path from . import views urlpatterns = [ path('Mood/', views.MoodView.as_view(), name='Mood-all'), path('<int:user_id>', views.HappyPlacesView, name='HappyPlacesView'), path('user/<int:userID>', views.stats, name='stats'), #path('stats/<int:user_id>', stats, name="stats"), ]
29.818182
74
0.643293
from django.urls import path from . import views urlpatterns = [ path('Mood/', views.MoodView.as_view(), name='Mood-all'), path('<int:user_id>', views.HappyPlacesView, name='HappyPlacesView'), path('user/<int:userID>', views.stats, name='stats'), ]
true
true
1c39bfb5d105d684c875003b253f1ba0480ad5bc
3,733
py
Python
Tools/concat.py
ka10ryu1/keytouch_cam
a99fbb16d0c5054cf462602fb73c025924d77a8a
[ "MIT" ]
7
2018-02-25T22:47:01.000Z
2020-09-14T05:39:33.000Z
Tools/concat.py
ka10ryu1/human_delete
042b0caacb5af31cfa9c71ae012d58e798777c8d
[ "MIT" ]
null
null
null
Tools/concat.py
ka10ryu1/human_delete
042b0caacb5af31cfa9c71ae012d58e798777c8d
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*-coding: utf-8 -*- # help = '複数の画像を任意の行列で結合する' # import os import sys import cv2 import argparse import numpy as np [sys.path.append(d) for d in ['./Tools/', '../Tools/'] if os.path.isdir(d)] import func as F import imgfunc as IMG def command(): parser = argparse.ArgumentParser(description=help) parser.add_argument('jpeg', nargs='+', help='使用する画像のパス') parser.add_argument('--out_path', '-o', default='./result/', help='生成物の保存先 [default: ./result/]') parser.add_argument('--row', '-r', type=int, default=-1, help='画像を連結する行(負数で自動計算) [default: -1]') parser.add_argument('--line_width', '-lw', type=int, default=2, help='画像を連結する行 [default: 2]') parser.add_argument('--resize', '-rs', type=float, default=0.5, help='画像の縮尺 [default: 0.5]') return parser.parse_args() def makeDivisorList(num): """ 入力された数の約数に1を加えたリストを返す [in] num: 約数を計算したい数 [out] divisor_list: numの約数に1を加えたリスト """ if num < 1: return [0] elif num == 1: return [1] else: divisor_list = [i for i in range(2, num // 2 + 1) if num % i == 0] divisor_list.append(1) return divisor_list def stackImgAndShape(imgs, row): """ 画像を縦横に連結するための画像リストと縦横画像数情報を取得する [in] imgs: 連結したい入力画像リスト [in] row: [out] 画像リスト [out] 縦横画像数情報 """ # row=0は強制的に1にする if row == 0: row = 1 # 入力画像リストがrowで割り切れない時用に # 黒塗画像を用意するが、3枚の根拠はない if row > 3 or 0 > row: bk = np.zeros(imgs[0].shape, dtype=np.uint8) imgs.append(bk) imgs.append(bk) imgs.append(bk) # rowが負数の場合はrowを自動計算する if 0 > row: # 黒塗画像を0枚含んだ状態でdiv_listが3以上になればdivとimgsを決定 # div_listが十分でなかった場合、 # 黒塗画像を1枚含んだ状態でdiv_listが3以上になればdivとimgsを決定 # これを黒塗画像3枚まで続ける for i in range(3, 0, -1): # 画像の数で約数を探す div_list = makeDivisorList(len(imgs[:-i])) if(len(div_list) > 2): # rowは約数のリストの中心の値を取得する # これにより正方形に近い連結画像が生成できる row = div_list[len(div_list) // 2] imgs = imgs[:-i] break else: img_len = len(imgs) // row * row imgs = imgs[:img_len] return np.array(imgs), np.arange(len(imgs)).reshape(-1, row) def makeBorder(img, top, bottom, left, right, flg, value=None): """ cv2.copyMakeBorder()のラッパー関数なので詳細は省く """ if flg == cv2.BORDER_CONSTANT: return cv2.copyMakeBorder(img, top, bottom, left, right, flg, value=value) else: return cv2.copyMakeBorder(img, top, bottom, left, right, flg) def main(args): # 画像を読み込む imgs = [cv2.imread(name) for name in args.jpeg if IMG.isImgPath(name)] # concatするためにすべての画像の高さを統一する h = np.max([img.shape[0] for img in imgs]) imgs = [IMG.resize(img, h / img.shape[0]) for img in imgs] # concatするためにすべての画像の幅を統一する flg = cv2.BORDER_REFLECT_101 w = np.max([img.shape[1] for img in imgs]) imgs = [makeBorder(img, 0, 0, 0, w - img.shape[1], flg) for img in imgs] # 画像に黒縁を追加する flg = cv2.BORDER_CONSTANT lw = args.line_width imgs = [makeBorder(img, 0, lw, 0, lw, flg, (0, 0, 0)) for img in imgs] # 縦横に連結するための画像リストと縦横情報を取得する imgs, size = stackImgAndShape(imgs, args.row) # 画像を連結してリサイズする buf = [np.vstack(imgs[s]) for s in size] img = IMG.resize(np.hstack(buf), args.resize) # 連結された画像を保存する name = F.getFilePath(args.out_path, 'concat', '.jpg') print('save:', name) cv2.imwrite(name, img) if __name__ == '__main__': args = command() F.argsPrint(args) main(args)
27.651852
82
0.584784
help = '複数の画像を任意の行列で結合する' import os import sys import cv2 import argparse import numpy as np [sys.path.append(d) for d in ['./Tools/', '../Tools/'] if os.path.isdir(d)] import func as F import imgfunc as IMG def command(): parser = argparse.ArgumentParser(description=help) parser.add_argument('jpeg', nargs='+', help='使用する画像のパス') parser.add_argument('--out_path', '-o', default='./result/', help='生成物の保存先 [default: ./result/]') parser.add_argument('--row', '-r', type=int, default=-1, help='画像を連結する行(負数で自動計算) [default: -1]') parser.add_argument('--line_width', '-lw', type=int, default=2, help='画像を連結する行 [default: 2]') parser.add_argument('--resize', '-rs', type=float, default=0.5, help='画像の縮尺 [default: 0.5]') return parser.parse_args() def makeDivisorList(num): if num < 1: return [0] elif num == 1: return [1] else: divisor_list = [i for i in range(2, num // 2 + 1) if num % i == 0] divisor_list.append(1) return divisor_list def stackImgAndShape(imgs, row): if row == 0: row = 1 if row > 3 or 0 > row: bk = np.zeros(imgs[0].shape, dtype=np.uint8) imgs.append(bk) imgs.append(bk) imgs.append(bk) if 0 > row: for i in range(3, 0, -1): div_list = makeDivisorList(len(imgs[:-i])) if(len(div_list) > 2): row = div_list[len(div_list) // 2] imgs = imgs[:-i] break else: img_len = len(imgs) // row * row imgs = imgs[:img_len] return np.array(imgs), np.arange(len(imgs)).reshape(-1, row) def makeBorder(img, top, bottom, left, right, flg, value=None): if flg == cv2.BORDER_CONSTANT: return cv2.copyMakeBorder(img, top, bottom, left, right, flg, value=value) else: return cv2.copyMakeBorder(img, top, bottom, left, right, flg) def main(args): imgs = [cv2.imread(name) for name in args.jpeg if IMG.isImgPath(name)] h = np.max([img.shape[0] for img in imgs]) imgs = [IMG.resize(img, h / img.shape[0]) for img in imgs] flg = cv2.BORDER_REFLECT_101 w = np.max([img.shape[1] for img in imgs]) imgs = [makeBorder(img, 0, 0, 0, w - img.shape[1], flg) for img in imgs] flg = cv2.BORDER_CONSTANT lw = args.line_width imgs = [makeBorder(img, 0, lw, 0, lw, flg, (0, 0, 0)) for img in imgs] imgs, size = stackImgAndShape(imgs, args.row) buf = [np.vstack(imgs[s]) for s in size] img = IMG.resize(np.hstack(buf), args.resize) name = F.getFilePath(args.out_path, 'concat', '.jpg') print('save:', name) cv2.imwrite(name, img) if __name__ == '__main__': args = command() F.argsPrint(args) main(args)
true
true
1c39bfde332307ca3cad3187669e4c969cf0f51d
320
py
Python
clipSync/__init__.py
AravindVasudev/clip-sync
8cf8c09687cbf1aa5db1fc95fd2e9a283b57e5ee
[ "MIT" ]
null
null
null
clipSync/__init__.py
AravindVasudev/clip-sync
8cf8c09687cbf1aa5db1fc95fd2e9a283b57e5ee
[ "MIT" ]
null
null
null
clipSync/__init__.py
AravindVasudev/clip-sync
8cf8c09687cbf1aa5db1fc95fd2e9a283b57e5ee
[ "MIT" ]
null
null
null
from flask import Flask from flask_socketio import SocketIO from tkinter import Tk # App Instance app = Flask(__name__) app.config['SECRET_KEY'] = 'shamballa' # SocketIO Init socketio = SocketIO(app) # tkinter window for reading clipboard win = Tk() win.withdraw() from . import views from . import clipboard_thread
17.777778
38
0.76875
from flask import Flask from flask_socketio import SocketIO from tkinter import Tk app = Flask(__name__) app.config['SECRET_KEY'] = 'shamballa' socketio = SocketIO(app) win = Tk() win.withdraw() from . import views from . import clipboard_thread
true
true
1c39c0426bd8361e249700059f1c06b48f11d7e8
41,711
py
Python
nova/tests/unit/virt/libvirt/test_imagecache.py
nicholaskuechler/nova
ff412c3888b234eb123161cc4e6d0d0d69c0004e
[ "Apache-2.0" ]
null
null
null
nova/tests/unit/virt/libvirt/test_imagecache.py
nicholaskuechler/nova
ff412c3888b234eb123161cc4e6d0d0d69c0004e
[ "Apache-2.0" ]
5
2016-07-11T20:59:47.000Z
2020-07-28T09:56:35.000Z
nova/tests/unit/virt/libvirt/test_imagecache.py
nicholaskuechler/nova
ff412c3888b234eb123161cc4e6d0d0d69c0004e
[ "Apache-2.0" ]
3
2018-01-29T00:44:44.000Z
2020-07-24T01:19:20.000Z
# Copyright 2012 Michael Still and Canonical Inc # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import hashlib import os import time import mock from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import formatters from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import importutils from six.moves import cStringIO from nova import conductor from nova import context from nova import db from nova import objects from nova import test from nova.tests.unit import fake_instance from nova import utils from nova.virt.libvirt import imagecache from nova.virt.libvirt import utils as libvirt_utils CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') CONF.import_opt('host', 'nova.netconf') @contextlib.contextmanager def intercept_log_messages(): try: mylog = logging.getLogger('nova') stream = cStringIO() handler = logging.logging.StreamHandler(stream) handler.setFormatter(formatters.ContextFormatter()) mylog.logger.addHandler(handler) yield stream finally: mylog.logger.removeHandler(handler) class ImageCacheManagerTestCase(test.NoDBTestCase): def setUp(self): super(ImageCacheManagerTestCase, self).setUp() self.stock_instance_names = set(['instance-00000001', 'instance-00000002', 'instance-00000003', 'banana-42-hamster']) def test_read_stored_checksum_missing(self): self.stubs.Set(os.path, 'exists', lambda x: False) csum = imagecache.read_stored_checksum('/tmp/foo', timestamped=False) self.assertIsNone(csum) @mock.patch.object(os.path, 'exists', return_value=True) @mock.patch.object(time, 'time', return_value=2000000) @mock.patch.object(os.path, 'getmtime', return_value=1000000) def test_get_age_of_file(self, mock_getmtime, mock_time, mock_exists): image_cache_manager = imagecache.ImageCacheManager() exists, age = image_cache_manager._get_age_of_file('/tmp') self.assertTrue(exists) self.assertEqual(1000000, age) @mock.patch.object(os.path, 'exists', return_value=False) def test_get_age_of_file_not_exists(self, mock_exists): image_cache_manager = imagecache.ImageCacheManager() exists, age = image_cache_manager._get_age_of_file('/tmp') self.assertFalse(exists) self.assertEqual(0, age) def test_read_stored_checksum(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') csum_input = '{"sha1": "fdghkfhkgjjksfdgjksjkghsdf"}\n' fname = os.path.join(tmpdir, 'aaa') info_fname = imagecache.get_info_filename(fname) f = open(info_fname, 'w') f.write(csum_input) f.close() csum_output = imagecache.read_stored_checksum(fname, timestamped=False) self.assertEqual(csum_input.rstrip(), '{"sha1": "%s"}' % csum_output) def test_read_stored_checksum_legacy_essex(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') old_fname = fname + '.sha1' f = open(old_fname, 'w') f.write('fdghkfhkgjjksfdgjksjkghsdf') f.close() csum_output = imagecache.read_stored_checksum(fname, timestamped=False) self.assertEqual(csum_output, 'fdghkfhkgjjksfdgjksjkghsdf') self.assertFalse(os.path.exists(old_fname)) info_fname = imagecache.get_info_filename(fname) self.assertTrue(os.path.exists(info_fname)) def test_list_base_images(self): listing = ['00000001', 'ephemeral_0_20_None', '17d1b00b81642842e514494a78e804e9a511637c_5368709120.info', '00000004', 'swap_1000'] images = ['e97222e91fc4241f49a7f520d1dcf446751129b3_sm', 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm', 'e97222e91fc4241f49a7f520d1dcf446751129b3', '17d1b00b81642842e514494a78e804e9a511637c', '17d1b00b81642842e514494a78e804e9a511637c_5368709120', '17d1b00b81642842e514494a78e804e9a511637c_10737418240'] listing.extend(images) self.stubs.Set(os, 'listdir', lambda x: listing) self.stubs.Set(os.path, 'isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' self.flags(instances_path='/var/lib/nova/instances') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) sanitized = [] for ent in image_cache_manager.unexplained_images: sanitized.append(ent.replace(base_dir + '/', '')) self.assertEqual(sorted(sanitized), sorted(images)) expected = os.path.join(base_dir, 'e97222e91fc4241f49a7f520d1dcf446751129b3') self.assertIn(expected, image_cache_manager.unexplained_images) expected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c_' '10737418240') self.assertIn(expected, image_cache_manager.unexplained_images) unexpected = os.path.join(base_dir, '00000004') self.assertNotIn(unexpected, image_cache_manager.unexplained_images) for ent in image_cache_manager.unexplained_images: self.assertTrue(ent.startswith(base_dir)) self.assertEqual(len(image_cache_manager.originals), 2) expected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c') self.assertIn(expected, image_cache_manager.originals) unexpected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c_' '10737418240') self.assertNotIn(unexpected, image_cache_manager.originals) self.assertEqual(1, len(image_cache_manager.back_swap_images)) self.assertIn('swap_1000', image_cache_manager.back_swap_images) def test_list_backing_images_small(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'instance-00000001', 'instance-00000002', 'instance-00000003']) self.stubs.Set(os.path, 'exists', lambda x: x.find('instance-') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_resized(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'instance-00000001', 'instance-00000002', 'instance-00000003']) self.stubs.Set(os.path, 'exists', lambda x: x.find('instance-') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: ('e97222e91fc4241f49a7f520d1dcf446751129b3_' '10737418240')) found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_' '10737418240') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_instancename(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'banana-42-hamster']) self.stubs.Set(os.path, 'exists', lambda x: x.find('banana-42-hamster') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_disk_notexist(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'banana-42-hamster']) self.stubs.Set(os.path, 'exists', lambda x: x.find('banana-42-hamster') != -1) def fake_get_disk(disk_path): raise processutils.ProcessExecutionError() self.stubs.Set(libvirt_utils, 'get_disk_backing_file', fake_get_disk) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [] image_cache_manager.instance_names = self.stock_instance_names self.assertRaises(processutils.ProcessExecutionError, image_cache_manager._list_backing_images) def test_find_base_file_nothing(self): self.stubs.Set(os.path, 'exists', lambda x: False) base_dir = '/var/lib/nova/instances/_base' fingerprint = '549867354867' image_cache_manager = imagecache.ImageCacheManager() res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) self.assertEqual(0, len(res)) def test_find_base_file_small(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' self.stubs.Set(os.path, 'exists', lambda x: x.endswith('%s_sm' % fingerprint)) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file = os.path.join(base_dir, fingerprint + '_sm') self.assertEqual(res, [(base_file, True, False)]) def test_find_base_file_resized(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' listing = ['00000001', 'ephemeral_0_20_None', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240', '00000004'] self.stubs.Set(os, 'listdir', lambda x: listing) self.stubs.Set(os.path, 'exists', lambda x: x.endswith('%s_10737418240' % fingerprint)) self.stubs.Set(os.path, 'isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file = os.path.join(base_dir, fingerprint + '_10737418240') self.assertEqual(res, [(base_file, False, True)]) def test_find_base_file_all(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' listing = ['00000001', 'ephemeral_0_20_None', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_sm', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240', '00000004'] self.stubs.Set(os, 'listdir', lambda x: listing) self.stubs.Set(os.path, 'exists', lambda x: True) self.stubs.Set(os.path, 'isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file1 = os.path.join(base_dir, fingerprint) base_file2 = os.path.join(base_dir, fingerprint + '_sm') base_file3 = os.path.join(base_dir, fingerprint + '_10737418240') self.assertEqual(res, [(base_file1, False, False), (base_file2, True, False), (base_file3, False, True)]) @contextlib.contextmanager def _make_base_file(self, checksum=True, lock=True): """Make a base file for testing.""" with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') base_file = open(fname, 'w') base_file.write('data') base_file.close() if lock: lockdir = os.path.join(tmpdir, 'locks') lockname = os.path.join(lockdir, 'nova-aaa') os.mkdir(lockdir) lock_file = open(lockname, 'w') lock_file.write('data') lock_file.close() base_file = open(fname, 'r') if checksum: imagecache.write_stored_checksum(fname) base_file.close() yield fname def test_remove_base_file(self): with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) info_fname = imagecache.get_info_filename(fname) lock_name = 'nova-' + os.path.split(fname)[-1] lock_dir = os.path.join(CONF.instances_path, 'locks') lock_file = os.path.join(lock_dir, lock_name) # Files are initially too new to delete self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) self.assertTrue(os.path.exists(lock_file)) # Old files get cleaned up though os.utime(fname, (-1, time.time() - 3601)) image_cache_manager._remove_base_file(fname) self.assertFalse(os.path.exists(fname)) self.assertFalse(os.path.exists(info_fname)) self.assertFalse(os.path.exists(lock_file)) def test_remove_base_file_original(self): with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.originals = [fname] image_cache_manager._remove_base_file(fname) info_fname = imagecache.get_info_filename(fname) # Files are initially too new to delete self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) # This file should stay longer than a resized image os.utime(fname, (-1, time.time() - 3601)) image_cache_manager._remove_base_file(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) # Originals don't stay forever though os.utime(fname, (-1, time.time() - 3600 * 25)) image_cache_manager._remove_base_file(fname) self.assertFalse(os.path.exists(fname)) self.assertFalse(os.path.exists(info_fname)) def test_remove_base_file_dne(self): # This test is solely to execute the "does not exist" code path. We # don't expect the method being tested to do anything in this case. with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) def test_remove_base_file_oserror(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') os.mkdir(fname) os.utime(fname, (-1, time.time() - 3601)) # This will raise an OSError because of file permissions image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) self.assertTrue(os.path.exists(fname)) self.assertNotEqual(stream.getvalue().find('Failed to remove'), -1) def test_handle_base_image_unused(self): img = '123' with self._make_base_file() as fname: os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, [fname]) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_used(self): self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) img = '123' with self._make_base_file() as fname: os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_used_remotely(self): self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) img = '123' with self._make_base_file() as fname: os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (0, 1, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_absent(self): img = '123' with intercept_log_messages() as stream: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, None) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) self.assertNotEqual(stream.getvalue().find('an absent base file'), -1) def test_handle_base_image_used_missing(self): img = '123' with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_checksum_fails(self): self.flags(checksum_base_images=True, group='libvirt') self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) img = '123' with self._make_base_file() as fname: with open(fname, 'w') as f: f.write('banana') d = {'sha1': '21323454'} with open('%s.info' % fname, 'w') as f: f.write(jsonutils.dumps(d)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, [fname]) def test_verify_base_images(self): hashed_1 = '356a192b7913b04c54574d18c28d46e6395428ab' hashed_21 = '472b07b9fcf2c2451e8781e944bf5f77cd8457c8' hashed_22 = '12c6fc06c99a462375eeb3f43dfd832b08ca9e17' hashed_42 = '92cfceb39d57d914ed8b14d0e37643de0797ae56' self.flags(instances_path='/instance_path', image_cache_subdirectory_name='_base') base_file_list = ['00000001', 'ephemeral_0_20_None', 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm', 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm', hashed_42, hashed_1, hashed_21, hashed_22, '%s_5368709120' % hashed_1, '%s_10737418240' % hashed_1, '00000004'] def fq_path(path): return os.path.join('/instance_path/_base/', path) # Fake base directory existence orig_exists = os.path.exists def exists(path): # The python coverage tool got angry with my overly broad mocks if not path.startswith('/instance_path'): return orig_exists(path) if path in ['/instance_path', '/instance_path/_base', '/instance_path/instance-1/disk', '/instance_path/instance-2/disk', '/instance_path/instance-3/disk', '/instance_path/_base/%s.info' % hashed_42]: return True for p in base_file_list: if path == fq_path(p): return True if path == fq_path(p) + '.info': return False if path in ['/instance_path/_base/%s_sm' % i for i in [hashed_1, hashed_21, hashed_22, hashed_42]]: return False self.fail('Unexpected path existence check: %s' % path) self.stubs.Set(os.path, 'exists', lambda x: exists(x)) self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) # We need to stub utime as well self.stubs.Set(os, 'utime', lambda x, y: None) # Fake up some instances in the instances directory orig_listdir = os.listdir def listdir(path): # The python coverage tool got angry with my overly broad mocks if not path.startswith('/instance_path'): return orig_listdir(path) if path == '/instance_path': return ['instance-1', 'instance-2', 'instance-3', '_base'] if path == '/instance_path/_base': return base_file_list self.fail('Unexpected directory listed: %s' % path) self.stubs.Set(os, 'listdir', lambda x: listdir(x)) # Fake isfile for these faked images in _base orig_isfile = os.path.isfile def isfile(path): # The python coverage tool got angry with my overly broad mocks if not path.startswith('/instance_path'): return orig_isfile(path) for p in base_file_list: if path == fq_path(p): return True self.fail('Unexpected isfile call: %s' % path) self.stubs.Set(os.path, 'isfile', lambda x: isfile(x)) # Fake the database call which lists running instances instances = [{'image_ref': '1', 'host': CONF.host, 'name': 'instance-1', 'uuid': '123', 'vm_state': '', 'task_state': ''}, {'image_ref': '1', 'kernel_id': '21', 'ramdisk_id': '22', 'host': CONF.host, 'name': 'instance-2', 'uuid': '456', 'vm_state': '', 'task_state': ''}] all_instances = [fake_instance.fake_instance_obj(None, **instance) for instance in instances] image_cache_manager = imagecache.ImageCacheManager() # Fake the utils call which finds the backing image def get_disk_backing_file(path): if path in ['/instance_path/instance-1/disk', '/instance_path/instance-2/disk']: return fq_path('%s_5368709120' % hashed_1) self.fail('Unexpected backing file lookup: %s' % path) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: get_disk_backing_file(x)) # Fake out verifying checksums, as that is tested elsewhere self.stubs.Set(image_cache_manager, '_verify_checksum', lambda x, y: True) # Fake getmtime as well orig_getmtime = os.path.getmtime def getmtime(path): if not path.startswith('/instance_path'): return orig_getmtime(path) return 1000000 self.stubs.Set(os.path, 'getmtime', lambda x: getmtime(x)) # Make sure we don't accidentally remove a real file orig_remove = os.remove def remove(path): if not path.startswith('/instance_path'): return orig_remove(path) # Don't try to remove fake files return self.stubs.Set(os, 'remove', lambda x: remove(x)) self.mox.StubOutWithMock(objects.block_device.BlockDeviceMappingList, 'get_by_instance_uuid') ctxt = context.get_admin_context() objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '123').AndReturn(None) objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '456').AndReturn(None) self.mox.ReplayAll() # And finally we can make the call we're actually testing... # The argument here should be a context, but it is mocked out image_cache_manager.update(ctxt, all_instances) # Verify active = [fq_path(hashed_1), fq_path('%s_5368709120' % hashed_1), fq_path(hashed_21), fq_path(hashed_22)] for act in active: self.assertIn(act, image_cache_manager.active_base_files) self.assertEqual(len(image_cache_manager.active_base_files), len(active)) for rem in [fq_path('e97222e91fc4241f49a7f520d1dcf446751129b3_sm'), fq_path('e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm'), fq_path(hashed_42), fq_path('%s_10737418240' % hashed_1)]: self.assertIn(rem, image_cache_manager.removable_base_files) # Ensure there are no "corrupt" images as well self.assertEqual(len(image_cache_manager.corrupt_base_files), 0) def test_verify_base_images_no_base(self): self.flags(instances_path='/tmp/no/such/dir/name/please') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.update(None, []) def test_is_valid_info_file(self): hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3' self.flags(instances_path='/tmp/no/such/dir/name/please') self.flags(image_info_filename_pattern=('$instances_path/_base/' '%(image)s.info'), group='libvirt') base_filename = os.path.join(CONF.instances_path, '_base', hashed) is_valid_info_file = imagecache.is_valid_info_file self.assertFalse(is_valid_info_file('banana')) self.assertFalse(is_valid_info_file( os.path.join(CONF.instances_path, '_base', '00000001'))) self.assertFalse(is_valid_info_file(base_filename)) self.assertFalse(is_valid_info_file(base_filename + '.sha1')) self.assertTrue(is_valid_info_file(base_filename + '.info')) def test_configured_checksum_path(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') # Ensure there is a base directory os.mkdir(os.path.join(tmpdir, '_base')) # Fake the database call which lists running instances instances = [{'image_ref': '1', 'host': CONF.host, 'name': 'instance-1', 'uuid': '123', 'vm_state': '', 'task_state': ''}, {'image_ref': '1', 'host': CONF.host, 'name': 'instance-2', 'uuid': '456', 'vm_state': '', 'task_state': ''}] all_instances = [] for instance in instances: all_instances.append(fake_instance.fake_instance_obj( None, **instance)) def touch(filename): f = open(filename, 'w') f.write('Touched') f.close() old = time.time() - (25 * 3600) hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3' base_filename = os.path.join(tmpdir, hashed) touch(base_filename) touch(base_filename + '.info') os.utime(base_filename + '.info', (old, old)) touch(base_filename + '.info') os.utime(base_filename + '.info', (old, old)) self.mox.StubOutWithMock( objects.block_device.BlockDeviceMappingList, 'get_by_instance_uuid') ctxt = context.get_admin_context() objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '123').AndReturn(None) objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '456').AndReturn(None) self.mox.ReplayAll() image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.update(ctxt, all_instances) self.assertTrue(os.path.exists(base_filename)) self.assertTrue(os.path.exists(base_filename + '.info')) def test_compute_manager(self): was = {'called': False} def fake_get_all_by_filters(context, *args, **kwargs): was['called'] = True instances = [] for x in range(2): instances.append(fake_instance.fake_db_instance( image_ref='1', uuid=x, name=x, vm_state='', task_state='')) return instances with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.stubs.Set(db, 'instance_get_all_by_filters', fake_get_all_by_filters) compute = importutils.import_object(CONF.compute_manager) self.flags(use_local=True, group='conductor') compute.conductor_api = conductor.API() compute._run_image_cache_manager_pass(None) self.assertTrue(was['called']) def test_store_swap_image(self): image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._store_swap_image('swap_') image_cache_manager._store_swap_image('swap_123') image_cache_manager._store_swap_image('swap_456') image_cache_manager._store_swap_image('swap_abc') image_cache_manager._store_swap_image('123_swap') image_cache_manager._store_swap_image('swap_129_') self.assertEqual(len(image_cache_manager.back_swap_images), 2) expect_set = set(['swap_123', 'swap_456']) self.assertEqual(image_cache_manager.back_swap_images, expect_set) @mock.patch.object(libvirt_utils, 'chown') @mock.patch('os.path.exists', return_value=True) @mock.patch('os.utime') @mock.patch('os.path.getmtime') @mock.patch('os.remove') def test_age_and_verify_swap_images(self, mock_remove, mock_getmtime, mock_utime, mock_exist, mock_chown): image_cache_manager = imagecache.ImageCacheManager() expected_remove = set() expected_exist = set(['swap_128', 'swap_256']) image_cache_manager.back_swap_images.add('swap_128') image_cache_manager.back_swap_images.add('swap_256') image_cache_manager.used_swap_images.add('swap_128') def getmtime(path): return time.time() - 1000000 mock_getmtime.side_effect = getmtime def removefile(path): if not path.startswith('/tmp_age_test'): return os.remove(path) fn = os.path.split(path)[-1] expected_remove.add(fn) expected_exist.remove(fn) mock_remove.side_effect = removefile image_cache_manager._age_and_verify_swap_images(None, '/tmp_age_test') self.assertEqual(1, len(expected_exist)) self.assertEqual(1, len(expected_remove)) self.assertIn('swap_128', expected_exist) self.assertIn('swap_256', expected_remove) class VerifyChecksumTestCase(test.NoDBTestCase): def setUp(self): super(VerifyChecksumTestCase, self).setUp() self.img = {'container_format': 'ami', 'id': '42'} self.flags(checksum_base_images=True, group='libvirt') def _make_checksum(self, tmpdir): testdata = ('OpenStack Software delivers a massively scalable cloud ' 'operating system.') fname = os.path.join(tmpdir, 'aaa') info_fname = imagecache.get_info_filename(fname) with open(fname, 'w') as f: f.write(testdata) return fname, info_fname, testdata def _write_file(self, info_fname, info_attr, testdata): f = open(info_fname, 'w') if info_attr == "csum valid": csum = hashlib.sha1() csum.update(testdata) f.write('{"sha1": "%s"}\n' % csum.hexdigest()) elif info_attr == "csum invalid, not json": f.write('banana') else: f.write('{"sha1": "banana"}') f.close() def _check_body(self, tmpdir, info_attr): self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname, info_fname, testdata = self._make_checksum(tmpdir) self._write_file(info_fname, info_attr, testdata) image_cache_manager = imagecache.ImageCacheManager() return image_cache_manager, fname def test_verify_checksum(self): with utils.tempdir() as tmpdir: image_cache_manager, fname = self._check_body(tmpdir, "csum valid") res = image_cache_manager._verify_checksum(self.img, fname) self.assertTrue(res) def test_verify_checksum_disabled(self): self.flags(checksum_base_images=False, group='libvirt') with utils.tempdir() as tmpdir: image_cache_manager, fname = self._check_body(tmpdir, "csum valid") res = image_cache_manager._verify_checksum(self.img, fname) self.assertIsNone(res) def test_verify_checksum_invalid_json(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, not json")) res = image_cache_manager._verify_checksum( self.img, fname, create_if_missing=False) self.assertFalse(res) log = stream.getvalue() # NOTE(mikal): this is a skip not a fail because the file is # present, but is not in valid json format and therefore is # skipped. self.assertNotEqual(log.find('image verification skipped'), -1) def test_verify_checksum_invalid_repaired(self): with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, not json")) res = image_cache_manager._verify_checksum( self.img, fname, create_if_missing=True) self.assertIsNone(res) def test_verify_checksum_invalid(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, valid json")) res = image_cache_manager._verify_checksum(self.img, fname) self.assertFalse(res) log = stream.getvalue() self.assertNotEqual(log.find('image verification failed'), -1) def test_verify_checksum_file_missing(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname, info_fname, testdata = self._make_checksum(tmpdir) image_cache_manager = imagecache.ImageCacheManager() res = image_cache_manager._verify_checksum('aaa', fname) self.assertIsNone(res) # Checksum requests for a file with no checksum now have the # side effect of creating the checksum self.assertTrue(os.path.exists(info_fname))
41.711
79
0.598068
import contextlib import hashlib import os import time import mock from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import formatters from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import importutils from six.moves import cStringIO from nova import conductor from nova import context from nova import db from nova import objects from nova import test from nova.tests.unit import fake_instance from nova import utils from nova.virt.libvirt import imagecache from nova.virt.libvirt import utils as libvirt_utils CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') CONF.import_opt('host', 'nova.netconf') @contextlib.contextmanager def intercept_log_messages(): try: mylog = logging.getLogger('nova') stream = cStringIO() handler = logging.logging.StreamHandler(stream) handler.setFormatter(formatters.ContextFormatter()) mylog.logger.addHandler(handler) yield stream finally: mylog.logger.removeHandler(handler) class ImageCacheManagerTestCase(test.NoDBTestCase): def setUp(self): super(ImageCacheManagerTestCase, self).setUp() self.stock_instance_names = set(['instance-00000001', 'instance-00000002', 'instance-00000003', 'banana-42-hamster']) def test_read_stored_checksum_missing(self): self.stubs.Set(os.path, 'exists', lambda x: False) csum = imagecache.read_stored_checksum('/tmp/foo', timestamped=False) self.assertIsNone(csum) @mock.patch.object(os.path, 'exists', return_value=True) @mock.patch.object(time, 'time', return_value=2000000) @mock.patch.object(os.path, 'getmtime', return_value=1000000) def test_get_age_of_file(self, mock_getmtime, mock_time, mock_exists): image_cache_manager = imagecache.ImageCacheManager() exists, age = image_cache_manager._get_age_of_file('/tmp') self.assertTrue(exists) self.assertEqual(1000000, age) @mock.patch.object(os.path, 'exists', return_value=False) def test_get_age_of_file_not_exists(self, mock_exists): image_cache_manager = imagecache.ImageCacheManager() exists, age = image_cache_manager._get_age_of_file('/tmp') self.assertFalse(exists) self.assertEqual(0, age) def test_read_stored_checksum(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') csum_input = '{"sha1": "fdghkfhkgjjksfdgjksjkghsdf"}\n' fname = os.path.join(tmpdir, 'aaa') info_fname = imagecache.get_info_filename(fname) f = open(info_fname, 'w') f.write(csum_input) f.close() csum_output = imagecache.read_stored_checksum(fname, timestamped=False) self.assertEqual(csum_input.rstrip(), '{"sha1": "%s"}' % csum_output) def test_read_stored_checksum_legacy_essex(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') old_fname = fname + '.sha1' f = open(old_fname, 'w') f.write('fdghkfhkgjjksfdgjksjkghsdf') f.close() csum_output = imagecache.read_stored_checksum(fname, timestamped=False) self.assertEqual(csum_output, 'fdghkfhkgjjksfdgjksjkghsdf') self.assertFalse(os.path.exists(old_fname)) info_fname = imagecache.get_info_filename(fname) self.assertTrue(os.path.exists(info_fname)) def test_list_base_images(self): listing = ['00000001', 'ephemeral_0_20_None', '17d1b00b81642842e514494a78e804e9a511637c_5368709120.info', '00000004', 'swap_1000'] images = ['e97222e91fc4241f49a7f520d1dcf446751129b3_sm', 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm', 'e97222e91fc4241f49a7f520d1dcf446751129b3', '17d1b00b81642842e514494a78e804e9a511637c', '17d1b00b81642842e514494a78e804e9a511637c_5368709120', '17d1b00b81642842e514494a78e804e9a511637c_10737418240'] listing.extend(images) self.stubs.Set(os, 'listdir', lambda x: listing) self.stubs.Set(os.path, 'isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' self.flags(instances_path='/var/lib/nova/instances') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) sanitized = [] for ent in image_cache_manager.unexplained_images: sanitized.append(ent.replace(base_dir + '/', '')) self.assertEqual(sorted(sanitized), sorted(images)) expected = os.path.join(base_dir, 'e97222e91fc4241f49a7f520d1dcf446751129b3') self.assertIn(expected, image_cache_manager.unexplained_images) expected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c_' '10737418240') self.assertIn(expected, image_cache_manager.unexplained_images) unexpected = os.path.join(base_dir, '00000004') self.assertNotIn(unexpected, image_cache_manager.unexplained_images) for ent in image_cache_manager.unexplained_images: self.assertTrue(ent.startswith(base_dir)) self.assertEqual(len(image_cache_manager.originals), 2) expected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c') self.assertIn(expected, image_cache_manager.originals) unexpected = os.path.join(base_dir, '17d1b00b81642842e514494a78e804e9a511637c_' '10737418240') self.assertNotIn(unexpected, image_cache_manager.originals) self.assertEqual(1, len(image_cache_manager.back_swap_images)) self.assertIn('swap_1000', image_cache_manager.back_swap_images) def test_list_backing_images_small(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'instance-00000001', 'instance-00000002', 'instance-00000003']) self.stubs.Set(os.path, 'exists', lambda x: x.find('instance-') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_resized(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'instance-00000001', 'instance-00000002', 'instance-00000003']) self.stubs.Set(os.path, 'exists', lambda x: x.find('instance-') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: ('e97222e91fc4241f49a7f520d1dcf446751129b3_' '10737418240')) found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_' '10737418240') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_instancename(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'banana-42-hamster']) self.stubs.Set(os.path, 'exists', lambda x: x.find('banana-42-hamster') != -1) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') found = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name, 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEqual(inuse_images, [found]) self.assertEqual(len(image_cache_manager.unexplained_images), 0) def test_list_backing_images_disk_notexist(self): self.stubs.Set(os, 'listdir', lambda x: ['_base', 'banana-42-hamster']) self.stubs.Set(os.path, 'exists', lambda x: x.find('banana-42-hamster') != -1) def fake_get_disk(disk_path): raise processutils.ProcessExecutionError() self.stubs.Set(libvirt_utils, 'get_disk_backing_file', fake_get_disk) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [] image_cache_manager.instance_names = self.stock_instance_names self.assertRaises(processutils.ProcessExecutionError, image_cache_manager._list_backing_images) def test_find_base_file_nothing(self): self.stubs.Set(os.path, 'exists', lambda x: False) base_dir = '/var/lib/nova/instances/_base' fingerprint = '549867354867' image_cache_manager = imagecache.ImageCacheManager() res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) self.assertEqual(0, len(res)) def test_find_base_file_small(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' self.stubs.Set(os.path, 'exists', lambda x: x.endswith('%s_sm' % fingerprint)) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file = os.path.join(base_dir, fingerprint + '_sm') self.assertEqual(res, [(base_file, True, False)]) def test_find_base_file_resized(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' listing = ['00000001', 'ephemeral_0_20_None', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240', '00000004'] self.stubs.Set(os, 'listdir', lambda x: listing) self.stubs.Set(os.path, 'exists', lambda x: x.endswith('%s_10737418240' % fingerprint)) self.stubs.Set(os.path, 'isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file = os.path.join(base_dir, fingerprint + '_10737418240') self.assertEqual(res, [(base_file, False, True)]) def test_find_base_file_all(self): fingerprint = '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a' listing = ['00000001', 'ephemeral_0_20_None', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_sm', '968dd6cc49e01aaa044ed11c0cce733e0fa44a6a_10737418240', '00000004'] self.stubs.Set(os, 'listdir', lambda x: listing) self.stubs.Set(os.path, 'exists', lambda x: True) self.stubs.Set(os.path, 'isfile', lambda x: True) base_dir = '/var/lib/nova/instances/_base' image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._list_base_images(base_dir) res = list(image_cache_manager._find_base_file(base_dir, fingerprint)) base_file1 = os.path.join(base_dir, fingerprint) base_file2 = os.path.join(base_dir, fingerprint + '_sm') base_file3 = os.path.join(base_dir, fingerprint + '_10737418240') self.assertEqual(res, [(base_file1, False, False), (base_file2, True, False), (base_file3, False, True)]) @contextlib.contextmanager def _make_base_file(self, checksum=True, lock=True): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') base_file = open(fname, 'w') base_file.write('data') base_file.close() if lock: lockdir = os.path.join(tmpdir, 'locks') lockname = os.path.join(lockdir, 'nova-aaa') os.mkdir(lockdir) lock_file = open(lockname, 'w') lock_file.write('data') lock_file.close() base_file = open(fname, 'r') if checksum: imagecache.write_stored_checksum(fname) base_file.close() yield fname def test_remove_base_file(self): with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) info_fname = imagecache.get_info_filename(fname) lock_name = 'nova-' + os.path.split(fname)[-1] lock_dir = os.path.join(CONF.instances_path, 'locks') lock_file = os.path.join(lock_dir, lock_name) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) self.assertTrue(os.path.exists(lock_file)) os.utime(fname, (-1, time.time() - 3601)) image_cache_manager._remove_base_file(fname) self.assertFalse(os.path.exists(fname)) self.assertFalse(os.path.exists(info_fname)) self.assertFalse(os.path.exists(lock_file)) def test_remove_base_file_original(self): with self._make_base_file() as fname: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.originals = [fname] image_cache_manager._remove_base_file(fname) info_fname = imagecache.get_info_filename(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) os.utime(fname, (-1, time.time() - 3601)) image_cache_manager._remove_base_file(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(info_fname)) os.utime(fname, (-1, time.time() - 3600 * 25)) image_cache_manager._remove_base_file(fname) self.assertFalse(os.path.exists(fname)) self.assertFalse(os.path.exists(info_fname)) def test_remove_base_file_dne(self): # This test is solely to execute the "does not exist" code path. We # don't expect the method being tested to do anything in this case. with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) def test_remove_base_file_oserror(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') os.mkdir(fname) os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._remove_base_file(fname) self.assertTrue(os.path.exists(fname)) self.assertNotEqual(stream.getvalue().find('Failed to remove'), -1) def test_handle_base_image_unused(self): img = '123' with self._make_base_file() as fname: os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, [fname]) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_used(self): self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) img = '123' with self._make_base_file() as fname: os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_used_remotely(self): self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) img = '123' with self._make_base_file() as fname: os.utime(fname, (-1, time.time() - 3601)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (0, 1, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_absent(self): img = '123' with intercept_log_messages() as stream: image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, None) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) self.assertNotEqual(stream.getvalue().find('an absent base file'), -1) def test_handle_base_image_used_missing(self): img = '123' with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname = os.path.join(tmpdir, 'aaa') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, []) def test_handle_base_image_checksum_fails(self): self.flags(checksum_base_images=True, group='libvirt') self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) img = '123' with self._make_base_file() as fname: with open(fname, 'w') as f: f.write('banana') d = {'sha1': '21323454'} with open('%s.info' % fname, 'w') as f: f.write(jsonutils.dumps(d)) image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [fname] image_cache_manager.used_images = {'123': (1, 0, ['banana-42'])} image_cache_manager._handle_base_image(img, fname) self.assertEqual(image_cache_manager.unexplained_images, []) self.assertEqual(image_cache_manager.removable_base_files, []) self.assertEqual(image_cache_manager.corrupt_base_files, [fname]) def test_verify_base_images(self): hashed_1 = '356a192b7913b04c54574d18c28d46e6395428ab' hashed_21 = '472b07b9fcf2c2451e8781e944bf5f77cd8457c8' hashed_22 = '12c6fc06c99a462375eeb3f43dfd832b08ca9e17' hashed_42 = '92cfceb39d57d914ed8b14d0e37643de0797ae56' self.flags(instances_path='/instance_path', image_cache_subdirectory_name='_base') base_file_list = ['00000001', 'ephemeral_0_20_None', 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm', 'e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm', hashed_42, hashed_1, hashed_21, hashed_22, '%s_5368709120' % hashed_1, '%s_10737418240' % hashed_1, '00000004'] def fq_path(path): return os.path.join('/instance_path/_base/', path) orig_exists = os.path.exists def exists(path): if not path.startswith('/instance_path'): return orig_exists(path) if path in ['/instance_path', '/instance_path/_base', '/instance_path/instance-1/disk', '/instance_path/instance-2/disk', '/instance_path/instance-3/disk', '/instance_path/_base/%s.info' % hashed_42]: return True for p in base_file_list: if path == fq_path(p): return True if path == fq_path(p) + '.info': return False if path in ['/instance_path/_base/%s_sm' % i for i in [hashed_1, hashed_21, hashed_22, hashed_42]]: return False self.fail('Unexpected path existence check: %s' % path) self.stubs.Set(os.path, 'exists', lambda x: exists(x)) self.stubs.Set(libvirt_utils, 'chown', lambda x, y: None) self.stubs.Set(os, 'utime', lambda x, y: None) orig_listdir = os.listdir def listdir(path): if not path.startswith('/instance_path'): return orig_listdir(path) if path == '/instance_path': return ['instance-1', 'instance-2', 'instance-3', '_base'] if path == '/instance_path/_base': return base_file_list self.fail('Unexpected directory listed: %s' % path) self.stubs.Set(os, 'listdir', lambda x: listdir(x)) orig_isfile = os.path.isfile def isfile(path): if not path.startswith('/instance_path'): return orig_isfile(path) for p in base_file_list: if path == fq_path(p): return True self.fail('Unexpected isfile call: %s' % path) self.stubs.Set(os.path, 'isfile', lambda x: isfile(x)) instances = [{'image_ref': '1', 'host': CONF.host, 'name': 'instance-1', 'uuid': '123', 'vm_state': '', 'task_state': ''}, {'image_ref': '1', 'kernel_id': '21', 'ramdisk_id': '22', 'host': CONF.host, 'name': 'instance-2', 'uuid': '456', 'vm_state': '', 'task_state': ''}] all_instances = [fake_instance.fake_instance_obj(None, **instance) for instance in instances] image_cache_manager = imagecache.ImageCacheManager() def get_disk_backing_file(path): if path in ['/instance_path/instance-1/disk', '/instance_path/instance-2/disk']: return fq_path('%s_5368709120' % hashed_1) self.fail('Unexpected backing file lookup: %s' % path) self.stubs.Set(libvirt_utils, 'get_disk_backing_file', lambda x: get_disk_backing_file(x)) self.stubs.Set(image_cache_manager, '_verify_checksum', lambda x, y: True) orig_getmtime = os.path.getmtime def getmtime(path): if not path.startswith('/instance_path'): return orig_getmtime(path) return 1000000 self.stubs.Set(os.path, 'getmtime', lambda x: getmtime(x)) orig_remove = os.remove def remove(path): if not path.startswith('/instance_path'): return orig_remove(path) # Don't try to remove fake files return self.stubs.Set(os, 'remove', lambda x: remove(x)) self.mox.StubOutWithMock(objects.block_device.BlockDeviceMappingList, 'get_by_instance_uuid') ctxt = context.get_admin_context() objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '123').AndReturn(None) objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '456').AndReturn(None) self.mox.ReplayAll() # The argument here should be a context, but it is mocked out image_cache_manager.update(ctxt, all_instances) # Verify active = [fq_path(hashed_1), fq_path('%s_5368709120' % hashed_1), fq_path(hashed_21), fq_path(hashed_22)] for act in active: self.assertIn(act, image_cache_manager.active_base_files) self.assertEqual(len(image_cache_manager.active_base_files), len(active)) for rem in [fq_path('e97222e91fc4241f49a7f520d1dcf446751129b3_sm'), fq_path('e09c675c2d1cfac32dae3c2d83689c8c94bc693b_sm'), fq_path(hashed_42), fq_path('%s_10737418240' % hashed_1)]: self.assertIn(rem, image_cache_manager.removable_base_files) # Ensure there are no "corrupt" images as well self.assertEqual(len(image_cache_manager.corrupt_base_files), 0) def test_verify_base_images_no_base(self): self.flags(instances_path='/tmp/no/such/dir/name/please') image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.update(None, []) def test_is_valid_info_file(self): hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3' self.flags(instances_path='/tmp/no/such/dir/name/please') self.flags(image_info_filename_pattern=('$instances_path/_base/' '%(image)s.info'), group='libvirt') base_filename = os.path.join(CONF.instances_path, '_base', hashed) is_valid_info_file = imagecache.is_valid_info_file self.assertFalse(is_valid_info_file('banana')) self.assertFalse(is_valid_info_file( os.path.join(CONF.instances_path, '_base', '00000001'))) self.assertFalse(is_valid_info_file(base_filename)) self.assertFalse(is_valid_info_file(base_filename + '.sha1')) self.assertTrue(is_valid_info_file(base_filename + '.info')) def test_configured_checksum_path(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') # Ensure there is a base directory os.mkdir(os.path.join(tmpdir, '_base')) # Fake the database call which lists running instances instances = [{'image_ref': '1', 'host': CONF.host, 'name': 'instance-1', 'uuid': '123', 'vm_state': '', 'task_state': ''}, {'image_ref': '1', 'host': CONF.host, 'name': 'instance-2', 'uuid': '456', 'vm_state': '', 'task_state': ''}] all_instances = [] for instance in instances: all_instances.append(fake_instance.fake_instance_obj( None, **instance)) def touch(filename): f = open(filename, 'w') f.write('Touched') f.close() old = time.time() - (25 * 3600) hashed = 'e97222e91fc4241f49a7f520d1dcf446751129b3' base_filename = os.path.join(tmpdir, hashed) touch(base_filename) touch(base_filename + '.info') os.utime(base_filename + '.info', (old, old)) touch(base_filename + '.info') os.utime(base_filename + '.info', (old, old)) self.mox.StubOutWithMock( objects.block_device.BlockDeviceMappingList, 'get_by_instance_uuid') ctxt = context.get_admin_context() objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '123').AndReturn(None) objects.block_device.BlockDeviceMappingList.get_by_instance_uuid( ctxt, '456').AndReturn(None) self.mox.ReplayAll() image_cache_manager = imagecache.ImageCacheManager() image_cache_manager.update(ctxt, all_instances) self.assertTrue(os.path.exists(base_filename)) self.assertTrue(os.path.exists(base_filename + '.info')) def test_compute_manager(self): was = {'called': False} def fake_get_all_by_filters(context, *args, **kwargs): was['called'] = True instances = [] for x in range(2): instances.append(fake_instance.fake_db_instance( image_ref='1', uuid=x, name=x, vm_state='', task_state='')) return instances with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.stubs.Set(db, 'instance_get_all_by_filters', fake_get_all_by_filters) compute = importutils.import_object(CONF.compute_manager) self.flags(use_local=True, group='conductor') compute.conductor_api = conductor.API() compute._run_image_cache_manager_pass(None) self.assertTrue(was['called']) def test_store_swap_image(self): image_cache_manager = imagecache.ImageCacheManager() image_cache_manager._store_swap_image('swap_') image_cache_manager._store_swap_image('swap_123') image_cache_manager._store_swap_image('swap_456') image_cache_manager._store_swap_image('swap_abc') image_cache_manager._store_swap_image('123_swap') image_cache_manager._store_swap_image('swap_129_') self.assertEqual(len(image_cache_manager.back_swap_images), 2) expect_set = set(['swap_123', 'swap_456']) self.assertEqual(image_cache_manager.back_swap_images, expect_set) @mock.patch.object(libvirt_utils, 'chown') @mock.patch('os.path.exists', return_value=True) @mock.patch('os.utime') @mock.patch('os.path.getmtime') @mock.patch('os.remove') def test_age_and_verify_swap_images(self, mock_remove, mock_getmtime, mock_utime, mock_exist, mock_chown): image_cache_manager = imagecache.ImageCacheManager() expected_remove = set() expected_exist = set(['swap_128', 'swap_256']) image_cache_manager.back_swap_images.add('swap_128') image_cache_manager.back_swap_images.add('swap_256') image_cache_manager.used_swap_images.add('swap_128') def getmtime(path): return time.time() - 1000000 mock_getmtime.side_effect = getmtime def removefile(path): if not path.startswith('/tmp_age_test'): return os.remove(path) fn = os.path.split(path)[-1] expected_remove.add(fn) expected_exist.remove(fn) mock_remove.side_effect = removefile image_cache_manager._age_and_verify_swap_images(None, '/tmp_age_test') self.assertEqual(1, len(expected_exist)) self.assertEqual(1, len(expected_remove)) self.assertIn('swap_128', expected_exist) self.assertIn('swap_256', expected_remove) class VerifyChecksumTestCase(test.NoDBTestCase): def setUp(self): super(VerifyChecksumTestCase, self).setUp() self.img = {'container_format': 'ami', 'id': '42'} self.flags(checksum_base_images=True, group='libvirt') def _make_checksum(self, tmpdir): testdata = ('OpenStack Software delivers a massively scalable cloud ' 'operating system.') fname = os.path.join(tmpdir, 'aaa') info_fname = imagecache.get_info_filename(fname) with open(fname, 'w') as f: f.write(testdata) return fname, info_fname, testdata def _write_file(self, info_fname, info_attr, testdata): f = open(info_fname, 'w') if info_attr == "csum valid": csum = hashlib.sha1() csum.update(testdata) f.write('{"sha1": "%s"}\n' % csum.hexdigest()) elif info_attr == "csum invalid, not json": f.write('banana') else: f.write('{"sha1": "banana"}') f.close() def _check_body(self, tmpdir, info_attr): self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname, info_fname, testdata = self._make_checksum(tmpdir) self._write_file(info_fname, info_attr, testdata) image_cache_manager = imagecache.ImageCacheManager() return image_cache_manager, fname def test_verify_checksum(self): with utils.tempdir() as tmpdir: image_cache_manager, fname = self._check_body(tmpdir, "csum valid") res = image_cache_manager._verify_checksum(self.img, fname) self.assertTrue(res) def test_verify_checksum_disabled(self): self.flags(checksum_base_images=False, group='libvirt') with utils.tempdir() as tmpdir: image_cache_manager, fname = self._check_body(tmpdir, "csum valid") res = image_cache_manager._verify_checksum(self.img, fname) self.assertIsNone(res) def test_verify_checksum_invalid_json(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, not json")) res = image_cache_manager._verify_checksum( self.img, fname, create_if_missing=False) self.assertFalse(res) log = stream.getvalue() # NOTE(mikal): this is a skip not a fail because the file is # present, but is not in valid json format and therefore is # skipped. self.assertNotEqual(log.find('image verification skipped'), -1) def test_verify_checksum_invalid_repaired(self): with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, not json")) res = image_cache_manager._verify_checksum( self.img, fname, create_if_missing=True) self.assertIsNone(res) def test_verify_checksum_invalid(self): with intercept_log_messages() as stream: with utils.tempdir() as tmpdir: image_cache_manager, fname = ( self._check_body(tmpdir, "csum invalid, valid json")) res = image_cache_manager._verify_checksum(self.img, fname) self.assertFalse(res) log = stream.getvalue() self.assertNotEqual(log.find('image verification failed'), -1) def test_verify_checksum_file_missing(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) self.flags(image_info_filename_pattern=('$instances_path/' '%(image)s.info'), group='libvirt') fname, info_fname, testdata = self._make_checksum(tmpdir) image_cache_manager = imagecache.ImageCacheManager() res = image_cache_manager._verify_checksum('aaa', fname) self.assertIsNone(res) # Checksum requests for a file with no checksum now have the # side effect of creating the checksum self.assertTrue(os.path.exists(info_fname))
true
true
1c39c1888e907fdbe3085235d0ac84a0ebe35965
497
py
Python
basicdevice/migrations/0002_status.py
dave-promulgare/Affinidi-Device
5eb9ff08eed652066e102dd49aa9cb3c2d70fdbe
[ "Apache-2.0" ]
1
2021-02-10T23:50:41.000Z
2021-02-10T23:50:41.000Z
basicdevice/migrations/0002_status.py
dave-promulgare/Affinidi-Device
5eb9ff08eed652066e102dd49aa9cb3c2d70fdbe
[ "Apache-2.0" ]
null
null
null
basicdevice/migrations/0002_status.py
dave-promulgare/Affinidi-Device
5eb9ff08eed652066e102dd49aa9cb3c2d70fdbe
[ "Apache-2.0" ]
null
null
null
# Generated by Django 2.2.10 on 2021-02-02 21:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basicdevice', '0001_initial'), ] operations = [ migrations.CreateModel( name='Status', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('current', models.TextField()), ], ), ]
23.666667
114
0.567404
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basicdevice', '0001_initial'), ] operations = [ migrations.CreateModel( name='Status', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('current', models.TextField()), ], ), ]
true
true
1c39c36a39a1532ef2f99ac92d06f1d1552bc659
742
py
Python
alipay/aop/api/response/AlipayMerchantItemFileUploadResponse.py
snowxmas/alipay-sdk-python-all
96870ced60facd96c5bce18d19371720cbda3317
[ "Apache-2.0" ]
1
2022-03-07T06:11:10.000Z
2022-03-07T06:11:10.000Z
alipay/aop/api/response/AlipayMerchantItemFileUploadResponse.py
snowxmas/alipay-sdk-python-all
96870ced60facd96c5bce18d19371720cbda3317
[ "Apache-2.0" ]
null
null
null
alipay/aop/api/response/AlipayMerchantItemFileUploadResponse.py
snowxmas/alipay-sdk-python-all
96870ced60facd96c5bce18d19371720cbda3317
[ "Apache-2.0" ]
1
2021-10-05T03:01:09.000Z
2021-10-05T03:01:09.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayMerchantItemFileUploadResponse(AlipayResponse): def __init__(self): super(AlipayMerchantItemFileUploadResponse, self).__init__() self._material_id = None @property def material_id(self): return self._material_id @material_id.setter def material_id(self, value): self._material_id = value def parse_response_content(self, response_content): response = super(AlipayMerchantItemFileUploadResponse, self).parse_response_content(response_content) if 'material_id' in response: self.material_id = response['material_id']
28.538462
109
0.725067
import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class AlipayMerchantItemFileUploadResponse(AlipayResponse): def __init__(self): super(AlipayMerchantItemFileUploadResponse, self).__init__() self._material_id = None @property def material_id(self): return self._material_id @material_id.setter def material_id(self, value): self._material_id = value def parse_response_content(self, response_content): response = super(AlipayMerchantItemFileUploadResponse, self).parse_response_content(response_content) if 'material_id' in response: self.material_id = response['material_id']
true
true
1c39c3b659c75e1d8cfc2b2b467ce2ec26bdd183
1,671
py
Python
UpdateOpencv2.0/AllDetection2.0.py
sujitmandal/python
9fbb1e5f58f9ff173874941dd2adb868088bf67a
[ "MIT" ]
1
2019-04-10T15:43:16.000Z
2019-04-10T15:43:16.000Z
UpdateOpencv2.0/AllDetection2.0.py
sujitmandal/python
9fbb1e5f58f9ff173874941dd2adb868088bf67a
[ "MIT" ]
null
null
null
UpdateOpencv2.0/AllDetection2.0.py
sujitmandal/python
9fbb1e5f58f9ff173874941dd2adb868088bf67a
[ "MIT" ]
null
null
null
import cv2 #Github: https://github.com/sujitmandal #This programe is create by Sujit Mandal """ Github: https://github.com/sujitmandal This programe is create by Sujit Mandal LinkedIn : https://www.linkedin.com/in/sujit-mandal-91215013a/ Facebook : https://www.facebook.com/sujit.mandal.33671748 Twitter : https://twitter.com/mandalsujit37 """ face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye = cv2.CascadeClassifier('haarcascade_eye.xml') video = cv2.VideoCapture(0) first_frame = None while True: check, frame = video.read() print(frame) faces = face.detectMultiScale(frame) eyes = eye.detectMultiScale(frame) for (x, y, w, h) in faces: cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 3) for (x, y, w, h) in eyes: cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 3) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) if first_frame is None: first_frame = gray continue diff_frame = cv2.absdiff(first_frame, gray) thresh_frame = cv2.threshold(diff_frame, 30, 255, cv2.THRESH_BINARY)[1] thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2) cnts, _ = cv2.findContours(thresh_frame.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for motion in cnts: if cv2.contourArea(motion) < 10000: continue (x, y, w, h) = cv2.boundingRect(motion) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 3) cv2.imshow("Frame", frame) key = cv2.waitKey(1) if key == ord('q'): break video.release() cv2.destroyAllWindows()
27.85
94
0.64991
import cv2 face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye = cv2.CascadeClassifier('haarcascade_eye.xml') video = cv2.VideoCapture(0) first_frame = None while True: check, frame = video.read() print(frame) faces = face.detectMultiScale(frame) eyes = eye.detectMultiScale(frame) for (x, y, w, h) in faces: cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 3) for (x, y, w, h) in eyes: cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 3) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (21, 21), 0) if first_frame is None: first_frame = gray continue diff_frame = cv2.absdiff(first_frame, gray) thresh_frame = cv2.threshold(diff_frame, 30, 255, cv2.THRESH_BINARY)[1] thresh_frame = cv2.dilate(thresh_frame, None, iterations = 2) cnts, _ = cv2.findContours(thresh_frame.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for motion in cnts: if cv2.contourArea(motion) < 10000: continue (x, y, w, h) = cv2.boundingRect(motion) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 3) cv2.imshow("Frame", frame) key = cv2.waitKey(1) if key == ord('q'): break video.release() cv2.destroyAllWindows()
true
true
1c39c3dc873b6363195497dd6c13bdd0aecff7cd
1,248
py
Python
src/versioningit/hook.py
jenshnielsen/versioningit
b575e300ae2ea78e283254537cffd30135ae7fe6
[ "MIT" ]
17
2021-07-05T23:41:36.000Z
2022-03-10T14:55:24.000Z
src/versioningit/hook.py
jenshnielsen/versioningit
b575e300ae2ea78e283254537cffd30135ae7fe6
[ "MIT" ]
20
2021-07-05T23:56:09.000Z
2022-03-14T13:04:09.000Z
src/versioningit/hook.py
jenshnielsen/versioningit
b575e300ae2ea78e283254537cffd30135ae7fe6
[ "MIT" ]
4
2021-09-04T13:24:49.000Z
2022-03-25T19:44:19.000Z
from pathlib import Path from typing import Any from .core import get_version from .errors import NoTagError, NotSdistError, NotVersioningitError from .logging import init_logging, log def setuptools_finalizer(dist: Any) -> None: """ The entry point called by setuptools to retrieve the version for a project """ init_logging() # PEP 517 says that "All hooks are run with working directory set to the # root of the source tree". PROJECT_ROOT = Path().resolve() log.info("Project dir: %s", PROJECT_ROOT) try: version = get_version(PROJECT_ROOT, write=True, fallback=True) except NotVersioningitError: log.info("versioningit not enabled in pyproject.toml; doing nothing") return except (NotSdistError, NoTagError): raise RuntimeError( "\nversioningit could not find a version for the project in" f" {PROJECT_ROOT}!\n\n" "You may be installing from a shallow clone, in which case you" " need to unshallow it first.\n\n" "Alternatively, you may be installing from a Git archive, which is" " not supported. Install from a git+https://... URL instead.\n\n" ) dist.metadata.version = version
39
79
0.672276
from pathlib import Path from typing import Any from .core import get_version from .errors import NoTagError, NotSdistError, NotVersioningitError from .logging import init_logging, log def setuptools_finalizer(dist: Any) -> None: init_logging() # root of the source tree". PROJECT_ROOT = Path().resolve() log.info("Project dir: %s", PROJECT_ROOT) try: version = get_version(PROJECT_ROOT, write=True, fallback=True) except NotVersioningitError: log.info("versioningit not enabled in pyproject.toml; doing nothing") return except (NotSdistError, NoTagError): raise RuntimeError( "\nversioningit could not find a version for the project in" f" {PROJECT_ROOT}!\n\n" "You may be installing from a shallow clone, in which case you" " need to unshallow it first.\n\n" "Alternatively, you may be installing from a Git archive, which is" " not supported. Install from a git+https://... URL instead.\n\n" ) dist.metadata.version = version
true
true
1c39c3e0a5de09df35a959cf57d62098a5fe12c1
1,971
py
Python
backend/project/migrations/0001_initial.py
Tim6FTN/UKS
3cf19f014cdc7845bf0b808b97c4e05dc49b062e
[ "MIT" ]
1
2021-01-10T12:34:59.000Z
2021-01-10T12:34:59.000Z
backend/project/migrations/0001_initial.py
Tim6FTN/UKS
3cf19f014cdc7845bf0b808b97c4e05dc49b062e
[ "MIT" ]
37
2021-01-07T22:31:25.000Z
2021-02-20T10:59:46.000Z
backend/project/migrations/0001_initial.py
Tim6FTN/UKS
3cf19f014cdc7845bf0b808b97c4e05dc49b062e
[ "MIT" ]
null
null
null
# Generated by Django 3.1.5 on 2021-02-20 09:18 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('repository', '0001_initial'), ] operations = [ migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('description', models.TextField(blank=True, default='')), ('is_public', models.BooleanField(default=True)), ('wiki_content', models.TextField(default='')), ('collaborators', models.ManyToManyField(blank=True, related_name='collaborators', to=settings.AUTH_USER_MODEL)), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='owner', to=settings.AUTH_USER_MODEL)), ('repository', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='repository.repository')), ('stars', models.ManyToManyField(blank=True, related_name='stars', to=settings.AUTH_USER_MODEL)), ], options={ 'unique_together': {('name', 'owner')}, }, ), migrations.CreateModel( name='Invite', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='project', to='project.project')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)), ], ), ]
44.795455
141
0.621005
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('repository', '0001_initial'), ] operations = [ migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('description', models.TextField(blank=True, default='')), ('is_public', models.BooleanField(default=True)), ('wiki_content', models.TextField(default='')), ('collaborators', models.ManyToManyField(blank=True, related_name='collaborators', to=settings.AUTH_USER_MODEL)), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='owner', to=settings.AUTH_USER_MODEL)), ('repository', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='repository.repository')), ('stars', models.ManyToManyField(blank=True, related_name='stars', to=settings.AUTH_USER_MODEL)), ], options={ 'unique_together': {('name', 'owner')}, }, ), migrations.CreateModel( name='Invite', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='project', to='project.project')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user', to=settings.AUTH_USER_MODEL)), ], ), ]
true
true
1c39c4ad5cb383418629f41da5cebcb5e997f379
2,987
py
Python
iqs_client/models/undefined_object.py
thomas-bc/mms-autocref
1db6697f929a1c782c902923209389e337ec6961
[ "Apache-2.0" ]
null
null
null
iqs_client/models/undefined_object.py
thomas-bc/mms-autocref
1db6697f929a1c782c902923209389e337ec6961
[ "Apache-2.0" ]
null
null
null
iqs_client/models/undefined_object.py
thomas-bc/mms-autocref
1db6697f929a1c782c902923209389e337ec6961
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ IncQuery Server No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 OpenAPI spec version: 0.12.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six class UndefinedObject(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'unknown': 'str' } attribute_map = { 'unknown': 'unknown' } def __init__(self, unknown=None): # noqa: E501 """UndefinedObject - a model defined in OpenAPI""" # noqa: E501 self._unknown = None self.discriminator = None if unknown is not None: self.unknown = unknown @property def unknown(self): """Gets the unknown of this UndefinedObject. # noqa: E501 :return: The unknown of this UndefinedObject. # noqa: E501 :rtype: str """ return self._unknown @unknown.setter def unknown(self, unknown): """Sets the unknown of this UndefinedObject. :param unknown: The unknown of this UndefinedObject. # noqa: E501 :type: str """ self._unknown = unknown def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, UndefinedObject): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
26.433628
124
0.559759
import pprint import re import six class UndefinedObject(object): openapi_types = { 'unknown': 'str' } attribute_map = { 'unknown': 'unknown' } def __init__(self, unknown=None): self._unknown = None self.discriminator = None if unknown is not None: self.unknown = unknown @property def unknown(self): return self._unknown @unknown.setter def unknown(self, unknown): self._unknown = unknown def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, UndefinedObject): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c39c6279e33098e6f563ad838b96d7935544f4f
15,416
py
Python
tests/helpers/test_dict.py
Centaurioun/PyFunceble
59b809f3322118f7824195752c6015220738d4a0
[ "Apache-2.0" ]
null
null
null
tests/helpers/test_dict.py
Centaurioun/PyFunceble
59b809f3322118f7824195752c6015220738d4a0
[ "Apache-2.0" ]
null
null
null
tests/helpers/test_dict.py
Centaurioun/PyFunceble
59b809f3322118f7824195752c6015220738d4a0
[ "Apache-2.0" ]
null
null
null
""" The tool to check the availability or syntax of domain, IP or URL. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔════╝ ██████╔╝ ╚████╔╝ █████╗ ██║ ██║██╔██╗ ██║██║ █████╗ ██████╔╝██║ █████╗ ██╔═══╝ ╚██╔╝ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██╔══╝ ██╔══██╗██║ ██╔══╝ ██║ ██║ ██║ ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝ Tests of our dictionnary helper. Author: Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom Special thanks: https://pyfunceble.github.io/special-thanks.html Contributors: https://pyfunceble.github.io/contributors.html Project link: https://github.com/funilrys/PyFunceble Project documentation: https://pyfunceble.readthedocs.io/en/dev/ Project homepage: https://pyfunceble.github.io/ License: :: Copyright 2017, 2018, 2019, 2020, 2021, 2021 Nissar Chababy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import copy import os import tempfile import unittest from PyFunceble.helpers.dict import DictHelper class TestDictHelper(unittest.TestCase): """ Provides the test of our dictionnary helper. """ def setUp(self) -> None: """ Setups everything needed for the tests. """ self.test_subject = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], } self.helper = DictHelper() def tearDown(self) -> None: """ Destroy everything needed by the tests. """ del self.test_subject del self.helper def test_set_subject_return(self) -> None: """ Tests the response from the method which let us set the subject to work with. """ actual = self.helper.set_subject(self.test_subject) self.assertIsInstance(actual, DictHelper) def test_set_subject_method(self) -> None: """ Tests the method which let us set the subject to work with. """ given = self.test_subject expected = dict(self.test_subject) self.helper.set_subject(given) actual = self.helper.subject self.assertEqual(expected, actual) def test_set_subject_attribute(self) -> None: """ Tests overwritting of the :code:`subject` attribute. """ given = self.test_subject expected = dict(self.test_subject) self.helper.subject = given actual = self.helper.subject self.assertEqual(expected, actual) def test_set_subject_through_init(self) -> None: """ Tests the overwritting of the subject to work through the class constructor. """ given = self.test_subject expected = dict(self.test_subject) helper = DictHelper(given) actual = helper.subject self.assertEqual(expected, actual) def test_has_same_key_as(self) -> None: """ Tests the method which let us know if the keys of 2 dicts are the same. """ origin = {"a": 1, "b": 1} target = {"a": 1, "b": 2, "c": {"a": 1, "b": 3, "c": {"x": "x"}}} expected = True actual = self.helper.set_subject(target).has_same_keys_as(origin) self.assertEqual(expected, actual) expected = False actual = self.helper.set_subject(origin).has_same_keys_as(target) self.assertEqual(expected, actual) origin["c"] = {"a": 1, "b": 3, "c": {"x": "x"}} expected = True actual = self.helper.set_subject(target).has_same_keys_as(origin) self.assertEqual(expected, actual) actual = self.helper.set_subject(origin).has_same_keys_as(target) self.assertEqual(expected, actual) del origin["c"]["c"] expected = False actual = self.helper.set_subject(origin).has_same_keys_as(target) self.assertEqual(expected, actual) def test_remove_key_not_dict(self) -> None: """ Tests the method which let us remove a key from a given dict for the case that the given subject is not a dict. """ given = "Hello" expected = "Hello" actual = self.helper.set_subject(given).remove_key("Py") self.assertEqual(expected, actual) def test_remove_key(self) -> None: """ Test the method which let us remove a key from a given dict. """ given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(given).remove_key("Py") self.assertEqual(expected, actual) actual = self.helper.set_subject(given).remove_key(["Py", "test"]) self.assertEqual(expected, actual) def test_remove_multiple_key(self) -> None: """ Tests the method which let us remove a key with multiple key to remove. """ given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(given).remove_key(["funilrys", "Py"]) self.assertEqual(expected, actual) def test_remove_key_not_exists(self) -> None: """ Tests the method which let us remove a key for the cas that the key to remove does not exists. """ given = copy.deepcopy(self.test_subject) expected = copy.deepcopy(self.test_subject) actual = self.helper.set_subject(given).remove_key("xxx.") self.assertEqual(expected, actual) def test_rename_key_not_dict(self) -> None: """ Tests the method which let us rename a key of a dict for the case that the given subject is not a dict. """ given = "Hello, World!" expected = "Hello, World!" actual = self.helper.set_subject(given).rename_key({"Py": "PyFunceble"}) self.assertEqual(expected, actual) def test_rename_key_strict_single(self) -> None: """ Tests the method which let us rename a key for the case that we only want to strictly rename one key. """ given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "PyFunceble": "Funceble", "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(given).rename_key( {"Py": "PyFunceble"}, strict=True ) self.assertEqual(expected, actual) def test_rename_key_not_strict_single(self) -> None: """ Tests the method which let us rename a key for the case that we only want to rename all occurrences of the given key. """ given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "nuilrys": ["Fun", "Ilrys"], "Py": "Funceble", "nuceble": ["funilrys"], } actual = self.helper.set_subject(given).rename_key({"fun": "nuf"}, strict=False) self.assertEqual(expected, actual) def test_to_and_from_json_file(self) -> None: """ Tests the method which let us save and load a dict into/from a JSON file. """ output_file = tempfile.NamedTemporaryFile("w", delete=False) given = copy.deepcopy(self.test_subject) expected = copy.deepcopy(self.test_subject) self.helper.set_subject(given).to_json_file(output_file.name) output_file.seek(0) actual = self.helper.from_json_file(output_file.name) self.assertEqual(expected, actual) output_file.close() os.remove(output_file.name) def test_from_json_file_not_json(self) -> None: """ Tests the method which let us load a JSON file for the case that no JSON file is given. """ output_file = tempfile.NamedTemporaryFile("wb", delete=False) output_file.write(b"Hello, World!") output_file.seek(0) expected = dict() actual = self.helper.from_json_file(output_file.name) self.assertEqual(expected, actual) output_file.close() os.remove(output_file.name) def test_to_json(self) -> None: """ Tests the method which let us convert a dict to a JSON and vice-versa. """ given = copy.deepcopy(self.test_subject) expected = """{ "Hello": "world", "Py": "Funceble", "World": { "world": "hello" }, "funilrys": [ "Fun", "Ilrys" ], "pyfunceble": [ "funilrys" ] }""" actual = self.helper.set_subject(given).to_json() self.assertIsInstance(actual, str) self.assertEqual(expected, actual) actual = self.helper.from_json(expected) expected = copy.deepcopy(self.test_subject) self.assertEqual(expected, actual) def test_from_json_not_json(self) -> None: """ Tests the method which let us convert a JSON to a JSON for the case that no JSON is given. """ given = "Hello, World!" expected = dict() actual = self.helper.from_json(given) self.assertEqual(expected, actual) def test_from_yaml_file(self) -> None: """ Tests the method which let us save and load a dict into/from a YAML file. """ output_file = tempfile.NamedTemporaryFile("w", delete=False) given = copy.deepcopy(self.test_subject) expected = copy.deepcopy(self.test_subject) self.helper.set_subject(given).to_yaml_file(output_file.name) output_file.seek(0) actual = self.helper.from_yaml_file(output_file.name) self.assertEqual(expected, actual) output_file.close() os.remove(output_file.name) def test_to_yaml(self) -> None: """ Tests the method which let us convert a dict into a YAML and vice-versa. """ expected = """Hello: world Py: Funceble World: world: hello funilrys: - Fun - Ilrys pyfunceble: - funilrys """ given = copy.deepcopy(self.test_subject) actual = self.helper.set_subject(given).to_yaml() self.assertEqual(expected, actual) actual = self.helper.from_yaml(expected) expected = copy.deepcopy(self.test_subject) self.assertEqual(expected, actual) def test_flatten(self) -> None: """ Tests the method which let us flatten a dict. """ expected = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(self.test_subject).flatten() self.assertEqual(expected, actual) def test_deeper_flatten(self) -> None: """ Tests the method which let us flatten a dict with more level. """ given = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this": { "is": { "a": { "test": { "id": 1, "deep": {"hello": {"world": ["Hello!"]}}, "response": "World", } }, "b": 1, "c": [{"hello": {"this": {"is": "a test"}}}], } }, "": {"hello-fun": "world", "": "hehe"}, } expected = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this.is.a.test.deep.hello.world": ["Hello!"], "this.is.a.test.id": 1, "this.is.a.test.response": "World", "this.is.b": 1, "this.is.c": [{"hello": {"this": {"is": "a test"}}}], "..": "hehe", ".hello-fun": "world", } actual = self.helper.set_subject(given).flatten() self.assertEqual(expected, actual) def test_unflatten(self) -> None: """ Tests the method which let us unflatten a dict. """ given = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], } expected = dict(self.test_subject) actual = self.helper.set_subject(given).unflatten() self.assertEqual(expected, actual) def test_deeper_unflatten(self) -> None: """ Tests the method which let us unflatten a dict with more level. """ given = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this.is.a.test.deep.hello.world": ["Hello!"], "this.is.a.test.id": 1, "this.is.a.test.response": "World", "this.is.b": 1, "this.is.c": [{"hello": {"this": {"is": "a test"}}}], "..": "hehe", ".hello-fun": "world", } expected = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this": { "is": { "a": { "test": { "id": 1, "deep": {"hello": {"world": ["Hello!"]}}, "response": "World", } }, "b": 1, "c": [{"hello": {"this": {"is": "a test"}}}], } }, "": {"hello-fun": "world", "": "hehe"}, } actual = self.helper.set_subject(given).unflatten() self.assertEqual(expected, actual) if __name__ == "__main__": unittest.main()
27.528571
88
0.526207
import copy import os import tempfile import unittest from PyFunceble.helpers.dict import DictHelper class TestDictHelper(unittest.TestCase): def setUp(self) -> None: self.test_subject = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], } self.helper = DictHelper() def tearDown(self) -> None: del self.test_subject del self.helper def test_set_subject_return(self) -> None: actual = self.helper.set_subject(self.test_subject) self.assertIsInstance(actual, DictHelper) def test_set_subject_method(self) -> None: given = self.test_subject expected = dict(self.test_subject) self.helper.set_subject(given) actual = self.helper.subject self.assertEqual(expected, actual) def test_set_subject_attribute(self) -> None: given = self.test_subject expected = dict(self.test_subject) self.helper.subject = given actual = self.helper.subject self.assertEqual(expected, actual) def test_set_subject_through_init(self) -> None: given = self.test_subject expected = dict(self.test_subject) helper = DictHelper(given) actual = helper.subject self.assertEqual(expected, actual) def test_has_same_key_as(self) -> None: origin = {"a": 1, "b": 1} target = {"a": 1, "b": 2, "c": {"a": 1, "b": 3, "c": {"x": "x"}}} expected = True actual = self.helper.set_subject(target).has_same_keys_as(origin) self.assertEqual(expected, actual) expected = False actual = self.helper.set_subject(origin).has_same_keys_as(target) self.assertEqual(expected, actual) origin["c"] = {"a": 1, "b": 3, "c": {"x": "x"}} expected = True actual = self.helper.set_subject(target).has_same_keys_as(origin) self.assertEqual(expected, actual) actual = self.helper.set_subject(origin).has_same_keys_as(target) self.assertEqual(expected, actual) del origin["c"]["c"] expected = False actual = self.helper.set_subject(origin).has_same_keys_as(target) self.assertEqual(expected, actual) def test_remove_key_not_dict(self) -> None: given = "Hello" expected = "Hello" actual = self.helper.set_subject(given).remove_key("Py") self.assertEqual(expected, actual) def test_remove_key(self) -> None: given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(given).remove_key("Py") self.assertEqual(expected, actual) actual = self.helper.set_subject(given).remove_key(["Py", "test"]) self.assertEqual(expected, actual) def test_remove_multiple_key(self) -> None: given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(given).remove_key(["funilrys", "Py"]) self.assertEqual(expected, actual) def test_remove_key_not_exists(self) -> None: given = copy.deepcopy(self.test_subject) expected = copy.deepcopy(self.test_subject) actual = self.helper.set_subject(given).remove_key("xxx.") self.assertEqual(expected, actual) def test_rename_key_not_dict(self) -> None: given = "Hello, World!" expected = "Hello, World!" actual = self.helper.set_subject(given).rename_key({"Py": "PyFunceble"}) self.assertEqual(expected, actual) def test_rename_key_strict_single(self) -> None: given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "PyFunceble": "Funceble", "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(given).rename_key( {"Py": "PyFunceble"}, strict=True ) self.assertEqual(expected, actual) def test_rename_key_not_strict_single(self) -> None: given = copy.deepcopy(self.test_subject) expected = { "Hello": "world", "World": {"world": "hello"}, "nuilrys": ["Fun", "Ilrys"], "Py": "Funceble", "nuceble": ["funilrys"], } actual = self.helper.set_subject(given).rename_key({"fun": "nuf"}, strict=False) self.assertEqual(expected, actual) def test_to_and_from_json_file(self) -> None: output_file = tempfile.NamedTemporaryFile("w", delete=False) given = copy.deepcopy(self.test_subject) expected = copy.deepcopy(self.test_subject) self.helper.set_subject(given).to_json_file(output_file.name) output_file.seek(0) actual = self.helper.from_json_file(output_file.name) self.assertEqual(expected, actual) output_file.close() os.remove(output_file.name) def test_from_json_file_not_json(self) -> None: output_file = tempfile.NamedTemporaryFile("wb", delete=False) output_file.write(b"Hello, World!") output_file.seek(0) expected = dict() actual = self.helper.from_json_file(output_file.name) self.assertEqual(expected, actual) output_file.close() os.remove(output_file.name) def test_to_json(self) -> None: given = copy.deepcopy(self.test_subject) expected = """{ "Hello": "world", "Py": "Funceble", "World": { "world": "hello" }, "funilrys": [ "Fun", "Ilrys" ], "pyfunceble": [ "funilrys" ] }""" actual = self.helper.set_subject(given).to_json() self.assertIsInstance(actual, str) self.assertEqual(expected, actual) actual = self.helper.from_json(expected) expected = copy.deepcopy(self.test_subject) self.assertEqual(expected, actual) def test_from_json_not_json(self) -> None: given = "Hello, World!" expected = dict() actual = self.helper.from_json(given) self.assertEqual(expected, actual) def test_from_yaml_file(self) -> None: output_file = tempfile.NamedTemporaryFile("w", delete=False) given = copy.deepcopy(self.test_subject) expected = copy.deepcopy(self.test_subject) self.helper.set_subject(given).to_yaml_file(output_file.name) output_file.seek(0) actual = self.helper.from_yaml_file(output_file.name) self.assertEqual(expected, actual) output_file.close() os.remove(output_file.name) def test_to_yaml(self) -> None: expected = """Hello: world Py: Funceble World: world: hello funilrys: - Fun - Ilrys pyfunceble: - funilrys """ given = copy.deepcopy(self.test_subject) actual = self.helper.set_subject(given).to_yaml() self.assertEqual(expected, actual) actual = self.helper.from_yaml(expected) expected = copy.deepcopy(self.test_subject) self.assertEqual(expected, actual) def test_flatten(self) -> None: expected = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], } actual = self.helper.set_subject(self.test_subject).flatten() self.assertEqual(expected, actual) def test_deeper_flatten(self) -> None: given = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this": { "is": { "a": { "test": { "id": 1, "deep": {"hello": {"world": ["Hello!"]}}, "response": "World", } }, "b": 1, "c": [{"hello": {"this": {"is": "a test"}}}], } }, "": {"hello-fun": "world", "": "hehe"}, } expected = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this.is.a.test.deep.hello.world": ["Hello!"], "this.is.a.test.id": 1, "this.is.a.test.response": "World", "this.is.b": 1, "this.is.c": [{"hello": {"this": {"is": "a test"}}}], "..": "hehe", ".hello-fun": "world", } actual = self.helper.set_subject(given).flatten() self.assertEqual(expected, actual) def test_unflatten(self) -> None: given = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], } expected = dict(self.test_subject) actual = self.helper.set_subject(given).unflatten() self.assertEqual(expected, actual) def test_deeper_unflatten(self) -> None: given = { "Hello": "world", "World.world": "hello", "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this.is.a.test.deep.hello.world": ["Hello!"], "this.is.a.test.id": 1, "this.is.a.test.response": "World", "this.is.b": 1, "this.is.c": [{"hello": {"this": {"is": "a test"}}}], "..": "hehe", ".hello-fun": "world", } expected = { "Hello": "world", "World": {"world": "hello"}, "funilrys": ["Fun", "Ilrys"], "Py": "Funceble", "pyfunceble": ["funilrys"], "this": { "is": { "a": { "test": { "id": 1, "deep": {"hello": {"world": ["Hello!"]}}, "response": "World", } }, "b": 1, "c": [{"hello": {"this": {"is": "a test"}}}], } }, "": {"hello-fun": "world", "": "hehe"}, } actual = self.helper.set_subject(given).unflatten() self.assertEqual(expected, actual) if __name__ == "__main__": unittest.main()
true
true
1c39c62bbe46fc73ad45448972754bd2cc90b8f4
2,976
py
Python
scripts/test_retrieval_algorithms.py
liam-clink/pypret
c84e954efc12137c6b5ade4fae920d60a15d4875
[ "MIT" ]
36
2019-03-16T18:38:10.000Z
2022-02-15T14:25:30.000Z
scripts/test_retrieval_algorithms.py
liam-clink/pypret
c84e954efc12137c6b5ade4fae920d60a15d4875
[ "MIT" ]
1
2019-06-24T21:32:14.000Z
2019-07-03T12:46:28.000Z
scripts/test_retrieval_algorithms.py
liam-clink/pypret
c84e954efc12137c6b5ade4fae920d60a15d4875
[ "MIT" ]
12
2019-07-23T22:03:55.000Z
2022-01-06T08:50:52.000Z
""" This script tests COPRA against a lot of different PNPS schemes and compares it against PCGPA and ptychographic retrieval for SHG-FROG. It reproduces the data of Fig. 4, 5 and 7 from [Geib2019]_. Notes ----- As we are using multiprocessing to speed up the parameter scan you may not be able to run this script inside of an IDE such as spyder. In that case please run the script from the commandline using standard Python. For plotting the results see `test_retrieval_algorithms_plot.py`. """ import path_helper import pypret from benchmarking import benchmark_retrieval, RetrievalResultPlot from pathlib import Path from concurrent import futures # the configs to test: (scheme, algorithm) configs = [ ("shg-frog", "copra"), ("shg-frog", "pcgpa"), ("shg-frog", "pie"), ("pg-frog", "copra"), ("shg-tdp", "copra"), ("shg-dscan", "copra"), ("thg-dscan", "copra"), ("sd-dscan", "copra"), ("shg-ifrog", "copra"), ("thg-ifrog", "copra"), ("sd-ifrog", "copra"), ("shg-miips", "copra"), ("thg-miips", "copra"), ("sd-miips", "copra") ] maxworkers = 10 # number of processes used maxiter = 100 # 300 in the paper npulses = 10 # 100 in the paper repeat = 3 # 10 in the paper # [0.0, 1e-3, 3e-3, 5e-3, 1e-2, 3e-2, 5e-2] in the paper noise_levels = [1e-2, 3e-2] # block the main routine as we are using multiprocessing if __name__ == "__main__": pulses = pypret.load("pulse_bank.hdf5") path = Path("results") if not path.exists(): path.mkdir() for scheme, algorithm in configs: for noise in noise_levels: print("Testing %s with %s and noise level %.1f%%" % (scheme.upper(), algorithm.upper(), noise * 100)) results = [] # run the different pulses in different processes, # not optimal but better than no parallelism fs = {} with futures.ProcessPoolExecutor(max_workers=maxworkers) as executor: for i, pulse in enumerate(pulses[:npulses]): future = executor.submit(benchmark_retrieval, pulses, scheme, algorithm, repeat=repeat, verbose=False, maxiter=maxiter, additive_noise=noise) fs[future] = i for future in futures.as_completed(fs): i = fs[future] try: res = future.result() except Exception as exc: print('Retrieval generated an exception: %s' % exc) results.append(res) print("Finished pulse %d/%d" % (i+1, npulses) ) fname = "%s_%s_noise_%.1e.hdf5.7z" % (scheme.upper(), algorithm.upper(), noise) pypret.save(results, path / fname, archive=True) print("Stored in %s" % fname)
38.153846
81
0.572581
import path_helper import pypret from benchmarking import benchmark_retrieval, RetrievalResultPlot from pathlib import Path from concurrent import futures configs = [ ("shg-frog", "copra"), ("shg-frog", "pcgpa"), ("shg-frog", "pie"), ("pg-frog", "copra"), ("shg-tdp", "copra"), ("shg-dscan", "copra"), ("thg-dscan", "copra"), ("sd-dscan", "copra"), ("shg-ifrog", "copra"), ("thg-ifrog", "copra"), ("sd-ifrog", "copra"), ("shg-miips", "copra"), ("thg-miips", "copra"), ("sd-miips", "copra") ] maxworkers = 10 maxiter = 100 npulses = 10 repeat = 3 noise_levels = [1e-2, 3e-2] if __name__ == "__main__": pulses = pypret.load("pulse_bank.hdf5") path = Path("results") if not path.exists(): path.mkdir() for scheme, algorithm in configs: for noise in noise_levels: print("Testing %s with %s and noise level %.1f%%" % (scheme.upper(), algorithm.upper(), noise * 100)) results = [] fs = {} with futures.ProcessPoolExecutor(max_workers=maxworkers) as executor: for i, pulse in enumerate(pulses[:npulses]): future = executor.submit(benchmark_retrieval, pulses, scheme, algorithm, repeat=repeat, verbose=False, maxiter=maxiter, additive_noise=noise) fs[future] = i for future in futures.as_completed(fs): i = fs[future] try: res = future.result() except Exception as exc: print('Retrieval generated an exception: %s' % exc) results.append(res) print("Finished pulse %d/%d" % (i+1, npulses) ) fname = "%s_%s_noise_%.1e.hdf5.7z" % (scheme.upper(), algorithm.upper(), noise) pypret.save(results, path / fname, archive=True) print("Stored in %s" % fname)
true
true
1c39c703ae95df60fc23f1e8f91243e265fca628
4,272
py
Python
autopandas_v2/tests/engines.py
chyanju/autopandas
16080ad12f0e8e7b0a614671aea1ed57b3fed7fe
[ "BSD-3-Clause" ]
16
2019-08-13T02:49:44.000Z
2022-02-08T03:14:34.000Z
autopandas_v2/tests/engines.py
chyanju/autopandas
16080ad12f0e8e7b0a614671aea1ed57b3fed7fe
[ "BSD-3-Clause" ]
2
2020-09-25T22:40:40.000Z
2022-02-09T23:42:53.000Z
autopandas_v2/tests/engines.py
chyanju/autopandas
16080ad12f0e8e7b0a614671aea1ed57b3fed7fe
[ "BSD-3-Clause" ]
3
2021-07-06T10:30:36.000Z
2022-01-11T23:21:31.000Z
import glob import logging import os import unittest from typing import List, Any import pandas as pd from autopandas_v2.generators.ml.networks.mocking.models import MockSelectModel, MockChainModel, MockSubsetsModel from autopandas_v2.iospecs import IOSpec from autopandas_v2.synthesis.search.engines.functions import BFSEngine, BaseEngine from autopandas_v2.utils import logger class TestBeamSearchEngine(unittest.TestCase): def setUp(self): pass def check(self, inputs: List[Any], output: Any, funcs: List[str], seqs: List[List[int]], model_dir: str): iospec: IOSpec = IOSpec(inputs, output) iospec.funcs = funcs iospec.seqs = seqs engine: BFSEngine = BFSEngine(iospec) engine.max_depth = max(len(i) for i in seqs) engine.silent = True engine.stop_first_solution = True engine.use_spec_funcs = True engine.use_spec_seqs = True engine.argument_engine = 'beam-search' engine.arg_model_dir = model_dir # try: # engine.search() # except Exception as e: # logging.exception(e) return self.check_engine(engine) def check_engine(self, engine: BaseEngine): self.assertTrue(engine.search(), msg='Did not find a solution') return engine.stats def test_pivot_selects_1(self): # foo bar baz # 0 one A 1 # 1 one B 2 # 2 one C 3 # 3 two A 4 # 4 two B 5 # 5 two C 6 inputs = [pd.DataFrame({ 'foo': ['one', 'one', 'one', 'two', 'two', 'two'], 'bar': ['A', 'B', 'C', 'A', 'B', 'C'], 'baz': [1, 2, 3, 4, 5, 6], })] # bar A B C # foo # one 1 2 3 # two 4 5 6R output = inputs[0].pivot(index='foo', columns='bar', values='baz') mocker_columns = MockSelectModel(behavior={ 'select_columns_1': [(1.0, 'bar'), (0.0, 'foo'), (0.0, 'baz')] }) mocker_index = MockSelectModel(behavior={ 'select_index_1': [(0.9, 'foo'), (0.1, 'baz')] }) mocker_values = MockSelectModel(behavior={ 'select_values_1': [(1.0, 'baz'), (0.0, 'bar'), (0.0, 'foo')] }) mocker_columns.save('/tmp/mock_autopandas_pivot_1/df.pivot/select_columns_1') mocker_index.save('/tmp/mock_autopandas_pivot_1/df.pivot/select_index_1') mocker_values.save('/tmp/mock_autopandas_pivot_1/df.pivot/select_values_1') funcs = ['df.pivot'] seqs = [[0]] stats = self.check(inputs, output, funcs, seqs, '/tmp/mock_autopandas_pivot_1') self.assertEqual(stats.num_cands_generated[1], 1) self.assertEqual(stats.num_cands_error[1], 0) def test_pivot_selects_2(self): # foo bar baz # 0 one A 1 # 1 one B 2 # 2 one C 3 # 3 two A 4 # 4 two B 5 # 5 two C 6 inputs = [pd.DataFrame({ 'foo': ['one', 'one', 'one', 'two', 'two', 'two'], 'bar': ['A', 'B', 'C', 'A', 'B', 'C'], 'baz': [1, 2, 3, 4, 5, 6], })] # bar A B C # foo # one 1 2 3 # two 4 5 6R output = inputs[0].pivot(index='foo', columns='bar', values='baz') mocker_columns = MockSelectModel(behavior={ 'select_columns_1': [(1.0, 'bar'), (0.0, 'foo'), (0.0, 'baz')] }) mocker_index = MockSelectModel(behavior={ 'select_index_1': [(0.1, 'foo'), (0.9, 'baz')] }) mocker_values = MockSelectModel(behavior={ 'select_values_1': [(1.0, 'baz'), (0.0, 'bar'), (0.0, 'foo')] }) mocker_columns.save('/tmp/mock_autopandas_pivot_2/df.pivot/select_columns_1') mocker_index.save('/tmp/mock_autopandas_pivot_2/df.pivot/select_index_1') mocker_values.save('/tmp/mock_autopandas_pivot_2/df.pivot/select_values_1') funcs = ['df.pivot'] seqs = [[0]] stats = self.check(inputs, output, funcs, seqs, '/tmp/mock_autopandas_pivot_2') self.assertEqual(stats.num_cands_generated[1], 2) self.assertEqual(stats.num_cands_error[1], 0)
33.637795
113
0.558755
import glob import logging import os import unittest from typing import List, Any import pandas as pd from autopandas_v2.generators.ml.networks.mocking.models import MockSelectModel, MockChainModel, MockSubsetsModel from autopandas_v2.iospecs import IOSpec from autopandas_v2.synthesis.search.engines.functions import BFSEngine, BaseEngine from autopandas_v2.utils import logger class TestBeamSearchEngine(unittest.TestCase): def setUp(self): pass def check(self, inputs: List[Any], output: Any, funcs: List[str], seqs: List[List[int]], model_dir: str): iospec: IOSpec = IOSpec(inputs, output) iospec.funcs = funcs iospec.seqs = seqs engine: BFSEngine = BFSEngine(iospec) engine.max_depth = max(len(i) for i in seqs) engine.silent = True engine.stop_first_solution = True engine.use_spec_funcs = True engine.use_spec_seqs = True engine.argument_engine = 'beam-search' engine.arg_model_dir = model_dir return self.check_engine(engine) def check_engine(self, engine: BaseEngine): self.assertTrue(engine.search(), msg='Did not find a solution') return engine.stats def test_pivot_selects_1(self): inputs = [pd.DataFrame({ 'foo': ['one', 'one', 'one', 'two', 'two', 'two'], 'bar': ['A', 'B', 'C', 'A', 'B', 'C'], 'baz': [1, 2, 3, 4, 5, 6], })] output = inputs[0].pivot(index='foo', columns='bar', values='baz') mocker_columns = MockSelectModel(behavior={ 'select_columns_1': [(1.0, 'bar'), (0.0, 'foo'), (0.0, 'baz')] }) mocker_index = MockSelectModel(behavior={ 'select_index_1': [(0.9, 'foo'), (0.1, 'baz')] }) mocker_values = MockSelectModel(behavior={ 'select_values_1': [(1.0, 'baz'), (0.0, 'bar'), (0.0, 'foo')] }) mocker_columns.save('/tmp/mock_autopandas_pivot_1/df.pivot/select_columns_1') mocker_index.save('/tmp/mock_autopandas_pivot_1/df.pivot/select_index_1') mocker_values.save('/tmp/mock_autopandas_pivot_1/df.pivot/select_values_1') funcs = ['df.pivot'] seqs = [[0]] stats = self.check(inputs, output, funcs, seqs, '/tmp/mock_autopandas_pivot_1') self.assertEqual(stats.num_cands_generated[1], 1) self.assertEqual(stats.num_cands_error[1], 0) def test_pivot_selects_2(self): inputs = [pd.DataFrame({ 'foo': ['one', 'one', 'one', 'two', 'two', 'two'], 'bar': ['A', 'B', 'C', 'A', 'B', 'C'], 'baz': [1, 2, 3, 4, 5, 6], })] output = inputs[0].pivot(index='foo', columns='bar', values='baz') mocker_columns = MockSelectModel(behavior={ 'select_columns_1': [(1.0, 'bar'), (0.0, 'foo'), (0.0, 'baz')] }) mocker_index = MockSelectModel(behavior={ 'select_index_1': [(0.1, 'foo'), (0.9, 'baz')] }) mocker_values = MockSelectModel(behavior={ 'select_values_1': [(1.0, 'baz'), (0.0, 'bar'), (0.0, 'foo')] }) mocker_columns.save('/tmp/mock_autopandas_pivot_2/df.pivot/select_columns_1') mocker_index.save('/tmp/mock_autopandas_pivot_2/df.pivot/select_index_1') mocker_values.save('/tmp/mock_autopandas_pivot_2/df.pivot/select_values_1') funcs = ['df.pivot'] seqs = [[0]] stats = self.check(inputs, output, funcs, seqs, '/tmp/mock_autopandas_pivot_2') self.assertEqual(stats.num_cands_generated[1], 2) self.assertEqual(stats.num_cands_error[1], 0)
true
true
1c39c7226c0d97bf8a0631733cf56849f214b531
5,896
py
Python
ask-sdk-model/ask_sdk_model/interfaces/alexa/presentation/apl/user_event.py
Signal-Kinetics/alexa-apis-for-python
abb8d3dce18a5510c48b215406ed36c024f01495
[ "Apache-2.0" ]
2
2021-10-30T06:52:48.000Z
2021-11-16T12:34:16.000Z
ask-sdk-model/ask_sdk_model/interfaces/alexa/presentation/apl/user_event.py
Signal-Kinetics/alexa-apis-for-python
abb8d3dce18a5510c48b215406ed36c024f01495
[ "Apache-2.0" ]
null
null
null
ask-sdk-model/ask_sdk_model/interfaces/alexa/presentation/apl/user_event.py
Signal-Kinetics/alexa-apis-for-python
abb8d3dce18a5510c48b215406ed36c024f01495
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # # Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for # the specific language governing permissions and limitations under the License. # import pprint import re # noqa: F401 import six import typing from enum import Enum from ask_sdk_model.request import Request if typing.TYPE_CHECKING: from typing import Dict, List, Optional, Union from datetime import datetime class UserEvent(Request): """ :param request_id: Represents the unique identifier for the specific request. :type request_id: (optional) str :param timestamp: Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service. :type timestamp: (optional) datetime :param locale: A string indicating the user’s locale. For example: en-US. This value is only provided with certain request types. :type locale: (optional) str :param token: A unique token for the active presentation. :type token: (optional) str :param arguments: The array of argument data to pass to Alexa. :type arguments: (optional) list[object] :param source: Meta-information about what caused the event to be generated. :type source: (optional) object :param components: Components associated with the request. :type components: (optional) object """ deserialized_types = { 'object_type': 'str', 'request_id': 'str', 'timestamp': 'datetime', 'locale': 'str', 'token': 'str', 'arguments': 'list[object]', 'source': 'object', 'components': 'object' } # type: Dict attribute_map = { 'object_type': 'type', 'request_id': 'requestId', 'timestamp': 'timestamp', 'locale': 'locale', 'token': 'token', 'arguments': 'arguments', 'source': 'source', 'components': 'components' } # type: Dict supports_multiple_types = False def __init__(self, request_id=None, timestamp=None, locale=None, token=None, arguments=None, source=None, components=None): # type: (Optional[str], Optional[datetime], Optional[str], Optional[str], Optional[List[object]], Optional[object], Optional[object]) -> None """ :param request_id: Represents the unique identifier for the specific request. :type request_id: (optional) str :param timestamp: Provides the date and time when Alexa sent the request as an ISO 8601 formatted string. Used to verify the request when hosting your skill as a web service. :type timestamp: (optional) datetime :param locale: A string indicating the user’s locale. For example: en-US. This value is only provided with certain request types. :type locale: (optional) str :param token: A unique token for the active presentation. :type token: (optional) str :param arguments: The array of argument data to pass to Alexa. :type arguments: (optional) list[object] :param source: Meta-information about what caused the event to be generated. :type source: (optional) object :param components: Components associated with the request. :type components: (optional) object """ self.__discriminator_value = "Alexa.Presentation.APL.UserEvent" # type: str self.object_type = self.__discriminator_value super(UserEvent, self).__init__(object_type=self.__discriminator_value, request_id=request_id, timestamp=timestamp, locale=locale) self.token = token self.arguments = arguments self.source = source self.components = components def to_dict(self): # type: () -> Dict[str, object] """Returns the model properties as a dict""" result = {} # type: Dict for attr, _ in six.iteritems(self.deserialized_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x.value if isinstance(x, Enum) else x, value )) elif isinstance(value, Enum): result[attr] = value.value elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else (item[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) else: result[attr] = value return result def to_str(self): # type: () -> str """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): # type: () -> str """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): # type: (object) -> bool """Returns true if both objects are equal""" if not isinstance(other, UserEvent): return False return self.__dict__ == other.__dict__ def __ne__(self, other): # type: (object) -> bool """Returns true if both objects are not equal""" return not self == other
39.046358
182
0.627714
import pprint import re import six import typing from enum import Enum from ask_sdk_model.request import Request if typing.TYPE_CHECKING: from typing import Dict, List, Optional, Union from datetime import datetime class UserEvent(Request): deserialized_types = { 'object_type': 'str', 'request_id': 'str', 'timestamp': 'datetime', 'locale': 'str', 'token': 'str', 'arguments': 'list[object]', 'source': 'object', 'components': 'object' } attribute_map = { 'object_type': 'type', 'request_id': 'requestId', 'timestamp': 'timestamp', 'locale': 'locale', 'token': 'token', 'arguments': 'arguments', 'source': 'source', 'components': 'components' } supports_multiple_types = False def __init__(self, request_id=None, timestamp=None, locale=None, token=None, arguments=None, source=None, components=None): self.__discriminator_value = "Alexa.Presentation.APL.UserEvent" self.object_type = self.__discriminator_value super(UserEvent, self).__init__(object_type=self.__discriminator_value, request_id=request_id, timestamp=timestamp, locale=locale) self.token = token self.arguments = arguments self.source = source self.components = components def to_dict(self): result = {} for attr, _ in six.iteritems(self.deserialized_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x.value if isinstance(x, Enum) else x, value )) elif isinstance(value, Enum): result[attr] = value.value elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else (item[0], item[1].value) if isinstance(item[1], Enum) else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, UserEvent): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c39c75e116fe30ffafbf9832e70de19b45788e8
11,505
py
Python
discovery-provider/integration_tests/queries/test_search.py
Tenderize/audius-protocol
aa15844e3f12812fe8aaa81e2cb6e5c5fa89ff51
[ "Apache-2.0" ]
null
null
null
discovery-provider/integration_tests/queries/test_search.py
Tenderize/audius-protocol
aa15844e3f12812fe8aaa81e2cb6e5c5fa89ff51
[ "Apache-2.0" ]
null
null
null
discovery-provider/integration_tests/queries/test_search.py
Tenderize/audius-protocol
aa15844e3f12812fe8aaa81e2cb6e5c5fa89ff51
[ "Apache-2.0" ]
null
null
null
from datetime import datetime from src.models import Block, Follow, Playlist, Save, SaveType, Track, User, UserBalance from src.queries.search_queries import ( playlist_search_query, track_search_query, user_search_query, ) from src.tasks.index_aggregate_user import UPDATE_AGGREGATE_USER_QUERY from src.utils.db_session import get_db def setup_search(db): # Import app so that it'll run migrations against the db now = datetime.now() blocks = [ Block( blockhash=hex(1), number=1, parenthash="0x01", is_current=False, ), Block( blockhash=hex(2), number=2, parenthash="0x02", is_current=False, ), Block( blockhash=hex(3), number=3, parenthash="0x03", is_current=True, ), ] tracks = [ Track( blockhash=hex(1), blocknumber=1, track_id=1, is_current=True, is_delete=False, owner_id=1, route_id="", track_segments=[], genre="", updated_at=now, created_at=now, is_unlisted=False, title="the track 1", download={"cid": None, "is_downloadable": False, "requires_follow": False}, ), Track( blockhash=hex(2), blocknumber=2, track_id=2, is_current=True, is_delete=False, owner_id=2, route_id="", track_segments=[], genre="", updated_at=now, created_at=now, is_unlisted=False, title="the track 2", download={"cid": None, "is_downloadable": True, "requires_follow": False}, ), Track( blockhash=hex(3), blocknumber=3, track_id=3, is_current=True, is_delete=False, owner_id=1, route_id="", track_segments=[], genre="", updated_at=now, created_at=now, is_unlisted=False, title="xyz", download={"cid": None, "is_downloadable": True, "requires_follow": False}, ), ] # need users for the lexeme dict to work users = [ User( blockhash=hex(1), blocknumber=1, user_id=1, is_current=True, handle="", wallet="", name="user 1", updated_at=now, created_at=now, ), User( blockhash=hex(2), blocknumber=2, user_id=2, is_current=True, handle="", name="user 2", wallet="", updated_at=now, created_at=now, ), User( blockhash=hex(3), blocknumber=3, user_id=3, is_current=True, handle="", wallet="", name="fdwea", updated_at=now, created_at=now, ), ] follows = [ Follow( blockhash=hex(1), blocknumber=1, follower_user_id=2, followee_user_id=1, is_current=True, is_delete=False, created_at=now, ) ] playlists = [ Playlist( blockhash=hex(1), blocknumber=1, playlist_id=1, playlist_owner_id=1, is_album=False, is_private=False, playlist_name="playlist 1", playlist_contents={"track_ids": [{"track": 1}]}, is_current=True, is_delete=False, updated_at=now, created_at=now, ), Playlist( blockhash=hex(2), blocknumber=2, playlist_id=2, playlist_owner_id=2, is_album=True, is_private=False, playlist_name="album 1", playlist_contents={"track_ids": [{"track": 2}]}, is_current=True, is_delete=False, updated_at=now, created_at=now, ), ] saves = [ Save( blockhash=hex(1), blocknumber=1, user_id=1, save_item_id=1, save_type=SaveType.track, created_at=now, is_current=True, is_delete=False, ), Save( blockhash=hex(1), blocknumber=1, user_id=1, save_item_id=1, save_type=SaveType.playlist, created_at=now, is_current=True, is_delete=False, ), Save( blockhash=hex(1), blocknumber=1, user_id=1, save_item_id=2, save_type=SaveType.album, created_at=now, is_current=True, is_delete=False, ), ] balances = [ UserBalance( user_id=1, balance=0, associated_wallets_balance=0, associated_sol_wallets_balance=0, waudio=0, ) ] with db.scoped_session() as session: for block in blocks: session.add(block) session.flush() for track in tracks: session.add(track) for user in users: session.add(user) session.flush() for follow in follows: session.add(follow) session.flush() for playlist in playlists: session.add(playlist) session.flush() for save in saves: session.add(save) session.flush() for balance in balances: session.add(balance) session.flush() # Refresh the lexeme matview session.execute("REFRESH MATERIALIZED VIEW aggregate_track;") session.execute("REFRESH MATERIALIZED VIEW track_lexeme_dict;") session.execute( UPDATE_AGGREGATE_USER_QUERY, {"most_recent_indexed_aggregate_block": 0} ) session.execute("REFRESH MATERIALIZED VIEW user_lexeme_dict;") session.execute("REFRESH MATERIALIZED VIEW aggregate_playlist;") session.execute("REFRESH MATERIALIZED VIEW playlist_lexeme_dict;") session.execute("REFRESH MATERIALIZED VIEW album_lexeme_dict;") def test_get_tracks_external(app): """Tests we get all tracks, including downloaded""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, False, None, False) assert len(res["all"]) == 2 assert len(res["saved"]) == 0 def test_get_autocomplete_tracks(app): """Tests we get all tracks with autocomplete""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, True, None, False) assert len(res["all"]) == 2 assert len(res["saved"]) == 0 def test_get_tracks_internal(app): """Tests we get all tracks when a user is logged in""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, False, 1, False) assert len(res["all"]) == 2 assert len(res["saved"]) == 1 def test_get_downloadable_tracks(app): """Tests we get only downloadable results""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, False, None, True) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_external_users(app): """Tests we get all users""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, False, None) assert len(res["all"]) == 2 assert len(res["followed"]) == 0 def test_get_autocomplete_users(app): """Tests we get all users with autocomplete""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, True, None) assert len(res["all"]) == 2 assert len(res["followed"]) == 0 def test_get_internal_users(app): """Tests we get all users when a user is logged in""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, False, 2) assert len(res["all"]) == 2 assert len(res["followed"]) == 1 def test_get_internal_users_no_following(app): """Tests we get all users for a user that doesn't follow anyone""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, False, 1) assert len(res["all"]) == 2 assert len(res["followed"]) == 0 def test_get_external_playlists(app): """Tests we get all playlists""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "playlist", 10, 0, False, False, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_autocomplete_playlists(app): """Tests we get all tracks with autocomplete""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "playlist", 10, 0, False, True, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_internal_playlists(app): """Tests we get playlists when a user is logged in""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "playlist", 10, 0, False, False, 1) assert len(res["all"]) == 1 assert len(res["saved"]) == 1 def test_get_external_albums(app): """Tests we get all albums""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "album", 10, 0, True, False, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_autocomplete_albums(app): """Tests we get all albums with autocomplete""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "album", 10, 0, True, True, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_internal_albums(app): """Tests we get albums when a user is logged in""" with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "album", 10, 0, True, False, 1) assert len(res["all"]) == 1 assert len(res["saved"]) == 1
28.907035
88
0.54585
from datetime import datetime from src.models import Block, Follow, Playlist, Save, SaveType, Track, User, UserBalance from src.queries.search_queries import ( playlist_search_query, track_search_query, user_search_query, ) from src.tasks.index_aggregate_user import UPDATE_AGGREGATE_USER_QUERY from src.utils.db_session import get_db def setup_search(db): now = datetime.now() blocks = [ Block( blockhash=hex(1), number=1, parenthash="0x01", is_current=False, ), Block( blockhash=hex(2), number=2, parenthash="0x02", is_current=False, ), Block( blockhash=hex(3), number=3, parenthash="0x03", is_current=True, ), ] tracks = [ Track( blockhash=hex(1), blocknumber=1, track_id=1, is_current=True, is_delete=False, owner_id=1, route_id="", track_segments=[], genre="", updated_at=now, created_at=now, is_unlisted=False, title="the track 1", download={"cid": None, "is_downloadable": False, "requires_follow": False}, ), Track( blockhash=hex(2), blocknumber=2, track_id=2, is_current=True, is_delete=False, owner_id=2, route_id="", track_segments=[], genre="", updated_at=now, created_at=now, is_unlisted=False, title="the track 2", download={"cid": None, "is_downloadable": True, "requires_follow": False}, ), Track( blockhash=hex(3), blocknumber=3, track_id=3, is_current=True, is_delete=False, owner_id=1, route_id="", track_segments=[], genre="", updated_at=now, created_at=now, is_unlisted=False, title="xyz", download={"cid": None, "is_downloadable": True, "requires_follow": False}, ), ] # need users for the lexeme dict to work users = [ User( blockhash=hex(1), blocknumber=1, user_id=1, is_current=True, handle="", wallet="", name="user 1", updated_at=now, created_at=now, ), User( blockhash=hex(2), blocknumber=2, user_id=2, is_current=True, handle="", name="user 2", wallet="", updated_at=now, created_at=now, ), User( blockhash=hex(3), blocknumber=3, user_id=3, is_current=True, handle="", wallet="", name="fdwea", updated_at=now, created_at=now, ), ] follows = [ Follow( blockhash=hex(1), blocknumber=1, follower_user_id=2, followee_user_id=1, is_current=True, is_delete=False, created_at=now, ) ] playlists = [ Playlist( blockhash=hex(1), blocknumber=1, playlist_id=1, playlist_owner_id=1, is_album=False, is_private=False, playlist_name="playlist 1", playlist_contents={"track_ids": [{"track": 1}]}, is_current=True, is_delete=False, updated_at=now, created_at=now, ), Playlist( blockhash=hex(2), blocknumber=2, playlist_id=2, playlist_owner_id=2, is_album=True, is_private=False, playlist_name="album 1", playlist_contents={"track_ids": [{"track": 2}]}, is_current=True, is_delete=False, updated_at=now, created_at=now, ), ] saves = [ Save( blockhash=hex(1), blocknumber=1, user_id=1, save_item_id=1, save_type=SaveType.track, created_at=now, is_current=True, is_delete=False, ), Save( blockhash=hex(1), blocknumber=1, user_id=1, save_item_id=1, save_type=SaveType.playlist, created_at=now, is_current=True, is_delete=False, ), Save( blockhash=hex(1), blocknumber=1, user_id=1, save_item_id=2, save_type=SaveType.album, created_at=now, is_current=True, is_delete=False, ), ] balances = [ UserBalance( user_id=1, balance=0, associated_wallets_balance=0, associated_sol_wallets_balance=0, waudio=0, ) ] with db.scoped_session() as session: for block in blocks: session.add(block) session.flush() for track in tracks: session.add(track) for user in users: session.add(user) session.flush() for follow in follows: session.add(follow) session.flush() for playlist in playlists: session.add(playlist) session.flush() for save in saves: session.add(save) session.flush() for balance in balances: session.add(balance) session.flush() # Refresh the lexeme matview session.execute("REFRESH MATERIALIZED VIEW aggregate_track;") session.execute("REFRESH MATERIALIZED VIEW track_lexeme_dict;") session.execute( UPDATE_AGGREGATE_USER_QUERY, {"most_recent_indexed_aggregate_block": 0} ) session.execute("REFRESH MATERIALIZED VIEW user_lexeme_dict;") session.execute("REFRESH MATERIALIZED VIEW aggregate_playlist;") session.execute("REFRESH MATERIALIZED VIEW playlist_lexeme_dict;") session.execute("REFRESH MATERIALIZED VIEW album_lexeme_dict;") def test_get_tracks_external(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, False, None, False) assert len(res["all"]) == 2 assert len(res["saved"]) == 0 def test_get_autocomplete_tracks(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, True, None, False) assert len(res["all"]) == 2 assert len(res["saved"]) == 0 def test_get_tracks_internal(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, False, 1, False) assert len(res["all"]) == 2 assert len(res["saved"]) == 1 def test_get_downloadable_tracks(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = track_search_query(session, "the track", 10, 0, False, None, True) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_external_users(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, False, None) assert len(res["all"]) == 2 assert len(res["followed"]) == 0 def test_get_autocomplete_users(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, True, None) assert len(res["all"]) == 2 assert len(res["followed"]) == 0 def test_get_internal_users(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, False, 2) assert len(res["all"]) == 2 assert len(res["followed"]) == 1 def test_get_internal_users_no_following(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = user_search_query(session, "user", 10, 0, False, 1) assert len(res["all"]) == 2 assert len(res["followed"]) == 0 def test_get_external_playlists(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "playlist", 10, 0, False, False, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_autocomplete_playlists(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "playlist", 10, 0, False, True, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_internal_playlists(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "playlist", 10, 0, False, False, 1) assert len(res["all"]) == 1 assert len(res["saved"]) == 1 def test_get_external_albums(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "album", 10, 0, True, False, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_autocomplete_albums(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "album", 10, 0, True, True, None) assert len(res["all"]) == 1 assert len(res["saved"]) == 0 def test_get_internal_albums(app): with app.app_context(): db = get_db() setup_search(db) with db.scoped_session() as session: res = playlist_search_query(session, "album", 10, 0, True, False, 1) assert len(res["all"]) == 1 assert len(res["saved"]) == 1
true
true
1c39c776ae095bb77e2c8b1c26d33151d9e9f281
138
py
Python
Codewars/6kyu/write-number-in-expanded-form/Python/solution1.py
RevansChen/online-judge
ad1b07fee7bd3c49418becccda904e17505f3018
[ "MIT" ]
7
2017-09-20T16:40:39.000Z
2021-08-31T18:15:08.000Z
Codewars/6kyu/write-number-in-expanded-form/Python/solution1.py
RevansChen/online-judge
ad1b07fee7bd3c49418becccda904e17505f3018
[ "MIT" ]
null
null
null
Codewars/6kyu/write-number-in-expanded-form/Python/solution1.py
RevansChen/online-judge
ad1b07fee7bd3c49418becccda904e17505f3018
[ "MIT" ]
null
null
null
# Python - 3.6.0 expanded_form = lambda num: ' + '.join([s + '0' * (len(str(num)) - i - 1) for i, s in enumerate(str(num)) if s != '0'])
34.5
119
0.536232
expanded_form = lambda num: ' + '.join([s + '0' * (len(str(num)) - i - 1) for i, s in enumerate(str(num)) if s != '0'])
true
true
1c39ca5f5b2ce225491816f042cfead88503b22d
4,299
py
Python
lib/googlecloudsdk/command_lib/compute/tpus/util.py
kustodian/google-cloud-sdk
b6bae4137d4b58030adb3dcb1271216dfb19f96d
[ "Apache-2.0" ]
null
null
null
lib/googlecloudsdk/command_lib/compute/tpus/util.py
kustodian/google-cloud-sdk
b6bae4137d4b58030adb3dcb1271216dfb19f96d
[ "Apache-2.0" ]
11
2020-02-29T02:51:12.000Z
2022-03-30T23:20:08.000Z
lib/googlecloudsdk/command_lib/compute/tpus/util.py
kustodian/google-cloud-sdk
b6bae4137d4b58030adb3dcb1271216dfb19f96d
[ "Apache-2.0" ]
1
2020-07-24T18:47:35.000Z
2020-07-24T18:47:35.000Z
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CLI Utilities for cloud tpu commands.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.services import exceptions from googlecloudsdk.api_lib.services import peering from googlecloudsdk.api_lib.util import apis from googlecloudsdk.command_lib.projects import util as projects_command_util from googlecloudsdk.core import exceptions as core_exceptions from googlecloudsdk.core import properties from googlecloudsdk.core import resources _PROJECT_LOOKUP_ERROR = ('Error determining VPC peering status ' 'for network [{}]: [{}]') _PEERING_VALIDATION_ERROR = ('Network [{}] is invalid for use ' 'with Service Networking') class ServiceNetworkingException(core_exceptions.Error): """Exception for creation failures involving Service Networking/Peering.""" def GetMessagesModule(version='v1'): return apis.GetMessagesModule('tpu', version) def StartRequestHook(ref, args, request): """Declarative request hook for TPU Start command.""" del ref del args start_request = GetMessagesModule().StartNodeRequest() request.startNodeRequest = start_request return request def StopRequestHook(ref, args, request): """Declarative request hook for TPU Stop command.""" del ref del args stop_request = GetMessagesModule().StopNodeRequest() request.stopNodeRequest = stop_request return request def _ParseProjectNumberFromNetwork(network, user_project): """Retrieves the project field from the provided network value.""" try: registry = resources.REGISTRY.Clone() network_ref = registry.Parse(network, collection='compute.networks') project_identifier = network_ref.project except resources.Error: # If not a parseable resource string, then use user_project project_identifier = user_project return projects_command_util.GetProjectNumber(project_identifier) def CreateValidateVPCHook(ref, args, request): """Validates that supplied network has been peered to a GoogleOrganization. Uses the Service Networking API to check if the network specified via --network flag has been peered to Google Organization. If it has, proceeds with TPU create operation otherwise will raise ServiceNetworking exception. Check is only valid if --use-service-networking has been specified otherwise check will return immediately. Args: ref: Reference to the TPU Node resource to be created. args: Argument namespace. request: TPU Create requests message. Returns: request: Passes requests through if args pass validation Raises: ServiceNetworkingException: if network is not properly peered """ del ref service_networking_enabled = args.use_service_networking if service_networking_enabled: project = args.project or properties.VALUES.core.project.Get(required=True) try: network_project_number = _ParseProjectNumberFromNetwork(args.network, project) lookup_result = peering.ListConnections( network_project_number, 'servicenetworking.googleapis.com', args.network) except (exceptions.ListConnectionsPermissionDeniedException, apitools_exceptions.HttpError) as e: raise ServiceNetworkingException( _PROJECT_LOOKUP_ERROR.format(args.network, project, e)) if not lookup_result: raise ServiceNetworkingException( _PEERING_VALIDATION_ERROR.format(args.network)) return request
36.12605
80
0.746453
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from apitools.base.py import exceptions as apitools_exceptions from googlecloudsdk.api_lib.services import exceptions from googlecloudsdk.api_lib.services import peering from googlecloudsdk.api_lib.util import apis from googlecloudsdk.command_lib.projects import util as projects_command_util from googlecloudsdk.core import exceptions as core_exceptions from googlecloudsdk.core import properties from googlecloudsdk.core import resources _PROJECT_LOOKUP_ERROR = ('Error determining VPC peering status ' 'for network [{}]: [{}]') _PEERING_VALIDATION_ERROR = ('Network [{}] is invalid for use ' 'with Service Networking') class ServiceNetworkingException(core_exceptions.Error): def GetMessagesModule(version='v1'): return apis.GetMessagesModule('tpu', version) def StartRequestHook(ref, args, request): del ref del args start_request = GetMessagesModule().StartNodeRequest() request.startNodeRequest = start_request return request def StopRequestHook(ref, args, request): del ref del args stop_request = GetMessagesModule().StopNodeRequest() request.stopNodeRequest = stop_request return request def _ParseProjectNumberFromNetwork(network, user_project): try: registry = resources.REGISTRY.Clone() network_ref = registry.Parse(network, collection='compute.networks') project_identifier = network_ref.project except resources.Error: project_identifier = user_project return projects_command_util.GetProjectNumber(project_identifier) def CreateValidateVPCHook(ref, args, request): del ref service_networking_enabled = args.use_service_networking if service_networking_enabled: project = args.project or properties.VALUES.core.project.Get(required=True) try: network_project_number = _ParseProjectNumberFromNetwork(args.network, project) lookup_result = peering.ListConnections( network_project_number, 'servicenetworking.googleapis.com', args.network) except (exceptions.ListConnectionsPermissionDeniedException, apitools_exceptions.HttpError) as e: raise ServiceNetworkingException( _PROJECT_LOOKUP_ERROR.format(args.network, project, e)) if not lookup_result: raise ServiceNetworkingException( _PEERING_VALIDATION_ERROR.format(args.network)) return request
true
true
1c39cb12905b1cd1f69475bf120720cda699220e
1,315
py
Python
p1-stock-code/stock-code.py
cclai999/pyxl-stock
3c0bb2f3e17f88770d16e9cb7171d56757a451b4
[ "MIT" ]
null
null
null
p1-stock-code/stock-code.py
cclai999/pyxl-stock
3c0bb2f3e17f88770d16e9cb7171d56757a451b4
[ "MIT" ]
null
null
null
p1-stock-code/stock-code.py
cclai999/pyxl-stock
3c0bb2f3e17f88770d16e9cb7171d56757a451b4
[ "MIT" ]
1
2020-12-27T01:55:19.000Z
2020-12-27T01:55:19.000Z
import pandas as pd from openpyxl import load_workbook from tools import get_html_to_file url1 = "https://isin.twse.com.tw/isin/class_main.jsp?owncode=&stockname=&isincode=&market=1&issuetype=1&industry_code=&Page=1&chklike=Y" url2 = "https://isin.twse.com.tw/isin/class_main.jsp?owncode=&stockname=&isincode=&market=2&issuetype=4&industry_code=&Page=1&chklike=Y" def get_stock_code(html_fname): f = open(html_fname, "r") stk_code_html = f.read() f.close() dfs = pd.read_html(stk_code_html) stk = dfs[0].loc[1:, :] compact_stk = stk[[2, 3, 7, 4, 6]] return compact_stk def insert_stock_code_to_excel(stk_df, stk_code_sheet): for index, row in stk_df.iterrows(): r = row.tolist() # print(r) stk_code_sheet.append(r) def recod_html(): get_html_to_file(url1, "stk_code1_html.txt") get_html_to_file(url2, "stk_code2_html.txt") if __name__ == '__main__': if 1 == 2: recod_html() workbook = load_workbook(filename="stock_code_blank.xlsx") stk_code_sheet = workbook["stk_code"] stk_df = get_stock_code("stk_code1_html.txt") insert_stock_code_to_excel(stk_df, stk_code_sheet) stk_df = get_stock_code("stk_code2_html.txt") insert_stock_code_to_excel(stk_df, stk_code_sheet) workbook.save("stock_code.xlsx")
29.222222
136
0.710266
import pandas as pd from openpyxl import load_workbook from tools import get_html_to_file url1 = "https://isin.twse.com.tw/isin/class_main.jsp?owncode=&stockname=&isincode=&market=1&issuetype=1&industry_code=&Page=1&chklike=Y" url2 = "https://isin.twse.com.tw/isin/class_main.jsp?owncode=&stockname=&isincode=&market=2&issuetype=4&industry_code=&Page=1&chklike=Y" def get_stock_code(html_fname): f = open(html_fname, "r") stk_code_html = f.read() f.close() dfs = pd.read_html(stk_code_html) stk = dfs[0].loc[1:, :] compact_stk = stk[[2, 3, 7, 4, 6]] return compact_stk def insert_stock_code_to_excel(stk_df, stk_code_sheet): for index, row in stk_df.iterrows(): r = row.tolist() stk_code_sheet.append(r) def recod_html(): get_html_to_file(url1, "stk_code1_html.txt") get_html_to_file(url2, "stk_code2_html.txt") if __name__ == '__main__': if 1 == 2: recod_html() workbook = load_workbook(filename="stock_code_blank.xlsx") stk_code_sheet = workbook["stk_code"] stk_df = get_stock_code("stk_code1_html.txt") insert_stock_code_to_excel(stk_df, stk_code_sheet) stk_df = get_stock_code("stk_code2_html.txt") insert_stock_code_to_excel(stk_df, stk_code_sheet) workbook.save("stock_code.xlsx")
true
true
1c39cbb5e1345dbab2efda224099029126a685d6
1,959
py
Python
spectrl/envs/finite_mdp.py
keyshor/high-nash
3ac6e09c554ec94a227f3e76756983295860d665
[ "MIT" ]
null
null
null
spectrl/envs/finite_mdp.py
keyshor/high-nash
3ac6e09c554ec94a227f3e76756983295860d665
[ "MIT" ]
null
null
null
spectrl/envs/finite_mdp.py
keyshor/high-nash
3ac6e09c554ec94a227f3e76756983295860d665
[ "MIT" ]
null
null
null
import gym import numpy as np class FiniteMDP(gym.Env): ''' Finite Multi-agent MDPs ''' def __init__(self, transitions, start_state, num_actions, max_steps=100, rewards={}): ''' 'transitions' is a dictionary mapping joint actions to transition matrices. Eg:- transitions[(0, 0, 1)] = [[0.5, 0.5], [0, 1]] (for 3 agents and 2 states) 'start_state' is an int specifying the starting state 'num_actions' is a list specifying the number of actions for each player. Eg:- num_actions = [2, 2, 3] (3 agents, last agent's actions are {0, 1, 2}) 'rewards' is a dict mapping state-action pairs to list of rewards. Can be empty when using Spectrl specs. ''' self.P = transitions self.start_state = start_state self.rewards = rewards self.max_steps = max_steps self.n = len(num_actions) # Define action space spaces = [gym.spaces.Discrete(na) for na in num_actions] self.action_space = gym.spaces.Tuple(spaces) # Define observation space joint_action = self.action_space.sample() self.observation_space = gym.spaces.Discrete(len(self.P[joint_action])) def reset(self): self.state = self.start_state self.t = 0 return self.state def step(self, action): next_state = np.random.choice(range(self.observation_space.n), p=self.P[action][self.state]) reward = 0.0 if (self.state, action) in self.rewards: reward = self.rewards[(self.state, action)] self.state = next_state self.t += 1 return self.state, reward, self.t >= self.max_steps, {} def render(self): print('s_{}'.format(self.state)) def get_sim_state(self): return self.state def set_sim_state(self, state): self.state = state return self.state
33.20339
90
0.60388
import gym import numpy as np class FiniteMDP(gym.Env): def __init__(self, transitions, start_state, num_actions, max_steps=100, rewards={}): self.P = transitions self.start_state = start_state self.rewards = rewards self.max_steps = max_steps self.n = len(num_actions) spaces = [gym.spaces.Discrete(na) for na in num_actions] self.action_space = gym.spaces.Tuple(spaces) joint_action = self.action_space.sample() self.observation_space = gym.spaces.Discrete(len(self.P[joint_action])) def reset(self): self.state = self.start_state self.t = 0 return self.state def step(self, action): next_state = np.random.choice(range(self.observation_space.n), p=self.P[action][self.state]) reward = 0.0 if (self.state, action) in self.rewards: reward = self.rewards[(self.state, action)] self.state = next_state self.t += 1 return self.state, reward, self.t >= self.max_steps, {} def render(self): print('s_{}'.format(self.state)) def get_sim_state(self): return self.state def set_sim_state(self, state): self.state = state return self.state
true
true
1c39cc563fc605a827f88d7b504a38495a6f1f3d
3,325
py
Python
setup.py
nardi/iocursor
11e88cec3efb8b94d4bde4a483572a5f135175a7
[ "MIT" ]
3
2021-06-01T16:53:15.000Z
2022-02-14T07:02:53.000Z
setup.py
nardi/iocursor
11e88cec3efb8b94d4bde4a483572a5f135175a7
[ "MIT" ]
null
null
null
setup.py
nardi/iocursor
11e88cec3efb8b94d4bde4a483572a5f135175a7
[ "MIT" ]
1
2021-07-01T16:35:14.000Z
2021-07-01T16:35:14.000Z
#!/usr/bin/env python # coding: utf-8 import configparser import glob import os import sys import setuptools from distutils.command.clean import clean as _clean from setuptools.command.build_ext import build_ext as _build_ext from setuptools.command.sdist import sdist as _sdist # --- `setup.py` commands ---------------------------------------------------- class sdist(_sdist): """A `sdist` that generates a `pyproject.toml` on the fly. """ def run(self): # build `pyproject.toml` from `setup.cfg` c = configparser.ConfigParser() c.add_section("build-system") c.set("build-system", "requires", str(self.distribution.setup_requires)) c.set("build-system", 'build-backend', '"setuptools.build_meta"') with open("pyproject.toml", "w") as pyproject: c.write(pyproject) # run the rest of the packaging _sdist.run(self) class build_ext(_build_ext): """A `build_ext` that disables optimizations if compiled in debug mode. """ user_options = _build_ext.user_options + [ ("coverage", "C", "compile extension with coverage support") ] def initialize_options(self): self.coverage = False _build_ext.initialize_options(self) def info(self, message): self.announce(message, level=2) def warn(self, message): self.announce(message, level=3) def build_extension(self, ext): # update compile flags if compiling in debug mode if self.debug: self.info("adding C flags to compile without optimisations") if self.compiler.compiler_type in {"unix", "cygwin", "mingw32"}: ext.extra_compile_args.append("-O0") elif self.compiler.compiler_type == "msvc": ext.extra_compile_args.append("/Od") else: self.warn("unknown C compiler, cannot add debug flags") if self.coverage: self.info("adding C flags to compile with coverage support") if self.compiler.compiler_type in {"unix", "cygwin", "mingw32"}: ext.extra_compile_args.append("--coverage") ext.extra_link_args.append("--coverage") else: self.warn("unknown C compiler, cannot add coverage flags") # run like normal _build_ext.build_extension(self, ext) class clean(_clean): def info(self, message): self.announce(message, level=2) def run(self): source_dir = os.path.join(os.path.dirname(__file__), "iocursor") if self.all: for file in glob.glob(os.path.join(source_dir, "*.so")): self.info("removing {!r}".format(file)) os.remove(file) _clean.run(self) # --- C extension ------------------------------------------------------------ if sys.implementation.name == "cpython": defines = [("CPYTHON", 1)] else: defines = [] extensions = [ setuptools.Extension( "iocursor.cursor", [os.path.join("iocursor", "cursor.c")], define_macros=defines, ) ] # --- Setup ------------------------------------------------------------------ setuptools.setup( ext_modules=extensions, cmdclass=dict( build_ext=build_ext, clean=clean, sdist=sdist, ) )
28.913043
80
0.583459
import configparser import glob import os import sys import setuptools from distutils.command.clean import clean as _clean from setuptools.command.build_ext import build_ext as _build_ext from setuptools.command.sdist import sdist as _sdist class sdist(_sdist): def run(self): c = configparser.ConfigParser() c.add_section("build-system") c.set("build-system", "requires", str(self.distribution.setup_requires)) c.set("build-system", 'build-backend', '"setuptools.build_meta"') with open("pyproject.toml", "w") as pyproject: c.write(pyproject) _sdist.run(self) class build_ext(_build_ext): user_options = _build_ext.user_options + [ ("coverage", "C", "compile extension with coverage support") ] def initialize_options(self): self.coverage = False _build_ext.initialize_options(self) def info(self, message): self.announce(message, level=2) def warn(self, message): self.announce(message, level=3) def build_extension(self, ext): if self.debug: self.info("adding C flags to compile without optimisations") if self.compiler.compiler_type in {"unix", "cygwin", "mingw32"}: ext.extra_compile_args.append("-O0") elif self.compiler.compiler_type == "msvc": ext.extra_compile_args.append("/Od") else: self.warn("unknown C compiler, cannot add debug flags") if self.coverage: self.info("adding C flags to compile with coverage support") if self.compiler.compiler_type in {"unix", "cygwin", "mingw32"}: ext.extra_compile_args.append("--coverage") ext.extra_link_args.append("--coverage") else: self.warn("unknown C compiler, cannot add coverage flags") _build_ext.build_extension(self, ext) class clean(_clean): def info(self, message): self.announce(message, level=2) def run(self): source_dir = os.path.join(os.path.dirname(__file__), "iocursor") if self.all: for file in glob.glob(os.path.join(source_dir, "*.so")): self.info("removing {!r}".format(file)) os.remove(file) _clean.run(self) if sys.implementation.name == "cpython": defines = [("CPYTHON", 1)] else: defines = [] extensions = [ setuptools.Extension( "iocursor.cursor", [os.path.join("iocursor", "cursor.c")], define_macros=defines, ) ] setuptools.setup( ext_modules=extensions, cmdclass=dict( build_ext=build_ext, clean=clean, sdist=sdist, ) )
true
true
1c39cc6db1874258fd396af5c835ea5525aa73a3
4,354
py
Python
doc/source/conf.py
4383/tobiko
f8e6916db890021fa17ddbfc5e6007a25093c8cb
[ "Apache-2.0" ]
null
null
null
doc/source/conf.py
4383/tobiko
f8e6916db890021fa17ddbfc5e6007a25093c8cb
[ "Apache-2.0" ]
null
null
null
doc/source/conf.py
4383/tobiko
f8e6916db890021fa17ddbfc5e6007a25093c8cb
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Red Hat # # 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. # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TOBIKO_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "..")) sys.path.insert(0, TOBIKO_DIR) # -- Project information ----------------------------------------------------- project = 'Tobiko' copyright = "2019, Red Hat" author = "Tobiko's Team" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # Version info from tobiko import version release = version.release # The short X.Y version. version = version.version # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.graphviz', 'sphinx.ext.todo', 'oslo_config.sphinxext', 'oslo_config.sphinxconfiggen', ] # Add any paths that contain templates here, relative to this directory. templates_path = [] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # openstackdocstheme options repository_name = 'x/tobiko' bug_project = 'tobiko' bug_tag = 'doc' # Set to True if using StoryBoard use_storyboard = True todo_include_todos = True # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = { "canonical_url": "https://docs.openstack.org/tobiko/latest/", "logo_only": False, "display_version": True, "prev_next_buttons_location": "top", "style_external_links": True, # Toc options "collapse_navigation": True, "sticky_navigation": True, "navigation_depth": 4, "includehidden": True, "titles_only": False, } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # -- Options for oslo_config.sphinxconfiggen --------------------------------- _config_generator_config_files = [ 'tobiko.conf', ] def _get_config_generator_config_definition(conf): config_file_path = '../../etc/oslo-config-generator/%s' % conf # oslo_config.sphinxconfiggen appends '.conf.sample' to the filename, # strip file extentension (.conf or .ini). output_file_path = '_static/config-samples/%s' % conf.rsplit('.', 1)[0] return (config_file_path, output_file_path) config_generator_config_file = [ _get_config_generator_config_definition(conf) for conf in _config_generator_config_files ]
32.014706
79
0.692696
import os import sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) TOBIKO_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "..")) sys.path.insert(0, TOBIKO_DIR) project = 'Tobiko' copyright = "2019, Red Hat" author = "Tobiko's Team" # The version info for the project you're documenting, acts as replacement for from tobiko import version release = version.release version = version.version extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.graphviz', 'sphinx.ext.todo', 'oslo_config.sphinxext', 'oslo_config.sphinxconfiggen', ] templates_path = [] exclude_patterns = [] repository_name = 'x/tobiko' bug_project = 'tobiko' bug_tag = 'doc' use_storyboard = True todo_include_todos = True html_theme = "sphinx_rtd_theme" html_theme_options = { "canonical_url": "https://docs.openstack.org/tobiko/latest/", "logo_only": False, "display_version": True, "prev_next_buttons_location": "top", "style_external_links": True, "collapse_navigation": True, "sticky_navigation": True, "navigation_depth": 4, "includehidden": True, "titles_only": False, } html_static_path = ['_static'] _config_generator_config_files = [ 'tobiko.conf', ] def _get_config_generator_config_definition(conf): config_file_path = '../../etc/oslo-config-generator/%s' % conf output_file_path = '_static/config-samples/%s' % conf.rsplit('.', 1)[0] return (config_file_path, output_file_path) config_generator_config_file = [ _get_config_generator_config_definition(conf) for conf in _config_generator_config_files ]
true
true
1c39cc78f7fc6d9dd231de1c9b2d6eebed2bd7ab
3,627
py
Python
official/cv/resnet/infer/ResNet152/sdk/main.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
77
2021-10-15T08:32:37.000Z
2022-03-30T13:09:11.000Z
official/cv/resnet/infer/ResNet152/sdk/main.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
3
2021-10-30T14:44:57.000Z
2022-02-14T06:57:57.000Z
official/cv/resnet/infer/ResNet152/sdk/main.py
leelige/mindspore
5199e05ba3888963473f2b07da3f7bca5b9ef6dc
[ "Apache-2.0" ]
24
2021-10-15T08:32:45.000Z
2022-03-24T18:45:20.000Z
# coding=utf-8 # Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """run sdk""" import datetime import json import os import sys from StreamManagerApi import StreamManagerApi from StreamManagerApi import MxDataInput def run(): """run sdk""" # init stream manager stream_manager_api = StreamManagerApi() ret = stream_manager_api.InitManager() if ret != 0: print("Failed to init Stream manager, ret=%s" % str(ret)) return # create streams by pipeline config file with open("./resnet152.pipeline", 'rb') as f: pipelineStr = f.read() ret = stream_manager_api.CreateMultipleStreams(pipelineStr) if ret != 0: print("Failed to create Stream, ret=%s" % str(ret)) return # Construct the input of the stream data_input = MxDataInput() dir_name = sys.argv[1] res_dir_name = sys.argv[2] file_list = os.listdir(dir_name) if not os.path.exists(res_dir_name): os.makedirs(res_dir_name) image_count = 0 for file_name in file_list: file_path = os.path.join(dir_name, file_name) if not (file_name.lower().endswith( ".jpg") or file_name.lower().endswith(".jpeg")): continue with open(file_path, 'rb') as f: data_input.data = f.read() stream_name = b'im_resnet152' in_plugin_id = 0 unique_id = stream_manager_api.SendData(stream_name, in_plugin_id, data_input) if unique_id < 0: print("Failed to send data to stream.") return # Obtain the inference result by specifying streamName and uniqueId. start_time = datetime.datetime.now() infer_result = stream_manager_api.GetResult(stream_name, unique_id) end_time = datetime.datetime.now() print('sdk run time: {}'.format((end_time - start_time).microseconds)) if infer_result.errorCode != 0: print("GetResultWithUniqueId error. errorCode=%d, errorMsg=%s" % ( infer_result.errorCode, infer_result.data.decode())) return # print the infer result infer_res = infer_result.data.decode() print("process img{}: {}, infer result: {}".format(image_count, file_name, infer_res)) image_count = image_count + 1 load_dict = json.loads(infer_result.data.decode()) if load_dict.get('MxpiClass') is None: with open(res_dir_name + "/" + file_name[:-5] + '.txt', 'w') as f_write: f_write.write("") continue res_vec = load_dict.get('MxpiClass') with open(res_dir_name + "/" + file_name[:-5] + '_1.txt', 'w') as f_write: res_list = [str(item.get("classId")) + " " for item in res_vec] f_write.writelines(res_list) f_write.write('\n') # destroy streams stream_manager_api.DestroyAllStreams() if __name__ == '__main__': run()
34.542857
94
0.61759
import datetime import json import os import sys from StreamManagerApi import StreamManagerApi from StreamManagerApi import MxDataInput def run(): stream_manager_api = StreamManagerApi() ret = stream_manager_api.InitManager() if ret != 0: print("Failed to init Stream manager, ret=%s" % str(ret)) return with open("./resnet152.pipeline", 'rb') as f: pipelineStr = f.read() ret = stream_manager_api.CreateMultipleStreams(pipelineStr) if ret != 0: print("Failed to create Stream, ret=%s" % str(ret)) return data_input = MxDataInput() dir_name = sys.argv[1] res_dir_name = sys.argv[2] file_list = os.listdir(dir_name) if not os.path.exists(res_dir_name): os.makedirs(res_dir_name) image_count = 0 for file_name in file_list: file_path = os.path.join(dir_name, file_name) if not (file_name.lower().endswith( ".jpg") or file_name.lower().endswith(".jpeg")): continue with open(file_path, 'rb') as f: data_input.data = f.read() stream_name = b'im_resnet152' in_plugin_id = 0 unique_id = stream_manager_api.SendData(stream_name, in_plugin_id, data_input) if unique_id < 0: print("Failed to send data to stream.") return start_time = datetime.datetime.now() infer_result = stream_manager_api.GetResult(stream_name, unique_id) end_time = datetime.datetime.now() print('sdk run time: {}'.format((end_time - start_time).microseconds)) if infer_result.errorCode != 0: print("GetResultWithUniqueId error. errorCode=%d, errorMsg=%s" % ( infer_result.errorCode, infer_result.data.decode())) return infer_res = infer_result.data.decode() print("process img{}: {}, infer result: {}".format(image_count, file_name, infer_res)) image_count = image_count + 1 load_dict = json.loads(infer_result.data.decode()) if load_dict.get('MxpiClass') is None: with open(res_dir_name + "/" + file_name[:-5] + '.txt', 'w') as f_write: f_write.write("") continue res_vec = load_dict.get('MxpiClass') with open(res_dir_name + "/" + file_name[:-5] + '_1.txt', 'w') as f_write: res_list = [str(item.get("classId")) + " " for item in res_vec] f_write.writelines(res_list) f_write.write('\n') stream_manager_api.DestroyAllStreams() if __name__ == '__main__': run()
true
true
1c39ccaa8632efa29bf1d6b281d47bd52b4b78c9
3,846
py
Python
python/tvm/topi/cuda/searchsorted.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
4,640
2017-08-17T19:22:15.000Z
2019-11-04T15:29:46.000Z
python/tvm/topi/cuda/searchsorted.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
3,022
2020-11-24T14:02:31.000Z
2022-03-31T23:55:31.000Z
python/tvm/topi/cuda/searchsorted.py
XiaoSong9905/tvm
48940f697e15d5b50fa1f032003e6c700ae1e423
[ "Apache-2.0" ]
1,352
2017-08-17T19:30:38.000Z
2019-11-04T16:09:29.000Z
# 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=invalid-name """searchsorted operator for GPU""" import tvm from tvm import te from .. import utils from ..searchsorted import binary_search def searchsorted(sorted_sequence, values, right, out_dtype="int64"): """Find indices where elements should be inserted to maintain order. If `sorted_sequence` is N-dimensional, the innermost dimension of `values` are searched in the corresponding dimension of `sorted_sequence`. Parameters ---------- sorted_sequence : te.Tensor N-D or 1-D Tensor, containing monotonically increasing sequence on the innermost dimension. values : te.Tensor N-D Tensor containing the search values. When `sorted_sequence` is 1-D, the shape of `values` can be arbitrary. Otherwise, ranks of `sorted_sequence` and `values` must be the same, and outer N-1 axes must have the same size. right : bool, optional Controls which index is returned if a value lands exactly on one of sorted values. If False, the index of the first suitable location found is given. If true, return the last such index. If there is no suitable index, return either 0 or N (where N is the size of the innermost dimension). dtype : string, optional The data type of the output indices. Returns ------- indices : te.Tensor Tensor with same shape as values, representing the indices of elements of `values` if they are inserted in `sorted_sequence`. """ def ir(sorted_sequence, values, indices): ib = tvm.tir.ir_builder.create() sorted_sequence_shape = sorted_sequence.shape values_shape = values.shape num_search = utils.prod(values_shape) search_range = sorted_sequence_shape[-1] sorted_sequence = ib.buffer_ptr(sorted_sequence) values = ib.buffer_ptr(values) indices = ib.buffer_ptr(indices) max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads) bx = te.thread_axis("blockIdx.x") tx = te.thread_axis("threadIdx.x") ib.scope_attr( bx, "thread_extent", tvm.tir.indexdiv(num_search + max_threads - 1, max_threads) ) ib.scope_attr(tx, "thread_extent", max_threads) tid = bx * max_threads + tx with ib.if_scope(tid < num_search): if len(sorted_sequence_shape) == 1: sequence_offset = 0 else: sequence_id = tid // values_shape[-1] sequence_offset = sequence_id * search_range indices[tid] = binary_search( ib, sequence_offset, search_range, sorted_sequence, values[tid], right, out_dtype, ) return ib.get() return te.extern( values.shape, [sorted_sequence, values], lambda ins, outs: ir(ins[0], ins[1], outs[0]), name="searchsorted", dtype=out_dtype, )
37.339806
93
0.658346
import tvm from tvm import te from .. import utils from ..searchsorted import binary_search def searchsorted(sorted_sequence, values, right, out_dtype="int64"): def ir(sorted_sequence, values, indices): ib = tvm.tir.ir_builder.create() sorted_sequence_shape = sorted_sequence.shape values_shape = values.shape num_search = utils.prod(values_shape) search_range = sorted_sequence_shape[-1] sorted_sequence = ib.buffer_ptr(sorted_sequence) values = ib.buffer_ptr(values) indices = ib.buffer_ptr(indices) max_threads = int(tvm.target.Target.current(allow_none=False).max_num_threads) bx = te.thread_axis("blockIdx.x") tx = te.thread_axis("threadIdx.x") ib.scope_attr( bx, "thread_extent", tvm.tir.indexdiv(num_search + max_threads - 1, max_threads) ) ib.scope_attr(tx, "thread_extent", max_threads) tid = bx * max_threads + tx with ib.if_scope(tid < num_search): if len(sorted_sequence_shape) == 1: sequence_offset = 0 else: sequence_id = tid // values_shape[-1] sequence_offset = sequence_id * search_range indices[tid] = binary_search( ib, sequence_offset, search_range, sorted_sequence, values[tid], right, out_dtype, ) return ib.get() return te.extern( values.shape, [sorted_sequence, values], lambda ins, outs: ir(ins[0], ins[1], outs[0]), name="searchsorted", dtype=out_dtype, )
true
true
1c39cd8c4cf42ebac589fbb1076b1761f7dbaeff
2,060
py
Python
cardea/fhir/Reference.py
Hector-hedb12/Cardea
75c75f343796555f08c4511d6427efd04261a105
[ "MIT" ]
null
null
null
cardea/fhir/Reference.py
Hector-hedb12/Cardea
75c75f343796555f08c4511d6427efd04261a105
[ "MIT" ]
null
null
null
cardea/fhir/Reference.py
Hector-hedb12/Cardea
75c75f343796555f08c4511d6427efd04261a105
[ "MIT" ]
null
null
null
from .fhirbase import fhirbase class Reference(fhirbase): """ A reference from one resource to another. Attributes: reference: A reference to a location at which the other resource is found. The reference may be a relative reference, in which case it is relative to the service base URL, or an absolute URL that resolves to the location where the resource is found. The reference may be version specific or not. If the reference is not to a FHIR RESTful server, then it should be assumed to be version specific. Internal fragment references (start with '#') refer to contained resources. identifier: An identifier for the other resource. This is used when there is no way to reference the other resource directly, either because the entity is not available through a FHIR server, or because there is no way for the author of the resource to convert a known identifier to an actual location. There is no requirement that a Reference.identifier point to something that is actually exposed as a FHIR instance, but it SHALL point to a business concept that would be expected to be exposed as a FHIR instance, and that instance would need to be of a FHIR resource type allowed by the reference. display: Plain text narrative that identifies the resource in addition to the resource reference. """ __name__ = 'Reference' def __init__(self, dict_values=None): self.reference = None # type: str self.display = None # type: str self.identifier = None # reference to Identifier if dict_values: self.set_attributes(dict_values) def get_relationships(self): return [ {'parent_entity': 'Identifier', 'parent_variable': 'object_id', 'child_entity': 'Reference', 'child_variable': 'identifier'}, ]
39.615385
82
0.647087
from .fhirbase import fhirbase class Reference(fhirbase): __name__ = 'Reference' def __init__(self, dict_values=None): self.reference = None self.display = None self.identifier = None if dict_values: self.set_attributes(dict_values) def get_relationships(self): return [ {'parent_entity': 'Identifier', 'parent_variable': 'object_id', 'child_entity': 'Reference', 'child_variable': 'identifier'}, ]
true
true
1c39d0ba68c5aa0475565e3a4ceea547d580d482
895
py
Python
netqasm/examples/apps/three_nodes/app_charlie.py
Doomsk/netqasm
5d6c6ad00c4e0f9ab0ec05518cfa827675f357e7
[ "MIT" ]
null
null
null
netqasm/examples/apps/three_nodes/app_charlie.py
Doomsk/netqasm
5d6c6ad00c4e0f9ab0ec05518cfa827675f357e7
[ "MIT" ]
null
null
null
netqasm/examples/apps/three_nodes/app_charlie.py
Doomsk/netqasm
5d6c6ad00c4e0f9ab0ec05518cfa827675f357e7
[ "MIT" ]
null
null
null
from netqasm.logging.glob import get_netqasm_logger from netqasm.sdk import EPRSocket from netqasm.sdk.external import NetQASMConnection logger = get_netqasm_logger() def main(app_config): epr_socket_alice = EPRSocket( remote_app_name="alice", epr_socket_id=0, remote_epr_socket_id=1 ) epr_socket_bob = EPRSocket( remote_app_name="bob", epr_socket_id=1, remote_epr_socket_id=1 ) charlie = NetQASMConnection( app_name=app_config.app_name, log_config=app_config.log_config, epr_sockets=[epr_socket_alice, epr_socket_bob], ) with charlie: epr_alice = epr_socket_alice.recv()[0] m_alice = epr_alice.measure() charlie.flush() epr_bob = epr_socket_bob.recv()[0] m_bob = epr_bob.measure() logger.info(f"charlie: m_alice: {m_alice}") logger.info(f"charlie: m_bob: {m_bob}")
27.96875
72
0.69162
from netqasm.logging.glob import get_netqasm_logger from netqasm.sdk import EPRSocket from netqasm.sdk.external import NetQASMConnection logger = get_netqasm_logger() def main(app_config): epr_socket_alice = EPRSocket( remote_app_name="alice", epr_socket_id=0, remote_epr_socket_id=1 ) epr_socket_bob = EPRSocket( remote_app_name="bob", epr_socket_id=1, remote_epr_socket_id=1 ) charlie = NetQASMConnection( app_name=app_config.app_name, log_config=app_config.log_config, epr_sockets=[epr_socket_alice, epr_socket_bob], ) with charlie: epr_alice = epr_socket_alice.recv()[0] m_alice = epr_alice.measure() charlie.flush() epr_bob = epr_socket_bob.recv()[0] m_bob = epr_bob.measure() logger.info(f"charlie: m_alice: {m_alice}") logger.info(f"charlie: m_bob: {m_bob}")
true
true
1c39d0c50c3baca0aa302babde060b258f61c9aa
9,066
py
Python
multimedia/south_migrations/0022_move_media.py
jbittel/django-multimedia
4ddd5e6d9f4f680e2f4f68cc3616ced8f0fc2a43
[ "BSD-3-Clause" ]
19
2015-01-28T08:40:20.000Z
2021-12-18T11:55:58.000Z
multimedia/south_migrations/0022_move_media.py
jbittel/django-multimedia
4ddd5e6d9f4f680e2f4f68cc3616ced8f0fc2a43
[ "BSD-3-Clause" ]
2
2015-02-09T17:03:24.000Z
2015-04-22T17:57:45.000Z
multimedia/south_migrations/0022_move_media.py
jbittel/django-multimedia
4ddd5e6d9f4f680e2f4f68cc3616ced8f0fc2a43
[ "BSD-3-Clause" ]
4
2015-02-02T14:05:08.000Z
2016-09-14T00:44:55.000Z
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): for audio in orm.Audio.objects.all(): old_profiles = audio.profiles.all() media = orm.Media(created=audio.created, description=audio.description, file=audio.file, modified=audio.modified, owner=audio.owner, slug=audio.slug, title=audio.title) media.save() media.profiles = old_profiles for profile in old_profiles: rs = orm.RemoteStorage(media=media, profile=profile, created=audio.created, modified=audio.modified) rs.save() for video in orm.Video.objects.all(): old_profiles = video.profiles.all() media = orm.Media(created=video.created, description=video.description, file=video.file, modified=video.modified, owner=video.owner, slug=video.slug, title=video.title) media.save() media.profiles = old_profiles for profile in old_profiles: rs = orm.RemoteStorage(media=media, profile=profile, created=video.created, modified=video.modified) rs.save() def backwards(self, orm): raise RuntimeError("Cannot reverse this migration.") models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'multimedia.audio': { 'Meta': {'object_name': 'Audio'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'profiles': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['multimedia.EncodeProfile']", 'symmetrical': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'multimedia.encodeprofile': { 'Meta': {'object_name': 'EncodeProfile'}, 'command': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'container': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'file_type': ('django.db.models.fields.CharField', [], {'max_length': '32'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'multimedia.media': { 'Meta': {'ordering': "(u'-created',)", 'object_name': 'Media'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'profiles': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['multimedia.EncodeProfile']", 'symmetrical': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'multimedia.remotestorage': { 'Meta': {'object_name': 'RemoteStorage'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'media': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['multimedia.Media']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'profile': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['multimedia.EncodeProfile']"}) }, u'multimedia.video': { 'Meta': {'object_name': 'Video'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'profiles': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['multimedia.EncodeProfile']", 'symmetrical': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['multimedia'] symmetrical = True
63.398601
195
0.539709
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): for audio in orm.Audio.objects.all(): old_profiles = audio.profiles.all() media = orm.Media(created=audio.created, description=audio.description, file=audio.file, modified=audio.modified, owner=audio.owner, slug=audio.slug, title=audio.title) media.save() media.profiles = old_profiles for profile in old_profiles: rs = orm.RemoteStorage(media=media, profile=profile, created=audio.created, modified=audio.modified) rs.save() for video in orm.Video.objects.all(): old_profiles = video.profiles.all() media = orm.Media(created=video.created, description=video.description, file=video.file, modified=video.modified, owner=video.owner, slug=video.slug, title=video.title) media.save() media.profiles = old_profiles for profile in old_profiles: rs = orm.RemoteStorage(media=media, profile=profile, created=video.created, modified=video.modified) rs.save() def backwards(self, orm): raise RuntimeError("Cannot reverse this migration.") models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'multimedia.audio': { 'Meta': {'object_name': 'Audio'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'profiles': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['multimedia.EncodeProfile']", 'symmetrical': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'multimedia.encodeprofile': { 'Meta': {'object_name': 'EncodeProfile'}, 'command': ('django.db.models.fields.CharField', [], {'max_length': '1024'}), 'container': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'file_type': ('django.db.models.fields.CharField', [], {'max_length': '32'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'multimedia.media': { 'Meta': {'ordering': "(u'-created',)", 'object_name': 'Media'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'profiles': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['multimedia.EncodeProfile']", 'symmetrical': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, u'multimedia.remotestorage': { 'Meta': {'object_name': 'RemoteStorage'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'media': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['multimedia.Media']"}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'profile': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['multimedia.EncodeProfile']"}) }, u'multimedia.video': { 'Meta': {'object_name': 'Video'}, 'created': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}), 'profiles': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['multimedia.EncodeProfile']", 'symmetrical': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '255'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['multimedia'] symmetrical = True
true
true
1c39d2ce35fa1d037a4d280d7d6f300feb05c36a
23,359
py
Python
armi/bookkeeping/memoryProfiler.py
bsculac/armi
22399244a88e67fc09996981081f7d5aab7032b4
[ "Apache-2.0" ]
null
null
null
armi/bookkeeping/memoryProfiler.py
bsculac/armi
22399244a88e67fc09996981081f7d5aab7032b4
[ "Apache-2.0" ]
null
null
null
armi/bookkeeping/memoryProfiler.py
bsculac/armi
22399244a88e67fc09996981081f7d5aab7032b4
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 TerraPower, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. r""" Interface to help diagnose memory issues during debugging/development. There are many approaches to memory profiling. 1. You can ask psutil for the memory used by the process from an OS perspective. This is great for top-down analysis. This module provides printouts that show info from every process running. This is very fast. 2. You can use ``asizeof`` (part of pympler) to measure the size of various individual objects. This will help you pin-point your issue. But it's slow. 3. You can use ``gc.get_objects()`` to list all objects that the garbage collector is tracking. If you want, you can filter it down and get the counts and sizes of objects of interest (e.g. all armi objects). This module has tools to do all of this. It should help you out. Note that if psutil is reporting way more memory usage than the asizeof reports, then you probably are dealing with a garbage collection queue. If you free a large number of objects, call `gc.collect()` to force a garbage collection and the psutil process memory should fall by a lot. Also, it seems that even if your garbage is collected, Windows does not de-allocate all the memory. So if you are a worker and you just got a 1.6GB reactor but then deleted it, Windows will keep you at 1.6GB for a while. See Also: http://packages.python.org/Pympler/index.html https://pythonhosted.org/psutil/ https://docs.python.org/2/library/gc.html#gc.garbage """ import gc import logging import tabulate from typing import Optional from armi import context from armi import interfaces from armi import mpiActions from armi import runLog from armi.reactor.composites import ArmiObject try: import psutil # psutil is an optional requirement, since it doesnt support MacOS very well _havePsutil = True except ImportError: runLog.warning( "Failed to import psutil; MemoryProfiler will not provide meaningful data." ) _havePsutil = False # disable the import warnings (Issue #88) logging.disable(logging.CRITICAL) from pympler.asizeof import asizeof # This is necessary to reset pympler's changes to the logging configuration logging.disable(logging.NOTSET) ORDER = interfaces.STACK_ORDER.POSTPROCESSING def describeInterfaces(cs): """Function for exposing interface(s) to other code""" return (MemoryProfiler, {}) class MemoryProfiler(interfaces.Interface): name = "memoryProfiler" def __init__(self, r, cs): interfaces.Interface.__init__(self, r, cs) self.sizes = {} def interactBOL(self): interfaces.Interface.interactBOL(self) mpiAction = PrintSystemMemoryUsageAction() mpiAction.broadcast().invoke(self.o, self.r, self.cs) mpiAction.printUsage("BOL SYS_MEM") # so we can debug mem profiler quickly if self.cs["debugMem"]: mpiAction = ProfileMemoryUsageAction("EveryNode") mpiAction.broadcast().invoke(self.o, self.r, self.cs) def interactEveryNode(self, cycle, node): mp = PrintSystemMemoryUsageAction() mp.broadcast() mp.invoke(self.o, self.r, self.cs) mp.printUsage("c{} n{} SYS_MEM".format(cycle, node)) self.r.core.p.minProcessMemoryInMB = round(mp.minProcessMemoryInMB * 10) / 10.0 self.r.core.p.maxProcessMemoryInMB = round(mp.maxProcessMemoryInMB * 10) / 10.0 if self.cs["debugMem"]: mpiAction = ProfileMemoryUsageAction("EveryNode") mpiAction.broadcast().invoke(self.o, self.r, self.cs) def interactEOL(self): r"""End of life hook. Good place to wrap up or print out summary outputs""" if self.cs["debugMem"]: mpiAction = ProfileMemoryUsageAction("EOL") mpiAction.broadcast().invoke(self.o, self.r, self.cs) def displayMemoryUsage(self, timeDescription): r""" Print out some information to stdout about the memory usage of ARMI. Makes use of the asizeof utility. Useful when the debugMem setting is set to True. Turn these on as appropriate to find all your problems. """ runLog.important( "----- Memory Usage Report at {} -----".format(timeDescription) ) self._printFullMemoryBreakdown( startsWith="", reportSize=self.cs["debugMemSize"] ) self._reactorAssemblyTrackingBreakdown() runLog.important( "----- End Memory Usage Report at {} -----".format(timeDescription) ) def _reactorAssemblyTrackingBreakdown(self): runLog.important("Reactor attribute ArmiObject tracking count") for attrName, attrObj in self.r.core.__dict__.items(): if ( isinstance(attrObj, list) and attrObj and isinstance(attrObj[0], ArmiObject) ): runLog.important( "List {:30s} has {:4d} assemblies".format(attrName, len(attrObj)) ) if ( isinstance(attrObj, dict) and attrObj and isinstance(list(attrObj.values())[0], ArmiObject) ): runLog.important( "Dict {:30s} has {:4d} assemblies".format(attrName, len(attrObj)) ) runLog.important("SFP has {:4d} assemblies".format(len(self.r.core.sfp))) def checkForDuplicateObjectsOnArmiModel(self, attrName, refObject): """Scans thorugh ARMI model for duplicate objects""" if self.r is None: return uniqueIds = set() uniqueObjTypes = set() def checkAttr(subObj): if getattr(subObj, attrName, refObject) != refObject: uniqueIds.add(id(getattr(subObj, attrName))) uniqueObjTypes.add(subObj.__class__.__name__) for a in self.r.core.getAssemblies(includeAll=True): checkAttr(a) for b in a: checkAttr(b) for c in b: checkAttr(c) checkAttr(c.material) for i in self.o.getInterfaces(): checkAttr(i) if i.name == "xsGroups": for _, block in i.representativeBlocks.items(): checkAttr(block) if len(uniqueIds) == 0: runLog.important("There are no duplicate `.{}` attributes".format(attrName)) else: runLog.error( "There are {} unique objects stored as `.{}` attributes!\n" "Expected id {}, but got {}.\nExpected object:{}\n" "These types of objects had unique attributes: {}".format( len(uniqueIds) + 1, attrName, id(refObject), uniqueIds, refObject, ", ".join(uniqueObjTypes), ) ) raise RuntimeError def _printFullMemoryBreakdown( self, startsWith="armi", reportSize=True, printReferrers=False ): """ looks for any class from any module in the garbage collector and prints their count and size Very powerful. Also very slow if you reportSize Parameters ---------- startsWith : str, optional limit to objects with classes that start with a certain string reportSize : bool, optional calculate size as well as counting individual objects. SLLOOOWW. Notes ----- Just because you use startsWith=armi doesn't mean you'll capture all ARMI objects. Some are in lists and dictionaries. """ cs = self.cs operator = self.o reactor = self.r if reportSize: self.r.detach() self.o.detach() gc.collect() allObjects = gc.get_objects() instanceCounters = KlassCounter(reportSize) runLog.info("GC returned {} objects".format(len(allObjects))) instanceCounters.countObjects(allObjects) for counter in sorted(instanceCounters.counters.values()): runLog.info( "UNIQUE_INSTANCE_COUNT: {:60s} {:10d} {:10.1f} MB".format( counter.classType.__name__, counter.count, counter.memSize / (1024 ** 2.0), ) ) if printReferrers and counter.memSize / (1024 ** 2.0) > 100: referrers = gc.get_referrers(counter.first) runLog.info(" Referrers of first one: ") for referrer in referrers: runLog.info(" {}".format(repr(referrer)[:150])) runLog.info("gc garbage: {}".format(gc.garbage)) if printReferrers: # if you want more info on the garbage referrers, run this. WARNING, it's generally like 1000000 lines. runLog.info("referrers") for o in gc.garbage: for r in gc.get_referrers(o): runLog.info("ref for {}: {}".format(o, r)) if reportSize: operator.reattach(reactor, cs) @staticmethod def getSpecificReferrers(klass, ancestorKlass): """Try to determine some useful information about the structure of ArmiObjects and potential orphans. This takes a class and an expected/nominal parent class, which should both be instances of ArmiObject. It will then locate all instances of klass that are tracked by the GC, igoring those that have an ancestor of ancestorKlass type. A report will be generated containing the counts of the instances of klass that are _not_ part of the ancestor_class along with their referrer class. This is useful for diagnosing memory leaks, as it points to unexpected referrers to ArmiObjects. """ if not issubclass(klass, ArmiObject) or not issubclass( ancestorKlass, ArmiObject ): raise TypeError( "klass and ancestorKlass should be subclasses of ArmiObject" ) # info will be a list containing a tuple for every instance of klass that does not have an # ancestorKlass somewhere in its chain of parents. Each tuple contains its parent object # and the set of classes of objects that refer to it info = [] nominalCount = 0 exampleObj = None maxObjects = 100 objectsSoFar = 0 for obj in (o for o in gc.get_objects() if isinstance(o, klass)): if objectsSoFar > maxObjects: break isNominal = False o2 = obj while o2.parent is not None: if isinstance(o2.parent, ancestorKlass): isNominal = True break o2 = o2.parent runLog.important("isNominal: {} parent: {}".format(isNominal, obj.parent)) if isNominal: nominalCount += 1 else: exampleObj = obj objectsSoFar += 1 referrers = gc.get_referrers(obj) referrerClasses = {type(o) for o in referrers} info.append((obj.parent, referrerClasses)) if exampleObj is not None: runLog.important("Walking referrers for {}".format(exampleObj)) _walkReferrers(exampleObj, maxLevel=8) raise RuntimeError("All done") runLog.important( "List of {} orphaned ArmiObjects (obj.parent, {{referring object " "classes}})".format(len(info)) ) for item in info: runLog.important("{}".format(item)) @staticmethod def getReferrers(obj): """Print referrers in a useful way (as opposed to gigabytes of text""" runLog.info("Printing first 100 character of first 100 referrers") for ref in gc.get_referrers(obj)[:100]: print("ref for {}: {}".format(obj, repr(ref)[:100])) @staticmethod def discussSkipped(skipped, errors): runLog.warning("Skipped {} objects".format(skipped)) runLog.warning( "errored out on {0} objects:\n {1}".format( len(errors), "\n".join([repr(ei)[:30] for ei in errors]) ) ) class KlassCounter: def __init__(self, reportSize): self.counters = dict() self.reportSize = reportSize self.count = 0 def __getitem__(self, classType): if classType not in self.counters: self.counters[classType] = InstanceCounter(classType, self.reportSize) return self.counters[classType] def __iadd__(self, item): klass = type(item) if klass in self.counters: counter = self.counters[klass] else: counter = InstanceCounter(klass, self.reportSize) counter.first = item # done here for speed self.counters[klass] = counter counter += item def countObjects(self, ao): """ Recursively find non-list,dict, tuple objects in containers. Essential for traversing the garbage collector """ itemType = type(ao) counter = self[itemType] if counter.add(ao): self.count += 1 if self.count % 100000 == 0: runLog.info("Counted {} items".format(self.count)) if isinstance(ao, dict): for k, v in ao.items(): self.countObjects(k) self.countObjects(v) elif isinstance(ao, (list, tuple, set)): for v in iter(ao): self.countObjects(v) class InstanceCounter: def __init__(self, classType, reportSize): self.classType = classType self.count = 0 self.reportSize = reportSize if reportSize: self.memSize = 0 else: self.memSize = float("nan") self.items = set() self.ids = set() self.first = None def add(self, item): itemId = id(item) if itemId in self.ids: return False self.ids.add(itemId) if self.reportSize: try: self.memSize += asizeof(item) except: self.memSize = float("nan") self.count += 1 return True def __cmp__(self, that): return (self.count > that.count) - (self.count < that.count) def __ls__(self, that): return self.count < that.count def __gt__(self, that): return self.count > that.count def _getClsName(obj): try: return obj.__class__.__name__ except: try: return obj.__name__ except: return repr(obj)[:20] def _getModName(obj): try: return obj.__class__.__module__ except: return None class ObjectSizeBreakdown: def __init__( self, name, minMBToShowAttrBreakdown=30.0, excludedAttributes=None, initialZeroes=0, ): # don't hold onto obj, otherwise we'll bloat like crazy!! self.name = name self.sizes = [0.0] * initialZeroes self.minMBToShowAttrBreakdown = minMBToShowAttrBreakdown self.excludedAttributes = excludedAttributes or [] self.attrSizes = {} @property def size(self): return self.sizes[-1] def calcSize(self, obj): tempAttrs = {} try: for attrName in self.excludedAttributes: if hasattr(obj, attrName): tempAttrs[attrName] = getattr(obj, attrName, None) setattr(obj, attrName, None) self.sizes.append(asizeof(obj) / (1024.0 ** 2)) self._breakdownAttributeSizes(obj) finally: for attrName, attrObj in tempAttrs.items(): setattr(obj, attrName, attrObj) def _breakdownAttributeSizes(self, obj): if self.size > self.minMBToShowAttrBreakdown: # make a getter where getter(obj, key) gives obj.key or obj[key] if isinstance(obj, dict): keys = obj.keys() getter = lambda obj, key: obj.get(key) elif isinstance(obj, list): keys = range(len(obj)) getter = lambda obj, key: obj[key] else: keys = obj.__dict__.keys() getter = getattr for attrName in set(keys) - set(self.excludedAttributes): name = " .{}".format(attrName) if name not in self.attrSizes: # arbitrarily, we don't care unless the attribute is a GB self.attrSizes[name] = ObjectSizeBreakdown( name, 1000.0, initialZeroes=len(self.sizes) - 1 ) attrSize = self.attrSizes[name] attrSize.calcSize(getter(obj, attrName)) def __repr__(self): message = [] name = self.name if self.excludedAttributes: name += " except(.{})".format(", .".join(self.excludedAttributes)) message.append("{0:53s} {1:8.4f}MB".format(name, self.size)) for attr in self.attrSizes.values(): message.append(repr(attr)) return "\n".join(message) class ProfileMemoryUsageAction(mpiActions.MpiAction): def __init__(self, timeDescription): mpiActions.MpiAction.__init__(self) self.timeDescription = timeDescription def invokeHook(self): mem = self.o.getInterface("memoryProfiler") mem.displayMemoryUsage(self.timeDescription) class SystemAndProcessMemoryUsage: def __init__(self): self.nodeName = context.MPI_NODENAME # no psutil, no memory diagnostics. # TODO: Ideally, we could cut MemoryProfiler entirely, but it is referred to # directly by the standard operator and reports, so easier said than done. self.percentNodeRamUsed: Optional[float] = None self.processMemoryInMB: Optional[float] = None if _havePsutil: self.percentNodeRamUsed = psutil.virtual_memory().percent self.processMemoryInMB = psutil.Process().memory_info().rss / (1012.0 ** 2) def __isub__(self, other): if self.percentNodeRamUsed is not None and other.percentNodeRamUsed is not None: self.percentNodeRamUsed -= other.percentNodeRamUsed self.processMemoryInMB -= other.processMemoryInMB return self class PrintSystemMemoryUsageAction(mpiActions.MpiAction): def __init__(self): mpiActions.MpiAction.__init__(self) self.usages = [] self.percentNodeRamUsed: Optional[float] = None def __iter__(self): return iter(self.usages) def __isub__(self, other): if self.percentNodeRamUsed is not None and other.percentNodeRamUsed is not None: self.percentNodeRamUsed -= other.percentNodeRamUsed for mine, theirs in zip(self, other): mine -= theirs return self @property def minProcessMemoryInMB(self): if len(self.usages) == 0: return 0.0 return min(mu.processMemoryInMB or 0.0 for mu in self) @property def maxProcessMemoryInMB(self): if len(self.usages) == 0: return 0.0 return max(mu.processMemoryInMB or 0.0 for mu in self) def invokeHook(self): spmu = SystemAndProcessMemoryUsage() self.percentNodeRamUsed = spmu.percentNodeRamUsed self.usages = self.gather(spmu) def printUsage(self, description=None): """This method prints the usage of all MPI nodes. The printout looks something like: SYS_MEM HOSTNAME 14.4% RAM. Proc mem (MB): 491 472 471 471 471 470 SYS_MEM HOSTNAME 13.9% RAM. Proc mem (MB): 474 473 472 471 460 461 SYS_MEM HOSTNAME ... SYS_MEM HOSTNAME ... """ printedNodes = set() prefix = description or "SYS_MEM" memoryData = [] for memoryUsage in self: if memoryUsage.nodeName in printedNodes: continue printedNodes.add(memoryUsage.nodeName) nodeUsages = [mu for mu in self if mu.nodeName == memoryUsage.nodeName] sysMemAvg = sum(mu.percentNodeRamUsed or 0.0 for mu in nodeUsages) / len( nodeUsages ) memoryData.append( ( "{:<24}".format(memoryUsage.nodeName), "{:5.1f}%".format(sysMemAvg), "{}".format( " ".join( "{:5.0f}".format(mu.processMemoryInMB or 0.0) for mu in nodeUsages ) ), ) ) runLog.info( "Summary of the system memory usage at `{}`:\n".format(prefix) + tabulate.tabulate( memoryData, headers=[ "Machine", "Average System RAM Usage", "Processor Memory Usage (MB)", ], tablefmt="armi", ) ) def _getFunctionObject(): """Return the function object of the calling function. Useful for debugging""" from inspect import currentframe, getframeinfo caller = currentframe().f_back func_name = getframeinfo(caller)[2] caller = caller.f_back func = caller.f_locals.get(func_name, caller.f_globals.get(func_name)) return func def _walkReferrers(o, maxLevel=0, level=0, memo=None, whitelist=None): """Walk the tree of objects that refer to the passed object, printing diagnostics.""" if maxLevel and level > maxLevel: return if level == 0: gc.collect() whitelist = {id(obj) for obj in gc.get_objects()} whitelist.remove(id(_getFunctionObject())) whitelist.remove(id(_getFunctionObject)) if memo is None: memo = set() gc.collect() referrers = [ (referrer, id(referrer), id(referrer) in memo) for referrer in gc.get_referrers(o) if referrer.__class__.__name__ != "frame" and id(referrer) in whitelist ] memo.update({oid for (_obj, oid, _seen) in referrers}) for (obj, _, seen) in referrers: runLog.important( "{}{} {} at {:x} seen: {}".format( "-" * level, type(obj), "{}".format(obj)[:100], id(obj), seen ) ) if seen: return _walkReferrers( obj, maxLevel=maxLevel, level=level + 1, memo=memo, whitelist=whitelist )
35.179217
115
0.593176
import gc import logging import tabulate from typing import Optional from armi import context from armi import interfaces from armi import mpiActions from armi import runLog from armi.reactor.composites import ArmiObject try: import psutil _havePsutil = True except ImportError: runLog.warning( "Failed to import psutil; MemoryProfiler will not provide meaningful data." ) _havePsutil = False ging.disable(logging.CRITICAL) from pympler.asizeof import asizeof logging.disable(logging.NOTSET) ORDER = interfaces.STACK_ORDER.POSTPROCESSING def describeInterfaces(cs): return (MemoryProfiler, {}) class MemoryProfiler(interfaces.Interface): name = "memoryProfiler" def __init__(self, r, cs): interfaces.Interface.__init__(self, r, cs) self.sizes = {} def interactBOL(self): interfaces.Interface.interactBOL(self) mpiAction = PrintSystemMemoryUsageAction() mpiAction.broadcast().invoke(self.o, self.r, self.cs) mpiAction.printUsage("BOL SYS_MEM") # so we can debug mem profiler quickly if self.cs["debugMem"]: mpiAction = ProfileMemoryUsageAction("EveryNode") mpiAction.broadcast().invoke(self.o, self.r, self.cs) def interactEveryNode(self, cycle, node): mp = PrintSystemMemoryUsageAction() mp.broadcast() mp.invoke(self.o, self.r, self.cs) mp.printUsage("c{} n{} SYS_MEM".format(cycle, node)) self.r.core.p.minProcessMemoryInMB = round(mp.minProcessMemoryInMB * 10) / 10.0 self.r.core.p.maxProcessMemoryInMB = round(mp.maxProcessMemoryInMB * 10) / 10.0 if self.cs["debugMem"]: mpiAction = ProfileMemoryUsageAction("EveryNode") mpiAction.broadcast().invoke(self.o, self.r, self.cs) def interactEOL(self): if self.cs["debugMem"]: mpiAction = ProfileMemoryUsageAction("EOL") mpiAction.broadcast().invoke(self.o, self.r, self.cs) def displayMemoryUsage(self, timeDescription): runLog.important( "----- Memory Usage Report at {} -----".format(timeDescription) ) self._printFullMemoryBreakdown( startsWith="", reportSize=self.cs["debugMemSize"] ) self._reactorAssemblyTrackingBreakdown() runLog.important( "----- End Memory Usage Report at {} -----".format(timeDescription) ) def _reactorAssemblyTrackingBreakdown(self): runLog.important("Reactor attribute ArmiObject tracking count") for attrName, attrObj in self.r.core.__dict__.items(): if ( isinstance(attrObj, list) and attrObj and isinstance(attrObj[0], ArmiObject) ): runLog.important( "List {:30s} has {:4d} assemblies".format(attrName, len(attrObj)) ) if ( isinstance(attrObj, dict) and attrObj and isinstance(list(attrObj.values())[0], ArmiObject) ): runLog.important( "Dict {:30s} has {:4d} assemblies".format(attrName, len(attrObj)) ) runLog.important("SFP has {:4d} assemblies".format(len(self.r.core.sfp))) def checkForDuplicateObjectsOnArmiModel(self, attrName, refObject): if self.r is None: return uniqueIds = set() uniqueObjTypes = set() def checkAttr(subObj): if getattr(subObj, attrName, refObject) != refObject: uniqueIds.add(id(getattr(subObj, attrName))) uniqueObjTypes.add(subObj.__class__.__name__) for a in self.r.core.getAssemblies(includeAll=True): checkAttr(a) for b in a: checkAttr(b) for c in b: checkAttr(c) checkAttr(c.material) for i in self.o.getInterfaces(): checkAttr(i) if i.name == "xsGroups": for _, block in i.representativeBlocks.items(): checkAttr(block) if len(uniqueIds) == 0: runLog.important("There are no duplicate `.{}` attributes".format(attrName)) else: runLog.error( "There are {} unique objects stored as `.{}` attributes!\n" "Expected id {}, but got {}.\nExpected object:{}\n" "These types of objects had unique attributes: {}".format( len(uniqueIds) + 1, attrName, id(refObject), uniqueIds, refObject, ", ".join(uniqueObjTypes), ) ) raise RuntimeError def _printFullMemoryBreakdown( self, startsWith="armi", reportSize=True, printReferrers=False ): cs = self.cs operator = self.o reactor = self.r if reportSize: self.r.detach() self.o.detach() gc.collect() allObjects = gc.get_objects() instanceCounters = KlassCounter(reportSize) runLog.info("GC returned {} objects".format(len(allObjects))) instanceCounters.countObjects(allObjects) for counter in sorted(instanceCounters.counters.values()): runLog.info( "UNIQUE_INSTANCE_COUNT: {:60s} {:10d} {:10.1f} MB".format( counter.classType.__name__, counter.count, counter.memSize / (1024 ** 2.0), ) ) if printReferrers and counter.memSize / (1024 ** 2.0) > 100: referrers = gc.get_referrers(counter.first) runLog.info(" Referrers of first one: ") for referrer in referrers: runLog.info(" {}".format(repr(referrer)[:150])) runLog.info("gc garbage: {}".format(gc.garbage)) if printReferrers: # if you want more info on the garbage referrers, run this. WARNING, it's generally like 1000000 lines. runLog.info("referrers") for o in gc.garbage: for r in gc.get_referrers(o): runLog.info("ref for {}: {}".format(o, r)) if reportSize: operator.reattach(reactor, cs) @staticmethod def getSpecificReferrers(klass, ancestorKlass): if not issubclass(klass, ArmiObject) or not issubclass( ancestorKlass, ArmiObject ): raise TypeError( "klass and ancestorKlass should be subclasses of ArmiObject" ) info = [] nominalCount = 0 exampleObj = None maxObjects = 100 objectsSoFar = 0 for obj in (o for o in gc.get_objects() if isinstance(o, klass)): if objectsSoFar > maxObjects: break isNominal = False o2 = obj while o2.parent is not None: if isinstance(o2.parent, ancestorKlass): isNominal = True break o2 = o2.parent runLog.important("isNominal: {} parent: {}".format(isNominal, obj.parent)) if isNominal: nominalCount += 1 else: exampleObj = obj objectsSoFar += 1 referrers = gc.get_referrers(obj) referrerClasses = {type(o) for o in referrers} info.append((obj.parent, referrerClasses)) if exampleObj is not None: runLog.important("Walking referrers for {}".format(exampleObj)) _walkReferrers(exampleObj, maxLevel=8) raise RuntimeError("All done") runLog.important( "List of {} orphaned ArmiObjects (obj.parent, {{referring object " "classes}})".format(len(info)) ) for item in info: runLog.important("{}".format(item)) @staticmethod def getReferrers(obj): runLog.info("Printing first 100 character of first 100 referrers") for ref in gc.get_referrers(obj)[:100]: print("ref for {}: {}".format(obj, repr(ref)[:100])) @staticmethod def discussSkipped(skipped, errors): runLog.warning("Skipped {} objects".format(skipped)) runLog.warning( "errored out on {0} objects:\n {1}".format( len(errors), "\n".join([repr(ei)[:30] for ei in errors]) ) ) class KlassCounter: def __init__(self, reportSize): self.counters = dict() self.reportSize = reportSize self.count = 0 def __getitem__(self, classType): if classType not in self.counters: self.counters[classType] = InstanceCounter(classType, self.reportSize) return self.counters[classType] def __iadd__(self, item): klass = type(item) if klass in self.counters: counter = self.counters[klass] else: counter = InstanceCounter(klass, self.reportSize) counter.first = item self.counters[klass] = counter counter += item def countObjects(self, ao): itemType = type(ao) counter = self[itemType] if counter.add(ao): self.count += 1 if self.count % 100000 == 0: runLog.info("Counted {} items".format(self.count)) if isinstance(ao, dict): for k, v in ao.items(): self.countObjects(k) self.countObjects(v) elif isinstance(ao, (list, tuple, set)): for v in iter(ao): self.countObjects(v) class InstanceCounter: def __init__(self, classType, reportSize): self.classType = classType self.count = 0 self.reportSize = reportSize if reportSize: self.memSize = 0 else: self.memSize = float("nan") self.items = set() self.ids = set() self.first = None def add(self, item): itemId = id(item) if itemId in self.ids: return False self.ids.add(itemId) if self.reportSize: try: self.memSize += asizeof(item) except: self.memSize = float("nan") self.count += 1 return True def __cmp__(self, that): return (self.count > that.count) - (self.count < that.count) def __ls__(self, that): return self.count < that.count def __gt__(self, that): return self.count > that.count def _getClsName(obj): try: return obj.__class__.__name__ except: try: return obj.__name__ except: return repr(obj)[:20] def _getModName(obj): try: return obj.__class__.__module__ except: return None class ObjectSizeBreakdown: def __init__( self, name, minMBToShowAttrBreakdown=30.0, excludedAttributes=None, initialZeroes=0, ): self.name = name self.sizes = [0.0] * initialZeroes self.minMBToShowAttrBreakdown = minMBToShowAttrBreakdown self.excludedAttributes = excludedAttributes or [] self.attrSizes = {} @property def size(self): return self.sizes[-1] def calcSize(self, obj): tempAttrs = {} try: for attrName in self.excludedAttributes: if hasattr(obj, attrName): tempAttrs[attrName] = getattr(obj, attrName, None) setattr(obj, attrName, None) self.sizes.append(asizeof(obj) / (1024.0 ** 2)) self._breakdownAttributeSizes(obj) finally: for attrName, attrObj in tempAttrs.items(): setattr(obj, attrName, attrObj) def _breakdownAttributeSizes(self, obj): if self.size > self.minMBToShowAttrBreakdown: if isinstance(obj, dict): keys = obj.keys() getter = lambda obj, key: obj.get(key) elif isinstance(obj, list): keys = range(len(obj)) getter = lambda obj, key: obj[key] else: keys = obj.__dict__.keys() getter = getattr for attrName in set(keys) - set(self.excludedAttributes): name = " .{}".format(attrName) if name not in self.attrSizes: self.attrSizes[name] = ObjectSizeBreakdown( name, 1000.0, initialZeroes=len(self.sizes) - 1 ) attrSize = self.attrSizes[name] attrSize.calcSize(getter(obj, attrName)) def __repr__(self): message = [] name = self.name if self.excludedAttributes: name += " except(.{})".format(", .".join(self.excludedAttributes)) message.append("{0:53s} {1:8.4f}MB".format(name, self.size)) for attr in self.attrSizes.values(): message.append(repr(attr)) return "\n".join(message) class ProfileMemoryUsageAction(mpiActions.MpiAction): def __init__(self, timeDescription): mpiActions.MpiAction.__init__(self) self.timeDescription = timeDescription def invokeHook(self): mem = self.o.getInterface("memoryProfiler") mem.displayMemoryUsage(self.timeDescription) class SystemAndProcessMemoryUsage: def __init__(self): self.nodeName = context.MPI_NODENAME # no psutil, no memory diagnostics. # TODO: Ideally, we could cut MemoryProfiler entirely, but it is referred to # directly by the standard operator and reports, so easier said than done. self.percentNodeRamUsed: Optional[float] = None self.processMemoryInMB: Optional[float] = None if _havePsutil: self.percentNodeRamUsed = psutil.virtual_memory().percent self.processMemoryInMB = psutil.Process().memory_info().rss / (1012.0 ** 2) def __isub__(self, other): if self.percentNodeRamUsed is not None and other.percentNodeRamUsed is not None: self.percentNodeRamUsed -= other.percentNodeRamUsed self.processMemoryInMB -= other.processMemoryInMB return self class PrintSystemMemoryUsageAction(mpiActions.MpiAction): def __init__(self): mpiActions.MpiAction.__init__(self) self.usages = [] self.percentNodeRamUsed: Optional[float] = None def __iter__(self): return iter(self.usages) def __isub__(self, other): if self.percentNodeRamUsed is not None and other.percentNodeRamUsed is not None: self.percentNodeRamUsed -= other.percentNodeRamUsed for mine, theirs in zip(self, other): mine -= theirs return self @property def minProcessMemoryInMB(self): if len(self.usages) == 0: return 0.0 return min(mu.processMemoryInMB or 0.0 for mu in self) @property def maxProcessMemoryInMB(self): if len(self.usages) == 0: return 0.0 return max(mu.processMemoryInMB or 0.0 for mu in self) def invokeHook(self): spmu = SystemAndProcessMemoryUsage() self.percentNodeRamUsed = spmu.percentNodeRamUsed self.usages = self.gather(spmu) def printUsage(self, description=None): printedNodes = set() prefix = description or "SYS_MEM" memoryData = [] for memoryUsage in self: if memoryUsage.nodeName in printedNodes: continue printedNodes.add(memoryUsage.nodeName) nodeUsages = [mu for mu in self if mu.nodeName == memoryUsage.nodeName] sysMemAvg = sum(mu.percentNodeRamUsed or 0.0 for mu in nodeUsages) / len( nodeUsages ) memoryData.append( ( "{:<24}".format(memoryUsage.nodeName), "{:5.1f}%".format(sysMemAvg), "{}".format( " ".join( "{:5.0f}".format(mu.processMemoryInMB or 0.0) for mu in nodeUsages ) ), ) ) runLog.info( "Summary of the system memory usage at `{}`:\n".format(prefix) + tabulate.tabulate( memoryData, headers=[ "Machine", "Average System RAM Usage", "Processor Memory Usage (MB)", ], tablefmt="armi", ) ) def _getFunctionObject(): from inspect import currentframe, getframeinfo caller = currentframe().f_back func_name = getframeinfo(caller)[2] caller = caller.f_back func = caller.f_locals.get(func_name, caller.f_globals.get(func_name)) return func def _walkReferrers(o, maxLevel=0, level=0, memo=None, whitelist=None): if maxLevel and level > maxLevel: return if level == 0: gc.collect() whitelist = {id(obj) for obj in gc.get_objects()} whitelist.remove(id(_getFunctionObject())) whitelist.remove(id(_getFunctionObject)) if memo is None: memo = set() gc.collect() referrers = [ (referrer, id(referrer), id(referrer) in memo) for referrer in gc.get_referrers(o) if referrer.__class__.__name__ != "frame" and id(referrer) in whitelist ] memo.update({oid for (_obj, oid, _seen) in referrers}) for (obj, _, seen) in referrers: runLog.important( "{}{} {} at {:x} seen: {}".format( "-" * level, type(obj), "{}".format(obj)[:100], id(obj), seen ) ) if seen: return _walkReferrers( obj, maxLevel=maxLevel, level=level + 1, memo=memo, whitelist=whitelist )
true
true
1c39d3c48cb80c4e4808e18b8ba1a690569e1369
2,070
py
Python
gammapy/spectrum/tests/test_results.py
gabemery/gammapy
99e5c5d38e4920dddd7bca41fb1539ccda8bea2d
[ "BSD-3-Clause" ]
null
null
null
gammapy/spectrum/tests/test_results.py
gabemery/gammapy
99e5c5d38e4920dddd7bca41fb1539ccda8bea2d
[ "BSD-3-Clause" ]
null
null
null
gammapy/spectrum/tests/test_results.py
gabemery/gammapy
99e5c5d38e4920dddd7bca41fb1539ccda8bea2d
[ "BSD-3-Clause" ]
null
null
null
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import astropy.units as u from ...utils.testing import assert_quantity_allclose from ...utils.testing import requires_dependency, requires_data from ..models import PowerLaw from .. import SpectrumObservation, SpectrumFitResult @requires_dependency('scipy') @requires_data('gammapy-extra') class TestSpectrumFitResult: def setup(self): filename = "$GAMMAPY_EXTRA/datasets/hess-crab4_pha/pha_obs23592.fits" self.obs = SpectrumObservation.read(filename) self.best_fit_model = PowerLaw(index=2 * u.Unit(''), amplitude=1e-11 * u.Unit('cm-2 s-1 TeV-1'), reference=1 * u.TeV) self.npred = self.obs.predicted_counts(self.best_fit_model).data.data.value covar_axis = ['index', 'amplitude'] covar = np.diag([0.1 ** 2, 1e-12 ** 2]) self.best_fit_model.parameters.set_parameter_covariance(covar, covar_axis) self.fit_range = [0.1, 50] * u.TeV self.fit_result = SpectrumFitResult( model=self.best_fit_model, fit_range=self.fit_range, statname='wstat', statval=42, npred_src=self.npred, npred_bkg=self.npred * 0.5, obs=self.obs, ) @requires_dependency('uncertainties') def test_basic(self): assert 'PowerLaw' in str(self.fit_result) assert 'index' in self.fit_result.to_table().colnames @requires_dependency('yaml') def test_io(self, tmpdir): filename = tmpdir / 'test.yaml' self.fit_result.to_yaml(filename) read_result = SpectrumFitResult.from_yaml(filename) test_e = 12.5 * u.TeV assert_quantity_allclose(self.fit_result.model(test_e), read_result.model(test_e)) @requires_dependency('matplotlib') def test_plot(self): self.fit_result.plot()
39.807692
83
0.647343
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import astropy.units as u from ...utils.testing import assert_quantity_allclose from ...utils.testing import requires_dependency, requires_data from ..models import PowerLaw from .. import SpectrumObservation, SpectrumFitResult @requires_dependency('scipy') @requires_data('gammapy-extra') class TestSpectrumFitResult: def setup(self): filename = "$GAMMAPY_EXTRA/datasets/hess-crab4_pha/pha_obs23592.fits" self.obs = SpectrumObservation.read(filename) self.best_fit_model = PowerLaw(index=2 * u.Unit(''), amplitude=1e-11 * u.Unit('cm-2 s-1 TeV-1'), reference=1 * u.TeV) self.npred = self.obs.predicted_counts(self.best_fit_model).data.data.value covar_axis = ['index', 'amplitude'] covar = np.diag([0.1 ** 2, 1e-12 ** 2]) self.best_fit_model.parameters.set_parameter_covariance(covar, covar_axis) self.fit_range = [0.1, 50] * u.TeV self.fit_result = SpectrumFitResult( model=self.best_fit_model, fit_range=self.fit_range, statname='wstat', statval=42, npred_src=self.npred, npred_bkg=self.npred * 0.5, obs=self.obs, ) @requires_dependency('uncertainties') def test_basic(self): assert 'PowerLaw' in str(self.fit_result) assert 'index' in self.fit_result.to_table().colnames @requires_dependency('yaml') def test_io(self, tmpdir): filename = tmpdir / 'test.yaml' self.fit_result.to_yaml(filename) read_result = SpectrumFitResult.from_yaml(filename) test_e = 12.5 * u.TeV assert_quantity_allclose(self.fit_result.model(test_e), read_result.model(test_e)) @requires_dependency('matplotlib') def test_plot(self): self.fit_result.plot()
true
true
1c39d3f944c9c5d2cf7faae8bf17a3e63cac88c4
3,703
py
Python
models/layers/split_att_conv2d.py
HotaekHan/classification-pytorch
41185301709280c78ce1e51e3c9bc5c4d23d6443
[ "MIT" ]
5
2020-11-19T02:03:55.000Z
2021-07-13T12:26:05.000Z
models/layers/split_att_conv2d.py
HotaekHan/classification-pytorch
41185301709280c78ce1e51e3c9bc5c4d23d6443
[ "MIT" ]
1
2020-11-23T13:21:20.000Z
2020-12-01T11:45:09.000Z
models/layers/split_att_conv2d.py
HotaekHan/classification-pytorch
41185301709280c78ce1e51e3c9bc5c4d23d6443
[ "MIT" ]
1
2021-07-13T13:04:16.000Z
2021-07-13T13:04:16.000Z
"""Split-Attention""" import torch from torch import nn import torch.nn.functional as F from torch.nn import Conv2d, Module, Linear, BatchNorm2d, ReLU from torch.nn.modules.utils import _pair __all__ = ['SplAtConv2d'] class SplAtConv2d(Module): """Split-Attention Conv2d """ def __init__(self, in_channels, channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=True, radix=2, reduction_factor=4, rectify=False, rectify_avg=False, norm_layer=None, dropblock_prob=0.0, **kwargs): super(SplAtConv2d, self).__init__() padding = _pair(padding) self.rectify = rectify and (padding[0] > 0 or padding[1] > 0) self.rectify_avg = rectify_avg inter_channels = max(in_channels*radix//reduction_factor, 32) self.radix = radix self.cardinality = groups self.channels = channels self.dropblock_prob = dropblock_prob if self.rectify: # from rfconv import RFConv2d # self.conv = RFConv2d(in_channels, channels*radix, kernel_size, stride, padding, dilation, # groups=groups*radix, bias=bias, average_mode=rectify_avg, **kwargs) raise NotImplementedError else: self.conv = Conv2d(in_channels, channels*radix, kernel_size, stride, padding, dilation, groups=groups*radix, bias=bias, **kwargs) self.use_bn = norm_layer is not None if self.use_bn: self.bn0 = norm_layer(channels*radix) self.relu = ReLU(inplace=True) self.fc1 = Conv2d(channels, inter_channels, 1, groups=self.cardinality) if self.use_bn: self.bn1 = norm_layer(inter_channels) self.fc2 = Conv2d(inter_channels, channels*radix, 1, groups=self.cardinality) if dropblock_prob > 0.0: # self.dropblock = DropBlock2D(dropblock_prob, 3) raise NotImplementedError self.rsoftmax = rSoftMax(radix, groups) def forward(self, x): x = self.conv(x) if self.use_bn: x = self.bn0(x) if self.dropblock_prob > 0.0: x = self.dropblock(x) x = self.relu(x) batch, rchannel = x.shape[:2] if self.radix > 1: if torch.__version__ < '1.5': splited = torch.split(x, int(rchannel//self.radix), dim=1) else: splited = torch.split(x, rchannel//self.radix, dim=1) gap = sum(splited) else: gap = x gap = F.adaptive_avg_pool2d(gap, 1) gap = self.fc1(gap) if self.use_bn: gap = self.bn1(gap) gap = self.relu(gap) atten = self.fc2(gap) atten = self.rsoftmax(atten).view(batch, -1, 1, 1) if self.radix > 1: if torch.__version__ < '1.5': attens = torch.split(atten, int(rchannel//self.radix), dim=1) else: attens = torch.split(atten, rchannel//self.radix, dim=1) out = sum([att*split for (att, split) in zip(attens, splited)]) else: out = atten * x return out.contiguous() class rSoftMax(nn.Module): def __init__(self, radix, cardinality): super().__init__() self.radix = radix self.cardinality = cardinality def forward(self, x): batch = x.size(0) if self.radix > 1: x = x.view(batch, self.cardinality, self.radix, -1).transpose(1, 2) x = F.softmax(x, dim=1) x = x.reshape(batch, -1) else: x = torch.sigmoid(x) return x
36.303922
103
0.572239
import torch from torch import nn import torch.nn.functional as F from torch.nn import Conv2d, Module, Linear, BatchNorm2d, ReLU from torch.nn.modules.utils import _pair __all__ = ['SplAtConv2d'] class SplAtConv2d(Module): def __init__(self, in_channels, channels, kernel_size, stride=(1, 1), padding=(0, 0), dilation=(1, 1), groups=1, bias=True, radix=2, reduction_factor=4, rectify=False, rectify_avg=False, norm_layer=None, dropblock_prob=0.0, **kwargs): super(SplAtConv2d, self).__init__() padding = _pair(padding) self.rectify = rectify and (padding[0] > 0 or padding[1] > 0) self.rectify_avg = rectify_avg inter_channels = max(in_channels*radix//reduction_factor, 32) self.radix = radix self.cardinality = groups self.channels = channels self.dropblock_prob = dropblock_prob if self.rectify: raise NotImplementedError else: self.conv = Conv2d(in_channels, channels*radix, kernel_size, stride, padding, dilation, groups=groups*radix, bias=bias, **kwargs) self.use_bn = norm_layer is not None if self.use_bn: self.bn0 = norm_layer(channels*radix) self.relu = ReLU(inplace=True) self.fc1 = Conv2d(channels, inter_channels, 1, groups=self.cardinality) if self.use_bn: self.bn1 = norm_layer(inter_channels) self.fc2 = Conv2d(inter_channels, channels*radix, 1, groups=self.cardinality) if dropblock_prob > 0.0: raise NotImplementedError self.rsoftmax = rSoftMax(radix, groups) def forward(self, x): x = self.conv(x) if self.use_bn: x = self.bn0(x) if self.dropblock_prob > 0.0: x = self.dropblock(x) x = self.relu(x) batch, rchannel = x.shape[:2] if self.radix > 1: if torch.__version__ < '1.5': splited = torch.split(x, int(rchannel//self.radix), dim=1) else: splited = torch.split(x, rchannel//self.radix, dim=1) gap = sum(splited) else: gap = x gap = F.adaptive_avg_pool2d(gap, 1) gap = self.fc1(gap) if self.use_bn: gap = self.bn1(gap) gap = self.relu(gap) atten = self.fc2(gap) atten = self.rsoftmax(atten).view(batch, -1, 1, 1) if self.radix > 1: if torch.__version__ < '1.5': attens = torch.split(atten, int(rchannel//self.radix), dim=1) else: attens = torch.split(atten, rchannel//self.radix, dim=1) out = sum([att*split for (att, split) in zip(attens, splited)]) else: out = atten * x return out.contiguous() class rSoftMax(nn.Module): def __init__(self, radix, cardinality): super().__init__() self.radix = radix self.cardinality = cardinality def forward(self, x): batch = x.size(0) if self.radix > 1: x = x.view(batch, self.cardinality, self.radix, -1).transpose(1, 2) x = F.softmax(x, dim=1) x = x.reshape(batch, -1) else: x = torch.sigmoid(x) return x
true
true
1c39d450e97701185e55969fad7b43f942a77878
76
py
Python
ABC038/ABC038f.py
VolgaKurvar/AtCoder
21acb489f1594bbb1cdc64fbf8421d876b5b476d
[ "Unlicense" ]
null
null
null
ABC038/ABC038f.py
VolgaKurvar/AtCoder
21acb489f1594bbb1cdc64fbf8421d876b5b476d
[ "Unlicense" ]
null
null
null
ABC038/ABC038f.py
VolgaKurvar/AtCoder
21acb489f1594bbb1cdc64fbf8421d876b5b476d
[ "Unlicense" ]
null
null
null
#ABC038f import sys input = sys.stdin.readline sys.setrecursionlimit(10**6)
15.2
28
0.789474
import sys input = sys.stdin.readline sys.setrecursionlimit(10**6)
true
true
1c39d47124c3ced2c1f626a08e83d57f514ab838
623
py
Python
app/core/migrations/0004_auto_20190113_2046.py
jazziesf/scout-travel-api
09cb599d869e0a67b94bc58803822774fa658c65
[ "MIT" ]
null
null
null
app/core/migrations/0004_auto_20190113_2046.py
jazziesf/scout-travel-api
09cb599d869e0a67b94bc58803822774fa658c65
[ "MIT" ]
null
null
null
app/core/migrations/0004_auto_20190113_2046.py
jazziesf/scout-travel-api
09cb599d869e0a67b94bc58803822774fa658c65
[ "MIT" ]
null
null
null
# Generated by Django 2.1.5 on 2019-01-13 20:46 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('core', '0003_pin_likes'), ] operations = [ migrations.AddField( model_name='pin', name='dish', field=models.CharField(default=django.utils.timezone.now, max_length=255), preserve_default=False, ), migrations.AlterField( model_name='board', name='pin', field=models.ManyToManyField(to='core.Pin'), ), ]
23.961538
86
0.585875
from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('core', '0003_pin_likes'), ] operations = [ migrations.AddField( model_name='pin', name='dish', field=models.CharField(default=django.utils.timezone.now, max_length=255), preserve_default=False, ), migrations.AlterField( model_name='board', name='pin', field=models.ManyToManyField(to='core.Pin'), ), ]
true
true
1c39d5bf3f5bb26180c473498b62eef86a13aa48
3,077
py
Python
src/conversor.py
xandao6/url-to-desktop
750dc0db9717e0e50e3af3f2c1ac8fb7047cb375
[ "MIT" ]
1
2020-02-23T13:47:19.000Z
2020-02-23T13:47:19.000Z
src/conversor.py
xandao6/url-to-desktop
750dc0db9717e0e50e3af3f2c1ac8fb7047cb375
[ "MIT" ]
null
null
null
src/conversor.py
xandao6/url-to-desktop
750dc0db9717e0e50e3af3f2c1ac8fb7047cb375
[ "MIT" ]
1
2020-01-20T05:11:14.000Z
2020-01-20T05:11:14.000Z
import os, shutil, fire from typing import List, Optional from pyfiglet import Figlet def main(path: Optional[str] = None) -> None: __print_logo('url - desktop') fire.Fire(__convert) def __convert(path: Optional[str] = None) -> None: if path is None: path = os.getcwd() try: url_list_path = __get_url_files_path(path) exit_if_no_files(url_list_path) url_filenames = __get_url_filenames_without_extension(url_list_path) old_url_folder_name = __create_old_url_folder(path, url_list_path) __copy_url_files_to_old_url_folder( path, url_list_path, old_url_folder_name) __change_url_to_desktop(url_list_path, url_filenames) print('\nSuccessful conversion!\n') except Exception as e: print(f'Error: {str(e)}') def __print_logo(text_logo: str) -> None: figlet = Figlet(font='slant') print(figlet.renderText(text_logo)) def __get_url_files_path(path: str) -> List[str]: url_list_path = list() for file in os.listdir(path): if file.endswith(".url") or file.endswith(".URL"): url_list_path.append(os.path.join(path, file)) return url_list_path def exit_if_no_files(url_list_path: List[str]) -> None: if len(url_list_path) <= 0: print('No URL to convert!') exit() def __get_url_filenames_without_extension( url_list_path: List[str] ) -> List[str]: url_filenames = list() for path in url_list_path: url_filenames.append(os.path.splitext(os.path.basename(path))[0]) return url_filenames def __create_old_url_folder( path: str, url_list_path: List[str] ) -> str: if path is None: path = os.getcwd() old_url_folder_name = 'old urls' if not os.path.isdir(os.path.join(path, old_url_folder_name)): os.mkdir(os.path.join(path, old_url_folder_name)) return old_url_folder_name def __copy_url_files_to_old_url_folder( path: str, url_list_path: List[str], old_url_folder_name: str ) -> None: for file_path in url_list_path: shutil.copy(file_path, os.path.join(path, old_url_folder_name)) def __change_url_to_desktop( url_list_path: List[str], url_filenames: List[str] ) -> None: for file_path, filename in zip(url_list_path, url_filenames): # Take the URL from file url_file = open(file_path, 'r') for i, line in enumerate(url_file): if i == 1: url = line url_file.close() # Verify if we got the URL if not url.startswith('URL'): break # Convert to DESKTOP url_file = open(file_path, 'w') url_file.write('[Desktop Entry]\n') url_file.write('Encoding=UTF-8\n') url_file.write(f'Name={filename}\n') url_file.write('Type=Link\n') url_file.write(url) url_file.write('Icon=text-html\n') url_file.close() # Rename the file from .url to .desktop os.rename( file_path, f'{os.path.join(os.path.dirname(file_path),filename)}.desktop')
29.028302
86
0.653884
import os, shutil, fire from typing import List, Optional from pyfiglet import Figlet def main(path: Optional[str] = None) -> None: __print_logo('url - desktop') fire.Fire(__convert) def __convert(path: Optional[str] = None) -> None: if path is None: path = os.getcwd() try: url_list_path = __get_url_files_path(path) exit_if_no_files(url_list_path) url_filenames = __get_url_filenames_without_extension(url_list_path) old_url_folder_name = __create_old_url_folder(path, url_list_path) __copy_url_files_to_old_url_folder( path, url_list_path, old_url_folder_name) __change_url_to_desktop(url_list_path, url_filenames) print('\nSuccessful conversion!\n') except Exception as e: print(f'Error: {str(e)}') def __print_logo(text_logo: str) -> None: figlet = Figlet(font='slant') print(figlet.renderText(text_logo)) def __get_url_files_path(path: str) -> List[str]: url_list_path = list() for file in os.listdir(path): if file.endswith(".url") or file.endswith(".URL"): url_list_path.append(os.path.join(path, file)) return url_list_path def exit_if_no_files(url_list_path: List[str]) -> None: if len(url_list_path) <= 0: print('No URL to convert!') exit() def __get_url_filenames_without_extension( url_list_path: List[str] ) -> List[str]: url_filenames = list() for path in url_list_path: url_filenames.append(os.path.splitext(os.path.basename(path))[0]) return url_filenames def __create_old_url_folder( path: str, url_list_path: List[str] ) -> str: if path is None: path = os.getcwd() old_url_folder_name = 'old urls' if not os.path.isdir(os.path.join(path, old_url_folder_name)): os.mkdir(os.path.join(path, old_url_folder_name)) return old_url_folder_name def __copy_url_files_to_old_url_folder( path: str, url_list_path: List[str], old_url_folder_name: str ) -> None: for file_path in url_list_path: shutil.copy(file_path, os.path.join(path, old_url_folder_name)) def __change_url_to_desktop( url_list_path: List[str], url_filenames: List[str] ) -> None: for file_path, filename in zip(url_list_path, url_filenames): url_file = open(file_path, 'r') for i, line in enumerate(url_file): if i == 1: url = line url_file.close() if not url.startswith('URL'): break url_file = open(file_path, 'w') url_file.write('[Desktop Entry]\n') url_file.write('Encoding=UTF-8\n') url_file.write(f'Name={filename}\n') url_file.write('Type=Link\n') url_file.write(url) url_file.write('Icon=text-html\n') url_file.close() os.rename( file_path, f'{os.path.join(os.path.dirname(file_path),filename)}.desktop')
true
true
1c39d5cea93358a6f1f58385273c38feaecd9d64
2,746
py
Python
cogs/counting.py
rssnyder/discord-bot
0430515abf49e94529c064574f23bf9d48fcf6e1
[ "MIT" ]
1
2022-03-31T20:30:55.000Z
2022-03-31T20:30:55.000Z
cogs/counting.py
rssnyder/discord-bot
0430515abf49e94529c064574f23bf9d48fcf6e1
[ "MIT" ]
null
null
null
cogs/counting.py
rssnyder/discord-bot
0430515abf49e94529c064574f23bf9d48fcf6e1
[ "MIT" ]
null
null
null
from discord.ext import commands class Counting(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_ready(self): print('Counting cog ready') @commands.Cog.listener() async def on_message(self, message): # Don't do this in DMs if not message.guild: return # TODO add channel ID to database instead of checking if called "counting" # TODO set a channel as binary or decimal # check if channel is named "counting" channel = message.channel if "counting" not in channel.name: return # Delete message if bot or not numeric or negative or has leading zeroes content = message.content if message.author.bot \ or not content.isnumeric() \ or "-" in content \ or (content.startswith('0') and len(content) > 1): await message.delete() return try: messages = await channel.history(limit=3).flatten() # Get previous number previous_number_str = messages[1].content previous_num = int(previous_number_str) # Try to get them if they're binary. Some bugs could occur if the next number is the same in binary and decimal. current_num_binary = 0 previous_num_binary = 0 try: previous_num_binary = int(previous_number_str, 2) current_num_binary = int(content, 2) except ValueError: pass # Check if it's 1 more current_num = int(content) if current_num is not previous_num + 1 \ and current_num_binary is not previous_num_binary + 1: await message.delete() # Send DM of correct number. try: two_nums_ago_binary = int(messages[2].content, 2) if previous_num_binary - two_nums_ago_binary == 1: await message.author.send(f"The next number is {bin(previous_num_binary + 1)[2:]}", delete_after=300) return except ValueError: pass two_nums_ago = int(messages[2].content) if previous_num - two_nums_ago == 1: await message.author.send(f"The next number is {previous_num + 1}", delete_after=300) return except IndexError: # We only start at 0 or 1 if content != '0' and content != '1': await message.delete() return def setup(client): client.add_cog(Counting(client))
34.759494
125
0.557174
from discord.ext import commands class Counting(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_ready(self): print('Counting cog ready') @commands.Cog.listener() async def on_message(self, message): if not message.guild: return # TODO add channel ID to database instead of checking if called "counting" # TODO set a channel as binary or decimal # check if channel is named "counting" channel = message.channel if "counting" not in channel.name: return # Delete message if bot or not numeric or negative or has leading zeroes content = message.content if message.author.bot \ or not content.isnumeric() \ or "-" in content \ or (content.startswith('0') and len(content) > 1): await message.delete() return try: messages = await channel.history(limit=3).flatten() # Get previous number previous_number_str = messages[1].content previous_num = int(previous_number_str) # Try to get them if they're binary. Some bugs could occur if the next number is the same in binary and decimal. current_num_binary = 0 previous_num_binary = 0 try: previous_num_binary = int(previous_number_str, 2) current_num_binary = int(content, 2) except ValueError: pass current_num = int(content) if current_num is not previous_num + 1 \ and current_num_binary is not previous_num_binary + 1: await message.delete() # Send DM of correct number. try: two_nums_ago_binary = int(messages[2].content, 2) if previous_num_binary - two_nums_ago_binary == 1: await message.author.send(f"The next number is {bin(previous_num_binary + 1)[2:]}", delete_after=300) return except ValueError: pass two_nums_ago = int(messages[2].content) if previous_num - two_nums_ago == 1: await message.author.send(f"The next number is {previous_num + 1}", delete_after=300) return except IndexError: # We only start at 0 or 1 if content != '0' and content != '1': await message.delete() return def setup(client): client.add_cog(Counting(client))
true
true
1c39d6ee5aa7792bea311f30b618e62f61c84356
1,476
py
Python
python-examples/classical-mds-image.py
amazing89/mathtoolbox
8904bb06ced2ac501594f9574ef1ba3454b8e38e
[ "MIT" ]
1
2020-02-01T03:39:24.000Z
2020-02-01T03:39:24.000Z
python-examples/classical-mds-image.py
amazing89/mathtoolbox
8904bb06ced2ac501594f9574ef1ba3454b8e38e
[ "MIT" ]
null
null
null
python-examples/classical-mds-image.py
amazing89/mathtoolbox
8904bb06ced2ac501594f9574ef1ba3454b8e38e
[ "MIT" ]
null
null
null
import pymathtoolbox import numpy as np import matplotlib.pyplot as plt import os import seaborn as sns from PIL import Image from scipy.spatial.distance import pdist, squareform # Load an image asset_dir_path = os.path.dirname(os.path.abspath(__file__)) + "/assets" image = Image.open(asset_dir_path + "/autumn-leaves.jpg") resized_image = image.resize((30, 20), Image.BILINEAR) # Generate a color array colors = np.asarray(resized_image) colors = colors.reshape(colors.shape[0] * colors.shape[1], 3) / 255.0 # Generate a distance matrix D = squareform(pdist(colors)) # Compute metric MDS (embedding into a 2-dimensional space) X = pymathtoolbox.compute_classical_mds(D=D, dim=2) # Define constants for plot FIG_SIZE = (8, 3) IMAGE_FORMAT = "png" DPI = 200 # Set style sns.set() sns.set_context() plt.rcParams['font.sans-serif'] = ["Linux Biolinum O", "Linux Biolinum"] # Draw plot fig = plt.figure(figsize=FIG_SIZE, dpi=DPI) ax = fig.add_subplot(1, 2, 1) ax.set_title("Target Image") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) ax.imshow(image) ax = fig.add_subplot(1, 2, 2) ax.set_title("Pixel Colors Embedded into a 2D Space") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect("equal", adjustable="datalim") num_pixels = colors.shape[0] for i in range(num_pixels): ax.plot(X[0][i], X[1][i], color=colors[i], marker=".") # Export plot fig.tight_layout() fig.savefig("./classical-mds-image-out." + IMAGE_FORMAT)
25.894737
72
0.732385
import pymathtoolbox import numpy as np import matplotlib.pyplot as plt import os import seaborn as sns from PIL import Image from scipy.spatial.distance import pdist, squareform asset_dir_path = os.path.dirname(os.path.abspath(__file__)) + "/assets" image = Image.open(asset_dir_path + "/autumn-leaves.jpg") resized_image = image.resize((30, 20), Image.BILINEAR) colors = np.asarray(resized_image) colors = colors.reshape(colors.shape[0] * colors.shape[1], 3) / 255.0 D = squareform(pdist(colors)) X = pymathtoolbox.compute_classical_mds(D=D, dim=2) FIG_SIZE = (8, 3) IMAGE_FORMAT = "png" DPI = 200 sns.set() sns.set_context() plt.rcParams['font.sans-serif'] = ["Linux Biolinum O", "Linux Biolinum"] fig = plt.figure(figsize=FIG_SIZE, dpi=DPI) ax = fig.add_subplot(1, 2, 1) ax.set_title("Target Image") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) ax.imshow(image) ax = fig.add_subplot(1, 2, 2) ax.set_title("Pixel Colors Embedded into a 2D Space") ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_aspect("equal", adjustable="datalim") num_pixels = colors.shape[0] for i in range(num_pixels): ax.plot(X[0][i], X[1][i], color=colors[i], marker=".") fig.tight_layout() fig.savefig("./classical-mds-image-out." + IMAGE_FORMAT)
true
true
1c39d8b39e4b2b44f37d76664f9ffbf7dbb1a736
540
py
Python
Python/Para Checker.py
bhupendpatil/Practice
9663b3f41e359787cbbd04aedb3db3c605c6ec8e
[ "MIT" ]
1
2020-12-23T06:22:29.000Z
2020-12-23T06:22:29.000Z
Python/Para Checker.py
bhupendpatil/Practice
9663b3f41e359787cbbd04aedb3db3c605c6ec8e
[ "MIT" ]
8
2020-06-18T19:32:39.000Z
2022-03-11T11:37:07.000Z
Python/Para Checker.py
bhupendpatil/Practice
9663b3f41e359787cbbd04aedb3db3c605c6ec8e
[ "MIT" ]
1
2021-01-19T00:16:34.000Z
2021-01-19T00:16:34.000Z
from Properties import Stack def par_checker(symbol_string): s = Stack() balanced = True index = 0 while index < len(symbol_string) and balanced: symbol = symbol_string[index] if symbol=='(': s.push(symbol) else: if s.is_empty(): balanced = False else: s.pop() index = index + 1 if balanced and s.is_empty(): return True else: return False print(par_checker('(())')) print(par_checker("(()()))"))
21.6
50
0.522222
from Properties import Stack def par_checker(symbol_string): s = Stack() balanced = True index = 0 while index < len(symbol_string) and balanced: symbol = symbol_string[index] if symbol=='(': s.push(symbol) else: if s.is_empty(): balanced = False else: s.pop() index = index + 1 if balanced and s.is_empty(): return True else: return False print(par_checker('(())')) print(par_checker("(()()))"))
true
true
1c39d8bec0f0297cd94594c0cd15fb0cea38d8c7
2,032
py
Python
Code/venv/src/Account/admin.py
WebMetadataRetrieval/15-Web_Metadata_Retrieval
96a9c8869ccc5429c4de9e97d37705bbb9e19c5b
[ "Apache-2.0" ]
null
null
null
Code/venv/src/Account/admin.py
WebMetadataRetrieval/15-Web_Metadata_Retrieval
96a9c8869ccc5429c4de9e97d37705bbb9e19c5b
[ "Apache-2.0" ]
38
2021-04-01T18:09:31.000Z
2021-05-08T17:27:03.000Z
Code/venv/src/Account/admin.py
WebMetadataRetrieval/15-Web_Metadata_Retrieval
96a9c8869ccc5429c4de9e97d37705bbb9e19c5b
[ "Apache-2.0" ]
3
2021-04-16T07:25:11.000Z
2022-01-29T10:24:33.000Z
from django.contrib import admin from django import forms from .models import UserAccount from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.contrib.auth.models import Group class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = UserAccount fields = ('email',) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = UserAccount fields = ('email', 'password', 'daily_limit', 'is_active', 'is_staff') def clean_password(self): return self.initial["password"] # Register your models here. class UserAdminConfig(UserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email','api_key','daily_limit',) search_fields = ('email',) readonly_fields = ('date_joined','last_login','api_key') ordering = () list_filter = () filter_horizontal = () fieldsets = ( (None, {'fields': ('email', 'api_key', 'daily_limit', 'password','date_joined','last_login', 'is_staff','is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }), ) admin.site.register(UserAccount, UserAdminConfig) admin.site.unregister(Group)
29.449275
127
0.662402
from django.contrib import admin from django import forms from .models import UserAccount from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.contrib.auth.models import Group class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = UserAccount fields = ('email',) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = UserAccount fields = ('email', 'password', 'daily_limit', 'is_active', 'is_staff') def clean_password(self): return self.initial["password"] # Register your models here. class UserAdminConfig(UserAdmin): form = UserChangeForm add_form = UserCreationForm list_display = ('email','api_key','daily_limit',) search_fields = ('email',) readonly_fields = ('date_joined','last_login','api_key') ordering = () list_filter = () filter_horizontal = () fieldsets = ( (None, {'fields': ('email', 'api_key', 'daily_limit', 'password','date_joined','last_login', 'is_staff','is_active')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }), ) admin.site.register(UserAccount, UserAdminConfig) admin.site.unregister(Group)
true
true
1c39d90848805f177260a317dc93179e49b0e348
846
py
Python
test/test_cart_coupon.py
gstingy/uc_python_api
9a0bd3f6e63f616586681518e44fe37c6bae2bba
[ "Apache-2.0" ]
null
null
null
test/test_cart_coupon.py
gstingy/uc_python_api
9a0bd3f6e63f616586681518e44fe37c6bae2bba
[ "Apache-2.0" ]
null
null
null
test/test_cart_coupon.py
gstingy/uc_python_api
9a0bd3f6e63f616586681518e44fe37c6bae2bba
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 """ UltraCart Rest API V2 UltraCart REST API Version 2 OpenAPI spec version: 2.0.0 Contact: support@ultracart.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import ultracart from ultracart.rest import ApiException from ultracart.models.cart_coupon import CartCoupon class TestCartCoupon(unittest.TestCase): """ CartCoupon unit test stubs """ def setUp(self): pass def tearDown(self): pass def testCartCoupon(self): """ Test CartCoupon """ # FIXME: construct object with mandatory attributes with example values #model = ultracart.models.cart_coupon.CartCoupon() pass if __name__ == '__main__': unittest.main()
18.8
79
0.680851
from __future__ import absolute_import import os import sys import unittest import ultracart from ultracart.rest import ApiException from ultracart.models.cart_coupon import CartCoupon class TestCartCoupon(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testCartCoupon(self): pass if __name__ == '__main__': unittest.main()
true
true
1c39d9f362d75c3f11fa331666751886a38a5eeb
1,930
py
Python
Source/GridWorldDrivingDQNMain.py
claytonkanderson/SimplyRL
3e808f519f174d081c80c04a8adba88cf93c9c9d
[ "MIT" ]
null
null
null
Source/GridWorldDrivingDQNMain.py
claytonkanderson/SimplyRL
3e808f519f174d081c80c04a8adba88cf93c9c9d
[ "MIT" ]
null
null
null
Source/GridWorldDrivingDQNMain.py
claytonkanderson/SimplyRL
3e808f519f174d081c80c04a8adba88cf93c9c9d
[ "MIT" ]
null
null
null
import numpy as np import gym from time import time from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam from keras.callbacks import TensorBoard from rl.agents.dqn import DQNAgent from rl.policy import BoltzmannQPolicy from rl.memory import SequentialMemory ENV_NAME = 'GridWorldDrivingDiscrete-v0' # Get the environment and extract the number of actions. env = gym.make(ENV_NAME) np.random.seed(123) env.seed(123) nb_actions = env.action_space.n # Next, we build a very simple model. model = Sequential() model.add(Flatten(input_shape=(1,) + env.observation_space.shape)) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(nb_actions)) model.add(Activation('linear')) print(model.summary()) # Finally, we configure and compile our agent. You can use every built-in Keras optimizer and # even the metrics! memory = SequentialMemory(limit=100000, window_length=1) policy = BoltzmannQPolicy() dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=32, target_model_update=1e-2, policy=policy) dqn.compile(Adam(lr=1e-3), metrics=['mae']) tensorboard = TensorBoard(log_dir="logs/{}".format(time())) # Okay, now it's time to learn something! We visualize the training here for show, but this # slows down training quite a lot. You can always safely abort the training prematurely using # Ctrl + C. #dqn.fit(env, nb_steps=300000, visualize=False, verbose=2, nb_max_episode_steps=100, callbacks=[tensorboard]) dqn.load_weights('dqn_GridWorldDrivingDiscrete-v0_weights.h5f') # After training is done, we save the final weights. #dqn.save_weights('dqn_{}_weights.h5f'.format(ENV_NAME), overwrite=True) # Finally, evaluate our algorithm for 5 episodes. dqn.test(env, nb_episodes=25, visualize=True)
33.275862
109
0.774093
import numpy as np import gym from time import time from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.optimizers import Adam from keras.callbacks import TensorBoard from rl.agents.dqn import DQNAgent from rl.policy import BoltzmannQPolicy from rl.memory import SequentialMemory ENV_NAME = 'GridWorldDrivingDiscrete-v0' env = gym.make(ENV_NAME) np.random.seed(123) env.seed(123) nb_actions = env.action_space.n model = Sequential() model.add(Flatten(input_shape=(1,) + env.observation_space.shape)) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(16)) model.add(Activation('relu')) model.add(Dense(nb_actions)) model.add(Activation('linear')) print(model.summary()) memory = SequentialMemory(limit=100000, window_length=1) policy = BoltzmannQPolicy() dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=32, target_model_update=1e-2, policy=policy) dqn.compile(Adam(lr=1e-3), metrics=['mae']) tensorboard = TensorBoard(log_dir="logs/{}".format(time())) # slows down training quite a lot. You can always safely abort the training prematurely using # Ctrl + C. #dqn.fit(env, nb_steps=300000, visualize=False, verbose=2, nb_max_episode_steps=100, callbacks=[tensorboard]) dqn.load_weights('dqn_GridWorldDrivingDiscrete-v0_weights.h5f') # After training is done, we save the final weights. #dqn.save_weights('dqn_{}_weights.h5f'.format(ENV_NAME), overwrite=True) # Finally, evaluate our algorithm for 5 episodes. dqn.test(env, nb_episodes=25, visualize=True)
true
true
1c39da935d7fec5f8dd0559596ea48273ebc07a6
3,864
py
Python
src/SurvivalCalculator/calculator/views.py
computer-geek64/covid19-survival-calculator
c52879ca562220bdfd5634f3d83ed09df18ea771
[ "MIT" ]
3
2020-03-31T17:01:46.000Z
2020-06-25T02:57:10.000Z
src/SurvivalCalculator/calculator/views.py
varunlakshmanan/covid19-survival-calculator
33b447f8dc99ed5060a117b68b362403ec0b6e38
[ "MIT" ]
null
null
null
src/SurvivalCalculator/calculator/views.py
varunlakshmanan/covid19-survival-calculator
33b447f8dc99ed5060a117b68b362403ec0b6e38
[ "MIT" ]
2
2020-03-30T17:05:26.000Z
2020-03-30T17:49:02.000Z
from django.shortcuts import render from django.http import HttpResponse import os import sys import json import math import numpy as np import requests import pandas as pd from subprocess import Popen, PIPE sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from data import dataset from models import model_ensemble from django.views.decorators.csrf import csrf_exempt from calculator.models import Person def index(request): return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'index.html'), {'title': 'COVID-19 Survival Calculator'}) # Need a POST request for this API endpoint # Must be: /predict/ # Needs the following POST form data: # ip: string representing user's public IP address # age: integer representing user age # gender: string of either 'male' or 'female' # symptom_onset_hospitalization: integer representing the number of days between symptom onset and hospitalization # high_risk_travel: string of either 'yes' or 'no' # medical_conditions: list of chosen medical conditions (see Google Doc for possible choices) @csrf_exempt def predict(request): ip = request.POST.get('ip') response = requests.get('http://ip-api.com/json/' + ip) if not response.status_code == 200: return HttpResponse('HTTP 500 Error', status=500) ip_data = json.loads(response.text) region = ip_data['regionName'].lower() country = 'us' if ip_data['country'] == 'United States' else ip_data['country'].lower() data = { 'age': int(request.POST.get('age')), 'male': 1 - int(request.POST.get('gender').lower() in ['female', 'f']), 'female': int(request.POST.get('gender').lower() in ['female', 'f']), 'symptom_onset_hospitalization': int(request.POST.get('symptom_onset_hospitalization')), 'mortality_rate': dataset.get_mortality_rate(country, region), 'pop_density': dataset.get_pop_density(country), 'high_risk_travel': int(request.POST.get('high_risk_travel').lower() in ['yes', 'y']) } df = pd.DataFrame({k: [v] for k, v in data.items()}) medical_condition_death_rates = { 'cardiovascular disease': 0.105, 'diabetes': 0.073, 'chronic respiratory disease': 0.063, 'hypertension': 0.06, 'cancer': 0.056, 'none': 0.009 } medical_condition_factor = np.prod([medical_condition_death_rates[x] / medical_condition_death_rates['none'] for x in request.POST.getlist('medical_conditions')]) medical_condition_factor = math.pow(medical_condition_factor, 2/3) if medical_condition_factor > 1 else 1.0 data['region'] = region data['country'] = country data['death'] = 0 p = Person(**data) p.save() prediction = model_ensemble.predict(df)[0] * 100 * medical_condition_factor if prediction > 50: prediction = -2500 / prediction + 100 probability = float('%.1f' % round(100 - min(prediction, 100), 1)) return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'predict.html'), {'title': 'COVID-19 Survival Calculator', 'probability': probability}) def privacy_policy(request): return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'privacy_policy.html'), {'title': 'Privacy Policy | COVID-19 Survival Calculator'}) def terms_of_use(request): return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'terms_of_use.html'), {'title': 'Terms of Use | COVID-19 Survival Calculator'}) def update(request): dataset.download_us_states_mortality_rates_dataset() dataset.download_country_mortality_rates_dataset() dataset.merge_mortality_rates_datasets() dataset.merge_into_original_dataset() return HttpResponse('Successfully updated datasets!')
40.25
184
0.709886
from django.shortcuts import render from django.http import HttpResponse import os import sys import json import math import numpy as np import requests import pandas as pd from subprocess import Popen, PIPE sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) from data import dataset from models import model_ensemble from django.views.decorators.csrf import csrf_exempt from calculator.models import Person def index(request): return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'index.html'), {'title': 'COVID-19 Survival Calculator'}) # age: integer representing user age # gender: string of either 'male' or 'female' # symptom_onset_hospitalization: integer representing the number of days between symptom onset and hospitalization # high_risk_travel: string of either 'yes' or 'no' # medical_conditions: list of chosen medical conditions (see Google Doc for possible choices) @csrf_exempt def predict(request): ip = request.POST.get('ip') response = requests.get('http://ip-api.com/json/' + ip) if not response.status_code == 200: return HttpResponse('HTTP 500 Error', status=500) ip_data = json.loads(response.text) region = ip_data['regionName'].lower() country = 'us' if ip_data['country'] == 'United States' else ip_data['country'].lower() data = { 'age': int(request.POST.get('age')), 'male': 1 - int(request.POST.get('gender').lower() in ['female', 'f']), 'female': int(request.POST.get('gender').lower() in ['female', 'f']), 'symptom_onset_hospitalization': int(request.POST.get('symptom_onset_hospitalization')), 'mortality_rate': dataset.get_mortality_rate(country, region), 'pop_density': dataset.get_pop_density(country), 'high_risk_travel': int(request.POST.get('high_risk_travel').lower() in ['yes', 'y']) } df = pd.DataFrame({k: [v] for k, v in data.items()}) medical_condition_death_rates = { 'cardiovascular disease': 0.105, 'diabetes': 0.073, 'chronic respiratory disease': 0.063, 'hypertension': 0.06, 'cancer': 0.056, 'none': 0.009 } medical_condition_factor = np.prod([medical_condition_death_rates[x] / medical_condition_death_rates['none'] for x in request.POST.getlist('medical_conditions')]) medical_condition_factor = math.pow(medical_condition_factor, 2/3) if medical_condition_factor > 1 else 1.0 data['region'] = region data['country'] = country data['death'] = 0 p = Person(**data) p.save() prediction = model_ensemble.predict(df)[0] * 100 * medical_condition_factor if prediction > 50: prediction = -2500 / prediction + 100 probability = float('%.1f' % round(100 - min(prediction, 100), 1)) return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'predict.html'), {'title': 'COVID-19 Survival Calculator', 'probability': probability}) def privacy_policy(request): return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'privacy_policy.html'), {'title': 'Privacy Policy | COVID-19 Survival Calculator'}) def terms_of_use(request): return render(request, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates', 'terms_of_use.html'), {'title': 'Terms of Use | COVID-19 Survival Calculator'}) def update(request): dataset.download_us_states_mortality_rates_dataset() dataset.download_country_mortality_rates_dataset() dataset.merge_mortality_rates_datasets() dataset.merge_into_original_dataset() return HttpResponse('Successfully updated datasets!')
true
true
1c39db80e816be69da88de2b0f5d099c1655af9d
75
py
Python
tests/test_water.py
fladi/qraz
7e2fb4b9dc1decb3f5aa390990c02091d4326ef8
[ "BSD-2-Clause" ]
null
null
null
tests/test_water.py
fladi/qraz
7e2fb4b9dc1decb3f5aa390990c02091d4326ef8
[ "BSD-2-Clause" ]
null
null
null
tests/test_water.py
fladi/qraz
7e2fb4b9dc1decb3f5aa390990c02091d4326ef8
[ "BSD-2-Clause" ]
null
null
null
import water def test_main(): assert water # use your library here
10.714286
41
0.693333
import water def test_main(): assert water
true
true
1c39dc85d475051c67b7ea6d510ba498bd7b66ba
30,533
py
Python
dual_annealing.py
website-fingerprinting/minipatch
682d86c0eca5331a8c001e83003cf79b5d4b1a78
[ "MIT" ]
null
null
null
dual_annealing.py
website-fingerprinting/minipatch
682d86c0eca5331a8c001e83003cf79b5d4b1a78
[ "MIT" ]
null
null
null
dual_annealing.py
website-fingerprinting/minipatch
682d86c0eca5331a8c001e83003cf79b5d4b1a78
[ "MIT" ]
null
null
null
# Dual Annealing implementation. # Copyright (c) 2018 Sylvain Gubian <sylvain.gubian@pmi.com>, # Yang Xiang <yang.xiang@pmi.com> # Author: Sylvain Gubian, Yang Xiang, PMP S.A. """ A slight modification to Scipy's implementation of simulated annealing. Fix bug in implementation of formula in p. 398 of reference [2] (line 273). Add function to display energy at each iteration by parameter 'disp' (line 679). Taken from scipy==1.4.1 ---------- A Dual Annealing global optimization algorithm """ from __future__ import division, print_function, absolute_import import numpy as np from scipy.optimize import OptimizeResult from scipy.optimize import minimize from scipy.special import gammaln from scipy._lib._util import check_random_state __all__ = ['dual_annealing'] class VisitingDistribution(object): """ Class used to generate new coordinates based on the distorted Cauchy-Lorentz distribution. Depending on the steps within the strategy chain, the class implements the strategy for generating new location changes. Parameters ---------- lb : array_like A 1-D numpy ndarray containing lower bounds of the generated components. Neither NaN or inf are allowed. ub : array_like A 1-D numpy ndarray containing upper bounds for the generated components. Neither NaN or inf are allowed. visiting_param : float Parameter for visiting distribution. Default value is 2.62. Higher values give the visiting distribution a heavier tail, this makes the algorithm jump to a more distant region. The value range is (0, 3]. It's value is fixed for the life of the object. rand_state : `~numpy.random.mtrand.RandomState` object A `~numpy.random.mtrand.RandomState` object for using the current state of the created random generator container. """ TAIL_LIMIT = 1.e8 MIN_VISIT_BOUND = 1.e-10 def __init__(self, lb, ub, visiting_param, rand_state): # if you wish to make _visiting_param adjustable during the life of # the object then _factor2, _factor3, _factor5, _d1, _factor6 will # have to be dynamically calculated in `visit_fn`. They're factored # out here so they don't need to be recalculated all the time. self._visiting_param = visiting_param self.rand_state = rand_state self.lower = lb self.upper = ub self.bound_range = ub - lb # these are invariant numbers unless visiting_param changes self._factor2 = np.exp((4.0 - self._visiting_param) * np.log( self._visiting_param - 1.0)) self._factor3 = np.exp((2.0 - self._visiting_param) * np.log(2.0) / (self._visiting_param - 1.0)) self._factor4_p = np.sqrt(np.pi) * self._factor2 / (self._factor3 * ( 3.0 - self._visiting_param)) self._factor5 = 1.0 / (self._visiting_param - 1.0) - 0.5 self._d1 = 2.0 - self._factor5 self._factor6 = np.pi * (1.0 - self._factor5) / np.sin( np.pi * (1.0 - self._factor5)) / np.exp(gammaln(self._d1)) def visiting(self, x, step, temperature): """ Based on the step in the strategy chain, new coordinated are generated by changing all components is the same time or only one of them, the new values are computed with visit_fn method """ dim = x.size if step < dim: # Changing all coordinates with a new visiting value visits = self.visit_fn(temperature, dim) upper_sample = self.rand_state.random_sample() lower_sample = self.rand_state.random_sample() visits[visits > self.TAIL_LIMIT] = self.TAIL_LIMIT * upper_sample visits[visits < -self.TAIL_LIMIT] = -self.TAIL_LIMIT * lower_sample x_visit = visits + x a = x_visit - self.lower b = np.fmod(a, self.bound_range) + self.bound_range x_visit = np.fmod(b, self.bound_range) + self.lower x_visit[np.fabs( x_visit - self.lower) < self.MIN_VISIT_BOUND] += 1.e-10 else: # Changing only one coordinate at a time based on strategy # chain step x_visit = np.copy(x) visit = self.visit_fn(temperature, 1) if visit > self.TAIL_LIMIT: visit = self.TAIL_LIMIT * self.rand_state.random_sample() elif visit < -self.TAIL_LIMIT: visit = -self.TAIL_LIMIT * self.rand_state.random_sample() index = step - dim x_visit[index] = visit + x[index] a = x_visit[index] - self.lower[index] b = np.fmod(a, self.bound_range[index]) + self.bound_range[index] x_visit[index] = np.fmod(b, self.bound_range[ index]) + self.lower[index] if np.fabs(x_visit[index] - self.lower[ index]) < self.MIN_VISIT_BOUND: x_visit[index] += self.MIN_VISIT_BOUND return x_visit def visit_fn(self, temperature, dim): """ Formula Visita from p. 405 of reference [2] """ x, y = self.rand_state.normal(size=(dim, 2)).T factor1 = np.exp(np.log(temperature) / (self._visiting_param - 1.0)) factor4 = self._factor4_p * factor1 # sigmax x *= np.exp(-(self._visiting_param - 1.0) * np.log( self._factor6 / factor4) / (3.0 - self._visiting_param)) den = np.exp((self._visiting_param - 1.0) * np.log(np.fabs(y)) / (3.0 - self._visiting_param)) return x / den class EnergyState(object): """ Class used to record the energy state. At any time, it knows what is the currently used coordinates and the most recent best location. Parameters ---------- lower : array_like A 1-D numpy ndarray containing lower bounds for generating an initial random components in the `reset` method. upper : array_like A 1-D numpy ndarray containing upper bounds for generating an initial random components in the `reset` method components. Neither NaN or inf are allowed. callback : callable, ``callback(x, f, context)``, optional A callback function which will be called for all minima found. ``x`` and ``f`` are the coordinates and function value of the latest minimum found, and `context` has value in [0, 1, 2] """ # Maximimum number of trials for generating a valid starting point MAX_REINIT_COUNT = 1000 def __init__(self, lower, upper, callback=None): self.ebest = None self.current_energy = None self.current_location = None self.xbest = None self.lower = lower self.upper = upper self.callback = callback def reset(self, func_wrapper, rand_state, x0=None): """ Initialize current location is the search domain. If `x0` is not provided, a random location within the bounds is generated. """ if x0 is None: self.current_location = self.lower + rand_state.random_sample( len(self.lower)) * (self.upper - self.lower) else: self.current_location = np.copy(x0) init_error = True reinit_counter = 0 while init_error: self.current_energy = func_wrapper.fun(self.current_location) if self.current_energy is None: raise ValueError('Objective function is returning None') if (not np.isfinite(self.current_energy) or np.isnan( self.current_energy)): if reinit_counter >= EnergyState.MAX_REINIT_COUNT: init_error = False message = ( 'Stopping algorithm because function ' 'create NaN or (+/-) infinity values even with ' 'trying new random parameters' ) raise ValueError(message) self.current_location = self.lower + rand_state.random_sample( self.lower.size) * (self.upper - self.lower) reinit_counter += 1 else: init_error = False # If first time reset, initialize ebest and xbest if self.ebest is None and self.xbest is None: self.ebest = self.current_energy self.xbest = np.copy(self.current_location) # Otherwise, we keep them in case of reannealing reset def update_best(self, e, x, context): self.ebest = e self.xbest = np.copy(x) if self.callback is not None: val = self.callback(x, e, context) if val is not None: if val: return('Callback function requested to stop early by ' 'returning True') def update_current(self, e, x): self.current_energy = e self.current_location = np.copy(x) class StrategyChain(object): """ Class that implements within a Markov chain the strategy for location acceptance and local search decision making. Parameters ---------- acceptance_param : float Parameter for acceptance distribution. It is used to control the probability of acceptance. The lower the acceptance parameter, the smaller the probability of acceptance. Default value is -5.0 with a range (-1e4, -5]. visit_dist : VisitingDistribution Instance of `VisitingDistribution` class. func_wrapper : ObjectiveFunWrapper Instance of `ObjectiveFunWrapper` class. minimizer_wrapper: LocalSearchWrapper Instance of `LocalSearchWrapper` class. rand_state : `~numpy.random.mtrand.RandomState` object A `~numpy.random.mtrand.RandomState` object for using the current state of the created random generator container. energy_state: EnergyState Instance of `EnergyState` class. """ def __init__(self, acceptance_param, visit_dist, func_wrapper, minimizer_wrapper, rand_state, energy_state): # Local strategy chain minimum energy and location self.emin = energy_state.current_energy self.xmin = np.array(energy_state.current_location) # Global optimizer state self.energy_state = energy_state # Acceptance parameter self.acceptance_param = acceptance_param # Visiting distribution instance self.visit_dist = visit_dist # Wrapper to objective function self.func_wrapper = func_wrapper # Wrapper to the local minimizer self.minimizer_wrapper = minimizer_wrapper self.not_improved_idx = 0 self.not_improved_max_idx = 1000 self._rand_state = rand_state self.temperature_step = 0 self.K = 100 * len(energy_state.current_location) def accept_reject(self, j, e, x_visit): r = self._rand_state.random_sample() # pqv_temp = (self.acceptance_param - 1.0) * ( # e - self.energy_state.current_energy) / ( # self.temperature_step + 1.) ############## ## CHANGES: fix implementation bug from p. 398 of reference [2] ############## pqv_temp = 1.0 - ((1.0 - self.acceptance_param) * (e - self.energy_state.current_energy) / self.temperature_step) if pqv_temp <= 0.: pqv = 0. else: pqv = np.exp(np.log(pqv_temp) / ( 1. - self.acceptance_param)) if r <= pqv: # We accept the new location and update state self.energy_state.update_current(e, x_visit) self.xmin = np.copy(self.energy_state.current_location) # No improvement for a long time if self.not_improved_idx >= self.not_improved_max_idx: if j == 0 or self.energy_state.current_energy < self.emin: self.emin = self.energy_state.current_energy self.xmin = np.copy(self.energy_state.current_location) def run(self, step, temperature): self.temperature_step = temperature / float(step + 1) self.not_improved_idx += 1 for j in range(self.energy_state.current_location.size * 2): if j == 0: if step == 0: self.energy_state_improved = True else: self.energy_state_improved = False x_visit = self.visit_dist.visiting( self.energy_state.current_location, j, temperature) # Calling the objective function e = self.func_wrapper.fun(x_visit) if e < self.energy_state.current_energy: # We have got a better energy value self.energy_state.update_current(e, x_visit) if e < self.energy_state.ebest: val = self.energy_state.update_best(e, x_visit, 0) if val is not None: if val: return val self.energy_state_improved = True self.not_improved_idx = 0 else: # We have not improved but do we accept the new location? self.accept_reject(j, e, x_visit) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during annealing') # End of StrategyChain loop def local_search(self): # Decision making for performing a local search # based on strategy chain results # If energy has been improved or no improvement since too long, # performing a local search with the best strategy chain location if self.energy_state_improved: # Global energy has improved, let's see if LS improves further e, x = self.minimizer_wrapper.local_search(self.energy_state.xbest, self.energy_state.ebest) if e < self.energy_state.ebest: self.not_improved_idx = 0 val = self.energy_state.update_best(e, x, 1) if val is not None: if val: return val self.energy_state.update_current(e, x) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during local search') # Check probability of a need to perform a LS even if no improvement do_ls = False if self.K < 90 * len(self.energy_state.current_location): pls = np.exp(self.K * ( self.energy_state.ebest - self.energy_state.current_energy) / self.temperature_step) if pls >= self._rand_state.random_sample(): do_ls = True # Global energy not improved, let's see what LS gives # on the best strategy chain location if self.not_improved_idx >= self.not_improved_max_idx: do_ls = True if do_ls: e, x = self.minimizer_wrapper.local_search(self.xmin, self.emin) self.xmin = np.copy(x) self.emin = e self.not_improved_idx = 0 self.not_improved_max_idx = self.energy_state.current_location.size if e < self.energy_state.ebest: val = self.energy_state.update_best( self.emin, self.xmin, 2) if val is not None: if val: return val self.energy_state.update_current(e, x) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during dual annealing') class ObjectiveFunWrapper(object): def __init__(self, func, maxfun=1e7, *args): self.func = func self.args = args # Number of objective function evaluations self.nfev = 0 # Number of gradient function evaluation if used self.ngev = 0 # Number of hessian of the objective function if used self.nhev = 0 self.maxfun = maxfun def fun(self, x): self.nfev += 1 return self.func(x, *self.args) class LocalSearchWrapper(object): """ Class used to wrap around the minimizer used for local search Default local minimizer is SciPy minimizer L-BFGS-B """ LS_MAXITER_RATIO = 6 LS_MAXITER_MIN = 100 LS_MAXITER_MAX = 1000 def __init__(self, bounds, func_wrapper, **kwargs): self.func_wrapper = func_wrapper self.kwargs = kwargs self.minimizer = minimize bounds_list = list(zip(*bounds)) self.lower = np.array(bounds_list[0]) self.upper = np.array(bounds_list[1]) # If no minimizer specified, use SciPy minimize with 'L-BFGS-B' method if not self.kwargs: n = len(self.lower) ls_max_iter = min(max(n * self.LS_MAXITER_RATIO, self.LS_MAXITER_MIN), self.LS_MAXITER_MAX) self.kwargs['method'] = 'L-BFGS-B' self.kwargs['options'] = { 'maxiter': ls_max_iter, } self.kwargs['bounds'] = list(zip(self.lower, self.upper)) def local_search(self, x, e): # Run local search from the given x location where energy value is e x_tmp = np.copy(x) mres = self.minimizer(self.func_wrapper.fun, x, **self.kwargs) if 'njev' in mres.keys(): self.func_wrapper.ngev += mres.njev if 'nhev' in mres.keys(): self.func_wrapper.nhev += mres.nhev # Check if is valid value is_finite = np.all(np.isfinite(mres.x)) and np.isfinite(mres.fun) in_bounds = np.all(mres.x >= self.lower) and np.all( mres.x <= self.upper) is_valid = is_finite and in_bounds # Use the new point only if it is valid and return a better results if is_valid and mres.fun < e: return mres.fun, mres.x else: return e, x_tmp def dual_annealing(func, bounds, args=(), maxiter=1000, local_search_options={}, initial_temp=5230., restart_temp_ratio=2.e-5, visit=2.62, accept=-5.0, maxfun=1e7, seed=None, no_local_search=False, callback=None, x0=None, disp=False): """ Find the global minimum of a function using Dual Annealing. Parameters ---------- func : callable The objective function to be minimized. Must be in the form ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array and ``args`` is a tuple of any additional fixed parameters needed to completely specify the function. bounds : sequence, shape (n, 2) Bounds for variables. ``(min, max)`` pairs for each element in ``x``, defining bounds for the objective function parameter. args : tuple, optional Any additional fixed parameters needed to completely specify the objective function. maxiter : int, optional The maximum number of global search iterations. Default value is 1000. local_search_options : dict, optional Extra keyword arguments to be passed to the local minimizer (`minimize`). Some important options could be: ``method`` for the minimizer method to use and ``args`` for objective function additional arguments. initial_temp : float, optional The initial temperature, use higher values to facilitates a wider search of the energy landscape, allowing dual_annealing to escape local minima that it is trapped in. Default value is 5230. Range is (0.01, 5.e4]. restart_temp_ratio : float, optional During the annealing process, temperature is decreasing, when it reaches ``initial_temp * restart_temp_ratio``, the reannealing process is triggered. Default value of the ratio is 2e-5. Range is (0, 1). visit : float, optional Parameter for visiting distribution. Default value is 2.62. Higher values give the visiting distribution a heavier tail, this makes the algorithm jump to a more distant region. The value range is (0, 3]. accept : float, optional Parameter for acceptance distribution. It is used to control the probability of acceptance. The lower the acceptance parameter, the smaller the probability of acceptance. Default value is -5.0 with a range (-1e4, -5]. maxfun : int, optional Soft limit for the number of objective function calls. If the algorithm is in the middle of a local search, this number will be exceeded, the algorithm will stop just after the local search is done. Default value is 1e7. seed : {int or `~numpy.random.mtrand.RandomState` instance}, optional If `seed` is not specified the `~numpy.random.mtrand.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``RandomState`` instance, then that instance is used. Specify `seed` for repeatable minimizations. The random numbers generated with this seed only affect the visiting distribution function and new coordinates generation. no_local_search : bool, optional If `no_local_search` is set to True, a traditional Generalized Simulated Annealing will be performed with no local search strategy applied. callback : callable, optional A callback function with signature ``callback(x, f, context)``, which will be called for all minima found. ``x`` and ``f`` are the coordinates and function value of the latest minimum found, and ``context`` has value in [0, 1, 2], with the following meaning: - 0: minimum detected in the annealing process. - 1: detection occurred in the local search process. - 2: detection done in the dual annealing process. If the callback implementation returns True, the algorithm will stop. x0 : ndarray, shape(n,), optional Coordinates of a single n-dimensional starting point. Returns ------- res : OptimizeResult The optimization result represented as a `OptimizeResult` object. Important attributes are: ``x`` the solution array, ``fun`` the value of the function at the solution, and ``message`` which describes the cause of the termination. See `OptimizeResult` for a description of other attributes. Notes ----- This function implements the Dual Annealing optimization. This stochastic approach derived from [3]_ combines the generalization of CSA (Classical Simulated Annealing) and FSA (Fast Simulated Annealing) [1]_ [2]_ coupled to a strategy for applying a local search on accepted locations [4]_. An alternative implementation of this same algorithm is described in [5]_ and benchmarks are presented in [6]_. This approach introduces an advanced method to refine the solution found by the generalized annealing process. This algorithm uses a distorted Cauchy-Lorentz visiting distribution, with its shape controlled by the parameter :math:`q_{v}` .. math:: g_{q_{v}}(\\Delta x(t)) \\propto \\frac{ \\ \\left[T_{q_{v}}(t) \\right]^{-\\frac{D}{3-q_{v}}}}{ \\ \\left[{1+(q_{v}-1)\\frac{(\\Delta x(t))^{2}} { \\ \\left[T_{q_{v}}(t)\\right]^{\\frac{2}{3-q_{v}}}}}\\right]^{ \\ \\frac{1}{q_{v}-1}+\\frac{D-1}{2}}} Where :math:`t` is the artificial time. This visiting distribution is used to generate a trial jump distance :math:`\\Delta x(t)` of variable :math:`x(t)` under artificial temperature :math:`T_{q_{v}}(t)`. From the starting point, after calling the visiting distribution function, the acceptance probability is computed as follows: .. math:: p_{q_{a}} = \\min{\\{1,\\left[1-(1-q_{a}) \\beta \\Delta E \\right]^{ \\ \\frac{1}{1-q_{a}}}\\}} Where :math:`q_{a}` is a acceptance parameter. For :math:`q_{a}<1`, zero acceptance probability is assigned to the cases where .. math:: [1-(1-q_{a}) \\beta \\Delta E] < 0 The artificial temperature :math:`T_{q_{v}}(t)` is decreased according to .. math:: T_{q_{v}}(t) = T_{q_{v}}(1) \\frac{2^{q_{v}-1}-1}{\\left( \\ 1 + t\\right)^{q_{v}-1}-1} Where :math:`q_{v}` is the visiting parameter. .. versionadded:: 1.2.0 References ---------- .. [1] Tsallis C. Possible generalization of Boltzmann-Gibbs statistics. Journal of Statistical Physics, 52, 479-487 (1998). .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing. Physica A, 233, 395-406 (1996). .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated Annealing Algorithm and Its Application to the Thomson Model. Physics Letters A, 233, 216-220 (1997). .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated Annealing. Physical Review E, 62, 4473 (2000). .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized Simulated Annealing for Efficient Global Optimization: the GenSA Package for R. The R Journal, Volume 5/1 (2013). .. [6] Mullen, K. Continuous Global Optimization in R. Journal of Statistical Software, 60(6), 1 - 45, (2014). DOI:10.18637/jss.v060.i06 Examples -------- The following example is a 10-dimensional problem, with many local minima. The function involved is called Rastrigin (https://en.wikipedia.org/wiki/Rastrigin_function) >>> from scipy.optimize import dual_annealing >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x) >>> lw = [-5.12] * 10 >>> up = [5.12] * 10 >>> ret = dual_annealing(func, bounds=list(zip(lw, up)), seed=1234) >>> print("global minimum: xmin = {0}, f(xmin) = {1:.6f}".format( ... ret.x, ret.fun)) global minimum: xmin = [-4.26437714e-09 -3.91699361e-09 -1.86149218e-09 -3.97165720e-09 -6.29151648e-09 -6.53145322e-09 -3.93616815e-09 -6.55623025e-09 -6.05775280e-09 -5.00668935e-09], f(xmin) = 0.000000 """ # noqa: E501 if x0 is not None and not len(x0) == len(bounds): raise ValueError('Bounds size does not match x0') lu = list(zip(*bounds)) lower = np.array(lu[0]) upper = np.array(lu[1]) # Check that restart temperature ratio is correct if restart_temp_ratio <= 0. or restart_temp_ratio >= 1.: raise ValueError('Restart temperature ratio has to be in range (0, 1)') # Checking bounds are valid if (np.any(np.isinf(lower)) or np.any(np.isinf(upper)) or np.any( np.isnan(lower)) or np.any(np.isnan(upper))): raise ValueError('Some bounds values are inf values or nan values') # Checking that bounds are consistent if not np.all(lower < upper): raise ValueError('Bounds are not consistent min < max') # Checking that bounds are the same length if not len(lower) == len(upper): raise ValueError('Bounds do not have the same dimensions') # Wrapper for the objective function func_wrapper = ObjectiveFunWrapper(func, maxfun, *args) # Wrapper fot the minimizer minimizer_wrapper = LocalSearchWrapper( bounds, func_wrapper, **local_search_options) # Initialization of RandomState for reproducible runs if seed provided rand_state = check_random_state(seed) # Initialization of the energy state energy_state = EnergyState(lower, upper, callback) energy_state.reset(func_wrapper, rand_state, x0) # Minimum value of annealing temperature reached to perform # re-annealing temperature_restart = initial_temp * restart_temp_ratio # VisitingDistribution instance visit_dist = VisitingDistribution(lower, upper, visit, rand_state) # Strategy chain instance strategy_chain = StrategyChain(accept, visit_dist, func_wrapper, minimizer_wrapper, rand_state, energy_state) need_to_stop = False iteration = 0 message = [] # OptimizeResult object to be returned optimize_res = OptimizeResult() optimize_res.success = True optimize_res.status = 0 t1 = np.exp((visit - 1) * np.log(2.0)) - 1.0 # Run the search loop while(not need_to_stop): for i in range(maxiter): # Compute temperature for this step s = float(i) + 2.0 t2 = np.exp((visit - 1) * np.log(s)) - 1.0 temperature = initial_temp * t1 / t2 if iteration >= maxiter: message.append("Maximum number of iteration reached") need_to_stop = True break # Need a re-annealing process? if temperature < temperature_restart: energy_state.reset(func_wrapper, rand_state) break ############## ## CHANGES: display energy per iteration ############## if disp: print("dual_annealing step %d: f(x)= %g" % (i, energy_state.ebest)) # starting strategy chain val = strategy_chain.run(i, temperature) if val is not None: message.append(val) need_to_stop = True optimize_res.success = False break # Possible local search at the end of the strategy chain if not no_local_search: val = strategy_chain.local_search() if val is not None: message.append(val) need_to_stop = True optimize_res.success = False break iteration += 1 # Setting the OptimizeResult values optimize_res.x = energy_state.xbest optimize_res.fun = energy_state.ebest optimize_res.nit = iteration optimize_res.nfev = func_wrapper.nfev optimize_res.njev = func_wrapper.ngev optimize_res.nhev = func_wrapper.nhev optimize_res.message = message return optimize_res
43.125706
91
0.616219
from __future__ import division, print_function, absolute_import import numpy as np from scipy.optimize import OptimizeResult from scipy.optimize import minimize from scipy.special import gammaln from scipy._lib._util import check_random_state __all__ = ['dual_annealing'] class VisitingDistribution(object): TAIL_LIMIT = 1.e8 MIN_VISIT_BOUND = 1.e-10 def __init__(self, lb, ub, visiting_param, rand_state): # out here so they don't need to be recalculated all the time. self._visiting_param = visiting_param self.rand_state = rand_state self.lower = lb self.upper = ub self.bound_range = ub - lb self._factor2 = np.exp((4.0 - self._visiting_param) * np.log( self._visiting_param - 1.0)) self._factor3 = np.exp((2.0 - self._visiting_param) * np.log(2.0) / (self._visiting_param - 1.0)) self._factor4_p = np.sqrt(np.pi) * self._factor2 / (self._factor3 * ( 3.0 - self._visiting_param)) self._factor5 = 1.0 / (self._visiting_param - 1.0) - 0.5 self._d1 = 2.0 - self._factor5 self._factor6 = np.pi * (1.0 - self._factor5) / np.sin( np.pi * (1.0 - self._factor5)) / np.exp(gammaln(self._d1)) def visiting(self, x, step, temperature): dim = x.size if step < dim: visits = self.visit_fn(temperature, dim) upper_sample = self.rand_state.random_sample() lower_sample = self.rand_state.random_sample() visits[visits > self.TAIL_LIMIT] = self.TAIL_LIMIT * upper_sample visits[visits < -self.TAIL_LIMIT] = -self.TAIL_LIMIT * lower_sample x_visit = visits + x a = x_visit - self.lower b = np.fmod(a, self.bound_range) + self.bound_range x_visit = np.fmod(b, self.bound_range) + self.lower x_visit[np.fabs( x_visit - self.lower) < self.MIN_VISIT_BOUND] += 1.e-10 else: x_visit = np.copy(x) visit = self.visit_fn(temperature, 1) if visit > self.TAIL_LIMIT: visit = self.TAIL_LIMIT * self.rand_state.random_sample() elif visit < -self.TAIL_LIMIT: visit = -self.TAIL_LIMIT * self.rand_state.random_sample() index = step - dim x_visit[index] = visit + x[index] a = x_visit[index] - self.lower[index] b = np.fmod(a, self.bound_range[index]) + self.bound_range[index] x_visit[index] = np.fmod(b, self.bound_range[ index]) + self.lower[index] if np.fabs(x_visit[index] - self.lower[ index]) < self.MIN_VISIT_BOUND: x_visit[index] += self.MIN_VISIT_BOUND return x_visit def visit_fn(self, temperature, dim): x, y = self.rand_state.normal(size=(dim, 2)).T factor1 = np.exp(np.log(temperature) / (self._visiting_param - 1.0)) factor4 = self._factor4_p * factor1 x *= np.exp(-(self._visiting_param - 1.0) * np.log( self._factor6 / factor4) / (3.0 - self._visiting_param)) den = np.exp((self._visiting_param - 1.0) * np.log(np.fabs(y)) / (3.0 - self._visiting_param)) return x / den class EnergyState(object): MAX_REINIT_COUNT = 1000 def __init__(self, lower, upper, callback=None): self.ebest = None self.current_energy = None self.current_location = None self.xbest = None self.lower = lower self.upper = upper self.callback = callback def reset(self, func_wrapper, rand_state, x0=None): if x0 is None: self.current_location = self.lower + rand_state.random_sample( len(self.lower)) * (self.upper - self.lower) else: self.current_location = np.copy(x0) init_error = True reinit_counter = 0 while init_error: self.current_energy = func_wrapper.fun(self.current_location) if self.current_energy is None: raise ValueError('Objective function is returning None') if (not np.isfinite(self.current_energy) or np.isnan( self.current_energy)): if reinit_counter >= EnergyState.MAX_REINIT_COUNT: init_error = False message = ( 'Stopping algorithm because function ' 'create NaN or (+/-) infinity values even with ' 'trying new random parameters' ) raise ValueError(message) self.current_location = self.lower + rand_state.random_sample( self.lower.size) * (self.upper - self.lower) reinit_counter += 1 else: init_error = False if self.ebest is None and self.xbest is None: self.ebest = self.current_energy self.xbest = np.copy(self.current_location) def update_best(self, e, x, context): self.ebest = e self.xbest = np.copy(x) if self.callback is not None: val = self.callback(x, e, context) if val is not None: if val: return('Callback function requested to stop early by ' 'returning True') def update_current(self, e, x): self.current_energy = e self.current_location = np.copy(x) class StrategyChain(object): def __init__(self, acceptance_param, visit_dist, func_wrapper, minimizer_wrapper, rand_state, energy_state): self.emin = energy_state.current_energy self.xmin = np.array(energy_state.current_location) self.energy_state = energy_state self.acceptance_param = acceptance_param self.visit_dist = visit_dist self.func_wrapper = func_wrapper self.minimizer_wrapper = minimizer_wrapper self.not_improved_idx = 0 self.not_improved_max_idx = 1000 self._rand_state = rand_state self.temperature_step = 0 self.K = 100 * len(energy_state.current_location) def accept_reject(self, j, e, x_visit): r = self._rand_state.random_sample() og(pqv_temp) / ( 1. - self.acceptance_param)) if r <= pqv: self.energy_state.update_current(e, x_visit) self.xmin = np.copy(self.energy_state.current_location) if self.not_improved_idx >= self.not_improved_max_idx: if j == 0 or self.energy_state.current_energy < self.emin: self.emin = self.energy_state.current_energy self.xmin = np.copy(self.energy_state.current_location) def run(self, step, temperature): self.temperature_step = temperature / float(step + 1) self.not_improved_idx += 1 for j in range(self.energy_state.current_location.size * 2): if j == 0: if step == 0: self.energy_state_improved = True else: self.energy_state_improved = False x_visit = self.visit_dist.visiting( self.energy_state.current_location, j, temperature) e = self.func_wrapper.fun(x_visit) if e < self.energy_state.current_energy: self.energy_state.update_current(e, x_visit) if e < self.energy_state.ebest: val = self.energy_state.update_best(e, x_visit, 0) if val is not None: if val: return val self.energy_state_improved = True self.not_improved_idx = 0 else: self.accept_reject(j, e, x_visit) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during annealing') def local_search(self): if self.energy_state_improved: e, x = self.minimizer_wrapper.local_search(self.energy_state.xbest, self.energy_state.ebest) if e < self.energy_state.ebest: self.not_improved_idx = 0 val = self.energy_state.update_best(e, x, 1) if val is not None: if val: return val self.energy_state.update_current(e, x) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during local search') # Check probability of a need to perform a LS even if no improvement do_ls = False if self.K < 90 * len(self.energy_state.current_location): pls = np.exp(self.K * ( self.energy_state.ebest - self.energy_state.current_energy) / self.temperature_step) if pls >= self._rand_state.random_sample(): do_ls = True # Global energy not improved, let's see what LS gives if self.not_improved_idx >= self.not_improved_max_idx: do_ls = True if do_ls: e, x = self.minimizer_wrapper.local_search(self.xmin, self.emin) self.xmin = np.copy(x) self.emin = e self.not_improved_idx = 0 self.not_improved_max_idx = self.energy_state.current_location.size if e < self.energy_state.ebest: val = self.energy_state.update_best( self.emin, self.xmin, 2) if val is not None: if val: return val self.energy_state.update_current(e, x) if self.func_wrapper.nfev >= self.func_wrapper.maxfun: return ('Maximum number of function call reached ' 'during dual annealing') class ObjectiveFunWrapper(object): def __init__(self, func, maxfun=1e7, *args): self.func = func self.args = args self.nfev = 0 self.ngev = 0 self.nhev = 0 self.maxfun = maxfun def fun(self, x): self.nfev += 1 return self.func(x, *self.args) class LocalSearchWrapper(object): LS_MAXITER_RATIO = 6 LS_MAXITER_MIN = 100 LS_MAXITER_MAX = 1000 def __init__(self, bounds, func_wrapper, **kwargs): self.func_wrapper = func_wrapper self.kwargs = kwargs self.minimizer = minimize bounds_list = list(zip(*bounds)) self.lower = np.array(bounds_list[0]) self.upper = np.array(bounds_list[1]) if not self.kwargs: n = len(self.lower) ls_max_iter = min(max(n * self.LS_MAXITER_RATIO, self.LS_MAXITER_MIN), self.LS_MAXITER_MAX) self.kwargs['method'] = 'L-BFGS-B' self.kwargs['options'] = { 'maxiter': ls_max_iter, } self.kwargs['bounds'] = list(zip(self.lower, self.upper)) def local_search(self, x, e): x_tmp = np.copy(x) mres = self.minimizer(self.func_wrapper.fun, x, **self.kwargs) if 'njev' in mres.keys(): self.func_wrapper.ngev += mres.njev if 'nhev' in mres.keys(): self.func_wrapper.nhev += mres.nhev is_finite = np.all(np.isfinite(mres.x)) and np.isfinite(mres.fun) in_bounds = np.all(mres.x >= self.lower) and np.all( mres.x <= self.upper) is_valid = is_finite and in_bounds if is_valid and mres.fun < e: return mres.fun, mres.x else: return e, x_tmp def dual_annealing(func, bounds, args=(), maxiter=1000, local_search_options={}, initial_temp=5230., restart_temp_ratio=2.e-5, visit=2.62, accept=-5.0, maxfun=1e7, seed=None, no_local_search=False, callback=None, x0=None, disp=False): if x0 is not None and not len(x0) == len(bounds): raise ValueError('Bounds size does not match x0') lu = list(zip(*bounds)) lower = np.array(lu[0]) upper = np.array(lu[1]) if restart_temp_ratio <= 0. or restart_temp_ratio >= 1.: raise ValueError('Restart temperature ratio has to be in range (0, 1)') if (np.any(np.isinf(lower)) or np.any(np.isinf(upper)) or np.any( np.isnan(lower)) or np.any(np.isnan(upper))): raise ValueError('Some bounds values are inf values or nan values') if not np.all(lower < upper): raise ValueError('Bounds are not consistent min < max') if not len(lower) == len(upper): raise ValueError('Bounds do not have the same dimensions') func_wrapper = ObjectiveFunWrapper(func, maxfun, *args) minimizer_wrapper = LocalSearchWrapper( bounds, func_wrapper, **local_search_options) rand_state = check_random_state(seed) energy_state = EnergyState(lower, upper, callback) energy_state.reset(func_wrapper, rand_state, x0) temperature_restart = initial_temp * restart_temp_ratio visit_dist = VisitingDistribution(lower, upper, visit, rand_state) strategy_chain = StrategyChain(accept, visit_dist, func_wrapper, minimizer_wrapper, rand_state, energy_state) need_to_stop = False iteration = 0 message = [] optimize_res = OptimizeResult() optimize_res.success = True optimize_res.status = 0 t1 = np.exp((visit - 1) * np.log(2.0)) - 1.0 while(not need_to_stop): for i in range(maxiter): s = float(i) + 2.0 t2 = np.exp((visit - 1) * np.log(s)) - 1.0 temperature = initial_temp * t1 / t2 if iteration >= maxiter: message.append("Maximum number of iteration reached") need_to_stop = True break if temperature < temperature_restart: energy_state.reset(func_wrapper, rand_state) break if val is not None: message.append(val) need_to_stop = True optimize_res.success = False break if not no_local_search: val = strategy_chain.local_search() if val is not None: message.append(val) need_to_stop = True optimize_res.success = False break iteration += 1 optimize_res.x = energy_state.xbest optimize_res.fun = energy_state.ebest optimize_res.nit = iteration optimize_res.nfev = func_wrapper.nfev optimize_res.njev = func_wrapper.ngev optimize_res.nhev = func_wrapper.nhev optimize_res.message = message return optimize_res
true
true
1c39dccda5ab4c3452bd526b158464ab5404df36
3,169
py
Python
splay_tree_trace.py
andribas404/splay_benchmark
1ba2fe4d715b25db806c0b241c6adadd8d442a77
[ "MIT" ]
null
null
null
splay_tree_trace.py
andribas404/splay_benchmark
1ba2fe4d715b25db806c0b241c6adadd8d442a77
[ "MIT" ]
null
null
null
splay_tree_trace.py
andribas404/splay_benchmark
1ba2fe4d715b25db806c0b241c6adadd8d442a77
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """Trace splay tree.""" import inspect import logging import os import pygraphviz as pgv from splay_tree_orig import SplayTree logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) os.makedirs("graph", exist_ok=True) def for_all_methods(decorator): """ Add decorator to all class methods. https://stackoverflow.com/questions/6307761/how-to-decorate-all-functions-of-a-class-without-typing-it-over-and-over-for-eac/6307868#6307868 :param decorator: decorator :return: decorated class """ def decorate(cls): members = inspect.getmembers(cls, predicate=inspect.isfunction) for name, value in members: if name in ("__init__", "draw"): continue setattr(cls, name, decorator(value)) return cls return decorate def draw_decorator(func): """ Draw state of tree. :param func: called function :return: decorated function """ def wrapper(*args, **kwargs): assert len(args) > 0 tree = args[0] assert isinstance(tree, SplayTree) func_name = func.__qualname__ message = f"{func_name}{args[1:]}" draw(tree, " before " + message) res = func(*args, **kwargs) draw(tree, " after " + message) return res return wrapper def draw(tree, message): """Draw state.""" logger.debug(str(tree._step) + message) tree._step += 1 A = pgv.AGraph() A.node_attr["style"] = "filled" A.node_attr["shape"] = "record" A.node_attr["fixedsize"] = "true" A.node_attr["fontsize"] = 12 for node in tree._nodes: label = f"""<f0> {node.val}|<f1> {node.counter}""" A.add_node(id(node), label=label) n = A.get_node(id(node)) if not node.parent: n.attr["fillcolor"] = "#CFC291" for node in tree._nodes: if node.parent: # красный A.add_edge(id(node), id(node.parent), color="#F15A5A") if node.left: # зеленый A.add_edge(id(node), id(node.left), color="#4EBA6F") if node.right: # синий A.add_edge(id(node), id(node.right), color="#2D95BF") A.layout() filename = os.path.join("graph", f"{tree._step:03}-{message}.dot") A.draw(filename) class Worker: """Worker.""" def __init__(self): """Worker init.""" self.tree = for_all_methods(draw_decorator)(SplayTree)() def process(self, commands): """Process commands.""" res = [] for cmd_code, x in commands: if cmd_code == 1: pos = self.tree.insert(x) res.append(pos) elif cmd_code == 2: self.tree.remove(x) else: raise ValueError("Invalid Command") return res if __name__ == "__main__": worker = Worker() n = int(input()) commands = [] for _ in range(n): command = list(map(int, input().strip().split())) commands.append(command) res = worker.process(commands) print("\n".join(map(str, res)))
25.556452
144
0.577469
import inspect import logging import os import pygraphviz as pgv from splay_tree_orig import SplayTree logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) os.makedirs("graph", exist_ok=True) def for_all_methods(decorator): def decorate(cls): members = inspect.getmembers(cls, predicate=inspect.isfunction) for name, value in members: if name in ("__init__", "draw"): continue setattr(cls, name, decorator(value)) return cls return decorate def draw_decorator(func): def wrapper(*args, **kwargs): assert len(args) > 0 tree = args[0] assert isinstance(tree, SplayTree) func_name = func.__qualname__ message = f"{func_name}{args[1:]}" draw(tree, " before " + message) res = func(*args, **kwargs) draw(tree, " after " + message) return res return wrapper def draw(tree, message): logger.debug(str(tree._step) + message) tree._step += 1 A = pgv.AGraph() A.node_attr["style"] = "filled" A.node_attr["shape"] = "record" A.node_attr["fixedsize"] = "true" A.node_attr["fontsize"] = 12 for node in tree._nodes: label = f"""<f0> {node.val}|<f1> {node.counter}""" A.add_node(id(node), label=label) n = A.get_node(id(node)) if not node.parent: n.attr["fillcolor"] = "#CFC291" for node in tree._nodes: if node.parent: A.add_edge(id(node), id(node.parent), color="#F15A5A") if node.left: A.add_edge(id(node), id(node.left), color="#4EBA6F") if node.right: A.add_edge(id(node), id(node.right), color="#2D95BF") A.layout() filename = os.path.join("graph", f"{tree._step:03}-{message}.dot") A.draw(filename) class Worker: def __init__(self): self.tree = for_all_methods(draw_decorator)(SplayTree)() def process(self, commands): res = [] for cmd_code, x in commands: if cmd_code == 1: pos = self.tree.insert(x) res.append(pos) elif cmd_code == 2: self.tree.remove(x) else: raise ValueError("Invalid Command") return res if __name__ == "__main__": worker = Worker() n = int(input()) commands = [] for _ in range(n): command = list(map(int, input().strip().split())) commands.append(command) res = worker.process(commands) print("\n".join(map(str, res)))
true
true
1c39dd072a1ea1d4d97dd6b71d7de7375b7976e5
50,281
py
Python
hdl21/tests/test_hdl21.py
dan-fritchman/Hdl21
adb7787b137f2bea720e576a3027314a1dcd0947
[ "BSD-3-Clause" ]
1
2022-02-19T18:48:45.000Z
2022-02-19T18:48:45.000Z
hdl21/tests/test_hdl21.py
dan-fritchman/Hdl21
adb7787b137f2bea720e576a3027314a1dcd0947
[ "BSD-3-Clause" ]
13
2021-07-21T17:48:49.000Z
2022-01-31T23:12:08.000Z
hdl21/tests/test_hdl21.py
dan-fritchman/Hdl21
adb7787b137f2bea720e576a3027314a1dcd0947
[ "BSD-3-Clause" ]
null
null
null
""" # hdl21 Unit Tests """ import sys, copy, pytest from io import StringIO from types import SimpleNamespace from enum import Enum, EnumMeta, auto from textwrap import dedent # Import the PUT (package under test) import hdl21 as h def test_version(): assert h.__version__ == "0.2.0" def test_module1(): """ Initial Module Test """ @h.module class M1: a = h.Input() b = h.Output() c = h.Inout() d = h.Port() e = h.Signal() f = h.Signal() assert isinstance(M1, h.Module) assert isinstance(M1.ports, dict) assert isinstance(M1.signals, dict) assert isinstance(M1.instances, dict) assert "a" in M1.ports assert "a" not in M1.signals assert "b" in M1.ports assert "b" not in M1.signals assert "c" in M1.ports assert "c" not in M1.signals assert "d" in M1.ports assert "d" not in M1.signals assert "e" in M1.signals assert "e" not in M1.ports assert "f" in M1.signals assert "f" not in M1.ports assert M1.e is not M1.f def test_module2(): @h.module class M1: s = h.Input() @h.module class M2: q = h.Signal() i = M1(s=q) assert isinstance(M1, h.Module) assert isinstance(M2, h.Module) assert isinstance(M1.ports["s"], h.Signal) assert isinstance(M2.signals["q"], h.Signal) assert isinstance(M2.instances["i"], h.Instance) # Test the getattr magic for signals, ports, and instances assert isinstance(M2.i, h.Instance) assert M2.instances["i"] is M2.i assert isinstance(M2.q, h.Signal) assert M2.signals["q"] is M2.q assert isinstance(M1.s, h.Signal) assert M1.ports["s"] is M1.s def test_generator1(): @h.paramclass class MyParams: w = h.Param(dtype=int, desc="five", default=5) @h.generator def gen1(params: MyParams) -> h.Module: m = h.Module() m.i = h.Input(width=params.w) return m m = h.elaborate(gen1(MyParams(w=3))) assert m.name == "gen1(MyParams(w=3))" assert isinstance(m.i, h.Signal) def test_generator2(): @h.paramclass class P2: f = h.Param(dtype=float, desc="a real number", default=1e-11) @h.generator def g2(params: P2, ctx: h.Context) -> h.Module: # Generator which takes a Context-argument assert isinstance(params, P2) assert isinstance(ctx, h.Context) return h.Module() m = h.elaborate(g2(P2())) assert isinstance(m, h.Module) assert m.name == "g2(P2(f=1e-11))" def test_generator3(): @h.paramclass class P3: width = h.Param(dtype=int, desc="bit-width, maybe", default=1) @h.generator def g3a(params: P3) -> h.Module: return h.Module() @h.generator def g3b(params: P3, ctx: h.Context) -> h.Module: return h.Module() M = h.Module(name="M") p3a = P3() p3b = P3(width=5) @h.module class HasGen: a = g3a(p3a)() b = g3b(p3b)() c = M() # Elaborate the top module h.elaborate(HasGen) # Post-elab checks assert isinstance(HasGen.a, h.Instance) assert isinstance(HasGen.a.of, h.GeneratorCall) assert HasGen.a.of.gen is g3a assert HasGen.a.of.arg == P3() assert isinstance(HasGen.a.of.result, h.Module) assert HasGen.a.of.result.name == "g3a(P3(width=1))" assert isinstance(HasGen.b, h.Instance) assert isinstance(HasGen.b.of, h.GeneratorCall) assert isinstance(HasGen.b.of.result, h.Module) assert HasGen.b.of.result.name == "g3b(P3(width=5))" assert HasGen.b.of.gen is g3b assert HasGen.b.of.arg == P3(width=5) assert isinstance(HasGen.c, h.Instance) assert isinstance(HasGen.c.of, h.Module) assert HasGen.c.of is M def test_params1(): # Initial param-class test @h.paramclass class MyParams: a = h.Param(dtype=int, default=5, desc="your fave") assert h.isparamclass(MyParams) m = MyParams() assert isinstance(m.a, int) assert m.a == 5 assert isinstance(m.__params__["a"], h.Param) assert m.defaults() == dict(a=5) assert m.descriptions() == dict(a="your fave") def test_params2(): @h.paramclass class Pc2: # Required r = h.Param(dtype=str, desc="required") # Optional o = h.Param(dtype=str, default="hmmm", desc="optional") assert h.isparamclass(Pc2) assert Pc2.defaults() == dict(o="hmmm") assert Pc2.descriptions() == dict(r="required", o="optional") p = Pc2(r="provided") assert isinstance(p.r, str) assert p.r == "provided" assert isinstance(p.o, str) assert p.o == "hmmm" assert p.defaults() == dict(o="hmmm") assert p.descriptions() == dict(r="required", o="optional") def test_params3(): # Test parameters with a creation-time list-tuple conversion @h.paramclass class HasTuple: t = h.Param(dtype=tuple, desc="Go ahead, try a list") ht = HasTuple(t=[1, 2, 3]) assert isinstance(ht.t, tuple) assert ht.t == (1, 2, 3) def test_params4(): # Test some param-class nesting from dataclasses import asdict @h.paramclass class Inner: i = h.Param(dtype=int, desc="Inner int-field") @h.paramclass class Outer: inner = h.Param(dtype=Inner, desc="Inner fields") f = h.Param(dtype=float, desc="A float", default=3.14159) o = Outer(inner=Inner(11)) assert isinstance(o, Outer) assert isinstance(o.inner, Inner) assert o.inner == Inner(11) assert o.inner.i == 11 assert o.f == 3.14159 # Create from a (nested) dictionary d1 = {"inner": {"i": 11}, "f": 22.2} o1 = Outer(**d1) uname1 = h.params._unique_name(o1) # Convert back to another dictionary d2 = asdict(o1) # And check they line up assert d1 == d2 # Round-trip back to an `Outer` o2 = Outer(**d2) uname2 = h.params._unique_name(o2) assert uname1 == uname2 assert uname1 == "Outer(3dcc309796996b3a8a61db66631c5a93)" def test_bad_params1(): # Test a handful of errors Params and paramclasses should raise. from hdl21 import ( paramclass, Param, ValidationError, FrozenInstanceError, ) with pytest.raises(RuntimeError): # Test that creating a paramclass with parent-class(es) fails @paramclass class C(TabError): # Of course this is a sub-class of the best built-in class ... @paramclass class C: a = Param(dtype=int, desc="Gonna Fail!") with pytest.raises(RuntimeError): # Test that sub-classing a paramclass fails class D(C): ... with pytest.raises(TypeError): # Test that missing arguments fail c = C() with pytest.raises(ValidationError): # Test invalid argument types fail c = C(a=TabError) with pytest.raises(FrozenInstanceError): # Test that attempts at mutating paramclasses fail c = C(a=3) c.a = 4 with pytest.raises(RuntimeError): # Test "no Module sub-classing" class E(h.Module): ... with pytest.raises(RuntimeError): # Test "no decorating inherited types" @h.module class E2(TabError): ... with pytest.raises(RuntimeError): # Test bad parameter names @h.paramclass class P: descriptions = h.Param(dtype=str, desc="", default="BAD!") with pytest.raises(RuntimeError): # Test bad parameter names @h.paramclass class P: defaults = h.Param(dtype=str, desc="", default="BAD!") with pytest.raises(RuntimeError): # Test non-params in `@paramclass` @h.paramclass class P: something = 11 with pytest.raises(RuntimeError): # Test a bad argument type h.params._unique_name(33) def test_array1(): @h.module class InArray: inp = h.Input() out = h.Output() m = h.Module(name="HasArray") m.s1 = h.Signal(width=8) m.s2 = h.Signal(width=1) m.arr = h.InstArray(InArray, 8) m.arr.inp = m.s1 m.arr.out = m.s2 assert m.name == "HasArray" def test_array2(): """ Basic Instance-Array Test """ a = h.Module(name="a") a.inp = h.Port(width=1) a.out = h.Port(width=1) @h.module class HasArray2: s1 = h.Signal(width=8) s2 = h.Signal(width=1) arr = h.InstArray(a, 8)(inp=s1, out=s2) assert len(HasArray2.instances) == 0 assert len(HasArray2.instarrays) == 1 # Elaborate, flattening arrays along the way h.elaborate(HasArray2) # Post-elab checks assert len(HasArray2.instances) == 8 assert len(HasArray2.instarrays) == 0 def test_cycle1(): """ Test cyclical connection-graphs, i.e. a back-to-back pair of instances """ @h.module class Thing: inp = h.Input() out = h.Output() @h.module class BackToBack: t1 = Thing() t2 = Thing(inp=t1.out, out=t1.inp) b = h.elaborate(BackToBack) assert isinstance(b.t1.inp, h.Signal) assert isinstance(b.t1.out, h.Signal) assert isinstance(b.t2.inp, h.Signal) assert isinstance(b.t2.out, h.Signal) # Doing the same thing in procedural code b2 = h.Module(name="BackToBack2") b2.t1 = Thing() b2.t2 = Thing() b2.t2.inp = b2.t1.out b2.t2.out = b2.t1.inp assert isinstance(b2.t1.inp, h.PortRef) assert isinstance(b2.t1.out, h.PortRef) assert isinstance(b2.t2.inp, h.PortRef) assert isinstance(b2.t2.out, h.PortRef) b2 = h.elaborate(b2) assert len(b2.instances) == 2 assert len(b2.instarrays) == 0 assert len(b2.bundles) == 0 assert len(b2.ports) == 0 assert len(b2.signals) == 2 assert "t2_inp_t1_out" in b2.signals assert "t2_out_t1_inp" in b2.signals def test_gen3(): @h.paramclass class MyParams: w = h.Param(dtype=int, desc="Input bit-width. Required") @h.generator def MyThirdGenerator(params: MyParams) -> h.Module: @h.module class Inner: i = h.Input(width=params.w) o = h.Output(width=2 * params.w) # Instantiate that in another Module @h.module class Outer: i = h.Signal(width=params.w) o = h.Signal(width=2 * params.w) inner = Inner(i=i, o=o) # And manipulate that some more too Outer.inp = h.Input(width=params.w) return Outer h.elaborate(MyThirdGenerator(MyParams(1))) # FIXME: post-elab checks def test_prim1(): # First test of transistor primitives params = h.Mos.Params() pmos = h.Pmos(params) nmos = h.Nmos(params) @h.module class HasMos: # Two transistors wired in parallel p = pmos() n = nmos(g=p.g, d=p.d, s=p.s, b=p.b) h.elaborate(HasMos) # FIXME: post-elab checks def test_prim2(): @h.module class HasPrims: p = h.Signal() n = h.Signal() _rp = h.R.Params(r=50) r = h.Resistor(_rp)(p=p, n=n) c = h.Capacitor(h.C.Params(c=1e-12))(p=p, n=n) l = h.Inductor(h.L.Params(l=1e-15))(p=p, n=n) d = h.Diode(h.D.Params())(p=p, n=n) s = h.Short(h.Short.Params())(p=p, n=n) h.elaborate(HasPrims) # FIXME: post-elab checks def test_prim_proto1(): # Test round-tripping primitives through proto @h.module class HasPrims: p = h.Signal() n = h.Signal() # Wire up a bunch of two-terminal primitives in parallel _rp = h.R.Params(r=50) r = h.Resistor(_rp)(p=p, n=n) _cp = h.C.Params(c=1e-12) c = h.Capacitor(_cp)(p=p, n=n) _lp = h.L.Params(l=1e-15) l = h.Inductor(_lp)(p=p, n=n) _dp = h.D.Params() d = h.Diode(_dp)(p=p, n=n) _sp = h.Short.Params() s = h.Short(_sp)(p=p, n=n) ppkg = h.to_proto(HasPrims) assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 1 assert ppkg.domain == "" # Check the proto-Module pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.HasPrims" assert len(pm.ports) == 0 assert len(pm.signals) == 2 assert len(pm.instances) == 5 assert len(pm.default_parameters) == 0 for inst in pm.instances: assert isinstance(inst, h.proto.Instance) assert inst.module.WhichOneof("to") == "external" assert inst.module.external.domain in ["hdl21.ideal", "hdl21.primitives"] ns = h.from_proto(ppkg) assert isinstance(ns, SimpleNamespace) ns = ns.hdl21.tests.test_hdl21 assert isinstance(ns, SimpleNamespace) assert hasattr(ns, "HasPrims") HasPrims = ns.HasPrims assert isinstance(HasPrims, h.Module) assert len(HasPrims.ports) == 0 assert len(HasPrims.signals) == 2 assert len(HasPrims.instances) == 5 for inst in HasPrims.instances.values(): assert isinstance(inst._resolved, h.primitives.PrimitiveCall) def test_bundle1(): # Create an bundle i1 = h.Bundle(name="MyFirstBundle") i1.s1 = h.Signal() i1.s2 = h.Signal() assert isinstance(i1, h.Bundle) assert isinstance(i1.s1, h.Signal) assert isinstance(i1.s2, h.Signal) ii1 = i1() assert isinstance(ii1, h.BundleInstance) assert ii1.role is None assert ii1.port == False def test_bundle2(): # Wire up a few Modules via bundles MySecondBundle = h.Bundle(name="MySecondBundle") MySecondBundle.s = h.Signal() m1 = h.Module(name="M1") m1.i = MySecondBundle(port=True) m2 = h.Module(name="M2") m2.i = MySecondBundle(port=True) # Now create a parent Module connecting the two m3 = h.Module(name="M3") m3.i1 = m1() m3.i2 = m2(i=m3.i1.i) assert "i2_i_i1_i" not in m3.namespace # First run the "implicit bundles" pass, and see that an explicit one is created from hdl21.elab import ElabPass m3 = h.elaborate(m3, passes=[ElabPass.IMPLICIT_BUNDLES]) assert isinstance(m3, h.Module) assert isinstance(m3.i1, h.Instance) assert isinstance(m3.i2, h.Instance) assert "i2_i_i1_i" in m3.namespace # Now elaborate it the rest of the way, to scalar signals m3 = h.elaborate(m3) assert "i2_i_i1_i" not in m3.namespace assert "i2_i_i1_i_s" in m3.namespace assert isinstance(m3.get("i2_i_i1_i_s"), h.Signal) assert m3.get("i2_i_i1_i_s") in m3.i1.conns.values() def test_bundle3(): # Test the bundle-definition decorator @h.bundle class Diff: # Differential Signal Bundle p = h.Signal() n = h.Signal() @h.bundle class DisplayPort: # DisplayPort, kinda main_link = Diff() aux = h.Signal() assert isinstance(DisplayPort, h.Bundle) assert isinstance(DisplayPort(), h.BundleInstance) assert isinstance(DisplayPort.main_link, h.BundleInstance) assert isinstance(DisplayPort.main_link.p, h.PortRef) assert isinstance(DisplayPort.main_link.n, h.PortRef) assert isinstance(DisplayPort.aux, h.Signal) assert isinstance(Diff, h.Bundle) assert isinstance(Diff(), h.BundleInstance) assert isinstance(Diff.p, h.Signal) assert isinstance(Diff.n, h.Signal) # Instantiate one in a Module m = h.Module(name="M") m.dp = DisplayPort() assert isinstance(m.dp, h.BundleInstance) assert len(m.bundles) == 1 assert len(m.signals) == 0 # And elaborate it h.elaborate(m) assert not hasattr(m, "dp") assert len(m.bundles) == 0 assert len(m.signals) == 3 assert isinstance(m.get("dp_aux"), h.Signal) assert isinstance(m.get("dp_main_link_p"), h.Signal) assert isinstance(m.get("dp_main_link_n"), h.Signal) def test_bundle4(): # Test bundle roles @h.bundle class Diff: # Differential Signal Bundle p = h.Signal() n = h.Signal() @h.bundle class HasRoles: # An Bundle with Roles class Roles(Enum): # USB-Style Role Nomenclature HOST = auto() DEVICE = auto() # Create signals going in either direction tx = h.Signal(src=Roles.HOST, dest=Roles.DEVICE) rx = h.Signal(src=Roles.DEVICE, dest=Roles.HOST) # And create differential versions thereof txd = Diff(src=Roles.HOST, dest=Roles.DEVICE) rxd = Diff(src=Roles.DEVICE, dest=Roles.HOST) hr = HasRoles() assert isinstance(HasRoles, h.Bundle) assert isinstance(HasRoles.roles, EnumMeta) assert isinstance(HasRoles.Roles, EnumMeta) assert isinstance(hr, h.BundleInstance) assert isinstance(HasRoles.tx, h.Signal) assert isinstance(HasRoles.rx, h.Signal) assert isinstance(HasRoles.txd, h.BundleInstance) assert isinstance(HasRoles.rxd, h.BundleInstance) @h.module class Host: # A thing with a HOST-roled bundle-port hr = HasRoles(port=True, role=HasRoles.Roles.HOST) @h.module class Device: # A thing with a DEVICE-roled bundle-port hr = HasRoles(port=True, role=HasRoles.Roles.DEVICE) @h.module class System: # Parent system-module including a host and device host = Host() devc = Device(hr=host.hr) assert isinstance(System, h.Module) assert isinstance(System.host, h.Instance) assert isinstance(System.devc, h.Instance) assert "devc_hr_host_hr" not in System.namespace # First run the "implicit bundles" pass, and see that an explicit one is created from hdl21.elab import ElabPass sys = h.elaborate(System, passes=[ElabPass.IMPLICIT_BUNDLES]) assert "devc_hr_host_hr" in sys.namespace # Now expand the rest of the way, down to scalar signals # Check that bundle went away, and its constituent signals replaced it sys = h.elaborate(sys) assert "devc_hr_host_hr" not in sys.namespace assert "devc_hr_host_hr_tx" in sys.namespace assert "devc_hr_host_hr_rx" in sys.namespace assert "devc_hr_host_hr_txd_p" in sys.namespace assert "devc_hr_host_hr_txd_n" in sys.namespace assert "devc_hr_host_hr_rxd_p" in sys.namespace assert "devc_hr_host_hr_rxd_n" in sys.namespace def test_proto1(): # First Proto-export test m = h.Module(name="TestProto1") ppkg = h.to_proto(m) assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 1 assert ppkg.domain == "" pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.TestProto1" assert len(pm.ports) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 def test_proto2(): # Proto-export test with some hierarchy Child1 = h.Module(name="Child1") Child1.inp = h.Input(width=8) Child1.out = h.Output() Child2 = h.Module(name="Child2") Child2.inp = h.Input() Child2.out = h.Output(width=8) TestProto2 = h.Module(name="TestProto2") TestProto2.c1 = Child1() TestProto2.c2 = Child2() TestProto2.c2(inp=TestProto2.c1.out, out=TestProto2.c1.inp) ppkg = h.to_proto(TestProto2) assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 3 assert ppkg.domain == "" # Check the first Module in, Child1 pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.Child1" assert len(pm.ports) == 2 assert len(pm.signals) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 # Check the second Module in, Child2 pm = ppkg.modules[1] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.Child2" assert len(pm.ports) == 2 assert len(pm.signals) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 # And check the parent module pm = ppkg.modules[2] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.TestProto2" assert len(pm.ports) == 0 assert len(pm.instances) == 2 assert len(pm.default_parameters) == 0 def test_proto3(): # Proto-export test with some slicing and concatenation M1 = h.Module(name="M1") M1.p8 = h.Inout(width=8) M1.p1 = h.Inout(width=1) M2 = h.Module(name="M2") M2.s = h.Signal(width=4) M2.i = M1() M2.i(p1=M2.s[0]) M2.i(p8=h.Concat(M2.s, h.Concat(M2.s[0], M2.s[1]), M2.s[2:4])) ppkg = h.to_proto(M2, domain="test_proto3") assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 2 assert ppkg.domain == "test_proto3" # Check the child module pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.M1" assert len(pm.ports) == 2 assert len(pm.signals) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 # And check the parent module pm = ppkg.modules[1] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.M2" assert len(pm.ports) == 0 assert len(pm.signals) == 1 assert len(pm.instances) == 1 assert len(pm.default_parameters) == 0 ns = h.from_proto(ppkg) assert isinstance(ns, SimpleNamespace) ns = ns.hdl21.tests.test_hdl21 assert isinstance(ns, SimpleNamespace) assert isinstance(ns.M1, h.Module) assert len(ns.M1.ports) == 2 assert len(ns.M1.signals) == 0 assert len(ns.M1.instances) == 0 assert isinstance(M2, h.Module) assert len(M2.ports) == 0 assert len(M2.signals) == 1 assert len(M2.instances) == 1 assert "s" in M2.signals assert "i" in M2.instances inst = M2.i assert isinstance(inst.conns["p1"], h.signal.Slice) assert inst.conns["p1"].signal is M2.s assert inst.conns["p1"].top == 1 assert inst.conns["p1"].bot == 0 assert inst.conns["p1"].width == 1 assert isinstance(inst.conns["p8"], h.signal.Concat) assert len(inst.conns["p8"].parts) == 4 assert inst.conns["p8"].parts[0] is M2.s assert isinstance(inst.conns["p8"].parts[0], h.signal.Signal) assert isinstance(inst.conns["p8"].parts[1], h.signal.Slice) assert isinstance(inst.conns["p8"].parts[2], h.signal.Slice) assert isinstance(inst.conns["p8"].parts[3], h.signal.Slice) def test_proto_roundtrip(): # Test protobuf round-tripping # Create an empty (named) Module M1 = h.Module(name="M1") # Protobuf round-trip it ppkg = h.to_proto(M1) ns = h.from_proto(ppkg) assert isinstance(ns, SimpleNamespace) ns = ns.hdl21.tests.test_hdl21 assert isinstance(ns, SimpleNamespace) assert isinstance(ns.M1, h.Module) assert len(ns.M1.signals) == 0 assert len(ns.M1.ports) == 0 assert len(ns.M1.instances) == 0 def test_proto_roundtrip2(): # Create a child/leaf Module M1 = h.Module(name="M1") M1.i = h.Input() M1.o = h.Output() M1.p = h.Port() # Create an instantiating parent-module M2 = h.Module(name="M2") M2.i = h.Input() M2.o = h.Output() M2.p = h.Port() M2.s = h.Signal() # Add a few instances of it M2.i0 = M1() M2.i1 = M1() M2.i2 = M1() M2.i0(i=M2.i, o=M2.i1.i, p=M2.p) M2.i1(i=M2.i0.o, o=M2.s, p=M2.p) M2.i2(i=M2.s, o=M2.o, p=M2.p) # Protobuf round-trip it ppkg = h.to_proto(M2) ns = h.from_proto(ppkg) # And check all kinda stuff about what comes back assert isinstance(ns, SimpleNamespace) M1 = ns.hdl21.tests.test_hdl21.M1 M2 = ns.hdl21.tests.test_hdl21.M2 assert isinstance(M1, h.Module) assert isinstance(M2, h.Module) assert len(M1.signals) == 0 assert len(M1.ports) == 3 assert "i" in M1.ports assert M1.i.direction == h.signal.PortDir.INPUT assert M1.i.vis == h.signal.Visibility.PORT assert "o" in M1.ports assert M1.o.direction == h.signal.PortDir.OUTPUT assert M1.o.vis == h.signal.Visibility.PORT assert "p" in M1.ports assert M1.p.direction == h.signal.PortDir.NONE assert M1.p.vis == h.signal.Visibility.PORT assert len(M1.instances) == 0 assert len(M2.instances) == 3 for i in M2.instances.values(): assert i.of is M1 assert i.conns["p"] is M2.p assert len(M2.ports) == 3 assert len(M2.signals) == 2 assert "s" in M2.signals assert "i1_i_i0_o" in M2.signals def test_bigger_bundles(): """ Test a slightly more elaborate Bundle-based system """ class HostDevice(Enum): HOST = auto() DEVICE = auto() @h.bundle class Jtag: # Jtag Bundle roles = HostDevice tck, tdi, tms = h.Signals(3, src=roles.HOST, dest=roles.DEVICE) tdo = h.Signal(src=roles.DEVICE, dest=roles.HOST) @h.bundle class Uart: # Uart Bundle class Roles(Enum): # Uart roles are essentially peers, here named `ME` and `YOU`. # Essentially everything will use the role `ME`, # except for interconnect which swaps between the two. ME = auto() YOU = auto() tx = h.Signal(src=Roles.ME, dest=Roles.YOU) rx = h.Signal(src=Roles.YOU, dest=Roles.ME) @h.bundle class Spi: # Spi Bundle roles = HostDevice sck, cs = h.Signals(2, src=roles.HOST, dest=roles.DEVICE) dq = h.Signal(src=roles.DEVICE, dest=roles.HOST, width=4) @h.module class Chip: spi = Spi(role=HostDevice.HOST, port=True) jtag = Jtag(role=HostDevice.DEVICE, port=True) uart = Uart(role=Uart.Roles.ME, port=True) ... # Actual internal content, which likely connects these down *many* levels of hierarchy @h.module class SpiFlash: # A typical flash memory with a SPI port spi = Spi(role=HostDevice.DEVICE, port=True) @h.module class Board: # A typical embedded board, featuring a custom chip, SPI-connected flash, and JTAG port jtag = Jtag(role=HostDevice.DEVICE, port=True) uart = Uart(role=Uart.Roles.ME, port=True) chip = Chip(jtag=jtag, uart=uart) flash = SpiFlash(spi=chip.spi) @h.module class Tester: # A typical test-widget with a JTAG port jtag = Jtag(role=HostDevice.HOST, port=True) uart = Uart(role=Uart.Roles.ME, port=True) @h.module class TestSystem: # A system in which `Tester` can test `Board` jtag = Jtag() tester = Tester(jtag=jtag) board = Board(jtag=jtag) # Connect UART, swapping `rx` and `tx` u0, u1 = h.Signals(2) board.uart = h.AnonymousBundle(tx=u0, rx=u1) tester.uart = h.AnonymousBundle(rx=u0, tx=u1) assert isinstance(TestSystem.jtag, h.BundleInstance) assert isinstance(TestSystem.tester, h.Instance) assert isinstance(TestSystem.board, h.Instance) assert isinstance(TestSystem.tester.uart, h.PortRef) assert isinstance(TestSystem.tester.uart.tx, h.PortRef) assert isinstance(TestSystem.tester.uart.rx, h.PortRef) assert isinstance(TestSystem.board.uart, h.PortRef) assert isinstance(TestSystem.board.uart.tx, h.PortRef) assert isinstance(TestSystem.board.uart.rx, h.PortRef) # Run this through elaboration h.elaborate(TestSystem) # Post-elab checks # TestSystem assert isinstance(TestSystem.tester, h.Instance) assert isinstance(TestSystem.board, h.Instance) assert TestSystem.tester.of is Tester assert TestSystem.board.of is Board assert not hasattr(TestSystem, "jtag") assert not hasattr(TestSystem, "uart") assert "u0" in TestSystem.namespace assert "u1" in TestSystem.namespace assert len(TestSystem.ports) == 0 assert len(TestSystem.signals) == 6 assert len(TestSystem.instances) == 2 assert isinstance(TestSystem.get("u0"), h.Signal) assert isinstance(TestSystem.get("u1"), h.Signal) assert isinstance(TestSystem.get("jtag_tck"), h.Signal) assert isinstance(TestSystem.get("jtag_tdi"), h.Signal) assert isinstance(TestSystem.get("jtag_tdo"), h.Signal) assert isinstance(TestSystem.get("jtag_tms"), h.Signal) # Tester assert len(Tester.ports) == 6 assert len(Tester.signals) == 0 assert len(Tester.instances) == 0 assert isinstance(Tester.get("jtag_tck"), h.Signal) assert Tester.get("jtag_tck").vis == h.signal.Visibility.PORT assert Tester.get("jtag_tdo").vis == h.signal.Visibility.PORT assert Tester.get("jtag_tdi").vis == h.signal.Visibility.PORT assert Tester.get("jtag_tms").vis == h.signal.Visibility.PORT assert Tester.get("uart_tx").vis == h.signal.Visibility.PORT assert Tester.get("uart_rx").vis == h.signal.Visibility.PORT # Board assert len(Board.ports) == 6 assert len(Board.signals) == 3 # SPI signals assert len(Board.instances) == 2 assert Board.chip.of is Chip assert Board.flash.of is SpiFlash assert Board.get("jtag_tck").vis == h.signal.Visibility.PORT assert Board.get("jtag_tdo").vis == h.signal.Visibility.PORT assert Board.get("jtag_tdi").vis == h.signal.Visibility.PORT assert Board.get("jtag_tms").vis == h.signal.Visibility.PORT assert Board.get("uart_tx").vis == h.signal.Visibility.PORT assert Board.get("uart_rx").vis == h.signal.Visibility.PORT assert Board.get("flash_spi_chip_spi_sck").vis == h.signal.Visibility.INTERNAL assert Board.get("flash_spi_chip_spi_cs").vis == h.signal.Visibility.INTERNAL assert Board.get("flash_spi_chip_spi_dq").vis == h.signal.Visibility.INTERNAL # Chip assert len(Chip.ports) == 9 assert len(Chip.signals) == 0 assert len(Chip.instances) == 0 assert Chip.get("jtag_tck").vis == h.signal.Visibility.PORT assert Chip.get("jtag_tdo").vis == h.signal.Visibility.PORT assert Chip.get("jtag_tdi").vis == h.signal.Visibility.PORT assert Chip.get("jtag_tms").vis == h.signal.Visibility.PORT assert Chip.get("spi_sck").vis == h.signal.Visibility.PORT assert Chip.get("spi_cs").vis == h.signal.Visibility.PORT assert Chip.get("spi_dq").vis == h.signal.Visibility.PORT assert Chip.get("uart_tx").vis == h.signal.Visibility.PORT assert Chip.get("uart_rx").vis == h.signal.Visibility.PORT # SpiFlash assert len(SpiFlash.ports) == 3 assert len(SpiFlash.signals) == 0 assert len(SpiFlash.instances) == 0 assert SpiFlash.get("spi_sck").vis == h.signal.Visibility.PORT assert SpiFlash.get("spi_cs").vis == h.signal.Visibility.PORT assert SpiFlash.get("spi_dq").vis == h.signal.Visibility.PORT def test_signal_slice1(): # Initial test of signal slicing sig = h.Signal(width=10) sl = sig[0] assert isinstance(sl, h.signal.Slice) assert sl.top == 1 assert sl.bot == 0 assert sl.width == 1 assert sl.step is None assert sl.signal is sig sl = sig[0:5] assert isinstance(sl, h.signal.Slice) assert sl.top == 5 assert sl.bot == 0 assert sl.width == 5 assert sl.step is None assert sl.signal is sig sl = sig[:] assert isinstance(sl, h.signal.Slice) assert sl.top == 10 assert sl.bot == 0 assert sl.width == 10 assert sl.step is None assert sl.signal is sig def test_signal_slice2(): # Test slicing advanced features sl = h.Signal(width=11)[-1] assert sl.top == 11 assert sl.bot == 10 assert sl.step is None assert sl.width == 1 sl = h.Signal(width=11)[:-1] assert sl.top == 10 assert sl.bot == 0 assert sl.step is None assert sl.width == 10 sl = h.Signal(width=11)[-2:] assert sl.top == 11 assert sl.bot == 9 assert sl.step is None assert sl.width == 2 def test_bad_slice1(): # Test slicing error-cases with pytest.raises(TypeError): h.Signal(width=11)[None] with pytest.raises(ValueError): h.Signal(width=11)[11] h.Signal(width=11)[2:1:-1] # OK with pytest.raises(ValueError): h.Signal(width=11)[2:1:1] # Not OK h.Signal(width=11)[1:9] # OK with pytest.raises(ValueError): h.Signal(width=11)[9:1] # Not OK def test_signal_concat1(): # Initial Signal concatenation test c = h.Concat(h.Signal(width=1), h.Signal(width=2), h.Signal(width=3)) assert isinstance(c, h.signal.Concat) assert len(c.parts) == 3 for p in c.parts: assert isinstance(p, h.signal.Signal) assert c.width == 6 c = h.Concat(h.Signal(width=1)[0], h.Signal(width=2)[0], h.Signal(width=3)[0]) assert isinstance(c, h.signal.Concat) assert len(c.parts) == 3 for p in c.parts: assert isinstance(p, h.signal.Slice) assert c.width == 3 c = h.Concat( h.Concat(h.Signal(), h.Signal()), h.Signal(width=2), h.Signal(width=2)[:] ) assert isinstance(c, h.signal.Concat) assert len(c.parts) == 3 assert c.width == 6 def test_slice_module1(): # Make use of slicing and concatenation in a module C = h.Module(name="C") C.p1 = h.Port(width=1) C.p4 = h.Port(width=4) C.p7 = h.Port(width=7) P = h.Module(name="P") C.s4 = h.Signal(width=4) C.s2 = h.Signal(width=2) P.ic = C(p1=C.s4[0], p4=C.s4, p7=h.Concat(C.s4, C.s2, C.s2[0])) h.elaborate(P) def test_bad_proto_naming(): # Test some cases which generate serialization naming conflicts # Same Module-names in same Python module with pytest.raises(RuntimeError): # Create a naming conflict between Module definitions Ma1 = h.Module(name="Ma") Ma2 = h.Module(name="Ma") @h.module class MaParent: ma1 = Ma1() ma2 = Ma2() h.to_proto(MaParent) with pytest.raises(RuntimeError): # Do the same via some functions that should be generators def m1(): return h.Module(name="Ma") def m2(): return h.Module(name="Ma") @h.module class MaParent: ma1 = m1()() ma2 = m2()() h.to_proto(MaParent) def test_generator_recall(): """ Test multi-calling generators """ @h.generator def CallMeTwice(_: h.HasNoParams) -> h.Module: return h.Module() @h.module class Caller: m1 = CallMeTwice(h.NoParams)() m2 = CallMeTwice(h.NoParams)() # Convert to proto ppkg = h.to_proto(Caller) assert len(ppkg.modules) == 2 assert ppkg.modules[0].name == "hdl21.tests.test_hdl21.CallMeTwice(NoParams())" assert ppkg.modules[1].name == "hdl21.tests.test_hdl21.Caller" # Convert the proto-package to a netlist, and run some (very basic) checks nl = StringIO() h.netlist(ppkg, nl) nl = nl.getvalue() assert "CallMeTwice_NoParams" in nl assert "Caller" in nl # Round-trip back from Proto to Modules rt = h.from_proto(ppkg) ns = rt.hdl21.tests.test_hdl21 assert isinstance(ns.Caller, h.Module) assert isinstance(getattr(ns, "CallMeTwice(NoParams())"), h.Module) def test_module_as_param(): """ Test using a `Module` as a parameter-value """ @h.paramclass class HasModuleParam: m = h.Param(dtype=h.Module, desc="A `Module` provided as a parameter") @h.generator def UsesModuleParam(params: HasModuleParam) -> h.Module: return params.m # Returns the Module unmodified Empty = h.Module(name="Empty") p = HasModuleParam(m=Empty) m = UsesModuleParam(p) m = h.elaborate(m) assert m == Empty def test_mos_generator(): """ Initial test of built-in series-Mos generator """ Mos = h.generators.Mos m = Mos(Mos.Params(nser=2)) assert isinstance(m, h.GeneratorCall) assert isinstance(m.arg, Mos.Params) m = h.elaborate(m) assert isinstance(m, h.Module) assert len(m.ports) == 4 assert m.ports == h.primitives.Mos.ports assert len(m.instances) == 2 assert "unit0" in m.instances assert "unit1" in m.instances assert isinstance(m.instances["unit0"].of, h.PrimitiveCall) assert isinstance(m.instances["unit1"].of, h.PrimitiveCall) assert m.instances["unit0"].of.params == h.primitives.MosParams() assert m.instances["unit1"].of.params == h.primitives.MosParams() assert len(m.signals) == 1 assert "unit1_s_unit0_d" in m.signals ppkg = h.to_proto(m) assert isinstance(ppkg, h.proto.Package) def test_series_parallel_generator(): """ Initial test of the general-purpose series-parallel generator """ from hdl21.generators import SeriesPar @h.module class M: # Unit cell a, b, c, d, e, f, g = h.Ports(7) params = SeriesPar.Params(unit=M, npar=2, nser=2, series_conns=["a", "b"]) m = SeriesPar(params) assert isinstance(m, h.GeneratorCall) assert isinstance(m.arg, SeriesPar.Params) m = h.elaborate(m) assert isinstance(m, h.Module) assert len(m.ports) == 7 assert m.ports == M.ports assert len(m.instances) == 4 assert "unit_0_0" in m.instances assert "unit_0_1" in m.instances assert "unit_1_0" in m.instances assert "unit_1_1" in m.instances for inst in m.instances.values(): assert inst.of is M assert len(m.signals) == 2 assert "unit_0_1_a_unit_0_0_b" in m.signals assert "unit_1_1_a_unit_1_0_b" in m.signals ppkg = h.to_proto(m) assert isinstance(ppkg, h.proto.Package) def test_instance_mult(): """ Initial tests of instance-array-generation by multiplication """ Child = h.Module(name="Child") Parent = h.Module(name="Parent") # Create an array via multiplication Parent.child = Child() * 5 # Lotta kids here # Check that the array is created correctly assert isinstance(Parent.child, h.InstArray) assert Parent.child.n == 5 assert Parent.child.of is Child # Test elaboration h.elaborate(Parent) # Post-elaboration checks assert len(Parent.instances) == 5 assert len(Parent.instarrays) == 0 for inst in Parent.instances.values(): assert inst.of is Child # Create another, this time via right-mul Parent = h.Module(name="Parent") Parent.child = 11 * Child() # Getting even more kids # Check that the array is created correctly assert isinstance(Parent.child, h.InstArray) assert Parent.child.n == 11 assert Parent.child.of is Child # Test elaboration h.elaborate(Parent) # Post-elaboration checks assert len(Parent.instances) == 11 assert len(Parent.instarrays) == 0 for inst in Parent.instances.values(): assert inst.of is Child def test_instance_mult2(): """ Test connecting to multiplication-generated InstArrays """ @h.module class Child: p = h.Port() @h.module class Parent: a = h.Signal(width=3) child = (Child() * 3)(p=a) assert len(Parent.instances) == 0 assert len(Parent.instarrays) == 1 h.elaborate(Parent) # Check that array-flattening completed correctly assert len(Parent.instances) == 3 assert len(Parent.instarrays) == 0 assert Parent.get("child_0").of is Child assert Parent.get("child_1").of is Child assert Parent.get("child_2").of is Child assert Parent.get("child_0").conns["p"] == Parent.a[0] assert Parent.get("child_1").conns["p"] == Parent.a[1] assert Parent.get("child_2").conns["p"] == Parent.a[2] def test_instance_mult3(): """ Test connecting to an "already connected" Instance """ @h.module class Child: p = h.Port() @h.module class Parent: a = h.Signal(width=3) child = 3 * Child(p=a) # <= this the one diff here from test_instance_mult2 h.elaborate(Parent) # Check that array-flattening completed correctly assert len(Parent.instances) == 3 assert len(Parent.instarrays) == 0 assert Parent.get("child_0").of is Child assert Parent.get("child_1").of is Child assert Parent.get("child_2").of is Child assert Parent.get("child_0").conns["p"] == Parent.a[0] assert Parent.get("child_1").conns["p"] == Parent.a[1] assert Parent.get("child_2").conns["p"] == Parent.a[2] def test_instance_mult4(): """ Test connecting non-unit-width Arrays """ @h.module class Child: a = h.Port(width=11) b = h.Port(width=16) @h.module class Parent: a = h.Signal(width=11) b = h.Signal(width=48) child = 3 * Child(a=a, b=b) h.elaborate(Parent) # Check that array-flattening completed correctly assert len(Parent.instances) == 3 assert len(Parent.instarrays) == 0 assert Parent.get("child_0").of is Child assert Parent.get("child_1").of is Child assert Parent.get("child_2").of is Child assert Parent.get("child_0").conns["a"] == Parent.a assert Parent.get("child_1").conns["a"] == Parent.a assert Parent.get("child_2").conns["a"] == Parent.a assert Parent.get("child_0").conns["b"] == Parent.b[0:16] assert Parent.get("child_1").conns["b"] == Parent.b[16:32] assert Parent.get("child_2").conns["b"] == Parent.b[32:48] def test_netlist_fmts(): """ Test netlisting basic types to several formats """ @h.module class Bot: s = h.Input(width=3) p = h.Output() @h.module class Top: s = h.Signal(width=3) p = h.Output() b = Bot(s=s, p=p) # Convert to proto ppkg = h.to_proto(Top) assert len(ppkg.modules) == 2 assert ppkg.modules[0].name == "hdl21.tests.test_hdl21.Bot" assert ppkg.modules[1].name == "hdl21.tests.test_hdl21.Top" # Convert the proto-package to a netlist nl = StringIO() h.netlist(ppkg, nl, "spectre") nl = nl.getvalue() # Basic checks on its contents assert "subckt Bot" in nl assert "+ s_2 s_1 s_0 p" in nl assert "subckt Top" in nl assert "b\n" in nl assert "+ ( s_2 s_1 s_0 p )" in nl assert "+ p" in nl assert "+ Bot " in nl # Convert the proto-package to another netlist format nl = StringIO() h.netlist(ppkg, nl, "verilog") nl = nl.getvalue() # Basic checks on its contents assert "module Bot" in nl assert "input wire [2:0] s," in nl assert "output wire p" in nl assert "endmodule // Bot" in nl assert "module Top" in nl assert ".s(s)" in nl assert ".p(p)" in nl assert "endmodule // Top" in nl nl = StringIO() h.netlist(ppkg, nl, "spice") nl = nl.getvalue() assert ".SUBCKT Bot \n+ s_2 s_1 s_0 p" in nl assert ".SUBCKT Top \n+ p" in nl assert "xb \n+ s_2 s_1 s_0 p \n+ Bot" in nl def test_spice_netlister(): @h.module class DUT: a = h.Input(width=5) b = h.Output(width=5) res = h.IdealResistor(h.ResistorParams(r=10e3))(p=a[0], n=b[0]) cap = h.IdealCapacitor(h.IdealCapacitorParams(c=10e-12))(p=a[1], n=b[1]) ind = h.IdealInductor(h.IdealInductorParams(l=10e-9))(p=a[2], n=b[2]) ppkg = h.to_proto(DUT) nl = StringIO() h.netlist(ppkg, nl, "spice") good = dedent( """\ .SUBCKT DUT + a_4 a_3 a_2 a_1 a_0 b_4 b_3 b_2 b_1 b_0 + * No parameters rres + a_0 b_0 + r=10000.0 ccap + a_1 b_1 + c=1e-11 lind + a_2 b_2 + l=1e-08 .ENDS """ ) assert good in nl.getvalue() def test_bad_width_conn(): """ Test invalid connection-widths """ c = h.Module(name="c") c.p = h.Port(width=3) # Width-3 Port q = h.Module(name="q") q.s = h.Signal(width=5) # Width-5 Signal q.c = c(p=q.s) # <= Bad connection here with pytest.raises(RuntimeError): h.elaborate(q) def test_bad_bundle_conn(): """ Test invalid Bundle connections """ @h.bundle class P: p = h.Signal(width=3) @h.bundle class R: z = h.Signal(width=11) @h.module class C: p = P(port=True) # `P`-type Bundle @h.module class Q: r = R() # `R`-type Bundle c = C(p=r) # <= Bad connection here with pytest.raises(RuntimeError): h.elaborate(Q) def test_illegal_module_attrs(): """ Test attempting to add illegal attributes """ m = h.Module() with pytest.raises(TypeError): m.a = list() with pytest.raises(TypeError): @h.module class M: a = list() @h.module class C: ... with pytest.raises(TypeError): C.b = TabError # Use combinations of legal attributes m = h.Module(name="m") with pytest.raises(TypeError): m.p = 5 with pytest.raises(TypeError): m.z = dict(a=h.Signal()) with pytest.raises(TypeError): m.q = [h.Port()] with pytest.raises(TypeError): m.p = (h.Input(), h.Output()) def test_copy_signal(): """ Copying a Signal """ copy.copy(h.Signal()) def test_copy_bundle_instance(): """ Copying a BundleInstance """ # This generally fails when run in the debugger, but seems alright stand-alone (?) copy.copy(h.BundleInstance(name="inst", of=h.Bundle())) def test_bundle_destructure(): """ Test de-structuring bundles to individual Signals """ @h.bundle class B: w1 = h.Signal(width=1) w3 = h.Signal(width=3) @h.module class Child: w1 = h.Port(width=1) w3 = h.Port(width=3) @h.module class Parent: b = B() # `B`-type Bundle instance c = Child(w1=b.w1, w3=b.w3) # `Child`-type instance, connected to `b` h.elaborate(Parent) assert len(Parent.instances) == 1 assert len(Parent.signals) == 2 assert "b_w1" in Parent.signals assert "b_w3" in Parent.signals assert Parent.c.conns["w1"] is Parent.signals["b_w1"] assert Parent.c.conns["w3"] is Parent.signals["b_w3"] def test_orphanage(): """ Test that orphaned Module-attributes fail at elaboration """ m1 = h.Module(name="m1") m1.s = h.Signal() # Signal `s` is now "parented" by `m1` m2 = h.Module(name="m2") m2.y = m1.s # Now `s` has been "orphaned" (or perhaps "cradle-robbed") by `m2` # Note elaborating `m2` continues to work h.elaborate(m2) with pytest.raises(RuntimeError): # Elaborating `m1` should fail, since `s` is orphaned h.elaborate(m1) def test_orphanage2(): """ Test orphaning a bundle instance """ @h.bundle class B: bb = h.Signal(width=1) b = B() # Instance of `B`-type Bundle, to be orphaned m1 = h.Module(name="m1") m1.b = b m2 = h.Module(name="m2") m2.b = b # Note elaborating `m2` continues to work h.elaborate(m2) with pytest.raises(RuntimeError): # Elaborating `m1` should fail, since `s` is orphaned h.elaborate(m1) def test_orphanage3(): """ Test orphaning an instance """ I = h.Module(name="I") i = I() # Instance to be orphaned m1 = h.Module(name="m1") m1.i = i m2 = h.Module(name="m2") m2.i = i # Note elaborating `m2` continues to work h.elaborate(m2) with pytest.raises(RuntimeError): # Elaborating `m1` should fail, since `s` is orphaned h.elaborate(m1) @pytest.mark.xfail(reason="#6") def test_wrong_decorator(): """ Mistake `Module` for `module` """ with pytest.raises(RuntimeError): @h.Module # Bad! class M: ... def test_elab_noconn(): """ Initial test of elaborating a `NoConn` """ @h.module class Inner: p = h.Port() @h.module class HasNoConn: i1 = Inner() i1.p = h.NoConn() h.elaborate(HasNoConn) assert len(HasNoConn.signals) == 1 def test_bad_noconn(): """ Test that a doubly-connected `NoConn` should fail """ @h.module class Inner: p = h.Port() @h.module class Bad: # Create two instances of `Inner` i1 = Inner() i2 = Inner() # Connect the first to a `NoConn` i1.p = h.NoConn() # And then connect the second to the first. # Herein lies the "problem" i2.p = i1.p with pytest.raises(RuntimeError): h.elaborate(Bad) def test_array_concat_conn(): """ Test connecting a `Concat` to an `InstArray` """ Child = h.Module(name="Child") Child.p3 = h.Input(width=3) Child.p5 = h.Input(width=5) Parent = h.Module(name="Parent") Parent.s5 = h.Signal(width=5) Parent.s9 = h.Signal(width=9) Parent.c = 2 * Child() Parent.c.p3 = Parent.s5[0:3] Parent.c.p5 = h.Concat(Parent.s5[3], Parent.s9) h.netlist(h.to_proto(Parent), StringIO(), "verilog") def test_slice_resolution(): """ Test resolutions of slice combinations """ from hdl21.elab import _resolve_slice # Slice of a Signal s = h.Signal(width=5) assert _resolve_slice(s[0]) == s[0] # Slice of a Concat s1 = h.Signal(name="s1", width=5) s2 = h.Signal(name="s2", width=5) c = h.Concat(s1, s2) assert _resolve_slice(c[0]) == s1[0] assert _resolve_slice(c[1]) == s1[1] assert _resolve_slice(c[2]) == s1[2] assert _resolve_slice(c[3]) == s1[3] assert _resolve_slice(c[4]) == s1[4] assert _resolve_slice(c[5]) == s2[0] assert _resolve_slice(c[6]) == s2[1] assert _resolve_slice(c[7]) == s2[2] assert _resolve_slice(c[8]) == s2[3] assert _resolve_slice(c[9]) == s2[4] # Slice of a Slice sa = h.Signal(name="sa", width=5) assert _resolve_slice(sa[2:5][0]) == sa[2] assert _resolve_slice(sa[2:5][1]) == sa[3] assert _resolve_slice(sa[2:5][2]) == sa[4] assert _resolve_slice(sa[:][0]) == sa[0] assert _resolve_slice(sa[:][1]) == sa[1] assert _resolve_slice(sa[:][2]) == sa[2] assert _resolve_slice(sa[:][3]) == sa[3] assert _resolve_slice(sa[:][4]) == sa[4] # Check a concatenation case. Note `Concat` does not support equality, so compare parts. assert _resolve_slice(sa[:][0:4]).parts == (sa[0], sa[1], sa[2], sa[3]) @pytest.mark.xfail(reason="#1") def test_export_strides(): """ Test exporting connections with non-unit Slice-strides """ c = h.Module(name="c") c.p = h.Input(width=2) p = h.Module(name="p") p.s = h.Signal(width=20) p.c = c(p=p.s[::10]) # Connect two of the 20 bits, with stride 10 h.netlist(h.to_proto(p), sys.stdout, "verilog")
27.902886
99
0.622879
import sys, copy, pytest from io import StringIO from types import SimpleNamespace from enum import Enum, EnumMeta, auto from textwrap import dedent import hdl21 as h def test_version(): assert h.__version__ == "0.2.0" def test_module1(): @h.module class M1: a = h.Input() b = h.Output() c = h.Inout() d = h.Port() e = h.Signal() f = h.Signal() assert isinstance(M1, h.Module) assert isinstance(M1.ports, dict) assert isinstance(M1.signals, dict) assert isinstance(M1.instances, dict) assert "a" in M1.ports assert "a" not in M1.signals assert "b" in M1.ports assert "b" not in M1.signals assert "c" in M1.ports assert "c" not in M1.signals assert "d" in M1.ports assert "d" not in M1.signals assert "e" in M1.signals assert "e" not in M1.ports assert "f" in M1.signals assert "f" not in M1.ports assert M1.e is not M1.f def test_module2(): @h.module class M1: s = h.Input() @h.module class M2: q = h.Signal() i = M1(s=q) assert isinstance(M1, h.Module) assert isinstance(M2, h.Module) assert isinstance(M1.ports["s"], h.Signal) assert isinstance(M2.signals["q"], h.Signal) assert isinstance(M2.instances["i"], h.Instance) assert isinstance(M2.i, h.Instance) assert M2.instances["i"] is M2.i assert isinstance(M2.q, h.Signal) assert M2.signals["q"] is M2.q assert isinstance(M1.s, h.Signal) assert M1.ports["s"] is M1.s def test_generator1(): @h.paramclass class MyParams: w = h.Param(dtype=int, desc="five", default=5) @h.generator def gen1(params: MyParams) -> h.Module: m = h.Module() m.i = h.Input(width=params.w) return m m = h.elaborate(gen1(MyParams(w=3))) assert m.name == "gen1(MyParams(w=3))" assert isinstance(m.i, h.Signal) def test_generator2(): @h.paramclass class P2: f = h.Param(dtype=float, desc="a real number", default=1e-11) @h.generator def g2(params: P2, ctx: h.Context) -> h.Module: assert isinstance(params, P2) assert isinstance(ctx, h.Context) return h.Module() m = h.elaborate(g2(P2())) assert isinstance(m, h.Module) assert m.name == "g2(P2(f=1e-11))" def test_generator3(): @h.paramclass class P3: width = h.Param(dtype=int, desc="bit-width, maybe", default=1) @h.generator def g3a(params: P3) -> h.Module: return h.Module() @h.generator def g3b(params: P3, ctx: h.Context) -> h.Module: return h.Module() M = h.Module(name="M") p3a = P3() p3b = P3(width=5) @h.module class HasGen: a = g3a(p3a)() b = g3b(p3b)() c = M() h.elaborate(HasGen) assert isinstance(HasGen.a, h.Instance) assert isinstance(HasGen.a.of, h.GeneratorCall) assert HasGen.a.of.gen is g3a assert HasGen.a.of.arg == P3() assert isinstance(HasGen.a.of.result, h.Module) assert HasGen.a.of.result.name == "g3a(P3(width=1))" assert isinstance(HasGen.b, h.Instance) assert isinstance(HasGen.b.of, h.GeneratorCall) assert isinstance(HasGen.b.of.result, h.Module) assert HasGen.b.of.result.name == "g3b(P3(width=5))" assert HasGen.b.of.gen is g3b assert HasGen.b.of.arg == P3(width=5) assert isinstance(HasGen.c, h.Instance) assert isinstance(HasGen.c.of, h.Module) assert HasGen.c.of is M def test_params1(): @h.paramclass class MyParams: a = h.Param(dtype=int, default=5, desc="your fave") assert h.isparamclass(MyParams) m = MyParams() assert isinstance(m.a, int) assert m.a == 5 assert isinstance(m.__params__["a"], h.Param) assert m.defaults() == dict(a=5) assert m.descriptions() == dict(a="your fave") def test_params2(): @h.paramclass class Pc2: r = h.Param(dtype=str, desc="required") o = h.Param(dtype=str, default="hmmm", desc="optional") assert h.isparamclass(Pc2) assert Pc2.defaults() == dict(o="hmmm") assert Pc2.descriptions() == dict(r="required", o="optional") p = Pc2(r="provided") assert isinstance(p.r, str) assert p.r == "provided" assert isinstance(p.o, str) assert p.o == "hmmm" assert p.defaults() == dict(o="hmmm") assert p.descriptions() == dict(r="required", o="optional") def test_params3(): @h.paramclass class HasTuple: t = h.Param(dtype=tuple, desc="Go ahead, try a list") ht = HasTuple(t=[1, 2, 3]) assert isinstance(ht.t, tuple) assert ht.t == (1, 2, 3) def test_params4(): from dataclasses import asdict @h.paramclass class Inner: i = h.Param(dtype=int, desc="Inner int-field") @h.paramclass class Outer: inner = h.Param(dtype=Inner, desc="Inner fields") f = h.Param(dtype=float, desc="A float", default=3.14159) o = Outer(inner=Inner(11)) assert isinstance(o, Outer) assert isinstance(o.inner, Inner) assert o.inner == Inner(11) assert o.inner.i == 11 assert o.f == 3.14159 d1 = {"inner": {"i": 11}, "f": 22.2} o1 = Outer(**d1) uname1 = h.params._unique_name(o1) d2 = asdict(o1) assert d1 == d2 o2 = Outer(**d2) uname2 = h.params._unique_name(o2) assert uname1 == uname2 assert uname1 == "Outer(3dcc309796996b3a8a61db66631c5a93)" def test_bad_params1(): from hdl21 import ( paramclass, Param, ValidationError, FrozenInstanceError, ) with pytest.raises(RuntimeError): @paramclass class C(TabError): ... @paramclass class C: a = Param(dtype=int, desc="Gonna Fail!") with pytest.raises(RuntimeError): class D(C): ... with pytest.raises(TypeError): c = C() with pytest.raises(ValidationError): c = C(a=TabError) with pytest.raises(FrozenInstanceError): c = C(a=3) c.a = 4 with pytest.raises(RuntimeError): class E(h.Module): ... with pytest.raises(RuntimeError): @h.module class E2(TabError): ... with pytest.raises(RuntimeError): @h.paramclass class P: descriptions = h.Param(dtype=str, desc="", default="BAD!") with pytest.raises(RuntimeError): @h.paramclass class P: defaults = h.Param(dtype=str, desc="", default="BAD!") with pytest.raises(RuntimeError): @h.paramclass class P: something = 11 with pytest.raises(RuntimeError): h.params._unique_name(33) def test_array1(): @h.module class InArray: inp = h.Input() out = h.Output() m = h.Module(name="HasArray") m.s1 = h.Signal(width=8) m.s2 = h.Signal(width=1) m.arr = h.InstArray(InArray, 8) m.arr.inp = m.s1 m.arr.out = m.s2 assert m.name == "HasArray" def test_array2(): a = h.Module(name="a") a.inp = h.Port(width=1) a.out = h.Port(width=1) @h.module class HasArray2: s1 = h.Signal(width=8) s2 = h.Signal(width=1) arr = h.InstArray(a, 8)(inp=s1, out=s2) assert len(HasArray2.instances) == 0 assert len(HasArray2.instarrays) == 1 h.elaborate(HasArray2) assert len(HasArray2.instances) == 8 assert len(HasArray2.instarrays) == 0 def test_cycle1(): @h.module class Thing: inp = h.Input() out = h.Output() @h.module class BackToBack: t1 = Thing() t2 = Thing(inp=t1.out, out=t1.inp) b = h.elaborate(BackToBack) assert isinstance(b.t1.inp, h.Signal) assert isinstance(b.t1.out, h.Signal) assert isinstance(b.t2.inp, h.Signal) assert isinstance(b.t2.out, h.Signal) b2 = h.Module(name="BackToBack2") b2.t1 = Thing() b2.t2 = Thing() b2.t2.inp = b2.t1.out b2.t2.out = b2.t1.inp assert isinstance(b2.t1.inp, h.PortRef) assert isinstance(b2.t1.out, h.PortRef) assert isinstance(b2.t2.inp, h.PortRef) assert isinstance(b2.t2.out, h.PortRef) b2 = h.elaborate(b2) assert len(b2.instances) == 2 assert len(b2.instarrays) == 0 assert len(b2.bundles) == 0 assert len(b2.ports) == 0 assert len(b2.signals) == 2 assert "t2_inp_t1_out" in b2.signals assert "t2_out_t1_inp" in b2.signals def test_gen3(): @h.paramclass class MyParams: w = h.Param(dtype=int, desc="Input bit-width. Required") @h.generator def MyThirdGenerator(params: MyParams) -> h.Module: @h.module class Inner: i = h.Input(width=params.w) o = h.Output(width=2 * params.w) @h.module class Outer: i = h.Signal(width=params.w) o = h.Signal(width=2 * params.w) inner = Inner(i=i, o=o) Outer.inp = h.Input(width=params.w) return Outer h.elaborate(MyThirdGenerator(MyParams(1))) def test_prim1(): params = h.Mos.Params() pmos = h.Pmos(params) nmos = h.Nmos(params) @h.module class HasMos: p = pmos() n = nmos(g=p.g, d=p.d, s=p.s, b=p.b) h.elaborate(HasMos) def test_prim2(): @h.module class HasPrims: p = h.Signal() n = h.Signal() _rp = h.R.Params(r=50) r = h.Resistor(_rp)(p=p, n=n) c = h.Capacitor(h.C.Params(c=1e-12))(p=p, n=n) l = h.Inductor(h.L.Params(l=1e-15))(p=p, n=n) d = h.Diode(h.D.Params())(p=p, n=n) s = h.Short(h.Short.Params())(p=p, n=n) h.elaborate(HasPrims) def test_prim_proto1(): @h.module class HasPrims: p = h.Signal() n = h.Signal() _rp = h.R.Params(r=50) r = h.Resistor(_rp)(p=p, n=n) _cp = h.C.Params(c=1e-12) c = h.Capacitor(_cp)(p=p, n=n) _lp = h.L.Params(l=1e-15) l = h.Inductor(_lp)(p=p, n=n) _dp = h.D.Params() d = h.Diode(_dp)(p=p, n=n) _sp = h.Short.Params() s = h.Short(_sp)(p=p, n=n) ppkg = h.to_proto(HasPrims) assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 1 assert ppkg.domain == "" pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.HasPrims" assert len(pm.ports) == 0 assert len(pm.signals) == 2 assert len(pm.instances) == 5 assert len(pm.default_parameters) == 0 for inst in pm.instances: assert isinstance(inst, h.proto.Instance) assert inst.module.WhichOneof("to") == "external" assert inst.module.external.domain in ["hdl21.ideal", "hdl21.primitives"] ns = h.from_proto(ppkg) assert isinstance(ns, SimpleNamespace) ns = ns.hdl21.tests.test_hdl21 assert isinstance(ns, SimpleNamespace) assert hasattr(ns, "HasPrims") HasPrims = ns.HasPrims assert isinstance(HasPrims, h.Module) assert len(HasPrims.ports) == 0 assert len(HasPrims.signals) == 2 assert len(HasPrims.instances) == 5 for inst in HasPrims.instances.values(): assert isinstance(inst._resolved, h.primitives.PrimitiveCall) def test_bundle1(): i1 = h.Bundle(name="MyFirstBundle") i1.s1 = h.Signal() i1.s2 = h.Signal() assert isinstance(i1, h.Bundle) assert isinstance(i1.s1, h.Signal) assert isinstance(i1.s2, h.Signal) ii1 = i1() assert isinstance(ii1, h.BundleInstance) assert ii1.role is None assert ii1.port == False def test_bundle2(): MySecondBundle = h.Bundle(name="MySecondBundle") MySecondBundle.s = h.Signal() m1 = h.Module(name="M1") m1.i = MySecondBundle(port=True) m2 = h.Module(name="M2") m2.i = MySecondBundle(port=True) m3 = h.Module(name="M3") m3.i1 = m1() m3.i2 = m2(i=m3.i1.i) assert "i2_i_i1_i" not in m3.namespace from hdl21.elab import ElabPass m3 = h.elaborate(m3, passes=[ElabPass.IMPLICIT_BUNDLES]) assert isinstance(m3, h.Module) assert isinstance(m3.i1, h.Instance) assert isinstance(m3.i2, h.Instance) assert "i2_i_i1_i" in m3.namespace m3 = h.elaborate(m3) assert "i2_i_i1_i" not in m3.namespace assert "i2_i_i1_i_s" in m3.namespace assert isinstance(m3.get("i2_i_i1_i_s"), h.Signal) assert m3.get("i2_i_i1_i_s") in m3.i1.conns.values() def test_bundle3(): @h.bundle class Diff: p = h.Signal() n = h.Signal() @h.bundle class DisplayPort: main_link = Diff() aux = h.Signal() assert isinstance(DisplayPort, h.Bundle) assert isinstance(DisplayPort(), h.BundleInstance) assert isinstance(DisplayPort.main_link, h.BundleInstance) assert isinstance(DisplayPort.main_link.p, h.PortRef) assert isinstance(DisplayPort.main_link.n, h.PortRef) assert isinstance(DisplayPort.aux, h.Signal) assert isinstance(Diff, h.Bundle) assert isinstance(Diff(), h.BundleInstance) assert isinstance(Diff.p, h.Signal) assert isinstance(Diff.n, h.Signal) m = h.Module(name="M") m.dp = DisplayPort() assert isinstance(m.dp, h.BundleInstance) assert len(m.bundles) == 1 assert len(m.signals) == 0 h.elaborate(m) assert not hasattr(m, "dp") assert len(m.bundles) == 0 assert len(m.signals) == 3 assert isinstance(m.get("dp_aux"), h.Signal) assert isinstance(m.get("dp_main_link_p"), h.Signal) assert isinstance(m.get("dp_main_link_n"), h.Signal) def test_bundle4(): @h.bundle class Diff: p = h.Signal() n = h.Signal() @h.bundle class HasRoles: class Roles(Enum): HOST = auto() DEVICE = auto() tx = h.Signal(src=Roles.HOST, dest=Roles.DEVICE) rx = h.Signal(src=Roles.DEVICE, dest=Roles.HOST) txd = Diff(src=Roles.HOST, dest=Roles.DEVICE) rxd = Diff(src=Roles.DEVICE, dest=Roles.HOST) hr = HasRoles() assert isinstance(HasRoles, h.Bundle) assert isinstance(HasRoles.roles, EnumMeta) assert isinstance(HasRoles.Roles, EnumMeta) assert isinstance(hr, h.BundleInstance) assert isinstance(HasRoles.tx, h.Signal) assert isinstance(HasRoles.rx, h.Signal) assert isinstance(HasRoles.txd, h.BundleInstance) assert isinstance(HasRoles.rxd, h.BundleInstance) @h.module class Host: hr = HasRoles(port=True, role=HasRoles.Roles.HOST) @h.module class Device: hr = HasRoles(port=True, role=HasRoles.Roles.DEVICE) @h.module class System: host = Host() devc = Device(hr=host.hr) assert isinstance(System, h.Module) assert isinstance(System.host, h.Instance) assert isinstance(System.devc, h.Instance) assert "devc_hr_host_hr" not in System.namespace from hdl21.elab import ElabPass sys = h.elaborate(System, passes=[ElabPass.IMPLICIT_BUNDLES]) assert "devc_hr_host_hr" in sys.namespace sys = h.elaborate(sys) assert "devc_hr_host_hr" not in sys.namespace assert "devc_hr_host_hr_tx" in sys.namespace assert "devc_hr_host_hr_rx" in sys.namespace assert "devc_hr_host_hr_txd_p" in sys.namespace assert "devc_hr_host_hr_txd_n" in sys.namespace assert "devc_hr_host_hr_rxd_p" in sys.namespace assert "devc_hr_host_hr_rxd_n" in sys.namespace def test_proto1(): m = h.Module(name="TestProto1") ppkg = h.to_proto(m) assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 1 assert ppkg.domain == "" pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.TestProto1" assert len(pm.ports) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 def test_proto2(): Child1 = h.Module(name="Child1") Child1.inp = h.Input(width=8) Child1.out = h.Output() Child2 = h.Module(name="Child2") Child2.inp = h.Input() Child2.out = h.Output(width=8) TestProto2 = h.Module(name="TestProto2") TestProto2.c1 = Child1() TestProto2.c2 = Child2() TestProto2.c2(inp=TestProto2.c1.out, out=TestProto2.c1.inp) ppkg = h.to_proto(TestProto2) assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 3 assert ppkg.domain == "" pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.Child1" assert len(pm.ports) == 2 assert len(pm.signals) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 pm = ppkg.modules[1] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.Child2" assert len(pm.ports) == 2 assert len(pm.signals) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 pm = ppkg.modules[2] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.TestProto2" assert len(pm.ports) == 0 assert len(pm.instances) == 2 assert len(pm.default_parameters) == 0 def test_proto3(): M1 = h.Module(name="M1") M1.p8 = h.Inout(width=8) M1.p1 = h.Inout(width=1) M2 = h.Module(name="M2") M2.s = h.Signal(width=4) M2.i = M1() M2.i(p1=M2.s[0]) M2.i(p8=h.Concat(M2.s, h.Concat(M2.s[0], M2.s[1]), M2.s[2:4])) ppkg = h.to_proto(M2, domain="test_proto3") assert isinstance(ppkg, h.proto.Package) assert len(ppkg.modules) == 2 assert ppkg.domain == "test_proto3" pm = ppkg.modules[0] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.M1" assert len(pm.ports) == 2 assert len(pm.signals) == 0 assert len(pm.instances) == 0 assert len(pm.default_parameters) == 0 pm = ppkg.modules[1] assert isinstance(pm, h.proto.Module) assert pm.name == "hdl21.tests.test_hdl21.M2" assert len(pm.ports) == 0 assert len(pm.signals) == 1 assert len(pm.instances) == 1 assert len(pm.default_parameters) == 0 ns = h.from_proto(ppkg) assert isinstance(ns, SimpleNamespace) ns = ns.hdl21.tests.test_hdl21 assert isinstance(ns, SimpleNamespace) assert isinstance(ns.M1, h.Module) assert len(ns.M1.ports) == 2 assert len(ns.M1.signals) == 0 assert len(ns.M1.instances) == 0 assert isinstance(M2, h.Module) assert len(M2.ports) == 0 assert len(M2.signals) == 1 assert len(M2.instances) == 1 assert "s" in M2.signals assert "i" in M2.instances inst = M2.i assert isinstance(inst.conns["p1"], h.signal.Slice) assert inst.conns["p1"].signal is M2.s assert inst.conns["p1"].top == 1 assert inst.conns["p1"].bot == 0 assert inst.conns["p1"].width == 1 assert isinstance(inst.conns["p8"], h.signal.Concat) assert len(inst.conns["p8"].parts) == 4 assert inst.conns["p8"].parts[0] is M2.s assert isinstance(inst.conns["p8"].parts[0], h.signal.Signal) assert isinstance(inst.conns["p8"].parts[1], h.signal.Slice) assert isinstance(inst.conns["p8"].parts[2], h.signal.Slice) assert isinstance(inst.conns["p8"].parts[3], h.signal.Slice) def test_proto_roundtrip(): M1 = h.Module(name="M1") ppkg = h.to_proto(M1) ns = h.from_proto(ppkg) assert isinstance(ns, SimpleNamespace) ns = ns.hdl21.tests.test_hdl21 assert isinstance(ns, SimpleNamespace) assert isinstance(ns.M1, h.Module) assert len(ns.M1.signals) == 0 assert len(ns.M1.ports) == 0 assert len(ns.M1.instances) == 0 def test_proto_roundtrip2(): M1 = h.Module(name="M1") M1.i = h.Input() M1.o = h.Output() M1.p = h.Port() M2 = h.Module(name="M2") M2.i = h.Input() M2.o = h.Output() M2.p = h.Port() M2.s = h.Signal() M2.i0 = M1() M2.i1 = M1() M2.i2 = M1() M2.i0(i=M2.i, o=M2.i1.i, p=M2.p) M2.i1(i=M2.i0.o, o=M2.s, p=M2.p) M2.i2(i=M2.s, o=M2.o, p=M2.p) ppkg = h.to_proto(M2) ns = h.from_proto(ppkg) assert isinstance(ns, SimpleNamespace) M1 = ns.hdl21.tests.test_hdl21.M1 M2 = ns.hdl21.tests.test_hdl21.M2 assert isinstance(M1, h.Module) assert isinstance(M2, h.Module) assert len(M1.signals) == 0 assert len(M1.ports) == 3 assert "i" in M1.ports assert M1.i.direction == h.signal.PortDir.INPUT assert M1.i.vis == h.signal.Visibility.PORT assert "o" in M1.ports assert M1.o.direction == h.signal.PortDir.OUTPUT assert M1.o.vis == h.signal.Visibility.PORT assert "p" in M1.ports assert M1.p.direction == h.signal.PortDir.NONE assert M1.p.vis == h.signal.Visibility.PORT assert len(M1.instances) == 0 assert len(M2.instances) == 3 for i in M2.instances.values(): assert i.of is M1 assert i.conns["p"] is M2.p assert len(M2.ports) == 3 assert len(M2.signals) == 2 assert "s" in M2.signals assert "i1_i_i0_o" in M2.signals def test_bigger_bundles(): class HostDevice(Enum): HOST = auto() DEVICE = auto() @h.bundle class Jtag: roles = HostDevice tck, tdi, tms = h.Signals(3, src=roles.HOST, dest=roles.DEVICE) tdo = h.Signal(src=roles.DEVICE, dest=roles.HOST) @h.bundle class Uart: class Roles(Enum): ME = auto() YOU = auto() tx = h.Signal(src=Roles.ME, dest=Roles.YOU) rx = h.Signal(src=Roles.YOU, dest=Roles.ME) @h.bundle class Spi: roles = HostDevice sck, cs = h.Signals(2, src=roles.HOST, dest=roles.DEVICE) dq = h.Signal(src=roles.DEVICE, dest=roles.HOST, width=4) @h.module class Chip: spi = Spi(role=HostDevice.HOST, port=True) jtag = Jtag(role=HostDevice.DEVICE, port=True) uart = Uart(role=Uart.Roles.ME, port=True) ... @h.module class SpiFlash: spi = Spi(role=HostDevice.DEVICE, port=True) @h.module class Board: jtag = Jtag(role=HostDevice.DEVICE, port=True) uart = Uart(role=Uart.Roles.ME, port=True) chip = Chip(jtag=jtag, uart=uart) flash = SpiFlash(spi=chip.spi) @h.module class Tester: jtag = Jtag(role=HostDevice.HOST, port=True) uart = Uart(role=Uart.Roles.ME, port=True) @h.module class TestSystem: jtag = Jtag() tester = Tester(jtag=jtag) board = Board(jtag=jtag) u0, u1 = h.Signals(2) board.uart = h.AnonymousBundle(tx=u0, rx=u1) tester.uart = h.AnonymousBundle(rx=u0, tx=u1) assert isinstance(TestSystem.jtag, h.BundleInstance) assert isinstance(TestSystem.tester, h.Instance) assert isinstance(TestSystem.board, h.Instance) assert isinstance(TestSystem.tester.uart, h.PortRef) assert isinstance(TestSystem.tester.uart.tx, h.PortRef) assert isinstance(TestSystem.tester.uart.rx, h.PortRef) assert isinstance(TestSystem.board.uart, h.PortRef) assert isinstance(TestSystem.board.uart.tx, h.PortRef) assert isinstance(TestSystem.board.uart.rx, h.PortRef) h.elaborate(TestSystem) assert isinstance(TestSystem.tester, h.Instance) assert isinstance(TestSystem.board, h.Instance) assert TestSystem.tester.of is Tester assert TestSystem.board.of is Board assert not hasattr(TestSystem, "jtag") assert not hasattr(TestSystem, "uart") assert "u0" in TestSystem.namespace assert "u1" in TestSystem.namespace assert len(TestSystem.ports) == 0 assert len(TestSystem.signals) == 6 assert len(TestSystem.instances) == 2 assert isinstance(TestSystem.get("u0"), h.Signal) assert isinstance(TestSystem.get("u1"), h.Signal) assert isinstance(TestSystem.get("jtag_tck"), h.Signal) assert isinstance(TestSystem.get("jtag_tdi"), h.Signal) assert isinstance(TestSystem.get("jtag_tdo"), h.Signal) assert isinstance(TestSystem.get("jtag_tms"), h.Signal) assert len(Tester.ports) == 6 assert len(Tester.signals) == 0 assert len(Tester.instances) == 0 assert isinstance(Tester.get("jtag_tck"), h.Signal) assert Tester.get("jtag_tck").vis == h.signal.Visibility.PORT assert Tester.get("jtag_tdo").vis == h.signal.Visibility.PORT assert Tester.get("jtag_tdi").vis == h.signal.Visibility.PORT assert Tester.get("jtag_tms").vis == h.signal.Visibility.PORT assert Tester.get("uart_tx").vis == h.signal.Visibility.PORT assert Tester.get("uart_rx").vis == h.signal.Visibility.PORT assert len(Board.ports) == 6 assert len(Board.signals) == 3 assert len(Board.instances) == 2 assert Board.chip.of is Chip assert Board.flash.of is SpiFlash assert Board.get("jtag_tck").vis == h.signal.Visibility.PORT assert Board.get("jtag_tdo").vis == h.signal.Visibility.PORT assert Board.get("jtag_tdi").vis == h.signal.Visibility.PORT assert Board.get("jtag_tms").vis == h.signal.Visibility.PORT assert Board.get("uart_tx").vis == h.signal.Visibility.PORT assert Board.get("uart_rx").vis == h.signal.Visibility.PORT assert Board.get("flash_spi_chip_spi_sck").vis == h.signal.Visibility.INTERNAL assert Board.get("flash_spi_chip_spi_cs").vis == h.signal.Visibility.INTERNAL assert Board.get("flash_spi_chip_spi_dq").vis == h.signal.Visibility.INTERNAL assert len(Chip.ports) == 9 assert len(Chip.signals) == 0 assert len(Chip.instances) == 0 assert Chip.get("jtag_tck").vis == h.signal.Visibility.PORT assert Chip.get("jtag_tdo").vis == h.signal.Visibility.PORT assert Chip.get("jtag_tdi").vis == h.signal.Visibility.PORT assert Chip.get("jtag_tms").vis == h.signal.Visibility.PORT assert Chip.get("spi_sck").vis == h.signal.Visibility.PORT assert Chip.get("spi_cs").vis == h.signal.Visibility.PORT assert Chip.get("spi_dq").vis == h.signal.Visibility.PORT assert Chip.get("uart_tx").vis == h.signal.Visibility.PORT assert Chip.get("uart_rx").vis == h.signal.Visibility.PORT assert len(SpiFlash.ports) == 3 assert len(SpiFlash.signals) == 0 assert len(SpiFlash.instances) == 0 assert SpiFlash.get("spi_sck").vis == h.signal.Visibility.PORT assert SpiFlash.get("spi_cs").vis == h.signal.Visibility.PORT assert SpiFlash.get("spi_dq").vis == h.signal.Visibility.PORT def test_signal_slice1(): sig = h.Signal(width=10) sl = sig[0] assert isinstance(sl, h.signal.Slice) assert sl.top == 1 assert sl.bot == 0 assert sl.width == 1 assert sl.step is None assert sl.signal is sig sl = sig[0:5] assert isinstance(sl, h.signal.Slice) assert sl.top == 5 assert sl.bot == 0 assert sl.width == 5 assert sl.step is None assert sl.signal is sig sl = sig[:] assert isinstance(sl, h.signal.Slice) assert sl.top == 10 assert sl.bot == 0 assert sl.width == 10 assert sl.step is None assert sl.signal is sig def test_signal_slice2(): sl = h.Signal(width=11)[-1] assert sl.top == 11 assert sl.bot == 10 assert sl.step is None assert sl.width == 1 sl = h.Signal(width=11)[:-1] assert sl.top == 10 assert sl.bot == 0 assert sl.step is None assert sl.width == 10 sl = h.Signal(width=11)[-2:] assert sl.top == 11 assert sl.bot == 9 assert sl.step is None assert sl.width == 2 def test_bad_slice1(): with pytest.raises(TypeError): h.Signal(width=11)[None] with pytest.raises(ValueError): h.Signal(width=11)[11] h.Signal(width=11)[2:1:-1] with pytest.raises(ValueError): h.Signal(width=11)[2:1:1] h.Signal(width=11)[1:9] with pytest.raises(ValueError): h.Signal(width=11)[9:1] def test_signal_concat1(): c = h.Concat(h.Signal(width=1), h.Signal(width=2), h.Signal(width=3)) assert isinstance(c, h.signal.Concat) assert len(c.parts) == 3 for p in c.parts: assert isinstance(p, h.signal.Signal) assert c.width == 6 c = h.Concat(h.Signal(width=1)[0], h.Signal(width=2)[0], h.Signal(width=3)[0]) assert isinstance(c, h.signal.Concat) assert len(c.parts) == 3 for p in c.parts: assert isinstance(p, h.signal.Slice) assert c.width == 3 c = h.Concat( h.Concat(h.Signal(), h.Signal()), h.Signal(width=2), h.Signal(width=2)[:] ) assert isinstance(c, h.signal.Concat) assert len(c.parts) == 3 assert c.width == 6 def test_slice_module1(): C = h.Module(name="C") C.p1 = h.Port(width=1) C.p4 = h.Port(width=4) C.p7 = h.Port(width=7) P = h.Module(name="P") C.s4 = h.Signal(width=4) C.s2 = h.Signal(width=2) P.ic = C(p1=C.s4[0], p4=C.s4, p7=h.Concat(C.s4, C.s2, C.s2[0])) h.elaborate(P) def test_bad_proto_naming(): with pytest.raises(RuntimeError): Ma1 = h.Module(name="Ma") Ma2 = h.Module(name="Ma") @h.module class MaParent: ma1 = Ma1() ma2 = Ma2() h.to_proto(MaParent) with pytest.raises(RuntimeError): def m1(): return h.Module(name="Ma") def m2(): return h.Module(name="Ma") @h.module class MaParent: ma1 = m1()() ma2 = m2()() h.to_proto(MaParent) def test_generator_recall(): @h.generator def CallMeTwice(_: h.HasNoParams) -> h.Module: return h.Module() @h.module class Caller: m1 = CallMeTwice(h.NoParams)() m2 = CallMeTwice(h.NoParams)() ppkg = h.to_proto(Caller) assert len(ppkg.modules) == 2 assert ppkg.modules[0].name == "hdl21.tests.test_hdl21.CallMeTwice(NoParams())" assert ppkg.modules[1].name == "hdl21.tests.test_hdl21.Caller" nl = StringIO() h.netlist(ppkg, nl) nl = nl.getvalue() assert "CallMeTwice_NoParams" in nl assert "Caller" in nl rt = h.from_proto(ppkg) ns = rt.hdl21.tests.test_hdl21 assert isinstance(ns.Caller, h.Module) assert isinstance(getattr(ns, "CallMeTwice(NoParams())"), h.Module) def test_module_as_param(): @h.paramclass class HasModuleParam: m = h.Param(dtype=h.Module, desc="A `Module` provided as a parameter") @h.generator def UsesModuleParam(params: HasModuleParam) -> h.Module: return params.m Empty = h.Module(name="Empty") p = HasModuleParam(m=Empty) m = UsesModuleParam(p) m = h.elaborate(m) assert m == Empty def test_mos_generator(): Mos = h.generators.Mos m = Mos(Mos.Params(nser=2)) assert isinstance(m, h.GeneratorCall) assert isinstance(m.arg, Mos.Params) m = h.elaborate(m) assert isinstance(m, h.Module) assert len(m.ports) == 4 assert m.ports == h.primitives.Mos.ports assert len(m.instances) == 2 assert "unit0" in m.instances assert "unit1" in m.instances assert isinstance(m.instances["unit0"].of, h.PrimitiveCall) assert isinstance(m.instances["unit1"].of, h.PrimitiveCall) assert m.instances["unit0"].of.params == h.primitives.MosParams() assert m.instances["unit1"].of.params == h.primitives.MosParams() assert len(m.signals) == 1 assert "unit1_s_unit0_d" in m.signals ppkg = h.to_proto(m) assert isinstance(ppkg, h.proto.Package) def test_series_parallel_generator(): from hdl21.generators import SeriesPar @h.module class M: a, b, c, d, e, f, g = h.Ports(7) params = SeriesPar.Params(unit=M, npar=2, nser=2, series_conns=["a", "b"]) m = SeriesPar(params) assert isinstance(m, h.GeneratorCall) assert isinstance(m.arg, SeriesPar.Params) m = h.elaborate(m) assert isinstance(m, h.Module) assert len(m.ports) == 7 assert m.ports == M.ports assert len(m.instances) == 4 assert "unit_0_0" in m.instances assert "unit_0_1" in m.instances assert "unit_1_0" in m.instances assert "unit_1_1" in m.instances for inst in m.instances.values(): assert inst.of is M assert len(m.signals) == 2 assert "unit_0_1_a_unit_0_0_b" in m.signals assert "unit_1_1_a_unit_1_0_b" in m.signals ppkg = h.to_proto(m) assert isinstance(ppkg, h.proto.Package) def test_instance_mult(): Child = h.Module(name="Child") Parent = h.Module(name="Parent") Parent.child = Child() * 5 assert isinstance(Parent.child, h.InstArray) assert Parent.child.n == 5 assert Parent.child.of is Child h.elaborate(Parent) assert len(Parent.instances) == 5 assert len(Parent.instarrays) == 0 for inst in Parent.instances.values(): assert inst.of is Child Parent = h.Module(name="Parent") Parent.child = 11 * Child() assert isinstance(Parent.child, h.InstArray) assert Parent.child.n == 11 assert Parent.child.of is Child h.elaborate(Parent) assert len(Parent.instances) == 11 assert len(Parent.instarrays) == 0 for inst in Parent.instances.values(): assert inst.of is Child def test_instance_mult2(): @h.module class Child: p = h.Port() @h.module class Parent: a = h.Signal(width=3) child = (Child() * 3)(p=a) assert len(Parent.instances) == 0 assert len(Parent.instarrays) == 1 h.elaborate(Parent) assert len(Parent.instances) == 3 assert len(Parent.instarrays) == 0 assert Parent.get("child_0").of is Child assert Parent.get("child_1").of is Child assert Parent.get("child_2").of is Child assert Parent.get("child_0").conns["p"] == Parent.a[0] assert Parent.get("child_1").conns["p"] == Parent.a[1] assert Parent.get("child_2").conns["p"] == Parent.a[2] def test_instance_mult3(): @h.module class Child: p = h.Port() @h.module class Parent: a = h.Signal(width=3) child = 3 * Child(p=a) h.elaborate(Parent) assert len(Parent.instances) == 3 assert len(Parent.instarrays) == 0 assert Parent.get("child_0").of is Child assert Parent.get("child_1").of is Child assert Parent.get("child_2").of is Child assert Parent.get("child_0").conns["p"] == Parent.a[0] assert Parent.get("child_1").conns["p"] == Parent.a[1] assert Parent.get("child_2").conns["p"] == Parent.a[2] def test_instance_mult4(): @h.module class Child: a = h.Port(width=11) b = h.Port(width=16) @h.module class Parent: a = h.Signal(width=11) b = h.Signal(width=48) child = 3 * Child(a=a, b=b) h.elaborate(Parent) assert len(Parent.instances) == 3 assert len(Parent.instarrays) == 0 assert Parent.get("child_0").of is Child assert Parent.get("child_1").of is Child assert Parent.get("child_2").of is Child assert Parent.get("child_0").conns["a"] == Parent.a assert Parent.get("child_1").conns["a"] == Parent.a assert Parent.get("child_2").conns["a"] == Parent.a assert Parent.get("child_0").conns["b"] == Parent.b[0:16] assert Parent.get("child_1").conns["b"] == Parent.b[16:32] assert Parent.get("child_2").conns["b"] == Parent.b[32:48] def test_netlist_fmts(): @h.module class Bot: s = h.Input(width=3) p = h.Output() @h.module class Top: s = h.Signal(width=3) p = h.Output() b = Bot(s=s, p=p) ppkg = h.to_proto(Top) assert len(ppkg.modules) == 2 assert ppkg.modules[0].name == "hdl21.tests.test_hdl21.Bot" assert ppkg.modules[1].name == "hdl21.tests.test_hdl21.Top" nl = StringIO() h.netlist(ppkg, nl, "spectre") nl = nl.getvalue() assert "subckt Bot" in nl assert "+ s_2 s_1 s_0 p" in nl assert "subckt Top" in nl assert "b\n" in nl assert "+ ( s_2 s_1 s_0 p )" in nl assert "+ p" in nl assert "+ Bot " in nl nl = StringIO() h.netlist(ppkg, nl, "verilog") nl = nl.getvalue() assert "module Bot" in nl assert "input wire [2:0] s," in nl assert "output wire p" in nl assert "endmodule // Bot" in nl assert "module Top" in nl assert ".s(s)" in nl assert ".p(p)" in nl assert "endmodule // Top" in nl nl = StringIO() h.netlist(ppkg, nl, "spice") nl = nl.getvalue() assert ".SUBCKT Bot \n+ s_2 s_1 s_0 p" in nl assert ".SUBCKT Top \n+ p" in nl assert "xb \n+ s_2 s_1 s_0 p \n+ Bot" in nl def test_spice_netlister(): @h.module class DUT: a = h.Input(width=5) b = h.Output(width=5) res = h.IdealResistor(h.ResistorParams(r=10e3))(p=a[0], n=b[0]) cap = h.IdealCapacitor(h.IdealCapacitorParams(c=10e-12))(p=a[1], n=b[1]) ind = h.IdealInductor(h.IdealInductorParams(l=10e-9))(p=a[2], n=b[2]) ppkg = h.to_proto(DUT) nl = StringIO() h.netlist(ppkg, nl, "spice") good = dedent( """\ .SUBCKT DUT + a_4 a_3 a_2 a_1 a_0 b_4 b_3 b_2 b_1 b_0 + * No parameters rres + a_0 b_0 + r=10000.0 ccap + a_1 b_1 + c=1e-11 lind + a_2 b_2 + l=1e-08 .ENDS """ ) assert good in nl.getvalue() def test_bad_width_conn(): c = h.Module(name="c") c.p = h.Port(width=3) q = h.Module(name="q") q.s = h.Signal(width=5) q.c = c(p=q.s) with pytest.raises(RuntimeError): h.elaborate(q) def test_bad_bundle_conn(): @h.bundle class P: p = h.Signal(width=3) @h.bundle class R: z = h.Signal(width=11) @h.module class C: p = P(port=True) @h.module class Q: r = R() c = C(p=r) with pytest.raises(RuntimeError): h.elaborate(Q) def test_illegal_module_attrs(): m = h.Module() with pytest.raises(TypeError): m.a = list() with pytest.raises(TypeError): @h.module class M: a = list() @h.module class C: ... with pytest.raises(TypeError): C.b = TabError m = h.Module(name="m") with pytest.raises(TypeError): m.p = 5 with pytest.raises(TypeError): m.z = dict(a=h.Signal()) with pytest.raises(TypeError): m.q = [h.Port()] with pytest.raises(TypeError): m.p = (h.Input(), h.Output()) def test_copy_signal(): copy.copy(h.Signal()) def test_copy_bundle_instance(): copy.copy(h.BundleInstance(name="inst", of=h.Bundle())) def test_bundle_destructure(): @h.bundle class B: w1 = h.Signal(width=1) w3 = h.Signal(width=3) @h.module class Child: w1 = h.Port(width=1) w3 = h.Port(width=3) @h.module class Parent: b = B() c = Child(w1=b.w1, w3=b.w3) h.elaborate(Parent) assert len(Parent.instances) == 1 assert len(Parent.signals) == 2 assert "b_w1" in Parent.signals assert "b_w3" in Parent.signals assert Parent.c.conns["w1"] is Parent.signals["b_w1"] assert Parent.c.conns["w3"] is Parent.signals["b_w3"] def test_orphanage(): m1 = h.Module(name="m1") m1.s = h.Signal() m2 = h.Module(name="m2") m2.y = m1.s h.elaborate(m2) with pytest.raises(RuntimeError): h.elaborate(m1) def test_orphanage2(): @h.bundle class B: bb = h.Signal(width=1) b = B() m1 = h.Module(name="m1") m1.b = b m2 = h.Module(name="m2") m2.b = b h.elaborate(m2) with pytest.raises(RuntimeError): h.elaborate(m1) def test_orphanage3(): I = h.Module(name="I") i = I() m1 = h.Module(name="m1") m1.i = i m2 = h.Module(name="m2") m2.i = i h.elaborate(m2) with pytest.raises(RuntimeError): h.elaborate(m1) @pytest.mark.xfail(reason="#6") def test_wrong_decorator(): with pytest.raises(RuntimeError): @h.Module class M: ... def test_elab_noconn(): @h.module class Inner: p = h.Port() @h.module class HasNoConn: i1 = Inner() i1.p = h.NoConn() h.elaborate(HasNoConn) assert len(HasNoConn.signals) == 1 def test_bad_noconn(): @h.module class Inner: p = h.Port() @h.module class Bad: i1 = Inner() i2 = Inner() i1.p = h.NoConn() i2.p = i1.p with pytest.raises(RuntimeError): h.elaborate(Bad) def test_array_concat_conn(): Child = h.Module(name="Child") Child.p3 = h.Input(width=3) Child.p5 = h.Input(width=5) Parent = h.Module(name="Parent") Parent.s5 = h.Signal(width=5) Parent.s9 = h.Signal(width=9) Parent.c = 2 * Child() Parent.c.p3 = Parent.s5[0:3] Parent.c.p5 = h.Concat(Parent.s5[3], Parent.s9) h.netlist(h.to_proto(Parent), StringIO(), "verilog") def test_slice_resolution(): from hdl21.elab import _resolve_slice s = h.Signal(width=5) assert _resolve_slice(s[0]) == s[0] s1 = h.Signal(name="s1", width=5) s2 = h.Signal(name="s2", width=5) c = h.Concat(s1, s2) assert _resolve_slice(c[0]) == s1[0] assert _resolve_slice(c[1]) == s1[1] assert _resolve_slice(c[2]) == s1[2] assert _resolve_slice(c[3]) == s1[3] assert _resolve_slice(c[4]) == s1[4] assert _resolve_slice(c[5]) == s2[0] assert _resolve_slice(c[6]) == s2[1] assert _resolve_slice(c[7]) == s2[2] assert _resolve_slice(c[8]) == s2[3] assert _resolve_slice(c[9]) == s2[4] sa = h.Signal(name="sa", width=5) assert _resolve_slice(sa[2:5][0]) == sa[2] assert _resolve_slice(sa[2:5][1]) == sa[3] assert _resolve_slice(sa[2:5][2]) == sa[4] assert _resolve_slice(sa[:][0]) == sa[0] assert _resolve_slice(sa[:][1]) == sa[1] assert _resolve_slice(sa[:][2]) == sa[2] assert _resolve_slice(sa[:][3]) == sa[3] assert _resolve_slice(sa[:][4]) == sa[4] assert _resolve_slice(sa[:][0:4]).parts == (sa[0], sa[1], sa[2], sa[3]) @pytest.mark.xfail(reason="#1") def test_export_strides(): c = h.Module(name="c") c.p = h.Input(width=2) p = h.Module(name="p") p.s = h.Signal(width=20) p.c = c(p=p.s[::10]) h.netlist(h.to_proto(p), sys.stdout, "verilog")
true
true
1c39dd1ce758aca3ce61780686afa04337bd16b5
3,328
py
Python
SCRM/cloud_plugin/urls.py
prakashar11/secure-cloud-native-fabric
8a6c51d8744c33afb8edc1455caaccb011f7e1de
[ "Apache-2.0" ]
2
2019-07-30T05:53:36.000Z
2019-10-26T20:11:52.000Z
SCRM/cloud_plugin/urls.py
prakashar11/secure-cloud-native-fabric
8a6c51d8744c33afb8edc1455caaccb011f7e1de
[ "Apache-2.0" ]
6
2019-06-17T05:22:32.000Z
2021-06-10T21:36:22.000Z
SCRM/cloud_plugin/urls.py
prakashar11/secure-cloud-native-fabric
8a6c51d8744c33afb8edc1455caaccb011f7e1de
[ "Apache-2.0" ]
3
2019-10-26T21:20:02.000Z
2020-06-01T14:25:17.000Z
# # Copyright 2019 Altran. 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 rest_framework.urlpatterns import format_suffix_patterns from .views import RegionViewSet, SecurityGroupViewSet, VpcViewSet from django.conf.urls import url securitygroup_list = SecurityGroupViewSet.as_view({ 'get': 'list', 'post': 'create' }) securitygroup_detail = SecurityGroupViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) region_list = RegionViewSet.as_view({ 'get': 'list' }) region_detail = RegionViewSet.as_view({ 'get': 'retrieve' }) vpc_list = VpcViewSet.as_view({ 'get': 'list' }) vpc_detail = VpcViewSet.as_view({ 'get': 'retrieve' }) urlpatterns = format_suffix_patterns([ url(r'^securitygroup/$', securitygroup_list, name='securitygroup-list'), url(r'^securitygroup/(?P<pk>[A-Za-z0-9-]+)/$', securitygroup_detail, name='securitygroup-detail'), url(r'^region/$', region_list, name='region-list'), url(r'^region/(?P<pk>[A-Za-z0-9-]+)/$', region_detail, name='region-detail'), url(r'^vpc/$', vpc_list, name='vpc-list'), url(r'^vpc_detail/(?P<pk>[A-Za-z0-9-]+)/$', vpc_detail, name='vpc-detail') ]) ''' from django.conf.urls import url from .views import MonitoredObject, Policies,VpcList, CrispPostureGraph, CrispPostureMap, Auditor, RunAuditor, PolicyTemplate, PolicyInstances, Clouds from rest_framework.urlpatterns import format_suffix_patterns from . import views urlpatterns = [ url(r'^index/$', views.index, name='index'), url(r'^secgrp/$', views.secgrp, name='secgrp'), #url(r'^region/$', RegionList.as_view()), url(r'^vpc/$', VpcList.as_view()), #url(r'^vpc/region/(?P<pk>[A-Za-z0-9-]+)/$', OnlyVpcList.as_view()), #url(r'^vpc/(?P<pk>[A-Za-z0-9-]+)/$', VpcDetail.as_view()), #url(r'^securitygroup/$', SecurityGroupList.as_view()), #url(r'^securitygroup/(?P<pk>[A-Za-z0-9-]+)/$', SecurityGroupDetail.as_view()), #url(r'^securitygroup/(?P<pk>[A-Za-z0-9-]+)/ingress/$', SecurityGroupIngressDetail.as_view()), #url(r'^securitygroup/(?P<pk>[A-Za-z0-9-]+)/egress/$', SecurityGroupEgressDetail.as_view()), #url(r'^securitymonkey/$', SmIssueList.as_view()), #url(r'^alarms/$',Alarms.as_view()), url(r'^monitoredobject/$',MonitoredObject.as_view()), url(r'^policies/$',Policies.as_view()), url(r'^policypostures/$',CrispPostureGraph.as_view()), url(r'^policyposturemaps/$',CrispPostureMap.as_view()), url(r'^auditors/$',Auditor.as_view()), url(r'^runauditor/$',RunAuditor.as_view()), url(r'^policytemplates/$',PolicyTemplate.as_view()), url(r'^policyinstances/$',PolicyInstances.as_view()), url(r'^clouds/$',Clouds.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns)
36.977778
151
0.684495
from django.conf.urls import url from .views import MonitoredObject, Policies,VpcList, CrispPostureGraph, CrispPostureMap, Auditor, RunAuditor, PolicyTemplate, PolicyInstances, Clouds from rest_framework.urlpatterns import format_suffix_patterns from . import views urlpatterns = [ url(r'^index/$', views.index, name='index'), url(r'^secgrp/$', views.secgrp, name='secgrp'), url(r'^vpc/$', VpcList.as_view()), url(r'^monitoredobject/$',MonitoredObject.as_view()), url(r'^policies/$',Policies.as_view()), url(r'^policypostures/$',CrispPostureGraph.as_view()), url(r'^policyposturemaps/$',CrispPostureMap.as_view()), url(r'^auditors/$',Auditor.as_view()), url(r'^runauditor/$',RunAuditor.as_view()), url(r'^policytemplates/$',PolicyTemplate.as_view()), url(r'^policyinstances/$',PolicyInstances.as_view()), url(r'^clouds/$',Clouds.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns)
true
true
1c39dd2dd92e8e1ee3914fc886a249531e1665e8
11,894
py
Python
skimage/feature/tests/test_corner.py
atemysemicolon/scikit-image
a48cf5822f9539c6602b9327c18253aed14fa692
[ "BSD-3-Clause" ]
1
2016-01-26T06:14:58.000Z
2016-01-26T06:14:58.000Z
skimage/feature/tests/test_corner.py
atemysemicolon/scikit-image
a48cf5822f9539c6602b9327c18253aed14fa692
[ "BSD-3-Clause" ]
null
null
null
skimage/feature/tests/test_corner.py
atemysemicolon/scikit-image
a48cf5822f9539c6602b9327c18253aed14fa692
[ "BSD-3-Clause" ]
null
null
null
import numpy as np from numpy.testing import (assert_array_equal, assert_raises, assert_almost_equal) from skimage import data from skimage import img_as_float from skimage.color import rgb2gray from skimage.morphology import octagon from skimage.feature import (corner_moravec, corner_harris, corner_shi_tomasi, corner_subpix, peak_local_max, corner_peaks, corner_kitchen_rosenfeld, corner_foerstner, corner_fast, corner_orientations, structure_tensor, structure_tensor_eigvals, hessian_matrix, hessian_matrix_eigvals, hessian_matrix_det) def test_structure_tensor(): square = np.zeros((5, 5)) square[2, 2] = 1 Axx, Axy, Ayy = structure_tensor(square, sigma=0.1) assert_array_equal(Axx, np.array([[ 0, 0, 0, 0, 0], [ 0, 1, 0, 1, 0], [ 0, 4, 0, 4, 0], [ 0, 1, 0, 1, 0], [ 0, 0, 0, 0, 0]])) assert_array_equal(Axy, np.array([[ 0, 0, 0, 0, 0], [ 0, 1, 0, -1, 0], [ 0, 0, 0, -0, 0], [ 0, -1, -0, 1, 0], [ 0, 0, 0, 0, 0]])) assert_array_equal(Ayy, np.array([[ 0, 0, 0, 0, 0], [ 0, 1, 4, 1, 0], [ 0, 0, 0, 0, 0], [ 0, 1, 4, 1, 0], [ 0, 0, 0, 0, 0]])) def test_hessian_matrix(): square = np.zeros((5, 5)) square[2, 2] = 1 Hxx, Hxy, Hyy = hessian_matrix(square, sigma=0.1) assert_array_equal(Hxx, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) assert_array_equal(Hxy, np.array([[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]])) assert_array_equal(Hyy, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) def test_structure_tensor_eigvals(): square = np.zeros((5, 5)) square[2, 2] = 1 Axx, Axy, Ayy = structure_tensor(square, sigma=0.1) l1, l2 = structure_tensor_eigvals(Axx, Axy, Ayy) assert_array_equal(l1, np.array([[0, 0, 0, 0, 0], [0, 2, 4, 2, 0], [0, 4, 0, 4, 0], [0, 2, 4, 2, 0], [0, 0, 0, 0, 0]])) assert_array_equal(l2, np.array([[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]])) def test_hessian_matrix_eigvals(): square = np.zeros((5, 5)) square[2, 2] = 1 Hxx, Hxy, Hyy = hessian_matrix(square, sigma=0.1) l1, l2 = hessian_matrix_eigvals(Hxx, Hxy, Hyy) assert_array_equal(l1, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) assert_array_equal(l2, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) def test_hessian_matrix_det(): image = np.zeros((5, 5)) image[2, 2] = 1 det = hessian_matrix_det(image, 5) assert_almost_equal(det, 0, decimal = 3) def test_square_image(): im = np.zeros((50, 50)).astype(float) im[:25, :25] = 1. # Moravec results = peak_local_max(corner_moravec(im)) # interest points along edge assert len(results) == 57 # Harris results = peak_local_max(corner_harris(im, method='k')) # interest at corner assert len(results) == 1 results = peak_local_max(corner_harris(im, method='eps')) # interest at corner assert len(results) == 1 # Shi-Tomasi results = peak_local_max(corner_shi_tomasi(im)) # interest at corner assert len(results) == 1 def test_noisy_square_image(): im = np.zeros((50, 50)).astype(float) im[:25, :25] = 1. np.random.seed(seed=1234) im = im + np.random.uniform(size=im.shape) * .2 # Moravec results = peak_local_max(corner_moravec(im)) # undefined number of interest points assert results.any() # Harris results = peak_local_max(corner_harris(im, sigma=1.5, method='k')) assert len(results) == 1 results = peak_local_max(corner_harris(im, sigma=1.5, method='eps')) assert len(results) == 1 # Shi-Tomasi results = peak_local_max(corner_shi_tomasi(im, sigma=1.5)) assert len(results) == 1 def test_squared_dot(): im = np.zeros((50, 50)) im[4:8, 4:8] = 1 im = img_as_float(im) # Moravec fails # Harris results = peak_local_max(corner_harris(im)) assert (results == np.array([[6, 6]])).all() # Shi-Tomasi results = peak_local_max(corner_shi_tomasi(im)) assert (results == np.array([[6, 6]])).all() def test_rotated_lena(): """ The harris filter should yield the same results with an image and it's rotation. """ im = img_as_float(data.lena().mean(axis=2)) im_rotated = im.T # Moravec results = peak_local_max(corner_moravec(im)) results_rotated = peak_local_max(corner_moravec(im_rotated)) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() # Harris results = peak_local_max(corner_harris(im)) results_rotated = peak_local_max(corner_harris(im_rotated)) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() # Shi-Tomasi results = peak_local_max(corner_shi_tomasi(im)) results_rotated = peak_local_max(corner_shi_tomasi(im_rotated)) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() def test_subpix_edge(): img = np.zeros((50, 50)) img[:25, :25] = 255 img[25:, 25:] = 255 corner = peak_local_max(corner_harris(img), num_peaks=1) subpix = corner_subpix(img, corner) assert_array_equal(subpix[0], (24.5, 24.5)) def test_subpix_dot(): img = np.zeros((50, 50)) img[25, 25] = 255 corner = peak_local_max(corner_harris(img), num_peaks=1) subpix = corner_subpix(img, corner) assert_array_equal(subpix[0], (25, 25)) def test_subpix_no_class(): img = np.zeros((50, 50)) subpix = corner_subpix(img, np.array([[25, 25]])) assert_array_equal(subpix[0], (np.nan, np.nan)) img[25, 25] = 1e-10 corner = peak_local_max(corner_harris(img), num_peaks=1) subpix = corner_subpix(img, np.array([[25, 25]])) assert_array_equal(subpix[0], (np.nan, np.nan)) def test_subpix_border(): img = np.zeros((50, 50)) img[1:25,1:25] = 255 img[25:-1,25:-1] = 255 corner = corner_peaks(corner_harris(img), min_distance=1) subpix = corner_subpix(img, corner, window_size=11) ref = np.array([[ 0.52040816, 0.52040816], [ 0.52040816, 24.47959184], [24.47959184, 0.52040816], [24.5 , 24.5 ], [24.52040816, 48.47959184], [48.47959184, 24.52040816], [48.47959184, 48.47959184]]) assert_almost_equal(subpix, ref) def test_num_peaks(): """For a bunch of different values of num_peaks, check that peak_local_max returns exactly the right amount of peaks. Test is run on Lena in order to produce a sufficient number of corners""" lena_corners = corner_harris(rgb2gray(data.lena())) for i in range(20): n = np.random.random_integers(20) results = peak_local_max(lena_corners, num_peaks=n) assert (results.shape[0] == n) def test_corner_peaks(): response = np.zeros((5, 5)) response[2:4, 2:4] = 1 corners = corner_peaks(response, exclude_border=False) assert len(corners) == 1 corners = corner_peaks(response, exclude_border=False, min_distance=0) assert len(corners) == 4 corners = corner_peaks(response, exclude_border=False, min_distance=0, indices=False) assert np.sum(corners) == 4 def test_blank_image_nans(): """Some of the corner detectors had a weakness in terms of returning NaN when presented with regions of constant intensity. This should be fixed by now. We test whether each detector returns something finite in the case of constant input""" detectors = [corner_moravec, corner_harris, corner_shi_tomasi, corner_kitchen_rosenfeld, corner_foerstner] constant_image = np.zeros((20, 20)) for det in detectors: response = det(constant_image) assert np.all(np.isfinite(response)) def test_corner_fast_image_unsupported_error(): img = np.zeros((20, 20, 3)) assert_raises(ValueError, corner_fast, img) def test_corner_fast_lena(): img = rgb2gray(data.lena()) expected = np.array([[ 67, 157], [204, 261], [247, 146], [269, 111], [318, 158], [386, 73], [413, 70], [435, 180], [455, 177], [461, 160]]) actual = corner_peaks(corner_fast(img, 12, 0.3)) assert_array_equal(actual, expected) def test_corner_orientations_image_unsupported_error(): img = np.zeros((20, 20, 3)) assert_raises(ValueError, corner_orientations, img, np.asarray([[7, 7]]), np.ones((3, 3))) def test_corner_orientations_even_shape_error(): img = np.zeros((20, 20)) assert_raises(ValueError, corner_orientations, img, np.asarray([[7, 7]]), np.ones((4, 4))) def test_corner_orientations_lena(): img = rgb2gray(data.lena()) corners = corner_peaks(corner_fast(img, 11, 0.35)) expected = np.array([-1.9195897 , -3.03159624, -1.05991162, -2.89573739, -2.61607644, 2.98660159]) actual = corner_orientations(img, corners, octagon(3, 2)) assert_almost_equal(actual, expected) def test_corner_orientations_square(): square = np.zeros((12, 12)) square[3:9, 3:9] = 1 corners = corner_peaks(corner_fast(square, 9), min_distance=1) actual_orientations = corner_orientations(square, corners, octagon(3, 2)) actual_orientations_degrees = np.rad2deg(actual_orientations) expected_orientations_degree = np.array([ 45., 135., -45., -135.]) assert_array_equal(actual_orientations_degrees, expected_orientations_degree) if __name__ == '__main__': from numpy import testing testing.run_module_suite()
35.610778
78
0.523962
import numpy as np from numpy.testing import (assert_array_equal, assert_raises, assert_almost_equal) from skimage import data from skimage import img_as_float from skimage.color import rgb2gray from skimage.morphology import octagon from skimage.feature import (corner_moravec, corner_harris, corner_shi_tomasi, corner_subpix, peak_local_max, corner_peaks, corner_kitchen_rosenfeld, corner_foerstner, corner_fast, corner_orientations, structure_tensor, structure_tensor_eigvals, hessian_matrix, hessian_matrix_eigvals, hessian_matrix_det) def test_structure_tensor(): square = np.zeros((5, 5)) square[2, 2] = 1 Axx, Axy, Ayy = structure_tensor(square, sigma=0.1) assert_array_equal(Axx, np.array([[ 0, 0, 0, 0, 0], [ 0, 1, 0, 1, 0], [ 0, 4, 0, 4, 0], [ 0, 1, 0, 1, 0], [ 0, 0, 0, 0, 0]])) assert_array_equal(Axy, np.array([[ 0, 0, 0, 0, 0], [ 0, 1, 0, -1, 0], [ 0, 0, 0, -0, 0], [ 0, -1, -0, 1, 0], [ 0, 0, 0, 0, 0]])) assert_array_equal(Ayy, np.array([[ 0, 0, 0, 0, 0], [ 0, 1, 4, 1, 0], [ 0, 0, 0, 0, 0], [ 0, 1, 4, 1, 0], [ 0, 0, 0, 0, 0]])) def test_hessian_matrix(): square = np.zeros((5, 5)) square[2, 2] = 1 Hxx, Hxy, Hyy = hessian_matrix(square, sigma=0.1) assert_array_equal(Hxx, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) assert_array_equal(Hxy, np.array([[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]])) assert_array_equal(Hyy, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) def test_structure_tensor_eigvals(): square = np.zeros((5, 5)) square[2, 2] = 1 Axx, Axy, Ayy = structure_tensor(square, sigma=0.1) l1, l2 = structure_tensor_eigvals(Axx, Axy, Ayy) assert_array_equal(l1, np.array([[0, 0, 0, 0, 0], [0, 2, 4, 2, 0], [0, 4, 0, 4, 0], [0, 2, 4, 2, 0], [0, 0, 0, 0, 0]])) assert_array_equal(l2, np.array([[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]])) def test_hessian_matrix_eigvals(): square = np.zeros((5, 5)) square[2, 2] = 1 Hxx, Hxy, Hyy = hessian_matrix(square, sigma=0.1) l1, l2 = hessian_matrix_eigvals(Hxx, Hxy, Hyy) assert_array_equal(l1, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) assert_array_equal(l2, np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]])) def test_hessian_matrix_det(): image = np.zeros((5, 5)) image[2, 2] = 1 det = hessian_matrix_det(image, 5) assert_almost_equal(det, 0, decimal = 3) def test_square_image(): im = np.zeros((50, 50)).astype(float) im[:25, :25] = 1. results = peak_local_max(corner_moravec(im)) assert len(results) == 57 results = peak_local_max(corner_harris(im, method='k')) assert len(results) == 1 results = peak_local_max(corner_harris(im, method='eps')) assert len(results) == 1 results = peak_local_max(corner_shi_tomasi(im)) assert len(results) == 1 def test_noisy_square_image(): im = np.zeros((50, 50)).astype(float) im[:25, :25] = 1. np.random.seed(seed=1234) im = im + np.random.uniform(size=im.shape) * .2 results = peak_local_max(corner_moravec(im)) assert results.any() results = peak_local_max(corner_harris(im, sigma=1.5, method='k')) assert len(results) == 1 results = peak_local_max(corner_harris(im, sigma=1.5, method='eps')) assert len(results) == 1 results = peak_local_max(corner_shi_tomasi(im, sigma=1.5)) assert len(results) == 1 def test_squared_dot(): im = np.zeros((50, 50)) im[4:8, 4:8] = 1 im = img_as_float(im) results = peak_local_max(corner_harris(im)) assert (results == np.array([[6, 6]])).all() results = peak_local_max(corner_shi_tomasi(im)) assert (results == np.array([[6, 6]])).all() def test_rotated_lena(): im = img_as_float(data.lena().mean(axis=2)) im_rotated = im.T results = peak_local_max(corner_moravec(im)) results_rotated = peak_local_max(corner_moravec(im_rotated)) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() results = peak_local_max(corner_harris(im)) results_rotated = peak_local_max(corner_harris(im_rotated)) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() results = peak_local_max(corner_shi_tomasi(im)) results_rotated = peak_local_max(corner_shi_tomasi(im_rotated)) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() def test_subpix_edge(): img = np.zeros((50, 50)) img[:25, :25] = 255 img[25:, 25:] = 255 corner = peak_local_max(corner_harris(img), num_peaks=1) subpix = corner_subpix(img, corner) assert_array_equal(subpix[0], (24.5, 24.5)) def test_subpix_dot(): img = np.zeros((50, 50)) img[25, 25] = 255 corner = peak_local_max(corner_harris(img), num_peaks=1) subpix = corner_subpix(img, corner) assert_array_equal(subpix[0], (25, 25)) def test_subpix_no_class(): img = np.zeros((50, 50)) subpix = corner_subpix(img, np.array([[25, 25]])) assert_array_equal(subpix[0], (np.nan, np.nan)) img[25, 25] = 1e-10 corner = peak_local_max(corner_harris(img), num_peaks=1) subpix = corner_subpix(img, np.array([[25, 25]])) assert_array_equal(subpix[0], (np.nan, np.nan)) def test_subpix_border(): img = np.zeros((50, 50)) img[1:25,1:25] = 255 img[25:-1,25:-1] = 255 corner = corner_peaks(corner_harris(img), min_distance=1) subpix = corner_subpix(img, corner, window_size=11) ref = np.array([[ 0.52040816, 0.52040816], [ 0.52040816, 24.47959184], [24.47959184, 0.52040816], [24.5 , 24.5 ], [24.52040816, 48.47959184], [48.47959184, 24.52040816], [48.47959184, 48.47959184]]) assert_almost_equal(subpix, ref) def test_num_peaks(): lena_corners = corner_harris(rgb2gray(data.lena())) for i in range(20): n = np.random.random_integers(20) results = peak_local_max(lena_corners, num_peaks=n) assert (results.shape[0] == n) def test_corner_peaks(): response = np.zeros((5, 5)) response[2:4, 2:4] = 1 corners = corner_peaks(response, exclude_border=False) assert len(corners) == 1 corners = corner_peaks(response, exclude_border=False, min_distance=0) assert len(corners) == 4 corners = corner_peaks(response, exclude_border=False, min_distance=0, indices=False) assert np.sum(corners) == 4 def test_blank_image_nans(): detectors = [corner_moravec, corner_harris, corner_shi_tomasi, corner_kitchen_rosenfeld, corner_foerstner] constant_image = np.zeros((20, 20)) for det in detectors: response = det(constant_image) assert np.all(np.isfinite(response)) def test_corner_fast_image_unsupported_error(): img = np.zeros((20, 20, 3)) assert_raises(ValueError, corner_fast, img) def test_corner_fast_lena(): img = rgb2gray(data.lena()) expected = np.array([[ 67, 157], [204, 261], [247, 146], [269, 111], [318, 158], [386, 73], [413, 70], [435, 180], [455, 177], [461, 160]]) actual = corner_peaks(corner_fast(img, 12, 0.3)) assert_array_equal(actual, expected) def test_corner_orientations_image_unsupported_error(): img = np.zeros((20, 20, 3)) assert_raises(ValueError, corner_orientations, img, np.asarray([[7, 7]]), np.ones((3, 3))) def test_corner_orientations_even_shape_error(): img = np.zeros((20, 20)) assert_raises(ValueError, corner_orientations, img, np.asarray([[7, 7]]), np.ones((4, 4))) def test_corner_orientations_lena(): img = rgb2gray(data.lena()) corners = corner_peaks(corner_fast(img, 11, 0.35)) expected = np.array([-1.9195897 , -3.03159624, -1.05991162, -2.89573739, -2.61607644, 2.98660159]) actual = corner_orientations(img, corners, octagon(3, 2)) assert_almost_equal(actual, expected) def test_corner_orientations_square(): square = np.zeros((12, 12)) square[3:9, 3:9] = 1 corners = corner_peaks(corner_fast(square, 9), min_distance=1) actual_orientations = corner_orientations(square, corners, octagon(3, 2)) actual_orientations_degrees = np.rad2deg(actual_orientations) expected_orientations_degree = np.array([ 45., 135., -45., -135.]) assert_array_equal(actual_orientations_degrees, expected_orientations_degree) if __name__ == '__main__': from numpy import testing testing.run_module_suite()
true
true
1c39ddc0de426696ab88abf4bdf8f1734b66de8b
3,769
py
Python
setup.py
NickleDave/williams
bfc362e82dfa5785116e11142e90e7f6908255b0
[ "BSD-3-Clause" ]
null
null
null
setup.py
NickleDave/williams
bfc362e82dfa5785116e11142e90e7f6908255b0
[ "BSD-3-Clause" ]
null
null
null
setup.py
NickleDave/williams
bfc362e82dfa5785116e11142e90e7f6908255b0
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # adopted from Kenneth Reitz # https://github.com/kennethreitz/setup.py # released under MIT license # (https://github.com/kennethreitz/setup.py/blob/master/LICENSE) # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Package meta-data. NAME = 'williams' DESCRIPTION = 'experiments with stochastic semilinear units and REINFORCE' URL = 'https://github.com/NickleDave/williams' EMAIL = 'dnicho4@emory.edu' AUTHOR = 'David Nicholson' REQUIRES_PYTHON = '>=3.6.0' VERSION = '0.1.0' LICENSE = 'BSD' REQUIRED = [ 'numpy', 'scipy', 'matplotlib', 'tqdm', ] dev_deps = [ 'twine', ] # this is here so that the .travis.yml script can install # dependencies just for the tests by running # pip install .[tests] EXTRAS = { 'dev': dev_deps, } # The rest you shouldn't have to touch too much :) # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! try: with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = '\n' + f.read() except FileNotFoundError: long_description = DESCRIPTION # Load the package's __version__.py module as a dictionary. about = {} if not VERSION: with open(os.path.join(here, NAME, '__version__.py')) as f: exec(f.read(), about) else: about['__version__'] = VERSION class UploadCommand(Command): """Support setup.py upload.""" description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): """Prints things in bold.""" print('\033[1m{0}\033[0m'.format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Removing previous builds…') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution…') os.system( '{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) self.status('Uploading the package to PyPI via Twine…') os.system('twine upload dist/*') self.status('Pushing git tags…') os.system('git tag v{0}'.format(about['__version__'])) os.system('git push --tags') sys.exit() # Where the magic happens: setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, long_description_content_type='text/markdown', author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(where="src", exclude=('tests',)), package_dir={"": "src"}, install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, license=LICENSE, classifiers=[ # Trove classifiers # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 'License :: OSI Approved :: BSD License', 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', ], # $ setup.py publish support. cmdclass={ 'upload': UploadCommand, }, )
27.311594
81
0.647652
import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command NAME = 'williams' DESCRIPTION = 'experiments with stochastic semilinear units and REINFORCE' URL = 'https://github.com/NickleDave/williams' EMAIL = 'dnicho4@emory.edu' AUTHOR = 'David Nicholson' REQUIRES_PYTHON = '>=3.6.0' VERSION = '0.1.0' LICENSE = 'BSD' REQUIRED = [ 'numpy', 'scipy', 'matplotlib', 'tqdm', ] dev_deps = [ 'twine', ] EXTRAS = { 'dev': dev_deps, } # ------------------------------------------------ # Except, perhaps the License and Trove Classifiers! # If you do change the License, remember to change the Trove Classifier for that! here = os.path.abspath(os.path.dirname(__file__)) # Import the README and use it as the long-description. # Note: this will only work if 'README.md' is present in your MANIFEST.in file! try: with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = '\n' + f.read() except FileNotFoundError: long_description = DESCRIPTION # Load the package's __version__.py module as a dictionary. about = {} if not VERSION: with open(os.path.join(here, NAME, '__version__.py')) as f: exec(f.read(), about) else: about['__version__'] = VERSION class UploadCommand(Command): description = 'Build and publish the package.' user_options = [] @staticmethod def status(s): print('\033[1m{0}\033[0m'.format(s)) def initialize_options(self): pass def finalize_options(self): pass def run(self): try: self.status('Removing previous builds…') rmtree(os.path.join(here, 'dist')) except OSError: pass self.status('Building Source and Wheel (universal) distribution…') os.system( '{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) self.status('Uploading the package to PyPI via Twine…') os.system('twine upload dist/*') self.status('Pushing git tags…') os.system('git tag v{0}'.format(about['__version__'])) os.system('git push --tags') sys.exit() setup( name=NAME, version=about['__version__'], description=DESCRIPTION, long_description=long_description, long_description_content_type='text/markdown', author=AUTHOR, author_email=EMAIL, python_requires=REQUIRES_PYTHON, url=URL, packages=find_packages(where="src", exclude=('tests',)), package_dir={"": "src"}, install_requires=REQUIRED, extras_require=EXTRAS, include_package_data=True, license=LICENSE, classifiers=[ 'License :: OSI Approved :: BSD License', 'Development Status :: 4 - Beta', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: Implementation :: CPython', ], cmdclass={ 'upload': UploadCommand, }, )
true
true
1c39de8304e631a1f28c5979e046c66e978f553d
841
py
Python
triplinker/accounts/migrations/0010_auto_20201009_1212.py
GonnaFlyMethod/triplinker
f4189e499ad48fd9102dd2211a8884078136eae9
[ "MIT" ]
null
null
null
triplinker/accounts/migrations/0010_auto_20201009_1212.py
GonnaFlyMethod/triplinker
f4189e499ad48fd9102dd2211a8884078136eae9
[ "MIT" ]
null
null
null
triplinker/accounts/migrations/0010_auto_20201009_1212.py
GonnaFlyMethod/triplinker
f4189e499ad48fd9102dd2211a8884078136eae9
[ "MIT" ]
null
null
null
# Generated by Django 3.0.8 on 2020-10-09 12:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0009_userphotogallery'), ] operations = [ migrations.CreateModel( name='PersonalQualities', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('qualities', models.CharField(max_length=50)), ], options={ 'verbose_name': 'Quality', 'verbose_name_plural': 'Qualities', }, ), migrations.AddField( model_name='tlaccount', name='qualities', field=models.ManyToManyField(to='accounts.PersonalQualities'), ), ]
28.033333
114
0.557669
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0009_userphotogallery'), ] operations = [ migrations.CreateModel( name='PersonalQualities', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('qualities', models.CharField(max_length=50)), ], options={ 'verbose_name': 'Quality', 'verbose_name_plural': 'Qualities', }, ), migrations.AddField( model_name='tlaccount', name='qualities', field=models.ManyToManyField(to='accounts.PersonalQualities'), ), ]
true
true
1c39dea512b95a1df786c32d360d7cdf2afe45c9
7,698
py
Python
lib/googlecloudsdk/command_lib/concepts/dependency_managers.py
bshaffer/google-cloud-sdk
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
[ "Apache-2.0" ]
null
null
null
lib/googlecloudsdk/command_lib/concepts/dependency_managers.py
bshaffer/google-cloud-sdk
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
[ "Apache-2.0" ]
null
null
null
lib/googlecloudsdk/command_lib/concepts/dependency_managers.py
bshaffer/google-cloud-sdk
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes that manage concepts and dependencies.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import functools from googlecloudsdk.calliope.concepts import deps as deps_lib from googlecloudsdk.command_lib.concepts import base from googlecloudsdk.command_lib.concepts import exceptions from googlecloudsdk.command_lib.concepts import names import six def GetPresentationNames(nodes): return (child.GetPresentationName() for child in nodes) class DependencyManager(object): """Holds dependency info for a single overall concept and creates views. Attributes: node: the DependencyNode at the root of the dependency tree for this concept. """ def __init__(self, node): self.node = node def ParseConcept(self, parsed_args): """Parse the concept recursively by building the dependencies in a DFS. Args are formatted in the same way as usage_text.py:GetArgsUsage, except concepts in a concept group are not sorted. Concepts are displayed in the order they were added to the group. Args: parsed_args: the raw parsed argparse namespace. Raises: googlecloudsdk.command_lib.concepts.exceptions.Error: if parsing fails. Returns: the parsed top-level concept. """ def _ParseConcept(node): """Recursive parsing.""" if not node.is_group: fallthroughs = [] if node.arg_name: fallthroughs.append(deps_lib.ArgFallthrough(node.arg_name)) fallthroughs += node.fallthroughs return node.concept.Parse( DependencyViewFromValue( functools.partial( deps_lib.GetFromFallthroughs, fallthroughs, parsed_args), marshalled_dependencies=node.dependencies)) # TODO(b/120132521) Replace and eliminate argparse extensions also_optional = [] # The optional concepts that were not specified. have_optional = [] # The specified optional (not required) concepts. have_required = [] # The specified required concepts. need_required = [] # The required concepts that must be specified. namespace = {} for name, child in six.iteritems(node.dependencies): result = None try: result = _ParseConcept(child) if result: if child.concept.required: have_required.append(child.concept) else: have_optional.append(child.concept) else: also_optional.append(child.concept) except exceptions.MissingRequiredArgumentError: need_required.append(child.concept) namespace[name] = result if need_required: missing = ' '.join(GetPresentationNames(need_required)) if have_optional or have_required: specified_parts = [] if have_required: specified_parts.append(' '.join( GetPresentationNames(have_required))) if have_required and have_optional: specified_parts.append(':') if have_optional: specified_parts.append(' '.join( GetPresentationNames(have_optional))) specified = ' '.join(specified_parts) if have_required and have_optional: if node.concept.required: specified = '({})'.format(specified) else: specified = '[{}]'.format(specified) raise exceptions.ModalGroupError( node.concept.GetPresentationName(), specified, missing) count = len(have_required) + len(have_optional) if node.concept.mutex: specified = ' | '.join( GetPresentationNames(node.concept.concepts)) if node.concept.required: specified = '({specified})'.format(specified=specified) if count != 1: raise exceptions.RequiredMutexGroupError( node.concept.GetPresentationName(), specified) else: if count > 1: raise exceptions.OptionalMutexGroupError( node.concept.GetPresentationName(), specified) return node.concept.Parse(DependencyView(namespace)) return _ParseConcept(self.node) class DependencyView(object): """Simple namespace used by concept.Parse for concept groups.""" def __init__(self, values_dict): for key, value in six.iteritems(values_dict): setattr(self, names.ConvertToNamespaceName(key), value) class DependencyViewFromValue(object): """Simple namespace for single value.""" def __init__(self, value_getter, marshalled_dependencies=None): self._value_getter = value_getter self._marshalled_dependencies = marshalled_dependencies @property def value(self): """Lazy value getter. Returns: the value of the attribute, from its fallthroughs. Raises: deps_lib.AttributeNotFoundError: if the value cannot be found. """ try: return self._value_getter() except TypeError: return self._value_getter @property def marshalled_dependencies(self): """Returns the marshalled dependencies or None if not marshalled.""" return self._marshalled_dependencies class DependencyNode(object): """A node of a dependency tree. Attributes: name: the name that will be used to look up the dependency from higher in the tree. Corresponds to the "key" of the attribute. concept: the concept of the attribute. dependencies: {str: DependencyNode}, a map from dependency names to sub-dependency trees. arg_name: str, the argument name of the attribute. fallthroughs: [deps_lib._Fallthrough], the list of fallthroughs for the dependency. marshalled: [base.Concept], the list of concepts marshalled by concept. The marshalled dependencies are generated here, but concept handles the parsing. """ def __init__(self, name, is_group, concept=None, dependencies=None, arg_name=None, fallthroughs=None): self.name = name self.is_group = is_group self.concept = concept self.dependencies = dependencies self.arg_name = arg_name self.fallthroughs = fallthroughs or [] @classmethod def FromAttribute(cls, attribute): """Builds the dependency tree from the attribute.""" kwargs = { 'concept': attribute.concept, } marshal = attribute.concept.Marshal() if marshal: attributes = [concept.Attribute() for concept in marshal] elif not isinstance(attribute, base.Attribute): attributes = attribute.attributes else: attributes = None if isinstance(attribute, base.Attribute) and (marshal or not attributes): kwargs['arg_name'] = attribute.arg_name kwargs['fallthroughs'] = attribute.fallthroughs if attributes: kwargs['dependencies'] = {a.concept.key: DependencyNode.FromAttribute(a) for a in attributes} return DependencyNode(attribute.concept.key, not isinstance(attribute, base.Attribute), **kwargs)
34.675676
78
0.681865
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import functools from googlecloudsdk.calliope.concepts import deps as deps_lib from googlecloudsdk.command_lib.concepts import base from googlecloudsdk.command_lib.concepts import exceptions from googlecloudsdk.command_lib.concepts import names import six def GetPresentationNames(nodes): return (child.GetPresentationName() for child in nodes) class DependencyManager(object): def __init__(self, node): self.node = node def ParseConcept(self, parsed_args): def _ParseConcept(node): if not node.is_group: fallthroughs = [] if node.arg_name: fallthroughs.append(deps_lib.ArgFallthrough(node.arg_name)) fallthroughs += node.fallthroughs return node.concept.Parse( DependencyViewFromValue( functools.partial( deps_lib.GetFromFallthroughs, fallthroughs, parsed_args), marshalled_dependencies=node.dependencies)) also_optional = [] have_optional = [] have_required = [] need_required = [] namespace = {} for name, child in six.iteritems(node.dependencies): result = None try: result = _ParseConcept(child) if result: if child.concept.required: have_required.append(child.concept) else: have_optional.append(child.concept) else: also_optional.append(child.concept) except exceptions.MissingRequiredArgumentError: need_required.append(child.concept) namespace[name] = result if need_required: missing = ' '.join(GetPresentationNames(need_required)) if have_optional or have_required: specified_parts = [] if have_required: specified_parts.append(' '.join( GetPresentationNames(have_required))) if have_required and have_optional: specified_parts.append(':') if have_optional: specified_parts.append(' '.join( GetPresentationNames(have_optional))) specified = ' '.join(specified_parts) if have_required and have_optional: if node.concept.required: specified = '({})'.format(specified) else: specified = '[{}]'.format(specified) raise exceptions.ModalGroupError( node.concept.GetPresentationName(), specified, missing) count = len(have_required) + len(have_optional) if node.concept.mutex: specified = ' | '.join( GetPresentationNames(node.concept.concepts)) if node.concept.required: specified = '({specified})'.format(specified=specified) if count != 1: raise exceptions.RequiredMutexGroupError( node.concept.GetPresentationName(), specified) else: if count > 1: raise exceptions.OptionalMutexGroupError( node.concept.GetPresentationName(), specified) return node.concept.Parse(DependencyView(namespace)) return _ParseConcept(self.node) class DependencyView(object): def __init__(self, values_dict): for key, value in six.iteritems(values_dict): setattr(self, names.ConvertToNamespaceName(key), value) class DependencyViewFromValue(object): def __init__(self, value_getter, marshalled_dependencies=None): self._value_getter = value_getter self._marshalled_dependencies = marshalled_dependencies @property def value(self): try: return self._value_getter() except TypeError: return self._value_getter @property def marshalled_dependencies(self): return self._marshalled_dependencies class DependencyNode(object): def __init__(self, name, is_group, concept=None, dependencies=None, arg_name=None, fallthroughs=None): self.name = name self.is_group = is_group self.concept = concept self.dependencies = dependencies self.arg_name = arg_name self.fallthroughs = fallthroughs or [] @classmethod def FromAttribute(cls, attribute): kwargs = { 'concept': attribute.concept, } marshal = attribute.concept.Marshal() if marshal: attributes = [concept.Attribute() for concept in marshal] elif not isinstance(attribute, base.Attribute): attributes = attribute.attributes else: attributes = None if isinstance(attribute, base.Attribute) and (marshal or not attributes): kwargs['arg_name'] = attribute.arg_name kwargs['fallthroughs'] = attribute.fallthroughs if attributes: kwargs['dependencies'] = {a.concept.key: DependencyNode.FromAttribute(a) for a in attributes} return DependencyNode(attribute.concept.key, not isinstance(attribute, base.Attribute), **kwargs)
true
true
1c39defa19c7d3ded9d65cfde924d0d825e870ad
10,956
py
Python
utils/performance.py
mmaguero/NCRFpp
65486d0160f24349751eafc307fa72be9f586b6e
[ "Apache-2.0" ]
null
null
null
utils/performance.py
mmaguero/NCRFpp
65486d0160f24349751eafc307fa72be9f586b6e
[ "Apache-2.0" ]
null
null
null
utils/performance.py
mmaguero/NCRFpp
65486d0160f24349751eafc307fa72be9f586b6e
[ "Apache-2.0" ]
null
null
null
#! /usr/bin/env python3 """ Development Version: Python 3.5.1 Author: Benjamin Cordier Description: Module For Performance Assessment of Classification Task License: BSD 3 Clause -- Copyright 2018 Benjamin Cordier Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # Import Modules import math from collections import OrderedDict class Performance(object): # # Metric Function Definitions # __metrics = { "statistics" : { "accuracy" : lambda tp, tn, fp, fn: (tp + tn) / (tp + tn + fp + fn) if (tp + tn) > 0 else 0.0, "f1score" : lambda tp, tn, fp, fn: (2 * tp) / ((2 * tp) + (fp + fn)) if tp > 0 else 0.0, "sensitivity" : lambda tp, tn, fp, fn: tp / (tp + fn) if tp > 0 else 0.0, "specificity" : lambda tp, tn, fp, fn: tn / (tn + fp) if tn > 0 else 0.0, "precision" : lambda tp, tn, fp, fn: tp / (tp + fp) if tp > 0 else 0.0, "recall" : lambda tp, tn, fp, fn: tp / (tp + fn) if tp > 0 else 0.0, "tpr" : lambda tp, tn, fp, fn: tp / (tp + fn) if tp > 0 else 0.0, "tnr" : lambda tp, tn, fp, fn: tn / (tn + fp) if tn > 0 else 0.0, "fpr" : lambda tp, tn, fp, fn: fp / (fp + tn) if fp > 0 else 0.0, "fnr" : lambda tp, tn, fp, fn: fn / (fn + tp) if fn > 0 else 0.0, "ppv" : lambda tp, tn, fp, fn: tp / (tp + fp) if tp > 0 else 0.0, "npv" : lambda tp, tn, fp, fn: tn / (tn + fn) if tn > 0 else 0.0, "mcc" : lambda tp, tn, fp, fn: ((tp * tn) - (fp * fn)) / math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) if (tp * tn * fn * fp) > 0 else 0.0, "j-statistic" : lambda tp, tn, fp, fn: (tp / (tp + fn)) + (tn / (tn + fp)) - 1 if (tp > 0 or (tp + fn) > 0) or (tn > 0 or (tn + fp) > 0) else -1.0 }, "counts" : { "tp" : lambda tp, tn, fp, fn: tp, "tn" : lambda tp, tn, fp, fn: tn, "fp" : lambda tp, tn, fp, fn: fp, "fn" : lambda tp, tn, fp, fn: fn, "pos" : lambda tp, tn, fp, fn: tp + fn, "neg" : lambda tp, tn, fp, fn: tn + fp, "prop" : lambda tp, tn, fp, fn: (tp + fn) / (tp + tn + fp + fn) } } # # Initialization # def __init__(self, actual = [], predicted = [], __metrics = __metrics): # Set Reference to Defaults self.metrics = __metrics self.actual = [] self.predicted = [] # Call Update Function self.update(actual, predicted) # # Update Function # def update (self, actual = [], predicted = []): # Type Check Inputs, Allow For Update of Actual and Predicted Simultaneously or Individually self.actual = actual if type(actual) is list and len(actual) > 0 else self.actual self.predicted = predicted if type(predicted) is list and len(predicted) > 0 else self.predicted assert len(self.actual) == len(self.predicted), "Actual and predicted lists must be equal in length" assert len(self.actual) > 0, "Actual and predicted lists should have a length greater than 0" # Additional References self.classes = sorted(set(self.actual)) self.matrix = [ [ 0 for _ in self.classes ] for _ in self.classes ] self.classToIndex = { key: i for i, key in enumerate(self.classes) } self.indexToClass = { i: key for i, key in enumerate(self.classes) } # Generate Confusion Matrix for p, a in zip(self.predicted, self.actual): self.matrix[self.classToIndex[p]][self.classToIndex[a]] += 1 # Matrix Sum self.n = sum([ sum(row) for row in self.matrix ]) # Matrix as Proportions (Normalized) self.normed = [ row for row in map(lambda i: list(map(lambda j: j / self.n, i)), self.matrix) ] # Generate Statistics Data Structure self.results = OrderedDict(((c, {"counts" : OrderedDict(), "stats" : OrderedDict()}) for c in self.classes)) # Compute Counts & Statistics for i in range(len(self.classes)): row = sum(self.matrix[i][:]) col = sum([row[i] for row in self.matrix]) # Can't Access Matrix Col Using matrix[:][i] With Vanilla Python tp = self.matrix[i][i] fp = row - tp fn = col - tp tn = self.n - row - col + tp # Populate Counts Dictionary for count, func in self.metrics["counts"].items(): self.results[self.indexToClass[i]]["counts"][count] = self.metrics["counts"][count](tp, tn, fp, fn) # Populate Statistics Dictionary for stat, func in self.metrics["statistics"].items(): self.results[self.indexToClass[i]]["stats"][stat] = self.metrics["statistics"][stat](tp, tn, fp, fn) return self # # Getter Methods # # Get Class Map def getClasses (self): return self.classes # Get Class Counts def getClassBalance (self): return { self.indexToClass[i] : self.results[self.indexToClass[i]]["counts"]["pos"] for i, _ in enumerate(self.classes) } # Get Class Proportions def getClassProportions (self): return { self.indexToClass[i] : self.results[self.indexToClass[i]]["counts"]["prop"] for i, _ in enumerate(self.classes) } # Get Available Keys For Counts & Statistics def getAvailable (self): return {"stats" : list(self.metrics["statistics"].keys()), "counts" : list(self.metrics["counts"].keys()) } # Get Statistic For All Classes def getStatistic (self, statistic = "accuracy"): return statistic, { self.indexToClass[i]: self.results[self.indexToClass[i]]["stats"][statistic] for i, _ in enumerate(self.classes) } # Get Counts For All Classes def getCount (self, count = "tp"): return count, { self.indexToClass[i]: self.results[self.indexToClass[i]]["counts"][count] for i, _ in enumerate(self.classes) } # Get All Statistics For All Classes def getStatistics (self): return { self.indexToClass[i]: self.results[self.indexToClass[i]]["stats"] for i, _ in enumerate(self.classes) } # Get All Counts For All Classes def getCounts (self): return { self.indexToClass[i]: self.results[self.indexToClass[i]]["counts"] for i, _ in enumerate(self.classes) } # Get Statistic By Specified Class def getStatisticByClass (self, c, statistic = "accuracy"): return statistic, self.results[c]["stats"][statistic] # Get Count By Specified Class def getCountByClass (self, c, count = "tp"): return count, self.results[c]["counts"][count] # Get All Counts & Statistics def getAll (self): return self.results # Get Confusion Matrix def getConfusionMatrix(self, normalized = False): if normalized: return self.normed else: return self.matrix # # Print Functions # # Print Summary Statistics def summarize (self): for i, c in enumerate(self.classes): print("=" * 30) print("%s" % str(c)) print("-- Counts") for key, val in sorted(self.results[self.indexToClass[i]]["counts"].items(), key = lambda item: (len(item[0]), item[0])): print(" %s: %s" % (key.ljust(16), str(val).ljust(8))) print("\n-- Statistics") for key, val in sorted(self.results[self.indexToClass[i]]["stats"].items(), key = lambda item: (len(item[0]), item[0])): print(" %s: %s" % (key.ljust(16), ("%0.4f%%" % (val * 100)).ljust(8))) print("=" * 30) # Print Confusion Matrix def tabulate (self, normalized = False): minlen = max([len(str(c)) for c, n in self.getClassBalance().items()]) cellwidth = minlen if minlen > 7 else 7 print("=" * (cellwidth * (len(self.classes) + 2))) if normalized: print(" %s\n" % " ".join([("%sᴬ" % c).ljust(cellwidth)[0:cellwidth] for c in self.classes])) for c, row in zip(self.classes, self.normed): print("%s %s\n" % (("%sᴾ" % c).ljust(cellwidth)[0:cellwidth], " ".join([("%0.2f%%" % (val * 100)).ljust(cellwidth)[0:cellwidth] for val in row]))) else: print(" %s\n" % " ".join([("%sᴬ" % c).ljust(cellwidth)[0:cellwidth] for c in self.classes])) for c, row in zip(self.classes, self.matrix): print("%s %s\n" % (("%sᴾ" % c).ljust(cellwidth)[0:cellwidth], " ".join([str(val).ljust(cellwidth)[0:cellwidth] for val in row]))) print("Note: classᴾ = Predicted, classᴬ = Actual") print("=" * (cellwidth * (len(self.classes) + 2))) # Example Usage if __name__ == "__main__": # Actual & Predicted Classes actual = ["A", "B", "C", "C", "B", "C", "C", "B", "A", "A", "B", "A", "B", "C", "A", "B", "C"] predicted = ["A", "B", "B", "C", "A", "C", "A", "B", "C", "A", "B", "B", "B", "C", "A", "A", "C"] # Initialize Performance Class performance = Performance(actual, predicted) # Print Statistical Summary performance.summarize() # Print Confusion Matrix performance.tabulate() # Print Normalized Confusion Matrix performance.tabulate(normalized = True) else: pass
45.841004
172
0.580869
import math from collections import OrderedDict class Performance(object): __metrics = { "statistics" : { "accuracy" : lambda tp, tn, fp, fn: (tp + tn) / (tp + tn + fp + fn) if (tp + tn) > 0 else 0.0, "f1score" : lambda tp, tn, fp, fn: (2 * tp) / ((2 * tp) + (fp + fn)) if tp > 0 else 0.0, "sensitivity" : lambda tp, tn, fp, fn: tp / (tp + fn) if tp > 0 else 0.0, "specificity" : lambda tp, tn, fp, fn: tn / (tn + fp) if tn > 0 else 0.0, "precision" : lambda tp, tn, fp, fn: tp / (tp + fp) if tp > 0 else 0.0, "recall" : lambda tp, tn, fp, fn: tp / (tp + fn) if tp > 0 else 0.0, "tpr" : lambda tp, tn, fp, fn: tp / (tp + fn) if tp > 0 else 0.0, "tnr" : lambda tp, tn, fp, fn: tn / (tn + fp) if tn > 0 else 0.0, "fpr" : lambda tp, tn, fp, fn: fp / (fp + tn) if fp > 0 else 0.0, "fnr" : lambda tp, tn, fp, fn: fn / (fn + tp) if fn > 0 else 0.0, "ppv" : lambda tp, tn, fp, fn: tp / (tp + fp) if tp > 0 else 0.0, "npv" : lambda tp, tn, fp, fn: tn / (tn + fn) if tn > 0 else 0.0, "mcc" : lambda tp, tn, fp, fn: ((tp * tn) - (fp * fn)) / math.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) if (tp * tn * fn * fp) > 0 else 0.0, "j-statistic" : lambda tp, tn, fp, fn: (tp / (tp + fn)) + (tn / (tn + fp)) - 1 if (tp > 0 or (tp + fn) > 0) or (tn > 0 or (tn + fp) > 0) else -1.0 }, "counts" : { "tp" : lambda tp, tn, fp, fn: tp, "tn" : lambda tp, tn, fp, fn: tn, "fp" : lambda tp, tn, fp, fn: fp, "fn" : lambda tp, tn, fp, fn: fn, "pos" : lambda tp, tn, fp, fn: tp + fn, "neg" : lambda tp, tn, fp, fn: tn + fp, "prop" : lambda tp, tn, fp, fn: (tp + fn) / (tp + tn + fp + fn) } } def __init__(self, actual = [], predicted = [], __metrics = __metrics): self.metrics = __metrics self.actual = [] self.predicted = [] self.update(actual, predicted) def update (self, actual = [], predicted = []): self.actual = actual if type(actual) is list and len(actual) > 0 else self.actual self.predicted = predicted if type(predicted) is list and len(predicted) > 0 else self.predicted assert len(self.actual) == len(self.predicted), "Actual and predicted lists must be equal in length" assert len(self.actual) > 0, "Actual and predicted lists should have a length greater than 0" self.classes = sorted(set(self.actual)) self.matrix = [ [ 0 for _ in self.classes ] for _ in self.classes ] self.classToIndex = { key: i for i, key in enumerate(self.classes) } self.indexToClass = { i: key for i, key in enumerate(self.classes) } for p, a in zip(self.predicted, self.actual): self.matrix[self.classToIndex[p]][self.classToIndex[a]] += 1 self.n = sum([ sum(row) for row in self.matrix ]) self.normed = [ row for row in map(lambda i: list(map(lambda j: j / self.n, i)), self.matrix) ] self.results = OrderedDict(((c, {"counts" : OrderedDict(), "stats" : OrderedDict()}) for c in self.classes)) for i in range(len(self.classes)): row = sum(self.matrix[i][:]) col = sum([row[i] for row in self.matrix]) tp = self.matrix[i][i] fp = row - tp fn = col - tp tn = self.n - row - col + tp # Populate Counts Dictionary for count, func in self.metrics["counts"].items(): self.results[self.indexToClass[i]]["counts"][count] = self.metrics["counts"][count](tp, tn, fp, fn) # Populate Statistics Dictionary for stat, func in self.metrics["statistics"].items(): self.results[self.indexToClass[i]]["stats"][stat] = self.metrics["statistics"][stat](tp, tn, fp, fn) return self # # Getter Methods # # Get Class Map def getClasses (self): return self.classes # Get Class Counts def getClassBalance (self): return { self.indexToClass[i] : self.results[self.indexToClass[i]]["counts"]["pos"] for i, _ in enumerate(self.classes) } # Get Class Proportions def getClassProportions (self): return { self.indexToClass[i] : self.results[self.indexToClass[i]]["counts"]["prop"] for i, _ in enumerate(self.classes) } # Get Available Keys For Counts & Statistics def getAvailable (self): return {"stats" : list(self.metrics["statistics"].keys()), "counts" : list(self.metrics["counts"].keys()) } # Get Statistic For All Classes def getStatistic (self, statistic = "accuracy"): return statistic, { self.indexToClass[i]: self.results[self.indexToClass[i]]["stats"][statistic] for i, _ in enumerate(self.classes) } # Get Counts For All Classes def getCount (self, count = "tp"): return count, { self.indexToClass[i]: self.results[self.indexToClass[i]]["counts"][count] for i, _ in enumerate(self.classes) } # Get All Statistics For All Classes def getStatistics (self): return { self.indexToClass[i]: self.results[self.indexToClass[i]]["stats"] for i, _ in enumerate(self.classes) } # Get All Counts For All Classes def getCounts (self): return { self.indexToClass[i]: self.results[self.indexToClass[i]]["counts"] for i, _ in enumerate(self.classes) } # Get Statistic By Specified Class def getStatisticByClass (self, c, statistic = "accuracy"): return statistic, self.results[c]["stats"][statistic] # Get Count By Specified Class def getCountByClass (self, c, count = "tp"): return count, self.results[c]["counts"][count] # Get All Counts & Statistics def getAll (self): return self.results # Get Confusion Matrix def getConfusionMatrix(self, normalized = False): if normalized: return self.normed else: return self.matrix # # Print Functions # # Print Summary Statistics def summarize (self): for i, c in enumerate(self.classes): print("=" * 30) print("%s" % str(c)) print("-- Counts") for key, val in sorted(self.results[self.indexToClass[i]]["counts"].items(), key = lambda item: (len(item[0]), item[0])): print(" %s: %s" % (key.ljust(16), str(val).ljust(8))) print("\n-- Statistics") for key, val in sorted(self.results[self.indexToClass[i]]["stats"].items(), key = lambda item: (len(item[0]), item[0])): print(" %s: %s" % (key.ljust(16), ("%0.4f%%" % (val * 100)).ljust(8))) print("=" * 30) # Print Confusion Matrix def tabulate (self, normalized = False): minlen = max([len(str(c)) for c, n in self.getClassBalance().items()]) cellwidth = minlen if minlen > 7 else 7 print("=" * (cellwidth * (len(self.classes) + 2))) if normalized: print(" %s\n" % " ".join([("%sᴬ" % c).ljust(cellwidth)[0:cellwidth] for c in self.classes])) for c, row in zip(self.classes, self.normed): print("%s %s\n" % (("%sᴾ" % c).ljust(cellwidth)[0:cellwidth], " ".join([("%0.2f%%" % (val * 100)).ljust(cellwidth)[0:cellwidth] for val in row]))) else: print(" %s\n" % " ".join([("%sᴬ" % c).ljust(cellwidth)[0:cellwidth] for c in self.classes])) for c, row in zip(self.classes, self.matrix): print("%s %s\n" % (("%sᴾ" % c).ljust(cellwidth)[0:cellwidth], " ".join([str(val).ljust(cellwidth)[0:cellwidth] for val in row]))) print("Note: classᴾ = Predicted, classᴬ = Actual") print("=" * (cellwidth * (len(self.classes) + 2))) # Example Usage if __name__ == "__main__": # Actual & Predicted Classes actual = ["A", "B", "C", "C", "B", "C", "C", "B", "A", "A", "B", "A", "B", "C", "A", "B", "C"] predicted = ["A", "B", "B", "C", "A", "C", "A", "B", "C", "A", "B", "B", "B", "C", "A", "A", "C"] # Initialize Performance Class performance = Performance(actual, predicted) # Print Statistical Summary performance.summarize() # Print Confusion Matrix performance.tabulate() # Print Normalized Confusion Matrix performance.tabulate(normalized = True) else: pass
true
true
1c39e00af8e8ccde2480fb3d4ba00de71126bf44
18,212
py
Python
reordering.py
dawn-ico/grid-experiments
882d73d2dc2f3dadeeb71dde6731c21397f37092
[ "MIT" ]
null
null
null
reordering.py
dawn-ico/grid-experiments
882d73d2dc2f3dadeeb71dde6731c21397f37092
[ "MIT" ]
null
null
null
reordering.py
dawn-ico/grid-experiments
882d73d2dc2f3dadeeb71dde6731c21397f37092
[ "MIT" ]
null
null
null
from grid_types import Grid, DEVICE_MISSING_VALUE, GridSet from location_type import LocationType from schemas import * import numpy as np import netCDF4 from functools import cmp_to_key NaN = float("nan") def apply_permutation( ncf, perm: np.ndarray, schema: GridScheme, location_type: LocationType ) -> None: rev_perm = revert_permutation(perm) for field_name, descr in schema.items(): field = ncf.variables[field_name] array = np.copy(field[:]) if ( descr.location_type is location_type and not descr.do_not_reorder_primary_loc ): if 1 < len(array.shape): assert descr.primary_axis is not None array = np.take(array, perm, axis=descr.primary_axis) else: array = array[perm] if descr.indexes_into is location_type and not descr.do_not_reorder_indexes: # go from fortran's 1-based indexing to python's 0-based indexing array = array - 1 # remap indices missing_values = array == DEVICE_MISSING_VALUE array = rev_perm[array] array[missing_values] = DEVICE_MISSING_VALUE array = array + 1 field[:] = array def fix_hole(ncf, schema: GridScheme): for field_name, descr in schema.items(): field = ncf.variables[field_name] array = np.copy(field[:]) nc = ncf.dimensions["cell"].size ne = ncf.dimensions["edge"].size nv = ncf.dimensions["vertex"].size # NOTE: this seems extremely brittle, but not sure how to improve if field_name == "end_idx_c": array[0, 8] = nc field[:] = array if field_name == "end_idx_v": array[0, 7] = nv field[:] = array if field_name == "end_idx_e": array[0, 13] = ne field[:] = array def get_grf_ranges(grid: Grid, location_type: LocationType = LocationType.Cell): # returns the index ranges of the grid refinement valid_regions # region 0 is the compute domain. # all other regions are the lateral boundary layers starting from most outer # and going to most inner. if location_type is LocationType.Vertex: n = grid.nv start, end = grid.v_grf[:, 0], grid.v_grf[:, 1] elif location_type is LocationType.Edge: n = grid.ne start, end = grid.e_grf[:, 0], grid.e_grf[:, 1] elif location_type is LocationType.Cell: n = grid.nc start, end = grid.c_grf[:, 0], grid.c_grf[:, 1] else: raise ValueError valid_regions = start <= end start = start[valid_regions] end = end[valid_regions] end = end + 1 # end is exclusive assert np.min(start) == 0 assert np.max(end) <= n # There's something very weird going on: # Some few vertices/edges/cells (at the end) aren't in any valid region, # but without them, there will be a hole in the compute domain. # We fix this by assigning them to region `0` by default. end[0] = n return list(zip(start, end)) def range_to_slice(range: typing.Tuple[typing.Optional[int], typing.Optional[int]]): return slice(range[0], range[1]) def normalize_angle(angle): return np.fmod(angle, 2 * np.pi) def get_angle(p): return np.arctan2(p[:, 1], p[:, 0]) def rotate(points, angle, origin=np.array([[0, 0]])): points = points - origin rotation_matrix = np.array( [[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]] ) points = (rotation_matrix @ points.T).T return points + origin class UnsupportedPentagonException(Exception): pass def neighbor_array_to_set(array): nbhs = np.unique(array) return nbhs[nbhs != DEVICE_MISSING_VALUE] ############################################################################### # Each vertex is the crossing point of 6 rays. Two of twos rays are defined as # the cartesian x- and y-axis (marked as double lines below). # With this, we can give each vertex a unique x/y coordinate, as shown below. # # 2 1 # \ // # \ // # \ // # [-1, 1] *-----------------------* [0, 1] # / \ // \ # / \ // \ # / \ // \ # / \ // \ # [-1, 0] / \ // [0, 0] \ [1, 0] # 3 ===========*======================*======================*=============== 0 # \ // \ / # \ // \ / # \ // \ / # \ // \ / # \ // \ / # [0, -1] *-----------------------* [1, -1] # // \ # // \ # // \ # 4 5 # ############################################################################### structured_v2v_offsets = np.array( [ # neighbor id/ray 0 [+1, +0], # neighbor id/ray 1 [+0, +1], # neighbor id/ray 2 [-1, +1], # neighbor id/ray 3 [-1, +0], # neighbor id/ray 4 [+0, -1], # neighbor id/ray 5 [+1, -1], ], dtype=int, ) ############################################################################### # Once each vertex has a unique x/y coordinate, we use those to assign # to each edge & cell a x/y coordinate and a color. For each edge & cell # we look for the closest vertex in the bottom left direction. This vertex # determines the x/y coordinate of each edge & cell. Then the coloring is done # from left to right in a counter clock-wise direction. # (This is similar to dawn's `ICOChainSize`, but uses a slightly different ordering) # # / \ / / # \ / \ / / # \ / \ / / # -*------------------------ [x, y+1] *==================================* [x+1, y+1] # / \ // \ // \ # \ // \ // \ # \ // \ [x, y, 1] // \ # \ // \ // \ # \ // \ // \ # \ [x, y, 0] [x, y, 1] // \ # \ // \ // \ # \ // \ // \ # \ // [x, y, 0] \ // # \ // \ // # \ // \ // # ---- [x, y] *============[x, y, 2]=============* [x+1, y] --------------------- # / \ / \ # / \ / \ # / \ / \ # / \ / \ # ############################################################################### structured_v2e_offsets = np.array( [ # neighbor id/ray 0 [+0, +0, +2], # neighbor id/ray 1 [+0, +0, +0], # neighbor id/ray 2 [-1, +0, +1], # neighbor id/ray 3 [-1, +0, +2], # neighbor id/ray 4 [+0, -1, +0], # neighbor id/ray 5 [+0, -1, +1], ], dtype=int, ) # (for the cells, we shift the rays 15 degrees counter clock-wise) structured_v2c_offsets = np.array( [ # neighbor id/ray 0 [+0, +0, +0], # neighbor id/ray 1 [-1, +0, +1], # neighbor id/ray 2 [-1, +0, +0], # neighbor id/ray 3 [-1, -1, +1], # neighbor id/ray 4 [+0, -1, +0], # neighbor id/ray 5 [+0, -1, +1], ], dtype=int, ) @dataclasses.dataclass class GridMapping: vertex_mapping: np.ndarray edge_mapping: np.ndarray cell_mapping: np.ndarray def create_structured_grid_mapping( grid: Grid, right_direction_angle, start_vertex=None, angle_threshold=np.deg2rad(30) ) -> GridMapping: # doesn't support pentagons! if start_vertex is None: start_vertex = 0 if isinstance(right_direction_angle, np.ndarray): right_direction_angle = float(right_direction_angle) vertex_mapping = np.full((grid.nv, 2), NaN) edge_mapping = np.full((grid.ne, 3), NaN) cell_mapping = np.full((grid.nc, 3), NaN) vertex_mapping[start_vertex] = [0, 0] # This algorithms works as follows: # # * Carry out a breadth-first search starting from `start_vertex`. # * For each vertex: # * Determine for each neighbor edge, cell, vertex what is their relative id. # (see `structured_<...>_offsets`) # * For each neighbor edge, cell, vertex check which ones have no coordinates assigned yet: # * Assign new coordinates to neighbors if they don't have coordinates yet. # * Check if coordinates are consistent if they already have coordinates. # * Update the right direction angle based on the neighboring vertices of the vertex # (this way the algorithm can handle a small local curvature) # * Continue the bsf with the vertices that have newly assigned coordinates. def bfs(vertex_id, right_direction_angle): # neighbor cells, edges, vertices cell_ids = neighbor_array_to_set(grid.v2c[vertex_id]) edge_ids = neighbor_array_to_set(grid.v2e[vertex_id]) vertex_ids = neighbor_array_to_set(grid.e2v[edge_ids]) vertex_ids = vertex_ids[vertex_ids != vertex_id] # some sanity checks if len(edge_ids) == 5 and len(cell_ids) == 5: raise UnsupportedPentagonException assert len(edge_ids) == len(cell_ids) == 6 or len(cell_ids) + 1 == len(edge_ids) assert len(vertex_ids) == len(edge_ids) assert 0 < len(cell_ids) <= len(edge_ids) <= 6 # get the coordinates of this vertex x, y = vertex_mapping[vertex_id] assert not np.isnan(x) and not np.isnan(y) self_lon_lat = grid.v_lon_lat[vertex_id] # compute angles of neighbor vertices vertices_angle = normalize_angle( get_angle(grid.v_lon_lat[vertex_ids] - self_lon_lat) - right_direction_angle ) vertices_nbh_ids = np.around(vertices_angle / (np.pi / 3)).astype(int) assert np.all( np.fabs(vertices_angle - vertices_nbh_ids * np.pi / 3) <= angle_threshold ) # compute angles of neighbor edges edges_angle = normalize_angle( get_angle(grid.e_lon_lat[edge_ids] - self_lon_lat) - right_direction_angle ) edges_nbh_ids = np.around(edges_angle / (np.pi / 3)).astype(int) assert np.all( np.fabs(edges_angle - edges_nbh_ids * np.pi / 3) <= angle_threshold ) # compute angles of neighbor cells # (we rotate the cells by 30 degrees clock-wise (`-np.pi/6`) to get the angle id) cells_angle = normalize_angle( get_angle(grid.c_lon_lat[cell_ids] - self_lon_lat) - right_direction_angle - np.pi / 6 ) cells_nbh_ids = np.around(cells_angle / (np.pi / 3)).astype(int) assert np.all( np.fabs(cells_angle - cells_nbh_ids * np.pi / 3) <= angle_threshold ) # update right direction angle self_right_direction_angle = ( np.average(vertices_angle - vertices_nbh_ids * np.pi / 3) + right_direction_angle ) # assign coordinates to vertex neighbors that don't have a coordinate yet vertices_nbh_structured_coords = structured_v2v_offsets[ vertices_nbh_ids ] + np.array([[x, y]], dtype=int) new_vertex_ids = np.all(np.isnan(vertex_mapping[vertex_ids, :]), axis=-1) vertex_mapping[vertex_ids[new_vertex_ids], :] = vertices_nbh_structured_coords[ new_vertex_ids ] # check vertex neighbors that already had a coordinate, that they are consistent with the ones we computed here assert np.all(vertex_mapping[vertex_ids, :] == vertices_nbh_structured_coords) # assign coordinates to edge neighbors that don't have a coordinate yet edges_nbh_structured_coords = structured_v2e_offsets[edges_nbh_ids] + np.array( [[x, y, 0]], dtype=int ) new_edge_ids = np.all(np.isnan(edge_mapping[edge_ids, :]), axis=-1) edge_mapping[edge_ids[new_edge_ids], :] = edges_nbh_structured_coords[ new_edge_ids ] # check edge neighbors that already had a coordinate, that they are consistent with the ones we computed here assert np.all(edge_mapping[edge_ids, :] == edges_nbh_structured_coords) # assign coordinates to cell neighbors that don't have a coordinate yet cells_nbh_structured_coords = structured_v2c_offsets[cells_nbh_ids] + np.array( [[x, y, 0]], dtype=int ) new_cell_ids = np.all(np.isnan(cell_mapping[cell_ids, :]), axis=-1) cell_mapping[cell_ids[new_cell_ids], :] = cells_nbh_structured_coords[ new_cell_ids ] # check cell neighbors that already had a coordinate, that they are consistent with the ones we computed here assert np.all(cell_mapping[cell_ids, :] == cells_nbh_structured_coords) # continue bfs with vertices that have newly assigned coordinates # (use the updated right direction angle for them) return { (int(next_vertex_id), self_right_direction_angle) for next_vertex_id in vertex_ids[new_vertex_ids] } current = set() next = {(start_vertex, right_direction_angle)} while 0 < len(next): # swap current, next = next, current next.clear() for vertex_args in current: next.update(bfs(*vertex_args)) assert not np.any(np.isnan(vertex_mapping)) assert not np.any(np.isnan(edge_mapping)) assert not np.any(np.isnan(cell_mapping)) return GridMapping( vertex_mapping=vertex_mapping, edge_mapping=edge_mapping, cell_mapping=cell_mapping, ) def argsort_simple( mapping: np.ndarray, cmp: typing.Callable[[typing.Any, typing.Any], int], idx_range: typing.Tuple[typing.Optional[int], typing.Optional[int]] = (None, None), ) -> np.ndarray: # Sorts the first axis based on a `cmp` function within the range [start_idx:end_idx]. # Returns the permutation array for the whole array. # # A permutation is an array `a` such that: `a[old_index] == new_index` total_end_idx = mapping.shape[0] start_idx, end_idx = idx_range if start_idx is None: start_idx = 0 if end_idx is None: end_idx = total_end_idx ids = list(range(start_idx, end_idx)) ids.sort(key=cmp_to_key(lambda a, b: cmp(mapping[a, :], mapping[b, :]))) return np.concatenate( (np.arange(start_idx), np.array(ids), np.arange(end_idx, total_end_idx)) ) def revert_permutation(perm: np.ndarray) -> np.ndarray: perm_rev = np.arange(perm.shape[0]) perm_rev[perm] = np.copy(perm_rev) return perm_rev class SimpleRowMajorSorting: # Provides comparison functions for mappings from `create_structured_grid_mapping`. @staticmethod def vertex_compare(a, b) -> int: return a[0] - b[0] if b[1] == a[1] else b[1] - a[1] @staticmethod def edge_compare(a, b) -> int: if a[2] == 2 and b[2] != 2: return b[1] - a[1] + 1 / 2 if a[2] != 2 and b[2] == 2: return b[1] - a[1] - 1 / 2 return ( (a[2] - b[2] if a[0] == b[0] else a[0] - b[0]) if b[1] == a[1] else b[1] - a[1] ) @staticmethod def cell_compare(a, b) -> int: return ( (a[2] - b[2] if a[0] == b[0] else a[0] - b[0]) if b[1] == a[1] else b[1] - a[1] ) def reorder_pool_folder(grid_set: GridSet, fix_hole_in_grid: bool): grid_file = netCDF4.Dataset(grid_set.grid.fname + ".nc") grid = Grid.from_netCDF4(grid_file) grid_set.make_data_sets("row-major") # the line of the right direction angle for vertex #0: p1 = np.array([[0.18511014, 0.79054856]]) p2 = np.array([[0.18593181, 0.79048109]]) right_direction_angle = np.squeeze(get_angle(p2 - p1)) mapping = create_structured_grid_mapping( grid, right_direction_angle, angle_threshold=np.deg2rad(15) ) v_grf = get_grf_ranges(grid, LocationType.Vertex) e_grf = get_grf_ranges(grid, LocationType.Edge) c_grf = get_grf_ranges(grid, LocationType.Cell) v_perm = argsort_simple( mapping.vertex_mapping, SimpleRowMajorSorting.vertex_compare, v_grf[0] ) e_perm = argsort_simple( mapping.edge_mapping, SimpleRowMajorSorting.edge_compare, e_grf[0] ) c_perm = argsort_simple( mapping.cell_mapping, SimpleRowMajorSorting.cell_compare, c_grf[0] ) for grid in grid_set: apply_permutation(grid.data_set, c_perm, grid.schema, LocationType.Cell) apply_permutation(grid.data_set, e_perm, grid.schema, LocationType.Edge) apply_permutation(grid.data_set, v_perm, grid.schema, LocationType.Vertex) if fix_hole_in_grid: fix_hole(grid_set.grid.data_set, grid_set.grid.schema) grid_set.sync_data_sets()
35.992095
119
0.527729
from grid_types import Grid, DEVICE_MISSING_VALUE, GridSet from location_type import LocationType from schemas import * import numpy as np import netCDF4 from functools import cmp_to_key NaN = float("nan") def apply_permutation( ncf, perm: np.ndarray, schema: GridScheme, location_type: LocationType ) -> None: rev_perm = revert_permutation(perm) for field_name, descr in schema.items(): field = ncf.variables[field_name] array = np.copy(field[:]) if ( descr.location_type is location_type and not descr.do_not_reorder_primary_loc ): if 1 < len(array.shape): assert descr.primary_axis is not None array = np.take(array, perm, axis=descr.primary_axis) else: array = array[perm] if descr.indexes_into is location_type and not descr.do_not_reorder_indexes: array = array - 1 missing_values = array == DEVICE_MISSING_VALUE array = rev_perm[array] array[missing_values] = DEVICE_MISSING_VALUE array = array + 1 field[:] = array def fix_hole(ncf, schema: GridScheme): for field_name, descr in schema.items(): field = ncf.variables[field_name] array = np.copy(field[:]) nc = ncf.dimensions["cell"].size ne = ncf.dimensions["edge"].size nv = ncf.dimensions["vertex"].size if field_name == "end_idx_c": array[0, 8] = nc field[:] = array if field_name == "end_idx_v": array[0, 7] = nv field[:] = array if field_name == "end_idx_e": array[0, 13] = ne field[:] = array def get_grf_ranges(grid: Grid, location_type: LocationType = LocationType.Cell): if location_type is LocationType.Vertex: n = grid.nv start, end = grid.v_grf[:, 0], grid.v_grf[:, 1] elif location_type is LocationType.Edge: n = grid.ne start, end = grid.e_grf[:, 0], grid.e_grf[:, 1] elif location_type is LocationType.Cell: n = grid.nc start, end = grid.c_grf[:, 0], grid.c_grf[:, 1] else: raise ValueError valid_regions = start <= end start = start[valid_regions] end = end[valid_regions] end = end + 1 assert np.min(start) == 0 assert np.max(end) <= n # Some few vertices/edges/cells (at the end) aren't in any valid region, end[0] = n return list(zip(start, end)) def range_to_slice(range: typing.Tuple[typing.Optional[int], typing.Optional[int]]): return slice(range[0], range[1]) def normalize_angle(angle): return np.fmod(angle, 2 * np.pi) def get_angle(p): return np.arctan2(p[:, 1], p[:, 0]) def rotate(points, angle, origin=np.array([[0, 0]])): points = points - origin rotation_matrix = np.array( [[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]] ) points = (rotation_matrix @ points.T).T return points + origin class UnsupportedPentagonException(Exception): pass def neighbor_array_to_set(array): nbhs = np.unique(array) return nbhs[nbhs != DEVICE_MISSING_VALUE] [2] != 2 and b[2] == 2: return b[1] - a[1] - 1 / 2 return ( (a[2] - b[2] if a[0] == b[0] else a[0] - b[0]) if b[1] == a[1] else b[1] - a[1] ) @staticmethod def cell_compare(a, b) -> int: return ( (a[2] - b[2] if a[0] == b[0] else a[0] - b[0]) if b[1] == a[1] else b[1] - a[1] ) def reorder_pool_folder(grid_set: GridSet, fix_hole_in_grid: bool): grid_file = netCDF4.Dataset(grid_set.grid.fname + ".nc") grid = Grid.from_netCDF4(grid_file) grid_set.make_data_sets("row-major") p1 = np.array([[0.18511014, 0.79054856]]) p2 = np.array([[0.18593181, 0.79048109]]) right_direction_angle = np.squeeze(get_angle(p2 - p1)) mapping = create_structured_grid_mapping( grid, right_direction_angle, angle_threshold=np.deg2rad(15) ) v_grf = get_grf_ranges(grid, LocationType.Vertex) e_grf = get_grf_ranges(grid, LocationType.Edge) c_grf = get_grf_ranges(grid, LocationType.Cell) v_perm = argsort_simple( mapping.vertex_mapping, SimpleRowMajorSorting.vertex_compare, v_grf[0] ) e_perm = argsort_simple( mapping.edge_mapping, SimpleRowMajorSorting.edge_compare, e_grf[0] ) c_perm = argsort_simple( mapping.cell_mapping, SimpleRowMajorSorting.cell_compare, c_grf[0] ) for grid in grid_set: apply_permutation(grid.data_set, c_perm, grid.schema, LocationType.Cell) apply_permutation(grid.data_set, e_perm, grid.schema, LocationType.Edge) apply_permutation(grid.data_set, v_perm, grid.schema, LocationType.Vertex) if fix_hole_in_grid: fix_hole(grid_set.grid.data_set, grid_set.grid.schema) grid_set.sync_data_sets()
true
true
1c39e059a56049c710059e652ade0e3185fb9417
1,253
py
Python
examples/fastapi_app.py
euri10/starsessions
6bd258a0f94d30b6ec4a8da41910f97c5dabbe54
[ "MIT" ]
31
2021-07-15T13:00:06.000Z
2022-03-17T08:25:52.000Z
examples/fastapi_app.py
euri10/starsessions
6bd258a0f94d30b6ec4a8da41910f97c5dabbe54
[ "MIT" ]
6
2021-09-01T15:25:20.000Z
2022-03-13T07:29:19.000Z
examples/fastapi_app.py
euri10/starsessions
6bd258a0f94d30b6ec4a8da41910f97c5dabbe54
[ "MIT" ]
5
2021-08-19T04:46:35.000Z
2022-03-09T15:27:22.000Z
"""This examples demonstrates integration with FastAPI This example requires `fastapi` to be installed: > pip install fastapi Usage: > uvicorn examples.fastapi_app:app Access localhost:8000/set to set test session data, and access localhost:8000/clean to clear session data """ import datetime import typing as t from fastapi import FastAPI from fastapi.requests import Request from fastapi.responses import JSONResponse, RedirectResponse from starsessions import SessionMiddleware app = FastAPI() app.add_middleware(SessionMiddleware, secret_key='secret', autoload=True) @app.get('/', response_class=JSONResponse) async def homepage(request: Request) -> t.Mapping: ''' Access this view (GET '/') to display session contents. ''' return request.session @app.get('/set', response_class=RedirectResponse) async def set_time(request: Request) -> str: ''' Access this view (GET '/set') to set session contents. ''' request.session['date'] = datetime.datetime.now().isoformat() return '/' @app.get('/clean', response_class=RedirectResponse) async def clean(request: Request) -> str: ''' Access this view (GET '/clean') to remove all session contents. ''' request.session.clear() return '/'
25.571429
73
0.727853
import datetime import typing as t from fastapi import FastAPI from fastapi.requests import Request from fastapi.responses import JSONResponse, RedirectResponse from starsessions import SessionMiddleware app = FastAPI() app.add_middleware(SessionMiddleware, secret_key='secret', autoload=True) @app.get('/', response_class=JSONResponse) async def homepage(request: Request) -> t.Mapping: return request.session @app.get('/set', response_class=RedirectResponse) async def set_time(request: Request) -> str: request.session['date'] = datetime.datetime.now().isoformat() return '/' @app.get('/clean', response_class=RedirectResponse) async def clean(request: Request) -> str: request.session.clear() return '/'
true
true
1c39e0a1a6217c4f10bf7fdf63a9f7ab4623c775
658
py
Python
blender/arm/logicnode/math/LN_vector_clamp_to_size.py
Lykdraft/armory
da1cf33930ce9a8b1865d35c128fe4842bef2933
[ "Zlib" ]
null
null
null
blender/arm/logicnode/math/LN_vector_clamp_to_size.py
Lykdraft/armory
da1cf33930ce9a8b1865d35c128fe4842bef2933
[ "Zlib" ]
null
null
null
blender/arm/logicnode/math/LN_vector_clamp_to_size.py
Lykdraft/armory
da1cf33930ce9a8b1865d35c128fe4842bef2933
[ "Zlib" ]
null
null
null
from arm.logicnode.arm_nodes import * class VectorClampToSizeNode(ArmLogicTreeNode): """Use to keep the vector value inside the defined range.""" bl_idname = 'LNVectorClampToSizeNode' bl_label = 'Vector Clamp To Size' arm_version = 1 def init(self, context): super(VectorClampToSizeNode, self).init(context) self.add_input('NodeSocketVector', 'Vector In', default_value=[0.0, 0.0, 0.0]) self.add_input('NodeSocketFloat', 'Min') self.add_input('NodeSocketFloat', 'Max') self.add_output('NodeSocketVector', 'Vector Out') add_node(VectorClampToSizeNode, category=PKG_AS_CATEGORY, section='vector')
38.705882
86
0.709726
from arm.logicnode.arm_nodes import * class VectorClampToSizeNode(ArmLogicTreeNode): bl_idname = 'LNVectorClampToSizeNode' bl_label = 'Vector Clamp To Size' arm_version = 1 def init(self, context): super(VectorClampToSizeNode, self).init(context) self.add_input('NodeSocketVector', 'Vector In', default_value=[0.0, 0.0, 0.0]) self.add_input('NodeSocketFloat', 'Min') self.add_input('NodeSocketFloat', 'Max') self.add_output('NodeSocketVector', 'Vector Out') add_node(VectorClampToSizeNode, category=PKG_AS_CATEGORY, section='vector')
true
true
1c39e11671ad141a09092bdd7164187b5921998b
7,217
py
Python
influxdb_client/domain/slack_notification_rule_base.py
MASIFAYUB/influxdb-client-python
a067fa5670a6fbc600db2ac4e54e29e1b7124998
[ "MIT" ]
null
null
null
influxdb_client/domain/slack_notification_rule_base.py
MASIFAYUB/influxdb-client-python
a067fa5670a6fbc600db2ac4e54e29e1b7124998
[ "MIT" ]
null
null
null
influxdb_client/domain/slack_notification_rule_base.py
MASIFAYUB/influxdb-client-python
a067fa5670a6fbc600db2ac4e54e29e1b7124998
[ "MIT" ]
null
null
null
# coding: utf-8 """ InfluxDB OSS API Service. The InfluxDB v2 API provides a programmatic interface for all interactions with InfluxDB. Access the InfluxDB API using the `/api/v2/` endpoint. # noqa: E501 OpenAPI spec version: 2.0.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from influxdb_client.domain.notification_rule_discriminator import NotificationRuleDiscriminator class SlackNotificationRuleBase(NotificationRuleDiscriminator): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'type': 'str', 'channel': 'str', 'message_template': 'str', 'latest_completed': 'datetime', 'last_run_status': 'str', 'last_run_error': 'str', 'id': 'str', 'endpoint_id': 'str', 'org_id': 'str', 'task_id': 'str', 'owner_id': 'str', 'created_at': 'datetime', 'updated_at': 'datetime', 'status': 'TaskStatusType', 'name': 'str', 'sleep_until': 'str', 'every': 'str', 'offset': 'str', 'runbook_link': 'str', 'limit_every': 'int', 'limit': 'int', 'tag_rules': 'list[TagRule]', 'description': 'str', 'status_rules': 'list[StatusRule]', 'labels': 'list[Label]', 'links': 'NotificationRuleBaseLinks' } attribute_map = { 'type': 'type', 'channel': 'channel', 'message_template': 'messageTemplate', 'latest_completed': 'latestCompleted', 'last_run_status': 'lastRunStatus', 'last_run_error': 'lastRunError', 'id': 'id', 'endpoint_id': 'endpointID', 'org_id': 'orgID', 'task_id': 'taskID', 'owner_id': 'ownerID', 'created_at': 'createdAt', 'updated_at': 'updatedAt', 'status': 'status', 'name': 'name', 'sleep_until': 'sleepUntil', 'every': 'every', 'offset': 'offset', 'runbook_link': 'runbookLink', 'limit_every': 'limitEvery', 'limit': 'limit', 'tag_rules': 'tagRules', 'description': 'description', 'status_rules': 'statusRules', 'labels': 'labels', 'links': 'links' } def __init__(self, type=None, channel=None, message_template=None, latest_completed=None, last_run_status=None, last_run_error=None, id=None, endpoint_id=None, org_id=None, task_id=None, owner_id=None, created_at=None, updated_at=None, status=None, name=None, sleep_until=None, every=None, offset=None, runbook_link=None, limit_every=None, limit=None, tag_rules=None, description=None, status_rules=None, labels=None, links=None): # noqa: E501,D401,D403 """SlackNotificationRuleBase - a model defined in OpenAPI.""" # noqa: E501 NotificationRuleDiscriminator.__init__(self, latest_completed=latest_completed, last_run_status=last_run_status, last_run_error=last_run_error, id=id, endpoint_id=endpoint_id, org_id=org_id, task_id=task_id, owner_id=owner_id, created_at=created_at, updated_at=updated_at, status=status, name=name, sleep_until=sleep_until, every=every, offset=offset, runbook_link=runbook_link, limit_every=limit_every, limit=limit, tag_rules=tag_rules, description=description, status_rules=status_rules, labels=labels, links=links) # noqa: E501 self._type = None self._channel = None self._message_template = None self.discriminator = None self.type = type if channel is not None: self.channel = channel self.message_template = message_template @property def type(self): """Get the type of this SlackNotificationRuleBase. :return: The type of this SlackNotificationRuleBase. :rtype: str """ # noqa: E501 return self._type @type.setter def type(self, type): """Set the type of this SlackNotificationRuleBase. :param type: The type of this SlackNotificationRuleBase. :type: str """ # noqa: E501 if type is None: raise ValueError("Invalid value for `type`, must not be `None`") # noqa: E501 self._type = type @property def channel(self): """Get the channel of this SlackNotificationRuleBase. :return: The channel of this SlackNotificationRuleBase. :rtype: str """ # noqa: E501 return self._channel @channel.setter def channel(self, channel): """Set the channel of this SlackNotificationRuleBase. :param channel: The channel of this SlackNotificationRuleBase. :type: str """ # noqa: E501 self._channel = channel @property def message_template(self): """Get the message_template of this SlackNotificationRuleBase. :return: The message_template of this SlackNotificationRuleBase. :rtype: str """ # noqa: E501 return self._message_template @message_template.setter def message_template(self, message_template): """Set the message_template of this SlackNotificationRuleBase. :param message_template: The message_template of this SlackNotificationRuleBase. :type: str """ # noqa: E501 if message_template is None: raise ValueError("Invalid value for `message_template`, must not be `None`") # noqa: E501 self._message_template = message_template def to_dict(self): """Return the model properties as a dict.""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Return the string representation of the model.""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`.""" return self.to_str() def __eq__(self, other): """Return true if both objects are equal.""" if not isinstance(other, SlackNotificationRuleBase): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Return true if both objects are not equal.""" return not self == other
34.864734
539
0.608979
import pprint import re import six from influxdb_client.domain.notification_rule_discriminator import NotificationRuleDiscriminator class SlackNotificationRuleBase(NotificationRuleDiscriminator): openapi_types = { 'type': 'str', 'channel': 'str', 'message_template': 'str', 'latest_completed': 'datetime', 'last_run_status': 'str', 'last_run_error': 'str', 'id': 'str', 'endpoint_id': 'str', 'org_id': 'str', 'task_id': 'str', 'owner_id': 'str', 'created_at': 'datetime', 'updated_at': 'datetime', 'status': 'TaskStatusType', 'name': 'str', 'sleep_until': 'str', 'every': 'str', 'offset': 'str', 'runbook_link': 'str', 'limit_every': 'int', 'limit': 'int', 'tag_rules': 'list[TagRule]', 'description': 'str', 'status_rules': 'list[StatusRule]', 'labels': 'list[Label]', 'links': 'NotificationRuleBaseLinks' } attribute_map = { 'type': 'type', 'channel': 'channel', 'message_template': 'messageTemplate', 'latest_completed': 'latestCompleted', 'last_run_status': 'lastRunStatus', 'last_run_error': 'lastRunError', 'id': 'id', 'endpoint_id': 'endpointID', 'org_id': 'orgID', 'task_id': 'taskID', 'owner_id': 'ownerID', 'created_at': 'createdAt', 'updated_at': 'updatedAt', 'status': 'status', 'name': 'name', 'sleep_until': 'sleepUntil', 'every': 'every', 'offset': 'offset', 'runbook_link': 'runbookLink', 'limit_every': 'limitEvery', 'limit': 'limit', 'tag_rules': 'tagRules', 'description': 'description', 'status_rules': 'statusRules', 'labels': 'labels', 'links': 'links' } def __init__(self, type=None, channel=None, message_template=None, latest_completed=None, last_run_status=None, last_run_error=None, id=None, endpoint_id=None, org_id=None, task_id=None, owner_id=None, created_at=None, updated_at=None, status=None, name=None, sleep_until=None, every=None, offset=None, runbook_link=None, limit_every=None, limit=None, tag_rules=None, description=None, status_rules=None, labels=None, links=None): NotificationRuleDiscriminator.__init__(self, latest_completed=latest_completed, last_run_status=last_run_status, last_run_error=last_run_error, id=id, endpoint_id=endpoint_id, org_id=org_id, task_id=task_id, owner_id=owner_id, created_at=created_at, updated_at=updated_at, status=status, name=name, sleep_until=sleep_until, every=every, offset=offset, runbook_link=runbook_link, limit_every=limit_every, limit=limit, tag_rules=tag_rules, description=description, status_rules=status_rules, labels=labels, links=links) self._type = None self._channel = None self._message_template = None self.discriminator = None self.type = type if channel is not None: self.channel = channel self.message_template = message_template @property def type(self): return self._type @type.setter def type(self, type): if type is None: raise ValueError("Invalid value for `type`, must not be `None`") self._type = type @property def channel(self): return self._channel @channel.setter def channel(self, channel): self._channel = channel @property def message_template(self): return self._message_template @message_template.setter def message_template(self, message_template): if message_template is None: raise ValueError("Invalid value for `message_template`, must not be `None`") self._message_template = message_template def to_dict(self): result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, SlackNotificationRuleBase): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
1c39e1f46642f562a9a58cee4cfedac1f0c43963
762
py
Python
useGoogleTranslate.py
babebeebaboo/WordCookiesLIST
5909bdd6667ed3d18f6e008c2562d3483e609c7f
[ "MIT" ]
1
2021-07-07T21:07:56.000Z
2021-07-07T21:07:56.000Z
useGoogleTranslate.py
babebeebaboo/WordCookiesLIST
5909bdd6667ed3d18f6e008c2562d3483e609c7f
[ "MIT" ]
null
null
null
useGoogleTranslate.py
babebeebaboo/WordCookiesLIST
5909bdd6667ed3d18f6e008c2562d3483e609c7f
[ "MIT" ]
null
null
null
from googletrans import Translator import random import operator as op import math import sys import itertools def run(): length = int(input("Length(-1 to quit): ")) if length == -1 : sys.exit() translator = Translator() translateShuffleWord = [] shuffleWord = [] ans = [] for i in itertools.permutations(inp, length): word = ''.join(i) shuffleWord.append(word) ab = translator.translate(word, src='en', dest='ja') translateShuffleWord.append(ab.text.upper()) if word != ab.text.upper() : ans.append(word) ansSet = list(set(ans)) ansSet.sort() for i in ansSet: print(i) if __name__ == '__main__': inp = input("CHAR: ").upper() while True: run()
25.4
60
0.60105
from googletrans import Translator import random import operator as op import math import sys import itertools def run(): length = int(input("Length(-1 to quit): ")) if length == -1 : sys.exit() translator = Translator() translateShuffleWord = [] shuffleWord = [] ans = [] for i in itertools.permutations(inp, length): word = ''.join(i) shuffleWord.append(word) ab = translator.translate(word, src='en', dest='ja') translateShuffleWord.append(ab.text.upper()) if word != ab.text.upper() : ans.append(word) ansSet = list(set(ans)) ansSet.sort() for i in ansSet: print(i) if __name__ == '__main__': inp = input("CHAR: ").upper() while True: run()
true
true
1c39e2c26a297f9fffddc0d096b983f1e7b2c225
9,455
py
Python
bindings/python/capstone/sparc_const.py
arizvisa/capstone
e1998a28c4cacbf70f3d4ca148aa0eac23213475
[ "BSD-3-Clause" ]
null
null
null
bindings/python/capstone/sparc_const.py
arizvisa/capstone
e1998a28c4cacbf70f3d4ca148aa0eac23213475
[ "BSD-3-Clause" ]
null
null
null
bindings/python/capstone/sparc_const.py
arizvisa/capstone
e1998a28c4cacbf70f3d4ca148aa0eac23213475
[ "BSD-3-Clause" ]
null
null
null
# For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT [sparc_const.py] # Enums corresponding to Sparc condition codes, both icc's and fcc's. SPARC_CC_INVALID = 0 # Integer condition codes SPARC_CC_ICC_A = 8+256 SPARC_CC_ICC_N = 0+256 SPARC_CC_ICC_NE = 9+256 SPARC_CC_ICC_E = 1+256 SPARC_CC_ICC_G = 10+256 SPARC_CC_ICC_LE = 2+256 SPARC_CC_ICC_GE = 11+256 SPARC_CC_ICC_L = 3+256 SPARC_CC_ICC_GU = 12+256 SPARC_CC_ICC_LEU = 4+256 SPARC_CC_ICC_CC = 13+256 SPARC_CC_ICC_CS = 5+256 SPARC_CC_ICC_POS = 14+256 SPARC_CC_ICC_NEG = 6+256 SPARC_CC_ICC_VC = 15+256 SPARC_CC_ICC_VS = 7+256 # Floating condition codes SPARC_CC_FCC_A = 8+16+256 SPARC_CC_FCC_N = 0+16+256 SPARC_CC_FCC_U = 7+16+256 SPARC_CC_FCC_G = 6+16+256 SPARC_CC_FCC_UG = 5+16+256 SPARC_CC_FCC_L = 4+16+256 SPARC_CC_FCC_UL = 3+16+256 SPARC_CC_FCC_LG = 2+16+256 SPARC_CC_FCC_NE = 1+16+256 SPARC_CC_FCC_E = 9+16+256 SPARC_CC_FCC_UE = 10+16+256 SPARC_CC_FCC_GE = 11+16+256 SPARC_CC_FCC_UGE = 12+16+256 SPARC_CC_FCC_LE = 13+16+256 SPARC_CC_FCC_ULE = 14+16+256 SPARC_CC_FCC_O = 15+16+256 # Branch hint SPARC_HINT_INVALID = 0 SPARC_HINT_A = 1<<0 SPARC_HINT_PT = 1<<1 SPARC_HINT_PN = 1<<2 # Operand type for instruction's operands SPARC_OP_INVALID = 0 SPARC_OP_REG = 1 SPARC_OP_IMM = 2 SPARC_OP_MEM = 3 # SPARC registers SPARC_REG_INVALID = 0 SPARC_REG_F0 = 1 SPARC_REG_F1 = 2 SPARC_REG_F2 = 3 SPARC_REG_F3 = 4 SPARC_REG_F4 = 5 SPARC_REG_F5 = 6 SPARC_REG_F6 = 7 SPARC_REG_F7 = 8 SPARC_REG_F8 = 9 SPARC_REG_F9 = 10 SPARC_REG_F10 = 11 SPARC_REG_F11 = 12 SPARC_REG_F12 = 13 SPARC_REG_F13 = 14 SPARC_REG_F14 = 15 SPARC_REG_F15 = 16 SPARC_REG_F16 = 17 SPARC_REG_F17 = 18 SPARC_REG_F18 = 19 SPARC_REG_F19 = 20 SPARC_REG_F20 = 21 SPARC_REG_F21 = 22 SPARC_REG_F22 = 23 SPARC_REG_F23 = 24 SPARC_REG_F24 = 25 SPARC_REG_F25 = 26 SPARC_REG_F26 = 27 SPARC_REG_F27 = 28 SPARC_REG_F28 = 29 SPARC_REG_F29 = 30 SPARC_REG_F30 = 31 SPARC_REG_F31 = 32 SPARC_REG_F32 = 33 SPARC_REG_F34 = 34 SPARC_REG_F36 = 35 SPARC_REG_F38 = 36 SPARC_REG_F40 = 37 SPARC_REG_F42 = 38 SPARC_REG_F44 = 39 SPARC_REG_F46 = 40 SPARC_REG_F48 = 41 SPARC_REG_F50 = 42 SPARC_REG_F52 = 43 SPARC_REG_F54 = 44 SPARC_REG_F56 = 45 SPARC_REG_F58 = 46 SPARC_REG_F60 = 47 SPARC_REG_F62 = 48 SPARC_REG_FCC0 = 49 SPARC_REG_FCC1 = 50 SPARC_REG_FCC2 = 51 SPARC_REG_FCC3 = 52 SPARC_REG_FP = 53 SPARC_REG_G0 = 54 SPARC_REG_G1 = 55 SPARC_REG_G2 = 56 SPARC_REG_G3 = 57 SPARC_REG_G4 = 58 SPARC_REG_G5 = 59 SPARC_REG_G6 = 60 SPARC_REG_G7 = 61 SPARC_REG_I0 = 62 SPARC_REG_I1 = 63 SPARC_REG_I2 = 64 SPARC_REG_I3 = 65 SPARC_REG_I4 = 66 SPARC_REG_I5 = 67 SPARC_REG_I7 = 68 SPARC_REG_ICC = 69 SPARC_REG_L0 = 70 SPARC_REG_L1 = 71 SPARC_REG_L2 = 72 SPARC_REG_L3 = 73 SPARC_REG_L4 = 74 SPARC_REG_L5 = 75 SPARC_REG_L6 = 76 SPARC_REG_L7 = 77 SPARC_REG_O0 = 78 SPARC_REG_O1 = 79 SPARC_REG_O2 = 80 SPARC_REG_O3 = 81 SPARC_REG_O4 = 82 SPARC_REG_O5 = 83 SPARC_REG_O7 = 84 SPARC_REG_SP = 85 SPARC_REG_Y = 86 SPARC_REG_MAX = 87 SPARC_REG_O6 = SPARC_REG_SP SPARC_REG_I6 = SPARC_REG_FP # SPARC instruction SPARC_INS_INVALID = 0 SPARC_INS_ADDCC = 1 SPARC_INS_ADDX = 2 SPARC_INS_ADDXCC = 3 SPARC_INS_ADDXC = 4 SPARC_INS_ADDXCCC = 5 SPARC_INS_ADD = 6 SPARC_INS_ALIGNADDR = 7 SPARC_INS_ALIGNADDRL = 8 SPARC_INS_ANDCC = 9 SPARC_INS_ANDNCC = 10 SPARC_INS_ANDN = 11 SPARC_INS_AND = 12 SPARC_INS_ARRAY16 = 13 SPARC_INS_ARRAY32 = 14 SPARC_INS_ARRAY8 = 15 SPARC_INS_BA = 16 SPARC_INS_B = 17 SPARC_INS_JMP = 18 SPARC_INS_BMASK = 19 SPARC_INS_FB = 20 SPARC_INS_BRGEZ = 21 SPARC_INS_BRGZ = 22 SPARC_INS_BRLEZ = 23 SPARC_INS_BRLZ = 24 SPARC_INS_BRNZ = 25 SPARC_INS_BRZ = 26 SPARC_INS_BSHUFFLE = 27 SPARC_INS_CALL = 28 SPARC_INS_CASX = 29 SPARC_INS_CAS = 30 SPARC_INS_CMASK16 = 31 SPARC_INS_CMASK32 = 32 SPARC_INS_CMASK8 = 33 SPARC_INS_CMP = 34 SPARC_INS_EDGE16 = 35 SPARC_INS_EDGE16L = 36 SPARC_INS_EDGE16LN = 37 SPARC_INS_EDGE16N = 38 SPARC_INS_EDGE32 = 39 SPARC_INS_EDGE32L = 40 SPARC_INS_EDGE32LN = 41 SPARC_INS_EDGE32N = 42 SPARC_INS_EDGE8 = 43 SPARC_INS_EDGE8L = 44 SPARC_INS_EDGE8LN = 45 SPARC_INS_EDGE8N = 46 SPARC_INS_FABSD = 47 SPARC_INS_FABSQ = 48 SPARC_INS_FABSS = 49 SPARC_INS_FADDD = 50 SPARC_INS_FADDQ = 51 SPARC_INS_FADDS = 52 SPARC_INS_FALIGNDATA = 53 SPARC_INS_FAND = 54 SPARC_INS_FANDNOT1 = 55 SPARC_INS_FANDNOT1S = 56 SPARC_INS_FANDNOT2 = 57 SPARC_INS_FANDNOT2S = 58 SPARC_INS_FANDS = 59 SPARC_INS_FCHKSM16 = 60 SPARC_INS_FCMPD = 61 SPARC_INS_FCMPEQ16 = 62 SPARC_INS_FCMPEQ32 = 63 SPARC_INS_FCMPGT16 = 64 SPARC_INS_FCMPGT32 = 65 SPARC_INS_FCMPLE16 = 66 SPARC_INS_FCMPLE32 = 67 SPARC_INS_FCMPNE16 = 68 SPARC_INS_FCMPNE32 = 69 SPARC_INS_FCMPQ = 70 SPARC_INS_FCMPS = 71 SPARC_INS_FDIVD = 72 SPARC_INS_FDIVQ = 73 SPARC_INS_FDIVS = 74 SPARC_INS_FDMULQ = 75 SPARC_INS_FDTOI = 76 SPARC_INS_FDTOQ = 77 SPARC_INS_FDTOS = 78 SPARC_INS_FDTOX = 79 SPARC_INS_FEXPAND = 80 SPARC_INS_FHADDD = 81 SPARC_INS_FHADDS = 82 SPARC_INS_FHSUBD = 83 SPARC_INS_FHSUBS = 84 SPARC_INS_FITOD = 85 SPARC_INS_FITOQ = 86 SPARC_INS_FITOS = 87 SPARC_INS_FLCMPD = 88 SPARC_INS_FLCMPS = 89 SPARC_INS_FLUSHW = 90 SPARC_INS_FMEAN16 = 91 SPARC_INS_FMOVD = 92 SPARC_INS_FMOVQ = 93 SPARC_INS_FMOVRDGEZ = 94 SPARC_INS_FMOVRQGEZ = 95 SPARC_INS_FMOVRSGEZ = 96 SPARC_INS_FMOVRDGZ = 97 SPARC_INS_FMOVRQGZ = 98 SPARC_INS_FMOVRSGZ = 99 SPARC_INS_FMOVRDLEZ = 100 SPARC_INS_FMOVRQLEZ = 101 SPARC_INS_FMOVRSLEZ = 102 SPARC_INS_FMOVRDLZ = 103 SPARC_INS_FMOVRQLZ = 104 SPARC_INS_FMOVRSLZ = 105 SPARC_INS_FMOVRDNZ = 106 SPARC_INS_FMOVRQNZ = 107 SPARC_INS_FMOVRSNZ = 108 SPARC_INS_FMOVRDZ = 109 SPARC_INS_FMOVRQZ = 110 SPARC_INS_FMOVRSZ = 111 SPARC_INS_FMOVS = 112 SPARC_INS_FMUL8SUX16 = 113 SPARC_INS_FMUL8ULX16 = 114 SPARC_INS_FMUL8X16 = 115 SPARC_INS_FMUL8X16AL = 116 SPARC_INS_FMUL8X16AU = 117 SPARC_INS_FMULD = 118 SPARC_INS_FMULD8SUX16 = 119 SPARC_INS_FMULD8ULX16 = 120 SPARC_INS_FMULQ = 121 SPARC_INS_FMULS = 122 SPARC_INS_FNADDD = 123 SPARC_INS_FNADDS = 124 SPARC_INS_FNAND = 125 SPARC_INS_FNANDS = 126 SPARC_INS_FNEGD = 127 SPARC_INS_FNEGQ = 128 SPARC_INS_FNEGS = 129 SPARC_INS_FNHADDD = 130 SPARC_INS_FNHADDS = 131 SPARC_INS_FNOR = 132 SPARC_INS_FNORS = 133 SPARC_INS_FNOT1 = 134 SPARC_INS_FNOT1S = 135 SPARC_INS_FNOT2 = 136 SPARC_INS_FNOT2S = 137 SPARC_INS_FONE = 138 SPARC_INS_FONES = 139 SPARC_INS_FOR = 140 SPARC_INS_FORNOT1 = 141 SPARC_INS_FORNOT1S = 142 SPARC_INS_FORNOT2 = 143 SPARC_INS_FORNOT2S = 144 SPARC_INS_FORS = 145 SPARC_INS_FPACK16 = 146 SPARC_INS_FPACK32 = 147 SPARC_INS_FPACKFIX = 148 SPARC_INS_FPADD16 = 149 SPARC_INS_FPADD16S = 150 SPARC_INS_FPADD32 = 151 SPARC_INS_FPADD32S = 152 SPARC_INS_FPADD64 = 153 SPARC_INS_FPMERGE = 154 SPARC_INS_FPSUB16 = 155 SPARC_INS_FPSUB16S = 156 SPARC_INS_FPSUB32 = 157 SPARC_INS_FPSUB32S = 158 SPARC_INS_FQTOD = 159 SPARC_INS_FQTOI = 160 SPARC_INS_FQTOS = 161 SPARC_INS_FQTOX = 162 SPARC_INS_FSLAS16 = 163 SPARC_INS_FSLAS32 = 164 SPARC_INS_FSLL16 = 165 SPARC_INS_FSLL32 = 166 SPARC_INS_FSMULD = 167 SPARC_INS_FSQRTD = 168 SPARC_INS_FSQRTQ = 169 SPARC_INS_FSQRTS = 170 SPARC_INS_FSRA16 = 171 SPARC_INS_FSRA32 = 172 SPARC_INS_FSRC1 = 173 SPARC_INS_FSRC1S = 174 SPARC_INS_FSRC2 = 175 SPARC_INS_FSRC2S = 176 SPARC_INS_FSRL16 = 177 SPARC_INS_FSRL32 = 178 SPARC_INS_FSTOD = 179 SPARC_INS_FSTOI = 180 SPARC_INS_FSTOQ = 181 SPARC_INS_FSTOX = 182 SPARC_INS_FSUBD = 183 SPARC_INS_FSUBQ = 184 SPARC_INS_FSUBS = 185 SPARC_INS_FXNOR = 186 SPARC_INS_FXNORS = 187 SPARC_INS_FXOR = 188 SPARC_INS_FXORS = 189 SPARC_INS_FXTOD = 190 SPARC_INS_FXTOQ = 191 SPARC_INS_FXTOS = 192 SPARC_INS_FZERO = 193 SPARC_INS_FZEROS = 194 SPARC_INS_JMPL = 195 SPARC_INS_LDD = 196 SPARC_INS_LD = 197 SPARC_INS_LDQ = 198 SPARC_INS_LDSB = 199 SPARC_INS_LDSH = 200 SPARC_INS_LDSW = 201 SPARC_INS_LDUB = 202 SPARC_INS_LDUH = 203 SPARC_INS_LDX = 204 SPARC_INS_LZCNT = 205 SPARC_INS_MEMBAR = 206 SPARC_INS_MOVDTOX = 207 SPARC_INS_MOV = 208 SPARC_INS_MOVRGEZ = 209 SPARC_INS_MOVRGZ = 210 SPARC_INS_MOVRLEZ = 211 SPARC_INS_MOVRLZ = 212 SPARC_INS_MOVRNZ = 213 SPARC_INS_MOVRZ = 214 SPARC_INS_MOVSTOSW = 215 SPARC_INS_MOVSTOUW = 216 SPARC_INS_MULX = 217 SPARC_INS_NOP = 218 SPARC_INS_ORCC = 219 SPARC_INS_ORNCC = 220 SPARC_INS_ORN = 221 SPARC_INS_OR = 222 SPARC_INS_PDIST = 223 SPARC_INS_PDISTN = 224 SPARC_INS_POPC = 225 SPARC_INS_RD = 226 SPARC_INS_RESTORE = 227 SPARC_INS_RETT = 228 SPARC_INS_SAVE = 229 SPARC_INS_SDIVCC = 230 SPARC_INS_SDIVX = 231 SPARC_INS_SDIV = 232 SPARC_INS_SETHI = 233 SPARC_INS_SHUTDOWN = 234 SPARC_INS_SIAM = 235 SPARC_INS_SLLX = 236 SPARC_INS_SLL = 237 SPARC_INS_SMULCC = 238 SPARC_INS_SMUL = 239 SPARC_INS_SRAX = 240 SPARC_INS_SRA = 241 SPARC_INS_SRLX = 242 SPARC_INS_SRL = 243 SPARC_INS_STBAR = 244 SPARC_INS_STB = 245 SPARC_INS_STD = 246 SPARC_INS_ST = 247 SPARC_INS_STH = 248 SPARC_INS_STQ = 249 SPARC_INS_STX = 250 SPARC_INS_SUBCC = 251 SPARC_INS_SUBX = 252 SPARC_INS_SUBXCC = 253 SPARC_INS_SUB = 254 SPARC_INS_SWAP = 255 SPARC_INS_TA = 256 SPARC_INS_TADDCCTV = 257 SPARC_INS_TADDCC = 258 SPARC_INS_T = 259 SPARC_INS_TSUBCCTV = 260 SPARC_INS_TSUBCC = 261 SPARC_INS_UDIVCC = 262 SPARC_INS_UDIVX = 263 SPARC_INS_UDIV = 264 SPARC_INS_UMULCC = 265 SPARC_INS_UMULXHI = 266 SPARC_INS_UMUL = 267 SPARC_INS_UNIMP = 268 SPARC_INS_FCMPED = 269 SPARC_INS_FCMPEQ = 270 SPARC_INS_FCMPES = 271 SPARC_INS_WR = 272 SPARC_INS_XMULX = 273 SPARC_INS_XMULXHI = 274 SPARC_INS_XNORCC = 275 SPARC_INS_XNOR = 276 SPARC_INS_XORCC = 277 SPARC_INS_XOR = 278 SPARC_INS_MAX = 279 # Group of SPARC instructions SPARC_GRP_INVALID = 0 SPARC_GRP_HARDQUAD = 1 SPARC_GRP_V9 = 2 SPARC_GRP_VIS = 3 SPARC_GRP_VIS2 = 4 SPARC_GRP_VIS3 = 5 SPARC_GRP_32BIT = 6 SPARC_GRP_64BIT = 7 SPARC_GRP_JUMP = 8 SPARC_GRP_MAX = 9
21.247191
72
0.807403
SPARC_CC_INVALID = 0 SPARC_CC_ICC_A = 8+256 SPARC_CC_ICC_N = 0+256 SPARC_CC_ICC_NE = 9+256 SPARC_CC_ICC_E = 1+256 SPARC_CC_ICC_G = 10+256 SPARC_CC_ICC_LE = 2+256 SPARC_CC_ICC_GE = 11+256 SPARC_CC_ICC_L = 3+256 SPARC_CC_ICC_GU = 12+256 SPARC_CC_ICC_LEU = 4+256 SPARC_CC_ICC_CC = 13+256 SPARC_CC_ICC_CS = 5+256 SPARC_CC_ICC_POS = 14+256 SPARC_CC_ICC_NEG = 6+256 SPARC_CC_ICC_VC = 15+256 SPARC_CC_ICC_VS = 7+256 SPARC_CC_FCC_A = 8+16+256 SPARC_CC_FCC_N = 0+16+256 SPARC_CC_FCC_U = 7+16+256 SPARC_CC_FCC_G = 6+16+256 SPARC_CC_FCC_UG = 5+16+256 SPARC_CC_FCC_L = 4+16+256 SPARC_CC_FCC_UL = 3+16+256 SPARC_CC_FCC_LG = 2+16+256 SPARC_CC_FCC_NE = 1+16+256 SPARC_CC_FCC_E = 9+16+256 SPARC_CC_FCC_UE = 10+16+256 SPARC_CC_FCC_GE = 11+16+256 SPARC_CC_FCC_UGE = 12+16+256 SPARC_CC_FCC_LE = 13+16+256 SPARC_CC_FCC_ULE = 14+16+256 SPARC_CC_FCC_O = 15+16+256 SPARC_HINT_INVALID = 0 SPARC_HINT_A = 1<<0 SPARC_HINT_PT = 1<<1 SPARC_HINT_PN = 1<<2 SPARC_OP_INVALID = 0 SPARC_OP_REG = 1 SPARC_OP_IMM = 2 SPARC_OP_MEM = 3 # SPARC registers SPARC_REG_INVALID = 0 SPARC_REG_F0 = 1 SPARC_REG_F1 = 2 SPARC_REG_F2 = 3 SPARC_REG_F3 = 4 SPARC_REG_F4 = 5 SPARC_REG_F5 = 6 SPARC_REG_F6 = 7 SPARC_REG_F7 = 8 SPARC_REG_F8 = 9 SPARC_REG_F9 = 10 SPARC_REG_F10 = 11 SPARC_REG_F11 = 12 SPARC_REG_F12 = 13 SPARC_REG_F13 = 14 SPARC_REG_F14 = 15 SPARC_REG_F15 = 16 SPARC_REG_F16 = 17 SPARC_REG_F17 = 18 SPARC_REG_F18 = 19 SPARC_REG_F19 = 20 SPARC_REG_F20 = 21 SPARC_REG_F21 = 22 SPARC_REG_F22 = 23 SPARC_REG_F23 = 24 SPARC_REG_F24 = 25 SPARC_REG_F25 = 26 SPARC_REG_F26 = 27 SPARC_REG_F27 = 28 SPARC_REG_F28 = 29 SPARC_REG_F29 = 30 SPARC_REG_F30 = 31 SPARC_REG_F31 = 32 SPARC_REG_F32 = 33 SPARC_REG_F34 = 34 SPARC_REG_F36 = 35 SPARC_REG_F38 = 36 SPARC_REG_F40 = 37 SPARC_REG_F42 = 38 SPARC_REG_F44 = 39 SPARC_REG_F46 = 40 SPARC_REG_F48 = 41 SPARC_REG_F50 = 42 SPARC_REG_F52 = 43 SPARC_REG_F54 = 44 SPARC_REG_F56 = 45 SPARC_REG_F58 = 46 SPARC_REG_F60 = 47 SPARC_REG_F62 = 48 SPARC_REG_FCC0 = 49 SPARC_REG_FCC1 = 50 SPARC_REG_FCC2 = 51 SPARC_REG_FCC3 = 52 SPARC_REG_FP = 53 SPARC_REG_G0 = 54 SPARC_REG_G1 = 55 SPARC_REG_G2 = 56 SPARC_REG_G3 = 57 SPARC_REG_G4 = 58 SPARC_REG_G5 = 59 SPARC_REG_G6 = 60 SPARC_REG_G7 = 61 SPARC_REG_I0 = 62 SPARC_REG_I1 = 63 SPARC_REG_I2 = 64 SPARC_REG_I3 = 65 SPARC_REG_I4 = 66 SPARC_REG_I5 = 67 SPARC_REG_I7 = 68 SPARC_REG_ICC = 69 SPARC_REG_L0 = 70 SPARC_REG_L1 = 71 SPARC_REG_L2 = 72 SPARC_REG_L3 = 73 SPARC_REG_L4 = 74 SPARC_REG_L5 = 75 SPARC_REG_L6 = 76 SPARC_REG_L7 = 77 SPARC_REG_O0 = 78 SPARC_REG_O1 = 79 SPARC_REG_O2 = 80 SPARC_REG_O3 = 81 SPARC_REG_O4 = 82 SPARC_REG_O5 = 83 SPARC_REG_O7 = 84 SPARC_REG_SP = 85 SPARC_REG_Y = 86 SPARC_REG_MAX = 87 SPARC_REG_O6 = SPARC_REG_SP SPARC_REG_I6 = SPARC_REG_FP # SPARC instruction SPARC_INS_INVALID = 0 SPARC_INS_ADDCC = 1 SPARC_INS_ADDX = 2 SPARC_INS_ADDXCC = 3 SPARC_INS_ADDXC = 4 SPARC_INS_ADDXCCC = 5 SPARC_INS_ADD = 6 SPARC_INS_ALIGNADDR = 7 SPARC_INS_ALIGNADDRL = 8 SPARC_INS_ANDCC = 9 SPARC_INS_ANDNCC = 10 SPARC_INS_ANDN = 11 SPARC_INS_AND = 12 SPARC_INS_ARRAY16 = 13 SPARC_INS_ARRAY32 = 14 SPARC_INS_ARRAY8 = 15 SPARC_INS_BA = 16 SPARC_INS_B = 17 SPARC_INS_JMP = 18 SPARC_INS_BMASK = 19 SPARC_INS_FB = 20 SPARC_INS_BRGEZ = 21 SPARC_INS_BRGZ = 22 SPARC_INS_BRLEZ = 23 SPARC_INS_BRLZ = 24 SPARC_INS_BRNZ = 25 SPARC_INS_BRZ = 26 SPARC_INS_BSHUFFLE = 27 SPARC_INS_CALL = 28 SPARC_INS_CASX = 29 SPARC_INS_CAS = 30 SPARC_INS_CMASK16 = 31 SPARC_INS_CMASK32 = 32 SPARC_INS_CMASK8 = 33 SPARC_INS_CMP = 34 SPARC_INS_EDGE16 = 35 SPARC_INS_EDGE16L = 36 SPARC_INS_EDGE16LN = 37 SPARC_INS_EDGE16N = 38 SPARC_INS_EDGE32 = 39 SPARC_INS_EDGE32L = 40 SPARC_INS_EDGE32LN = 41 SPARC_INS_EDGE32N = 42 SPARC_INS_EDGE8 = 43 SPARC_INS_EDGE8L = 44 SPARC_INS_EDGE8LN = 45 SPARC_INS_EDGE8N = 46 SPARC_INS_FABSD = 47 SPARC_INS_FABSQ = 48 SPARC_INS_FABSS = 49 SPARC_INS_FADDD = 50 SPARC_INS_FADDQ = 51 SPARC_INS_FADDS = 52 SPARC_INS_FALIGNDATA = 53 SPARC_INS_FAND = 54 SPARC_INS_FANDNOT1 = 55 SPARC_INS_FANDNOT1S = 56 SPARC_INS_FANDNOT2 = 57 SPARC_INS_FANDNOT2S = 58 SPARC_INS_FANDS = 59 SPARC_INS_FCHKSM16 = 60 SPARC_INS_FCMPD = 61 SPARC_INS_FCMPEQ16 = 62 SPARC_INS_FCMPEQ32 = 63 SPARC_INS_FCMPGT16 = 64 SPARC_INS_FCMPGT32 = 65 SPARC_INS_FCMPLE16 = 66 SPARC_INS_FCMPLE32 = 67 SPARC_INS_FCMPNE16 = 68 SPARC_INS_FCMPNE32 = 69 SPARC_INS_FCMPQ = 70 SPARC_INS_FCMPS = 71 SPARC_INS_FDIVD = 72 SPARC_INS_FDIVQ = 73 SPARC_INS_FDIVS = 74 SPARC_INS_FDMULQ = 75 SPARC_INS_FDTOI = 76 SPARC_INS_FDTOQ = 77 SPARC_INS_FDTOS = 78 SPARC_INS_FDTOX = 79 SPARC_INS_FEXPAND = 80 SPARC_INS_FHADDD = 81 SPARC_INS_FHADDS = 82 SPARC_INS_FHSUBD = 83 SPARC_INS_FHSUBS = 84 SPARC_INS_FITOD = 85 SPARC_INS_FITOQ = 86 SPARC_INS_FITOS = 87 SPARC_INS_FLCMPD = 88 SPARC_INS_FLCMPS = 89 SPARC_INS_FLUSHW = 90 SPARC_INS_FMEAN16 = 91 SPARC_INS_FMOVD = 92 SPARC_INS_FMOVQ = 93 SPARC_INS_FMOVRDGEZ = 94 SPARC_INS_FMOVRQGEZ = 95 SPARC_INS_FMOVRSGEZ = 96 SPARC_INS_FMOVRDGZ = 97 SPARC_INS_FMOVRQGZ = 98 SPARC_INS_FMOVRSGZ = 99 SPARC_INS_FMOVRDLEZ = 100 SPARC_INS_FMOVRQLEZ = 101 SPARC_INS_FMOVRSLEZ = 102 SPARC_INS_FMOVRDLZ = 103 SPARC_INS_FMOVRQLZ = 104 SPARC_INS_FMOVRSLZ = 105 SPARC_INS_FMOVRDNZ = 106 SPARC_INS_FMOVRQNZ = 107 SPARC_INS_FMOVRSNZ = 108 SPARC_INS_FMOVRDZ = 109 SPARC_INS_FMOVRQZ = 110 SPARC_INS_FMOVRSZ = 111 SPARC_INS_FMOVS = 112 SPARC_INS_FMUL8SUX16 = 113 SPARC_INS_FMUL8ULX16 = 114 SPARC_INS_FMUL8X16 = 115 SPARC_INS_FMUL8X16AL = 116 SPARC_INS_FMUL8X16AU = 117 SPARC_INS_FMULD = 118 SPARC_INS_FMULD8SUX16 = 119 SPARC_INS_FMULD8ULX16 = 120 SPARC_INS_FMULQ = 121 SPARC_INS_FMULS = 122 SPARC_INS_FNADDD = 123 SPARC_INS_FNADDS = 124 SPARC_INS_FNAND = 125 SPARC_INS_FNANDS = 126 SPARC_INS_FNEGD = 127 SPARC_INS_FNEGQ = 128 SPARC_INS_FNEGS = 129 SPARC_INS_FNHADDD = 130 SPARC_INS_FNHADDS = 131 SPARC_INS_FNOR = 132 SPARC_INS_FNORS = 133 SPARC_INS_FNOT1 = 134 SPARC_INS_FNOT1S = 135 SPARC_INS_FNOT2 = 136 SPARC_INS_FNOT2S = 137 SPARC_INS_FONE = 138 SPARC_INS_FONES = 139 SPARC_INS_FOR = 140 SPARC_INS_FORNOT1 = 141 SPARC_INS_FORNOT1S = 142 SPARC_INS_FORNOT2 = 143 SPARC_INS_FORNOT2S = 144 SPARC_INS_FORS = 145 SPARC_INS_FPACK16 = 146 SPARC_INS_FPACK32 = 147 SPARC_INS_FPACKFIX = 148 SPARC_INS_FPADD16 = 149 SPARC_INS_FPADD16S = 150 SPARC_INS_FPADD32 = 151 SPARC_INS_FPADD32S = 152 SPARC_INS_FPADD64 = 153 SPARC_INS_FPMERGE = 154 SPARC_INS_FPSUB16 = 155 SPARC_INS_FPSUB16S = 156 SPARC_INS_FPSUB32 = 157 SPARC_INS_FPSUB32S = 158 SPARC_INS_FQTOD = 159 SPARC_INS_FQTOI = 160 SPARC_INS_FQTOS = 161 SPARC_INS_FQTOX = 162 SPARC_INS_FSLAS16 = 163 SPARC_INS_FSLAS32 = 164 SPARC_INS_FSLL16 = 165 SPARC_INS_FSLL32 = 166 SPARC_INS_FSMULD = 167 SPARC_INS_FSQRTD = 168 SPARC_INS_FSQRTQ = 169 SPARC_INS_FSQRTS = 170 SPARC_INS_FSRA16 = 171 SPARC_INS_FSRA32 = 172 SPARC_INS_FSRC1 = 173 SPARC_INS_FSRC1S = 174 SPARC_INS_FSRC2 = 175 SPARC_INS_FSRC2S = 176 SPARC_INS_FSRL16 = 177 SPARC_INS_FSRL32 = 178 SPARC_INS_FSTOD = 179 SPARC_INS_FSTOI = 180 SPARC_INS_FSTOQ = 181 SPARC_INS_FSTOX = 182 SPARC_INS_FSUBD = 183 SPARC_INS_FSUBQ = 184 SPARC_INS_FSUBS = 185 SPARC_INS_FXNOR = 186 SPARC_INS_FXNORS = 187 SPARC_INS_FXOR = 188 SPARC_INS_FXORS = 189 SPARC_INS_FXTOD = 190 SPARC_INS_FXTOQ = 191 SPARC_INS_FXTOS = 192 SPARC_INS_FZERO = 193 SPARC_INS_FZEROS = 194 SPARC_INS_JMPL = 195 SPARC_INS_LDD = 196 SPARC_INS_LD = 197 SPARC_INS_LDQ = 198 SPARC_INS_LDSB = 199 SPARC_INS_LDSH = 200 SPARC_INS_LDSW = 201 SPARC_INS_LDUB = 202 SPARC_INS_LDUH = 203 SPARC_INS_LDX = 204 SPARC_INS_LZCNT = 205 SPARC_INS_MEMBAR = 206 SPARC_INS_MOVDTOX = 207 SPARC_INS_MOV = 208 SPARC_INS_MOVRGEZ = 209 SPARC_INS_MOVRGZ = 210 SPARC_INS_MOVRLEZ = 211 SPARC_INS_MOVRLZ = 212 SPARC_INS_MOVRNZ = 213 SPARC_INS_MOVRZ = 214 SPARC_INS_MOVSTOSW = 215 SPARC_INS_MOVSTOUW = 216 SPARC_INS_MULX = 217 SPARC_INS_NOP = 218 SPARC_INS_ORCC = 219 SPARC_INS_ORNCC = 220 SPARC_INS_ORN = 221 SPARC_INS_OR = 222 SPARC_INS_PDIST = 223 SPARC_INS_PDISTN = 224 SPARC_INS_POPC = 225 SPARC_INS_RD = 226 SPARC_INS_RESTORE = 227 SPARC_INS_RETT = 228 SPARC_INS_SAVE = 229 SPARC_INS_SDIVCC = 230 SPARC_INS_SDIVX = 231 SPARC_INS_SDIV = 232 SPARC_INS_SETHI = 233 SPARC_INS_SHUTDOWN = 234 SPARC_INS_SIAM = 235 SPARC_INS_SLLX = 236 SPARC_INS_SLL = 237 SPARC_INS_SMULCC = 238 SPARC_INS_SMUL = 239 SPARC_INS_SRAX = 240 SPARC_INS_SRA = 241 SPARC_INS_SRLX = 242 SPARC_INS_SRL = 243 SPARC_INS_STBAR = 244 SPARC_INS_STB = 245 SPARC_INS_STD = 246 SPARC_INS_ST = 247 SPARC_INS_STH = 248 SPARC_INS_STQ = 249 SPARC_INS_STX = 250 SPARC_INS_SUBCC = 251 SPARC_INS_SUBX = 252 SPARC_INS_SUBXCC = 253 SPARC_INS_SUB = 254 SPARC_INS_SWAP = 255 SPARC_INS_TA = 256 SPARC_INS_TADDCCTV = 257 SPARC_INS_TADDCC = 258 SPARC_INS_T = 259 SPARC_INS_TSUBCCTV = 260 SPARC_INS_TSUBCC = 261 SPARC_INS_UDIVCC = 262 SPARC_INS_UDIVX = 263 SPARC_INS_UDIV = 264 SPARC_INS_UMULCC = 265 SPARC_INS_UMULXHI = 266 SPARC_INS_UMUL = 267 SPARC_INS_UNIMP = 268 SPARC_INS_FCMPED = 269 SPARC_INS_FCMPEQ = 270 SPARC_INS_FCMPES = 271 SPARC_INS_WR = 272 SPARC_INS_XMULX = 273 SPARC_INS_XMULXHI = 274 SPARC_INS_XNORCC = 275 SPARC_INS_XNOR = 276 SPARC_INS_XORCC = 277 SPARC_INS_XOR = 278 SPARC_INS_MAX = 279 # Group of SPARC instructions SPARC_GRP_INVALID = 0 SPARC_GRP_HARDQUAD = 1 SPARC_GRP_V9 = 2 SPARC_GRP_VIS = 3 SPARC_GRP_VIS2 = 4 SPARC_GRP_VIS3 = 5 SPARC_GRP_32BIT = 6 SPARC_GRP_64BIT = 7 SPARC_GRP_JUMP = 8 SPARC_GRP_MAX = 9
true
true
1c39e2fab3f7eb9a227fdeba5b0d6ed471103be8
473
py
Python
content/posts/faking-python-imports/code/main.py
NathanVaughn/blog.nathanv.me-hugo
381955333a497914b1e1d1e26db37ccbda86923e
[ "MIT" ]
1
2020-01-30T16:02:38.000Z
2020-01-30T16:02:38.000Z
content/posts/faking-python-imports/code/main.py
NathanVaughn/blog.nathanv.me-hugo
381955333a497914b1e1d1e26db37ccbda86923e
[ "MIT" ]
14
2019-09-16T05:51:28.000Z
2021-10-15T00:16:56.000Z
content/posts/faking-python-imports/code/main.py
NathanVaughn/blog.nathanv.me-hugo
381955333a497914b1e1d1e26db37ccbda86923e
[ "MIT" ]
null
null
null
import sys import c VAL = 20 print("The real value of c.func is: {}".format(c.func(VAL))) # ideally, you would have never imported this module sys.modules.pop("c") # create reference to real import so we don't lose it a_real_import = __import__("a") a_fake_import = __import__("b") # fake the import sys.modules["a"] = a_fake_import import c # set it back to the real value sys.modules["a"] = a_real_import print("The fake value of c.func is: {}".format(c.func(VAL)))
22.52381
60
0.712474
import sys import c VAL = 20 print("The real value of c.func is: {}".format(c.func(VAL))) sys.modules.pop("c") a_real_import = __import__("a") a_fake_import = __import__("b") # fake the import sys.modules["a"] = a_fake_import import c # set it back to the real value sys.modules["a"] = a_real_import print("The fake value of c.func is: {}".format(c.func(VAL)))
true
true
1c39e4542a0969dd1be70c3e2bcf2c5197b76976
7,474
py
Python
bot/cogs/help.py
Kobu/MasarykBOT
9a6b6a026b4f39afaca5ab509c90f6da09e169a0
[ "MIT" ]
13
2019-09-14T16:51:35.000Z
2021-03-03T22:20:44.000Z
bot/cogs/help.py
Kobu/MasarykBOT
9a6b6a026b4f39afaca5ab509c90f6da09e169a0
[ "MIT" ]
15
2019-09-29T19:25:31.000Z
2022-02-13T16:40:45.000Z
bot/cogs/help.py
Kobu/MasarykBOT
9a6b6a026b4f39afaca5ab509c90f6da09e169a0
[ "MIT" ]
15
2019-09-18T10:50:59.000Z
2022-02-11T20:55:19.000Z
import asyncio import itertools import discord from discord.ext import commands from .utils.paginator import Pages class HelpPaginator(Pages): def __init__(self, help_command, ctx, entries, *, per_page=4): super().__init__(ctx, entries=entries, per_page=per_page) self.reaction_emojis.append( ('\N{WHITE QUESTION MARK ORNAMENT}', self.show_bot_help)) self.total = len(entries) self.help_command = help_command self.prefix = help_command.clean_prefix self.is_bot = False def get_bot_page(self, page): cog, description, cmds = self.entries[page - 1] self.title = f'{cog} Commands' self.description = description return cmds def prepare_embed(self, entries, page, *, first=False): self.embed.clear_fields() self.embed.title = self.title self.embed.set_footer( text=f'Use "{self.prefix}help command" for more info on a command.') cmds = "" for entry in entries: signature = f'**» {entry.qualified_name} {entry.signature}**\n' cmds += signature self.embed.description = cmds if self.maximum_pages: self.embed.set_author( name=f'Page {page}/{self.maximum_pages} ({self.total} commands)') async def show_help(self): """shows this message""" self.embed.title = 'Paginator help' self.embed.description = 'Hello! Welcome to the help page.' messages = [f'{emoji} {func.__doc__}' for emoji, func in self.reaction_emojis] self.embed.clear_fields() self.embed.add_field(name='What are these reactions for?', value='\n'.join(messages), inline=False) self.embed.set_footer( text=f'We were on page {self.current_page} before this message.') await self.message.edit(embed=self.embed) async def go_back_to_current_page(): await asyncio.sleep(30.0) await self.show_current_page() self.bot.loop.create_task(go_back_to_current_page()) async def show_bot_help(self): """shows how to use the bot""" self.embed.title = 'Using the bot' self.embed.description = 'Hello! Welcome to the help page.' self.embed.clear_fields() entries = ( ('<argument>', 'This means the argument is __**required**__.'), ('[argument]', 'This means the argument is __**optional**__.'), ('[A|B]', 'This means the it can be __**either A or B**__.'), ('[argument...]', 'This means you can have multiple arguments.\n' 'Now that you know the basics, it should be noted that...\n' '__**You do not type in the brackets!**__') ) self.embed.add_field(name='How do I use this bot?', value='Reading the bot signature is pretty simple.') for name, value in entries: self.embed.add_field(name=name, value=value, inline=False) self.embed.set_footer( text=f'We were on page {self.current_page} before this message.') await self.message.edit(embed=self.embed) async def go_back_to_current_page(): await asyncio.sleep(30.0) await self.show_current_page() self.bot.loop.create_task(go_back_to_current_page()) class PaginatedHelpCommand(commands.HelpCommand): def __init__(self): super().__init__(command_attrs={ 'cooldown': commands.Cooldown(1, 3.0, commands.BucketType.member), 'help': 'Shows help about the bot, a command, or a category' }) async def on_help_command_error(self, ctx, error): if isinstance(error, commands.CommandInvokeError): await ctx.send(str(error.original)) def get_command_signature(self, command): parent = command.full_parent_name if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = f'[{command.name}|{aliases}]' if parent: fmt = f'{parent} {fmt}' alias = fmt else: alias = command.name if not parent else f'{parent} {command.name}' return f'{alias} {command.signature}' async def send_bot_help(self, mapping): def key(cmd): return cmd.cog_name or '\u200bNo Category' bot = self.context.bot entries = await self.filter_commands(bot.commands, sort=True, key=key) nested_pages = [] per_page = 9 total = 0 for cog, _commands in itertools.groupby(entries, key=key): _commands = sorted(_commands, key=lambda c: c.name) if len(_commands) == 0: continue total += len(_commands) actual_cog = bot.get_cog(cog) # get the description if it exists (and the cog is valid) or return Empty embed. description = (actual_cog and actual_cog.description) or discord.Embed.Empty nested_pages.extend( (cog, description, _commands[i:i + per_page]) for i in range(0, len(_commands), per_page) ) # a value of 1 forces the pagination session pages = HelpPaginator(self, self.context, nested_pages, per_page=1) # swap the get_page implementation to work with our nested pages. pages.get_page = pages.get_bot_page pages.is_bot = True pages.total = total await pages.paginate() async def send_cog_help(self, cog): entries = await self.filter_commands(cog.get_commands(), sort=True) pages = HelpPaginator(self, self.context, entries) pages.title = f'{cog.qualified_name} Commands' pages.description = cog.description await pages.paginate() def common_command_formatting(self, page_or_embed, command): page_or_embed.title = self.get_command_signature(command) if command.description: page_or_embed.description = f'{command.description}\n\n{command.help}' else: page_or_embed.description = command.help or 'No help found...' async def send_command_help(self, command): # No pagination necessary for a single command. embed = discord.Embed(colour=discord.Colour.blurple()) self.common_command_formatting(embed, command) await self.context.send(embed=embed) async def send_group_help(self, group): subcommands = group.commands if len(subcommands) == 0: return await self.send_command_help(group) entries = await self.filter_commands(subcommands, sort=True) pages = HelpPaginator(self, self.context, entries) self.common_command_formatting(pages, group) await pages.paginate() class Help(commands.Cog): """Commands for utilities related to Discord or the Bot itself.""" def __init__(self, bot): self.bot = bot self.old_help_command = bot.help_command bot.help_command = PaginatedHelpCommand() bot.help_command.cog = self def cog_unload(self): self.bot.help_command = self.old_help_command @commands.command(hidden=True) async def hello(self, ctx): """Displays my intro message.""" await ctx.send('Hello! I\'m a robot! Zloutek1 made me.') def setup(bot): bot.add_cog(Help(bot))
35.932692
92
0.61734
import asyncio import itertools import discord from discord.ext import commands from .utils.paginator import Pages class HelpPaginator(Pages): def __init__(self, help_command, ctx, entries, *, per_page=4): super().__init__(ctx, entries=entries, per_page=per_page) self.reaction_emojis.append( ('\N{WHITE QUESTION MARK ORNAMENT}', self.show_bot_help)) self.total = len(entries) self.help_command = help_command self.prefix = help_command.clean_prefix self.is_bot = False def get_bot_page(self, page): cog, description, cmds = self.entries[page - 1] self.title = f'{cog} Commands' self.description = description return cmds def prepare_embed(self, entries, page, *, first=False): self.embed.clear_fields() self.embed.title = self.title self.embed.set_footer( text=f'Use "{self.prefix}help command" for more info on a command.') cmds = "" for entry in entries: signature = f'**» {entry.qualified_name} {entry.signature}**\n' cmds += signature self.embed.description = cmds if self.maximum_pages: self.embed.set_author( name=f'Page {page}/{self.maximum_pages} ({self.total} commands)') async def show_help(self): self.embed.title = 'Paginator help' self.embed.description = 'Hello! Welcome to the help page.' messages = [f'{emoji} {func.__doc__}' for emoji, func in self.reaction_emojis] self.embed.clear_fields() self.embed.add_field(name='What are these reactions for?', value='\n'.join(messages), inline=False) self.embed.set_footer( text=f'We were on page {self.current_page} before this message.') await self.message.edit(embed=self.embed) async def go_back_to_current_page(): await asyncio.sleep(30.0) await self.show_current_page() self.bot.loop.create_task(go_back_to_current_page()) async def show_bot_help(self): self.embed.title = 'Using the bot' self.embed.description = 'Hello! Welcome to the help page.' self.embed.clear_fields() entries = ( ('<argument>', 'This means the argument is __**required**__.'), ('[argument]', 'This means the argument is __**optional**__.'), ('[A|B]', 'This means the it can be __**either A or B**__.'), ('[argument...]', 'This means you can have multiple arguments.\n' 'Now that you know the basics, it should be noted that...\n' '__**You do not type in the brackets!**__') ) self.embed.add_field(name='How do I use this bot?', value='Reading the bot signature is pretty simple.') for name, value in entries: self.embed.add_field(name=name, value=value, inline=False) self.embed.set_footer( text=f'We were on page {self.current_page} before this message.') await self.message.edit(embed=self.embed) async def go_back_to_current_page(): await asyncio.sleep(30.0) await self.show_current_page() self.bot.loop.create_task(go_back_to_current_page()) class PaginatedHelpCommand(commands.HelpCommand): def __init__(self): super().__init__(command_attrs={ 'cooldown': commands.Cooldown(1, 3.0, commands.BucketType.member), 'help': 'Shows help about the bot, a command, or a category' }) async def on_help_command_error(self, ctx, error): if isinstance(error, commands.CommandInvokeError): await ctx.send(str(error.original)) def get_command_signature(self, command): parent = command.full_parent_name if len(command.aliases) > 0: aliases = '|'.join(command.aliases) fmt = f'[{command.name}|{aliases}]' if parent: fmt = f'{parent} {fmt}' alias = fmt else: alias = command.name if not parent else f'{parent} {command.name}' return f'{alias} {command.signature}' async def send_bot_help(self, mapping): def key(cmd): return cmd.cog_name or '\u200bNo Category' bot = self.context.bot entries = await self.filter_commands(bot.commands, sort=True, key=key) nested_pages = [] per_page = 9 total = 0 for cog, _commands in itertools.groupby(entries, key=key): _commands = sorted(_commands, key=lambda c: c.name) if len(_commands) == 0: continue total += len(_commands) actual_cog = bot.get_cog(cog) description = (actual_cog and actual_cog.description) or discord.Embed.Empty nested_pages.extend( (cog, description, _commands[i:i + per_page]) for i in range(0, len(_commands), per_page) ) pages = HelpPaginator(self, self.context, nested_pages, per_page=1) pages.get_page = pages.get_bot_page pages.is_bot = True pages.total = total await pages.paginate() async def send_cog_help(self, cog): entries = await self.filter_commands(cog.get_commands(), sort=True) pages = HelpPaginator(self, self.context, entries) pages.title = f'{cog.qualified_name} Commands' pages.description = cog.description await pages.paginate() def common_command_formatting(self, page_or_embed, command): page_or_embed.title = self.get_command_signature(command) if command.description: page_or_embed.description = f'{command.description}\n\n{command.help}' else: page_or_embed.description = command.help or 'No help found...' async def send_command_help(self, command): embed = discord.Embed(colour=discord.Colour.blurple()) self.common_command_formatting(embed, command) await self.context.send(embed=embed) async def send_group_help(self, group): subcommands = group.commands if len(subcommands) == 0: return await self.send_command_help(group) entries = await self.filter_commands(subcommands, sort=True) pages = HelpPaginator(self, self.context, entries) self.common_command_formatting(pages, group) await pages.paginate() class Help(commands.Cog): def __init__(self, bot): self.bot = bot self.old_help_command = bot.help_command bot.help_command = PaginatedHelpCommand() bot.help_command.cog = self def cog_unload(self): self.bot.help_command = self.old_help_command @commands.command(hidden=True) async def hello(self, ctx): await ctx.send('Hello! I\'m a robot! Zloutek1 made me.') def setup(bot): bot.add_cog(Help(bot))
true
true
1c39e4d37682c58f6b0bd26a132a4bb2379313a9
1,069
py
Python
mmpose/apis/__init__.py
jiangtaoo2333/mmpose
00e12ddc224b492e9c903df96d09aa04c3f2a5f3
[ "Apache-2.0" ]
null
null
null
mmpose/apis/__init__.py
jiangtaoo2333/mmpose
00e12ddc224b492e9c903df96d09aa04c3f2a5f3
[ "Apache-2.0" ]
null
null
null
mmpose/apis/__init__.py
jiangtaoo2333/mmpose
00e12ddc224b492e9c903df96d09aa04c3f2a5f3
[ "Apache-2.0" ]
null
null
null
# Copyright (c) OpenMMLab. All rights reserved. from .inference import (inference_bottom_up_pose_model,RMinference_top_down_pose_model, inference_top_down_pose_model, init_pose_model, process_mmdet_results, vis_pose_result) from .inference_3d import (extract_pose_sequence, inference_interhand_3d_model, inference_mesh_model, inference_pose_lifter_model, vis_3d_mesh_result, vis_3d_pose_result) from .inference_tracking import get_track_id, vis_pose_tracking_result from .test import multi_gpu_test, single_gpu_test from .train import train_model __all__ = [ 'train_model', 'init_pose_model', 'inference_top_down_pose_model', 'inference_bottom_up_pose_model', 'multi_gpu_test', 'single_gpu_test', 'vis_pose_result', 'get_track_id', 'vis_pose_tracking_result', 'inference_pose_lifter_model', 'vis_3d_pose_result', 'inference_interhand_3d_model', 'extract_pose_sequence', 'inference_mesh_model', 'vis_3d_mesh_result', 'process_mmdet_results' ]
53.45
87
0.755847
from .inference import (inference_bottom_up_pose_model,RMinference_top_down_pose_model, inference_top_down_pose_model, init_pose_model, process_mmdet_results, vis_pose_result) from .inference_3d import (extract_pose_sequence, inference_interhand_3d_model, inference_mesh_model, inference_pose_lifter_model, vis_3d_mesh_result, vis_3d_pose_result) from .inference_tracking import get_track_id, vis_pose_tracking_result from .test import multi_gpu_test, single_gpu_test from .train import train_model __all__ = [ 'train_model', 'init_pose_model', 'inference_top_down_pose_model', 'inference_bottom_up_pose_model', 'multi_gpu_test', 'single_gpu_test', 'vis_pose_result', 'get_track_id', 'vis_pose_tracking_result', 'inference_pose_lifter_model', 'vis_3d_pose_result', 'inference_interhand_3d_model', 'extract_pose_sequence', 'inference_mesh_model', 'vis_3d_mesh_result', 'process_mmdet_results' ]
true
true
1c39e519c33b9ae45a9b9f1373ec1c644ae313eb
12,152
py
Python
jenkinsapi_tests/unittests/test_plugins.py
ward-peng/jenkinsapi
f77259d36f3cb45fd82e79d9bf8fca9dda9f6966
[ "MIT" ]
null
null
null
jenkinsapi_tests/unittests/test_plugins.py
ward-peng/jenkinsapi
f77259d36f3cb45fd82e79d9bf8fca9dda9f6966
[ "MIT" ]
1
2019-07-03T11:16:39.000Z
2019-07-03T11:16:39.000Z
jenkinsapi_tests/unittests/test_plugins.py
TwistoPayments/jenkinsapi
aa3e23289b666feb02e1bde89aa2f75ca14cbd56
[ "MIT" ]
null
null
null
""" jenkinsapi_tests.test_plugins """ import mock # To run unittests on python 2.6 please use unittest2 library try: import unittest2 as unittest except ImportError: import unittest try: from StringIO import StringIO # python2 except ImportError: from io import BytesIO as StringIO # python3 import zipfile from jenkinsapi.jenkins import Requester from jenkinsapi.jenkins import Jenkins from jenkinsapi.plugins import Plugins from jenkinsapi.plugin import Plugin class TestPlugins(unittest.TestCase): DATA = { 'plugins': [ { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}, {}, {}], 'longName': 'Jenkins Subversion Plug-in', 'active': True, 'shortName': 'subversion', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/' 'JENKINS/Subversion+Plugin', 'enabled': True, 'pinned': False, 'version': '1.45', 'supportsDynamicLoad': 'MAYBE', 'bundled': True }, { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}], 'longName': 'Maven Integration plugin', 'active': True, 'shortName': 'maven-plugin', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/JENKINS/' 'Maven+Project+Plugin', 'enabled': True, 'pinned': False, 'version': '1.521', 'supportsDynamicLoad': 'MAYBE', 'bundled': True } ] } @mock.patch.object(Jenkins, '_poll') def setUp(self, _poll_jenkins): _poll_jenkins.return_value = {} self.J = Jenkins('http://localhost:8080') @mock.patch.object(Plugins, '_poll') def test_get_plugins(self, _poll_plugins): _poll_plugins.return_value = self.DATA # Can we produce a repr string for this object self.assertIsInstance(self.J.get_plugins(), Plugins) @mock.patch.object(Plugins, '_poll') def test_no_plugins_str(self, _poll_plugins): _poll_plugins.return_value = {} plugins = self.J.get_plugins() self.assertEqual(str(plugins), "[]") @mock.patch.object(Plugins, '_poll') def test_plugins_str(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertEqual(str(plugins), "['maven-plugin', 'subversion']") @mock.patch.object(Plugins, '_poll') def test_plugins_len(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertEqual(len(plugins), 2) @mock.patch.object(Plugins, '_poll') def test_plugins_contains(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertIn('subversion', plugins) self.assertIn('maven-plugin', plugins) @mock.patch.object(Plugins, '_poll') def test_plugins_values(self, _poll_plugins): _poll_plugins.return_value = self.DATA p = Plugin( { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}, {}, {}], 'longName': 'Jenkins Subversion Plug-in', 'active': True, 'shortName': 'subversion', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/JENKINS/' 'Subversion+Plugin', 'enabled': True, 'pinned': False, 'version': '1.45', 'supportsDynamicLoad': 'MAYBE', 'bundled': True } ) plugins = self.J.get_plugins().values() self.assertIn(p, plugins) @mock.patch.object(Plugins, '_poll') def test_plugins_keys(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins().keys() self.assertIn('subversion', plugins) self.assertIn('maven-plugin', plugins) @mock.patch.object(Plugins, '_poll') def test_plugins_empty(self, _poll_plugins): _poll_plugins.return_value = {} # list() is required here for python 3.x compatibility plugins = list(self.J.get_plugins().keys()) self.assertEqual([], plugins) @mock.patch.object(Plugins, '_poll') def test_plugin_get_by_name(self, _poll_plugins): _poll_plugins.return_value = self.DATA p = Plugin( { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}, {}, {}], 'longName': 'Jenkins Subversion Plug-in', 'active': True, 'shortName': 'subversion', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/JENKINS/' 'Subversion+Plugin', 'enabled': True, 'pinned': False, 'version': '1.45', 'supportsDynamicLoad': 'MAYBE', 'bundled': True } ) plugin = self.J.get_plugins()['subversion'] self.assertEqual(p, plugin) @mock.patch.object(Plugins, '_poll') def test_get_plugin_details(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugin = self.J.get_plugins()['subversion'] self.assertEqual('1.45', plugin.version) self.assertEqual('subversion', plugin.shortName) self.assertEqual('Jenkins Subversion Plug-in', plugin.longName) self.assertEqual('http://wiki.jenkins-ci.org/display/JENKINS/' 'Subversion+Plugin', plugin.url) @mock.patch.object(Requester, 'post_xml_and_confirm_status') def test_install_plugin_bad_input(self, _post): with self.assertRaises(ValueError): self.J.install_plugin('test') @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'plugin_version_already_installed') @mock.patch.object(Plugins, '_wait_until_plugin_installed') @mock.patch.object(Requester, 'post_xml_and_confirm_status') def test_install_plugin_good_input(self, _post, _wait, already_installed, _poll_plugins): _poll_plugins.return_value = self.DATA already_installed.return_value = False self.J.install_plugin('test@latest') expected_data = '<jenkins> <install plugin="test@latest" /> </jenkins>' _post.assert_called_with( '/'.join([self.J.baseurl, 'pluginManager', 'installNecessaryPlugins']), data=expected_data) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'plugin_version_already_installed') @mock.patch.object(Plugins, '_wait_until_plugin_installed') @mock.patch.object(Requester, 'post_xml_and_confirm_status') @mock.patch.object(Jenkins, 'safe_restart') def test_install_plugins_good_input_no_restart(self, _restart, _post, _wait, already_installed, _poll_plugins): _poll_plugins.return_value = self.DATA already_installed.return_value = False self.J.install_plugins(['test@latest', 'test@latest']) self.assertEqual(_post.call_count, 2) self.assertEqual(_restart.call_count, 0) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'plugin_version_already_installed') @mock.patch.object(Plugins, 'restart_required', new_callable=mock.mock.PropertyMock) @mock.patch.object(Plugins, '_wait_until_plugin_installed') @mock.patch.object(Requester, 'post_xml_and_confirm_status') @mock.patch.object(Jenkins, 'safe_restart') def test_install_plugins_good_input_with_restart(self, _restart, _post, _wait, restart_required, already_installed, _poll_plugins): _poll_plugins.return_value = self.DATA restart_required.return_value = True, already_installed.return_value = False self.J.install_plugins(['test@latest', 'test@latest'], restart=True) self.assertEqual(_post.call_count, 2) self.assertEqual(_restart.call_count, 1) @mock.patch.object(Plugins, '_poll') def test_get_plugin_dependencies(self, _poll_plugins): manifest = ( 'Manifest-Version: 1.0\n' 'bla: somestuff\n' 'Plugin-Dependencies: aws-java-sdk:1.10.45,aws-credentials:1.15' ) downloaded_plugin = StringIO() zipfile.ZipFile( downloaded_plugin, mode='w').writestr( 'META-INF/MANIFEST.MF', manifest) _poll_plugins.return_value = self.DATA dependencies = self.J.plugins._get_plugin_dependencies( downloaded_plugin) self.assertEqual(len(dependencies), 2) for dep in dependencies: self.assertIsInstance(dep, Plugin) @mock.patch.object(Plugins, '_poll') def test_plugin_version_already_installed(self, _poll_plugins): _poll_plugins.return_value = self.DATA already_installed = Plugin({'shortName': 'subversion', 'version': '1.45'}) self.assertTrue( self.J.plugins.plugin_version_already_installed(already_installed)) not_installed = Plugin({'shortName': 'subversion', 'version': '1.46'}) self.assertFalse( self.J.plugins.plugin_version_already_installed(not_installed)) latest = Plugin({'shortName': 'subversion', 'version': 'latest'}) self.assertFalse( self.J.plugins.plugin_version_already_installed(latest)) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'update_center_install_status', new_callable=mock.mock.PropertyMock) def test_restart_required_after_plugin_installation(self, status, _poll_plugins): _poll_plugins.return_value = self.DATA status.return_value = { 'data': { 'jobs': [{ 'installStatus': 'SuccessButRequiresRestart', 'name': 'credentials', 'requiresRestart': 'true', 'title': None, 'version': '0' }], 'state': 'RUNNING' }, 'status': 'ok' } self.assertTrue(self.J.plugins.restart_required) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'update_center_install_status', new_callable=mock.mock.PropertyMock) def test_restart_not_required_after_plugin_installation(self, status, _poll_plugins): _poll_plugins.return_value = self.DATA status.return_value = {'data': {'jobs': [], 'state': 'RUNNING'}, 'status': 'ok'} self.assertFalse(self.J.plugins.restart_required) def test_plugin_repr(self): p = Plugin( { 'shortName': 'subversion', } ) self.assertEqual(repr(p), '<jenkinsapi.plugin.Plugin subversion>') if __name__ == '__main__': unittest.main()
38.334385
79
0.563611
import mock try: import unittest2 as unittest except ImportError: import unittest try: from StringIO import StringIO except ImportError: from io import BytesIO as StringIO import zipfile from jenkinsapi.jenkins import Requester from jenkinsapi.jenkins import Jenkins from jenkinsapi.plugins import Plugins from jenkinsapi.plugin import Plugin class TestPlugins(unittest.TestCase): DATA = { 'plugins': [ { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}, {}, {}], 'longName': 'Jenkins Subversion Plug-in', 'active': True, 'shortName': 'subversion', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/' 'JENKINS/Subversion+Plugin', 'enabled': True, 'pinned': False, 'version': '1.45', 'supportsDynamicLoad': 'MAYBE', 'bundled': True }, { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}], 'longName': 'Maven Integration plugin', 'active': True, 'shortName': 'maven-plugin', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/JENKINS/' 'Maven+Project+Plugin', 'enabled': True, 'pinned': False, 'version': '1.521', 'supportsDynamicLoad': 'MAYBE', 'bundled': True } ] } @mock.patch.object(Jenkins, '_poll') def setUp(self, _poll_jenkins): _poll_jenkins.return_value = {} self.J = Jenkins('http://localhost:8080') @mock.patch.object(Plugins, '_poll') def test_get_plugins(self, _poll_plugins): _poll_plugins.return_value = self.DATA self.assertIsInstance(self.J.get_plugins(), Plugins) @mock.patch.object(Plugins, '_poll') def test_no_plugins_str(self, _poll_plugins): _poll_plugins.return_value = {} plugins = self.J.get_plugins() self.assertEqual(str(plugins), "[]") @mock.patch.object(Plugins, '_poll') def test_plugins_str(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertEqual(str(plugins), "['maven-plugin', 'subversion']") @mock.patch.object(Plugins, '_poll') def test_plugins_len(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertEqual(len(plugins), 2) @mock.patch.object(Plugins, '_poll') def test_plugins_contains(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins() self.assertIn('subversion', plugins) self.assertIn('maven-plugin', plugins) @mock.patch.object(Plugins, '_poll') def test_plugins_values(self, _poll_plugins): _poll_plugins.return_value = self.DATA p = Plugin( { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}, {}, {}], 'longName': 'Jenkins Subversion Plug-in', 'active': True, 'shortName': 'subversion', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/JENKINS/' 'Subversion+Plugin', 'enabled': True, 'pinned': False, 'version': '1.45', 'supportsDynamicLoad': 'MAYBE', 'bundled': True } ) plugins = self.J.get_plugins().values() self.assertIn(p, plugins) @mock.patch.object(Plugins, '_poll') def test_plugins_keys(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugins = self.J.get_plugins().keys() self.assertIn('subversion', plugins) self.assertIn('maven-plugin', plugins) @mock.patch.object(Plugins, '_poll') def test_plugins_empty(self, _poll_plugins): _poll_plugins.return_value = {} plugins = list(self.J.get_plugins().keys()) self.assertEqual([], plugins) @mock.patch.object(Plugins, '_poll') def test_plugin_get_by_name(self, _poll_plugins): _poll_plugins.return_value = self.DATA p = Plugin( { 'deleted': False, 'hasUpdate': True, 'downgradable': False, 'dependencies': [{}, {}, {}, {}], 'longName': 'Jenkins Subversion Plug-in', 'active': True, 'shortName': 'subversion', 'backupVersion': None, 'url': 'http://wiki.jenkins-ci.org/display/JENKINS/' 'Subversion+Plugin', 'enabled': True, 'pinned': False, 'version': '1.45', 'supportsDynamicLoad': 'MAYBE', 'bundled': True } ) plugin = self.J.get_plugins()['subversion'] self.assertEqual(p, plugin) @mock.patch.object(Plugins, '_poll') def test_get_plugin_details(self, _poll_plugins): _poll_plugins.return_value = self.DATA plugin = self.J.get_plugins()['subversion'] self.assertEqual('1.45', plugin.version) self.assertEqual('subversion', plugin.shortName) self.assertEqual('Jenkins Subversion Plug-in', plugin.longName) self.assertEqual('http://wiki.jenkins-ci.org/display/JENKINS/' 'Subversion+Plugin', plugin.url) @mock.patch.object(Requester, 'post_xml_and_confirm_status') def test_install_plugin_bad_input(self, _post): with self.assertRaises(ValueError): self.J.install_plugin('test') @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'plugin_version_already_installed') @mock.patch.object(Plugins, '_wait_until_plugin_installed') @mock.patch.object(Requester, 'post_xml_and_confirm_status') def test_install_plugin_good_input(self, _post, _wait, already_installed, _poll_plugins): _poll_plugins.return_value = self.DATA already_installed.return_value = False self.J.install_plugin('test@latest') expected_data = '<jenkins> <install plugin="test@latest" /> </jenkins>' _post.assert_called_with( '/'.join([self.J.baseurl, 'pluginManager', 'installNecessaryPlugins']), data=expected_data) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'plugin_version_already_installed') @mock.patch.object(Plugins, '_wait_until_plugin_installed') @mock.patch.object(Requester, 'post_xml_and_confirm_status') @mock.patch.object(Jenkins, 'safe_restart') def test_install_plugins_good_input_no_restart(self, _restart, _post, _wait, already_installed, _poll_plugins): _poll_plugins.return_value = self.DATA already_installed.return_value = False self.J.install_plugins(['test@latest', 'test@latest']) self.assertEqual(_post.call_count, 2) self.assertEqual(_restart.call_count, 0) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'plugin_version_already_installed') @mock.patch.object(Plugins, 'restart_required', new_callable=mock.mock.PropertyMock) @mock.patch.object(Plugins, '_wait_until_plugin_installed') @mock.patch.object(Requester, 'post_xml_and_confirm_status') @mock.patch.object(Jenkins, 'safe_restart') def test_install_plugins_good_input_with_restart(self, _restart, _post, _wait, restart_required, already_installed, _poll_plugins): _poll_plugins.return_value = self.DATA restart_required.return_value = True, already_installed.return_value = False self.J.install_plugins(['test@latest', 'test@latest'], restart=True) self.assertEqual(_post.call_count, 2) self.assertEqual(_restart.call_count, 1) @mock.patch.object(Plugins, '_poll') def test_get_plugin_dependencies(self, _poll_plugins): manifest = ( 'Manifest-Version: 1.0\n' 'bla: somestuff\n' 'Plugin-Dependencies: aws-java-sdk:1.10.45,aws-credentials:1.15' ) downloaded_plugin = StringIO() zipfile.ZipFile( downloaded_plugin, mode='w').writestr( 'META-INF/MANIFEST.MF', manifest) _poll_plugins.return_value = self.DATA dependencies = self.J.plugins._get_plugin_dependencies( downloaded_plugin) self.assertEqual(len(dependencies), 2) for dep in dependencies: self.assertIsInstance(dep, Plugin) @mock.patch.object(Plugins, '_poll') def test_plugin_version_already_installed(self, _poll_plugins): _poll_plugins.return_value = self.DATA already_installed = Plugin({'shortName': 'subversion', 'version': '1.45'}) self.assertTrue( self.J.plugins.plugin_version_already_installed(already_installed)) not_installed = Plugin({'shortName': 'subversion', 'version': '1.46'}) self.assertFalse( self.J.plugins.plugin_version_already_installed(not_installed)) latest = Plugin({'shortName': 'subversion', 'version': 'latest'}) self.assertFalse( self.J.plugins.plugin_version_already_installed(latest)) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'update_center_install_status', new_callable=mock.mock.PropertyMock) def test_restart_required_after_plugin_installation(self, status, _poll_plugins): _poll_plugins.return_value = self.DATA status.return_value = { 'data': { 'jobs': [{ 'installStatus': 'SuccessButRequiresRestart', 'name': 'credentials', 'requiresRestart': 'true', 'title': None, 'version': '0' }], 'state': 'RUNNING' }, 'status': 'ok' } self.assertTrue(self.J.plugins.restart_required) @mock.patch.object(Plugins, '_poll') @mock.patch.object(Plugins, 'update_center_install_status', new_callable=mock.mock.PropertyMock) def test_restart_not_required_after_plugin_installation(self, status, _poll_plugins): _poll_plugins.return_value = self.DATA status.return_value = {'data': {'jobs': [], 'state': 'RUNNING'}, 'status': 'ok'} self.assertFalse(self.J.plugins.restart_required) def test_plugin_repr(self): p = Plugin( { 'shortName': 'subversion', } ) self.assertEqual(repr(p), '<jenkinsapi.plugin.Plugin subversion>') if __name__ == '__main__': unittest.main()
true
true
1c39e6b7bfa4026293ba7f48cff72b75babd8ec7
15,846
py
Python
elasticsearch/_sync/client/nodes.py
stevepentland/elasticsearch-py
5a512a8f822ce2eff93fbc75f3629973427519bd
[ "Apache-2.0" ]
null
null
null
elasticsearch/_sync/client/nodes.py
stevepentland/elasticsearch-py
5a512a8f822ce2eff93fbc75f3629973427519bd
[ "Apache-2.0" ]
null
null
null
elasticsearch/_sync/client/nodes.py
stevepentland/elasticsearch-py
5a512a8f822ce2eff93fbc75f3629973427519bd
[ "Apache-2.0" ]
null
null
null
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from typing import Any, Dict, List, Optional, Union from elastic_transport import ObjectApiResponse, TextApiResponse from ._base import NamespacedClient from .utils import SKIP_IN_PATH, _quote, _rewrite_parameters class NodesClient(NamespacedClient): @_rewrite_parameters() def hot_threads( self, *, node_id: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, ignore_idle_threads: Optional[bool] = None, interval: Optional[Any] = None, master_timeout: Optional[Any] = None, pretty: Optional[bool] = None, snapshots: Optional[int] = None, sort: Optional[Any] = None, threads: Optional[int] = None, timeout: Optional[Any] = None, type: Optional[Any] = None, ) -> TextApiResponse: """ Returns information about hot threads on each node in the cluster. `<https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-hot-threads.html>`_ :param node_id: List of node IDs or names used to limit returned information. :param ignore_idle_threads: If true, known idle threads (e.g. waiting in a socket select, or to get a task from an empty queue) are filtered out. :param interval: The interval to do the second sampling of threads. :param master_timeout: Period to wait for a connection to the master node. If no response is received before the timeout expires, the request fails and returns an error. :param snapshots: Number of samples of thread stacktrace. :param sort: The sort order for 'cpu' type (default: total) :param threads: Specifies the number of hot threads to provide information for. :param timeout: Period to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. :param type: The type to sample. """ if node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/hot_threads" else: __path = "/_nodes/hot_threads" __query: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if ignore_idle_threads is not None: __query["ignore_idle_threads"] = ignore_idle_threads if interval is not None: __query["interval"] = interval if master_timeout is not None: __query["master_timeout"] = master_timeout if pretty is not None: __query["pretty"] = pretty if snapshots is not None: __query["snapshots"] = snapshots if sort is not None: __query["sort"] = sort if threads is not None: __query["threads"] = threads if timeout is not None: __query["timeout"] = timeout if type is not None: __query["type"] = type __headers = {"accept": "text/plain"} return self.perform_request( # type: ignore[return-value] "GET", __path, params=__query, headers=__headers ) @_rewrite_parameters() def info( self, *, node_id: Optional[Any] = None, metric: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, flat_settings: Optional[bool] = None, human: Optional[bool] = None, master_timeout: Optional[Any] = None, pretty: Optional[bool] = None, timeout: Optional[Any] = None, ) -> ObjectApiResponse[Any]: """ Returns information about nodes in the cluster. `<https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-info.html>`_ :param node_id: Comma-separated list of node IDs or names used to limit returned information. :param metric: Limits the information returned to the specific metrics. Supports a comma-separated list, such as http,ingest. :param flat_settings: If true, returns settings in flat format. :param master_timeout: Period to wait for a connection to the master node. If no response is received before the timeout expires, the request fails and returns an error. :param timeout: Period to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. """ if node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/{_quote(metric)}" elif node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}" elif metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(metric)}" else: __path = "/_nodes" __query: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if flat_settings is not None: __query["flat_settings"] = flat_settings if human is not None: __query["human"] = human if master_timeout is not None: __query["master_timeout"] = master_timeout if pretty is not None: __query["pretty"] = pretty if timeout is not None: __query["timeout"] = timeout __headers = {"accept": "application/json"} return self.perform_request( # type: ignore[return-value] "GET", __path, params=__query, headers=__headers ) @_rewrite_parameters( body_fields=True, ) def reload_secure_settings( self, *, node_id: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, secure_settings_password: Optional[Any] = None, timeout: Optional[Any] = None, ) -> ObjectApiResponse[Any]: """ Reloads secure settings. `<https://www.elastic.co/guide/en/elasticsearch/reference/master/secure-settings.html#reloadable-secure-settings>`_ :param node_id: A comma-separated list of node IDs to span the reload/reinit call. Should stay empty because reloading usually involves all cluster nodes. :param secure_settings_password: :param timeout: Explicit operation timeout """ if node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/reload_secure_settings" else: __path = "/_nodes/reload_secure_settings" __query: Dict[str, Any] = {} __body: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if pretty is not None: __query["pretty"] = pretty if secure_settings_password is not None: __body["secure_settings_password"] = secure_settings_password if timeout is not None: __query["timeout"] = timeout if not __body: __body = None # type: ignore[assignment] __headers = {"accept": "application/json"} if __body is not None: __headers["content-type"] = "application/json" return self.perform_request( # type: ignore[return-value] "POST", __path, params=__query, headers=__headers, body=__body ) @_rewrite_parameters() def stats( self, *, node_id: Optional[Any] = None, metric: Optional[Any] = None, index_metric: Optional[Any] = None, completion_fields: Optional[Any] = None, error_trace: Optional[bool] = None, fielddata_fields: Optional[Any] = None, fields: Optional[Any] = None, filter_path: Optional[Union[List[str], str]] = None, groups: Optional[bool] = None, human: Optional[bool] = None, include_segment_file_sizes: Optional[bool] = None, include_unloaded_segments: Optional[bool] = None, level: Optional[Any] = None, master_timeout: Optional[Any] = None, pretty: Optional[bool] = None, timeout: Optional[Any] = None, types: Optional[List[str]] = None, ) -> ObjectApiResponse[Any]: """ Returns statistical information about nodes in the cluster. `<https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-stats.html>`_ :param node_id: Comma-separated list of node IDs or names used to limit returned information. :param metric: Limit the information returned to the specified metrics :param index_metric: Limit the information returned for indices metric to the specific index metrics. It can be used only if indices (or all) metric is specified. :param completion_fields: Comma-separated list or wildcard expressions of fields to include in fielddata and suggest statistics. :param fielddata_fields: Comma-separated list or wildcard expressions of fields to include in fielddata statistics. :param fields: Comma-separated list or wildcard expressions of fields to include in the statistics. :param groups: Comma-separated list of search groups to include in the search statistics. :param include_segment_file_sizes: If true, the call reports the aggregated disk usage of each one of the Lucene index files (only applies if segment stats are requested). :param include_unloaded_segments: If set to true segment stats will include stats for segments that are not currently loaded into memory :param level: Indicates whether statistics are aggregated at the cluster, index, or shard level. :param master_timeout: Period to wait for a connection to the master node. If no response is received before the timeout expires, the request fails and returns an error. :param timeout: Period to wait for a response. If no response is received before the timeout expires, the request fails and returns an error. :param types: A comma-separated list of document types for the indexing index metric. """ if ( node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH and index_metric not in SKIP_IN_PATH ): __path = f"/_nodes/{_quote(node_id)}/stats/{_quote(metric)}/{_quote(index_metric)}" elif node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/stats/{_quote(metric)}" elif metric not in SKIP_IN_PATH and index_metric not in SKIP_IN_PATH: __path = f"/_nodes/stats/{_quote(metric)}/{_quote(index_metric)}" elif node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/stats" elif metric not in SKIP_IN_PATH: __path = f"/_nodes/stats/{_quote(metric)}" else: __path = "/_nodes/stats" __query: Dict[str, Any] = {} if completion_fields is not None: __query["completion_fields"] = completion_fields if error_trace is not None: __query["error_trace"] = error_trace if fielddata_fields is not None: __query["fielddata_fields"] = fielddata_fields if fields is not None: __query["fields"] = fields if filter_path is not None: __query["filter_path"] = filter_path if groups is not None: __query["groups"] = groups if human is not None: __query["human"] = human if include_segment_file_sizes is not None: __query["include_segment_file_sizes"] = include_segment_file_sizes if include_unloaded_segments is not None: __query["include_unloaded_segments"] = include_unloaded_segments if level is not None: __query["level"] = level if master_timeout is not None: __query["master_timeout"] = master_timeout if pretty is not None: __query["pretty"] = pretty if timeout is not None: __query["timeout"] = timeout if types is not None: __query["types"] = types __headers = {"accept": "application/json"} return self.perform_request( # type: ignore[return-value] "GET", __path, params=__query, headers=__headers ) @_rewrite_parameters() def usage( self, *, node_id: Optional[Any] = None, metric: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, timeout: Optional[Any] = None, ) -> ObjectApiResponse[Any]: """ Returns low-level information about REST actions usage on nodes. `<https://www.elastic.co/guide/en/elasticsearch/reference/master/cluster-nodes-usage.html>`_ :param node_id: A comma-separated list of node IDs or names to limit the returned information; use `_local` to return information from the node you're connecting to, leave empty to get information from all nodes :param metric: Limit the information returned to the specified metrics :param timeout: Explicit operation timeout """ if node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/usage/{_quote(metric)}" elif node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/usage" elif metric not in SKIP_IN_PATH: __path = f"/_nodes/usage/{_quote(metric)}" else: __path = "/_nodes/usage" __query: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if pretty is not None: __query["pretty"] = pretty if timeout is not None: __query["timeout"] = timeout __headers = {"accept": "application/json"} return self.perform_request( # type: ignore[return-value] "GET", __path, params=__query, headers=__headers )
44.139276
123
0.629181
from typing import Any, Dict, List, Optional, Union from elastic_transport import ObjectApiResponse, TextApiResponse from ._base import NamespacedClient from .utils import SKIP_IN_PATH, _quote, _rewrite_parameters class NodesClient(NamespacedClient): @_rewrite_parameters() def hot_threads( self, *, node_id: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, ignore_idle_threads: Optional[bool] = None, interval: Optional[Any] = None, master_timeout: Optional[Any] = None, pretty: Optional[bool] = None, snapshots: Optional[int] = None, sort: Optional[Any] = None, threads: Optional[int] = None, timeout: Optional[Any] = None, type: Optional[Any] = None, ) -> TextApiResponse: if node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/hot_threads" else: __path = "/_nodes/hot_threads" __query: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if ignore_idle_threads is not None: __query["ignore_idle_threads"] = ignore_idle_threads if interval is not None: __query["interval"] = interval if master_timeout is not None: __query["master_timeout"] = master_timeout if pretty is not None: __query["pretty"] = pretty if snapshots is not None: __query["snapshots"] = snapshots if sort is not None: __query["sort"] = sort if threads is not None: __query["threads"] = threads if timeout is not None: __query["timeout"] = timeout if type is not None: __query["type"] = type __headers = {"accept": "text/plain"} return self.perform_request( "GET", __path, params=__query, headers=__headers ) @_rewrite_parameters() def info( self, *, node_id: Optional[Any] = None, metric: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, flat_settings: Optional[bool] = None, human: Optional[bool] = None, master_timeout: Optional[Any] = None, pretty: Optional[bool] = None, timeout: Optional[Any] = None, ) -> ObjectApiResponse[Any]: if node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/{_quote(metric)}" elif node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}" elif metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(metric)}" else: __path = "/_nodes" __query: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if flat_settings is not None: __query["flat_settings"] = flat_settings if human is not None: __query["human"] = human if master_timeout is not None: __query["master_timeout"] = master_timeout if pretty is not None: __query["pretty"] = pretty if timeout is not None: __query["timeout"] = timeout __headers = {"accept": "application/json"} return self.perform_request( "GET", __path, params=__query, headers=__headers ) @_rewrite_parameters( body_fields=True, ) def reload_secure_settings( self, *, node_id: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, secure_settings_password: Optional[Any] = None, timeout: Optional[Any] = None, ) -> ObjectApiResponse[Any]: if node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/reload_secure_settings" else: __path = "/_nodes/reload_secure_settings" __query: Dict[str, Any] = {} __body: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if pretty is not None: __query["pretty"] = pretty if secure_settings_password is not None: __body["secure_settings_password"] = secure_settings_password if timeout is not None: __query["timeout"] = timeout if not __body: __body = None __headers = {"accept": "application/json"} if __body is not None: __headers["content-type"] = "application/json" return self.perform_request( "POST", __path, params=__query, headers=__headers, body=__body ) @_rewrite_parameters() def stats( self, *, node_id: Optional[Any] = None, metric: Optional[Any] = None, index_metric: Optional[Any] = None, completion_fields: Optional[Any] = None, error_trace: Optional[bool] = None, fielddata_fields: Optional[Any] = None, fields: Optional[Any] = None, filter_path: Optional[Union[List[str], str]] = None, groups: Optional[bool] = None, human: Optional[bool] = None, include_segment_file_sizes: Optional[bool] = None, include_unloaded_segments: Optional[bool] = None, level: Optional[Any] = None, master_timeout: Optional[Any] = None, pretty: Optional[bool] = None, timeout: Optional[Any] = None, types: Optional[List[str]] = None, ) -> ObjectApiResponse[Any]: if ( node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH and index_metric not in SKIP_IN_PATH ): __path = f"/_nodes/{_quote(node_id)}/stats/{_quote(metric)}/{_quote(index_metric)}" elif node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/stats/{_quote(metric)}" elif metric not in SKIP_IN_PATH and index_metric not in SKIP_IN_PATH: __path = f"/_nodes/stats/{_quote(metric)}/{_quote(index_metric)}" elif node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/stats" elif metric not in SKIP_IN_PATH: __path = f"/_nodes/stats/{_quote(metric)}" else: __path = "/_nodes/stats" __query: Dict[str, Any] = {} if completion_fields is not None: __query["completion_fields"] = completion_fields if error_trace is not None: __query["error_trace"] = error_trace if fielddata_fields is not None: __query["fielddata_fields"] = fielddata_fields if fields is not None: __query["fields"] = fields if filter_path is not None: __query["filter_path"] = filter_path if groups is not None: __query["groups"] = groups if human is not None: __query["human"] = human if include_segment_file_sizes is not None: __query["include_segment_file_sizes"] = include_segment_file_sizes if include_unloaded_segments is not None: __query["include_unloaded_segments"] = include_unloaded_segments if level is not None: __query["level"] = level if master_timeout is not None: __query["master_timeout"] = master_timeout if pretty is not None: __query["pretty"] = pretty if timeout is not None: __query["timeout"] = timeout if types is not None: __query["types"] = types __headers = {"accept": "application/json"} return self.perform_request( "GET", __path, params=__query, headers=__headers ) @_rewrite_parameters() def usage( self, *, node_id: Optional[Any] = None, metric: Optional[Any] = None, error_trace: Optional[bool] = None, filter_path: Optional[Union[List[str], str]] = None, human: Optional[bool] = None, pretty: Optional[bool] = None, timeout: Optional[Any] = None, ) -> ObjectApiResponse[Any]: if node_id not in SKIP_IN_PATH and metric not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/usage/{_quote(metric)}" elif node_id not in SKIP_IN_PATH: __path = f"/_nodes/{_quote(node_id)}/usage" elif metric not in SKIP_IN_PATH: __path = f"/_nodes/usage/{_quote(metric)}" else: __path = "/_nodes/usage" __query: Dict[str, Any] = {} if error_trace is not None: __query["error_trace"] = error_trace if filter_path is not None: __query["filter_path"] = filter_path if human is not None: __query["human"] = human if pretty is not None: __query["pretty"] = pretty if timeout is not None: __query["timeout"] = timeout __headers = {"accept": "application/json"} return self.perform_request( "GET", __path, params=__query, headers=__headers )
true
true
1c39e6bae743ac99b3e22d020d76719ff4de7e4c
569
py
Python
src/conf.py
mix2zeta/social-d
923cc2b224470e940ae6ac9cc712adb685c1b216
[ "MIT" ]
null
null
null
src/conf.py
mix2zeta/social-d
923cc2b224470e940ae6ac9cc712adb685c1b216
[ "MIT" ]
null
null
null
src/conf.py
mix2zeta/social-d
923cc2b224470e940ae6ac9cc712adb685c1b216
[ "MIT" ]
1
2021-03-11T09:07:11.000Z
2021-03-11T09:07:11.000Z
from dataclasses import dataclass import os @dataclass class settings: @dataclass class DATABASE: PGHOST: str = os.environ["PGHOST"] PGPORT: str = os.environ["PGPORT"] PGDBNAME: str = os.environ["PGDBNAME"] PGUSER: str = os.environ["PGUSER"] PGPASSWORD: str = os.environ["PGPASSWORD"] REDIS_URL: str = os.environ["REDIS_URL"] BASE_URL: str = os.environ["BASE_URL"] CSV_LINE_LIMIT = 50000 RAW_DATA_PATH = '/usr/src/raw_data' SPLIT_DATA_PATH = '/usr/src/split_data' MEDIA_PATH = '/usr/src/media'
27.095238
50
0.650264
from dataclasses import dataclass import os @dataclass class settings: @dataclass class DATABASE: PGHOST: str = os.environ["PGHOST"] PGPORT: str = os.environ["PGPORT"] PGDBNAME: str = os.environ["PGDBNAME"] PGUSER: str = os.environ["PGUSER"] PGPASSWORD: str = os.environ["PGPASSWORD"] REDIS_URL: str = os.environ["REDIS_URL"] BASE_URL: str = os.environ["BASE_URL"] CSV_LINE_LIMIT = 50000 RAW_DATA_PATH = '/usr/src/raw_data' SPLIT_DATA_PATH = '/usr/src/split_data' MEDIA_PATH = '/usr/src/media'
true
true
1c39e826c505c7f544a6b4004a45c4c5d6122363
1,567
py
Python
mime/envs/table_envs/tower_env.py
nikwl/mime-release
2f3d09d1d04bee2505bbb416f960c90f73f4346c
[ "MIT" ]
13
2020-06-24T10:52:28.000Z
2021-07-23T03:05:27.000Z
mime/envs/table_envs/tower_env.py
nikwl/mime-release
2f3d09d1d04bee2505bbb416f960c90f73f4346c
[ "MIT" ]
1
2020-08-18T12:45:15.000Z
2020-08-18T12:45:15.000Z
mime/envs/table_envs/tower_env.py
nikwl/mime-release
2f3d09d1d04bee2505bbb416f960c90f73f4346c
[ "MIT" ]
3
2020-09-09T18:17:46.000Z
2021-09-06T09:43:45.000Z
from .tower_scene import TowerScene from .table_env import TableEnv from .table_cam_env import TableCamEnv import numpy as np class TowerEnv(TableEnv): """ Tower environment, trajectory observation, linear tool control """ def __init__(self, **kwargs): scene = TowerScene(**kwargs) super(TowerEnv, self).__init__(scene) self.observation_space = self._make_dict_space( 'distance_to_target', 'target_position', 'linear_velocity', 'grip_forces', 'grip_width' ) self.action_space = self._make_dict_space( 'linear_velocity', # 'joint_velocity', 'grip_velocity' ) def _get_observation(self, scene): return dict( tool_position=scene.robot.arm.tool.state.position[0], cubes_position=scene.cubes_position, distance_to_cubes =scene.distance_to_cubes, linear_velocity=scene.robot.arm.tool.state.velocity[0], grip_state=scene.robot.gripper.controller.state,) class TowerCamEnv(TableCamEnv): """ Tower environment, camera observation, linear tool control """ def __init__(self, view_rand, gui_resolution, cam_resolution, num_cameras, **kwargs): scene = TowerScene(**kwargs) super(TowerCamEnv, self).__init__(scene, view_rand, gui_resolution, cam_resolution, num_cameras) self.action_space = self._make_dict_space( 'linear_velocity', # 'joint_velocity', 'grip_velocity' )
32.645833
104
0.644544
from .tower_scene import TowerScene from .table_env import TableEnv from .table_cam_env import TableCamEnv import numpy as np class TowerEnv(TableEnv): def __init__(self, **kwargs): scene = TowerScene(**kwargs) super(TowerEnv, self).__init__(scene) self.observation_space = self._make_dict_space( 'distance_to_target', 'target_position', 'linear_velocity', 'grip_forces', 'grip_width' ) self.action_space = self._make_dict_space( 'linear_velocity', 'grip_velocity' ) def _get_observation(self, scene): return dict( tool_position=scene.robot.arm.tool.state.position[0], cubes_position=scene.cubes_position, distance_to_cubes =scene.distance_to_cubes, linear_velocity=scene.robot.arm.tool.state.velocity[0], grip_state=scene.robot.gripper.controller.state,) class TowerCamEnv(TableCamEnv): def __init__(self, view_rand, gui_resolution, cam_resolution, num_cameras, **kwargs): scene = TowerScene(**kwargs) super(TowerCamEnv, self).__init__(scene, view_rand, gui_resolution, cam_resolution, num_cameras) self.action_space = self._make_dict_space( 'linear_velocity', 'grip_velocity' )
true
true
1c39e9326c83dea15da67c3d3d62970f9952f41d
10,185
py
Python
tests/test_packet_builder.py
hansroh/aioquic
491869f9faab05d8bcbcbabb2a4f9244e0cd06f9
[ "BSD-3-Clause" ]
null
null
null
tests/test_packet_builder.py
hansroh/aioquic
491869f9faab05d8bcbcbabb2a4f9244e0cd06f9
[ "BSD-3-Clause" ]
null
null
null
tests/test_packet_builder.py
hansroh/aioquic
491869f9faab05d8bcbcbabb2a4f9244e0cd06f9
[ "BSD-3-Clause" ]
2
2019-11-05T22:55:03.000Z
2020-06-12T12:57:36.000Z
from unittest import TestCase from aioquic.quic.crypto import CryptoPair from aioquic.quic.packet import ( PACKET_TYPE_HANDSHAKE, PACKET_TYPE_INITIAL, PACKET_TYPE_ONE_RTT, QuicFrameType, QuicProtocolVersion, ) from aioquic.quic.packet_builder import ( QuicPacketBuilder, QuicPacketBuilderStop, QuicSentPacket, ) from aioquic.tls import Epoch def create_builder(pad_first_datagram=False): return QuicPacketBuilder( host_cid=bytes(8), packet_number=0, pad_first_datagram=pad_first_datagram, peer_cid=bytes(8), peer_token=b"", spin_bit=False, version=QuicProtocolVersion.DRAFT_23, ) def create_crypto(): crypto = CryptoPair() crypto.setup_initial(bytes(8), is_client=True, version=QuicProtocolVersion.DRAFT_23) return crypto class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) # nothing to write self.assertFalse(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 0) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 1280) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() # INITIAL, fully padded builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 1280) # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], ) def test_long_header_then_long_header(self): builder = create_builder() crypto = create_crypto() # INITIAL builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(199)) self.assertEqual(builder.buffer.tell(), 228) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 244) # HANDSHAKE builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto) self.assertEqual(builder.buffer.tell(), 271) self.assertEqual(builder.remaining_space, 993) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(299)) self.assertEqual(builder.buffer.tell(), 571) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 587) # ONE_RTT builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 666) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(299)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 914) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=244, ), QuicSentPacket( epoch=Epoch.HANDSHAKE, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=1, packet_type=PACKET_TYPE_HANDSHAKE, sent_bytes=343, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=2, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=327, ), ], ) def test_short_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) # nothing to write self.assertFalse(builder.end_packet()) # check builder self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 0) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) def test_short_header_padding(self): builder = create_builder() crypto = create_crypto() # ONE_RTT, fully padded builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) # check builder self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 1) # check datagrams datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ) ], ) def test_short_header_max_total_bytes_1(self): """ max_total_bytes doesn't allow any packets. """ builder = create_builder() builder.max_total_bytes = 11 crypto = create_crypto() with self.assertRaises(QuicPacketBuilderStop): builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) def test_short_header_max_total_bytes_2(self): """ max_total_bytes allows a short packet. """ builder = create_builder() builder.max_total_bytes = 800 crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 773) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) with self.assertRaises(QuicPacketBuilderStop): builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) def test_short_header_max_total_bytes_3(self): builder = create_builder() builder.max_total_bytes = 2000 crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 693) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) with self.assertRaises(QuicPacketBuilderStop): builder.start_packet(PACKET_TYPE_ONE_RTT, crypto)
33.725166
88
0.606578
from unittest import TestCase from aioquic.quic.crypto import CryptoPair from aioquic.quic.packet import ( PACKET_TYPE_HANDSHAKE, PACKET_TYPE_INITIAL, PACKET_TYPE_ONE_RTT, QuicFrameType, QuicProtocolVersion, ) from aioquic.quic.packet_builder import ( QuicPacketBuilder, QuicPacketBuilderStop, QuicSentPacket, ) from aioquic.tls import Epoch def create_builder(pad_first_datagram=False): return QuicPacketBuilder( host_cid=bytes(8), packet_number=0, pad_first_datagram=pad_first_datagram, peer_cid=bytes(8), peer_token=b"", spin_bit=False, version=QuicProtocolVersion.DRAFT_23, ) def create_crypto(): crypto = CryptoPair() crypto.setup_initial(bytes(8), is_client=True, version=QuicProtocolVersion.DRAFT_23) return crypto class QuicPacketBuilderTest(TestCase): def test_long_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) self.assertFalse(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 0) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) def test_long_header_padding(self): builder = create_builder(pad_first_datagram=True) crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(100)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 1280) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ) ], ) def test_long_header_then_short_header(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 1280) builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.STREAM_BASE) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 2) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual(len(datagrams[1]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=1280, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=False, packet_number=1, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ), ], ) def test_long_header_then_long_header(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_INITIAL, crypto) self.assertEqual(builder.remaining_space, 1236) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(199)) self.assertEqual(builder.buffer.tell(), 228) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 244) builder.start_packet(PACKET_TYPE_HANDSHAKE, crypto) self.assertEqual(builder.buffer.tell(), 271) self.assertEqual(builder.remaining_space, 993) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(299)) self.assertEqual(builder.buffer.tell(), 571) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 587) builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 666) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(299)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 914) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.INITIAL, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_INITIAL, sent_bytes=244, ), QuicSentPacket( epoch=Epoch.HANDSHAKE, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=1, packet_type=PACKET_TYPE_HANDSHAKE, sent_bytes=343, ), QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=2, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=327, ), ], ) def test_short_header_empty(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) self.assertFalse(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 0) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 0) self.assertEqual(packets, []) def test_short_header_padding(self): builder = create_builder() crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.start_frame(QuicFrameType.CRYPTO) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) self.assertEqual(builder.buffer.tell(), 0) self.assertEqual(builder.packet_number, 1) datagrams, packets = builder.flush() self.assertEqual(len(datagrams), 1) self.assertEqual(len(datagrams[0]), 1280) self.assertEqual( packets, [ QuicSentPacket( epoch=Epoch.ONE_RTT, in_flight=True, is_ack_eliciting=True, is_crypto_packet=True, packet_number=0, packet_type=PACKET_TYPE_ONE_RTT, sent_bytes=1280, ) ], ) def test_short_header_max_total_bytes_1(self): builder = create_builder() builder.max_total_bytes = 11 crypto = create_crypto() with self.assertRaises(QuicPacketBuilderStop): builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) def test_short_header_max_total_bytes_2(self): builder = create_builder() builder.max_total_bytes = 800 crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 773) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) with self.assertRaises(QuicPacketBuilderStop): builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) def test_short_header_max_total_bytes_3(self): builder = create_builder() builder.max_total_bytes = 2000 crypto = create_crypto() builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 1253) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) builder.start_packet(PACKET_TYPE_ONE_RTT, crypto) self.assertEqual(builder.remaining_space, 693) builder.buffer.push_bytes(bytes(builder.remaining_space)) self.assertTrue(builder.end_packet()) with self.assertRaises(QuicPacketBuilderStop): builder.start_packet(PACKET_TYPE_ONE_RTT, crypto)
true
true
1c39e94973e2435380a45b7fbc88ce61e57de438
747
py
Python
post/migrations/0001_initial.py
zmojtaba/Django-code-post
1aa8ea60080239258ae5f1ca3f7facd6d548b2d9
[ "MIT" ]
null
null
null
post/migrations/0001_initial.py
zmojtaba/Django-code-post
1aa8ea60080239258ae5f1ca3f7facd6d548b2d9
[ "MIT" ]
null
null
null
post/migrations/0001_initial.py
zmojtaba/Django-code-post
1aa8ea60080239258ae5f1ca3f7facd6d548b2d9
[ "MIT" ]
null
null
null
# Generated by Django 3.0.3 on 2020-11-13 15:21 import datetime from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=50)), ('content', models.TextField()), ('date', models.DateField(verbose_name=datetime.datetime(2020, 11, 13, 18, 51, 19, 912640))), ('image', models.ImageField(blank=True, upload_to='photos/%Y/%m/%d/')), ], ), ]
28.730769
114
0.572959
import datetime from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=50)), ('content', models.TextField()), ('date', models.DateField(verbose_name=datetime.datetime(2020, 11, 13, 18, 51, 19, 912640))), ('image', models.ImageField(blank=True, upload_to='photos/%Y/%m/%d/')), ], ), ]
true
true
1c39e9fb9b8cf85d0e162ed57e110e82d4a13824
28,196
py
Python
csv2bufr/__init__.py
tomkralidis/CSV2BUFR
ba7ce4ed2bb41e42fcb9d03f10049ffc6a2073f8
[ "Apache-2.0" ]
null
null
null
csv2bufr/__init__.py
tomkralidis/CSV2BUFR
ba7ce4ed2bb41e42fcb9d03f10049ffc6a2073f8
[ "Apache-2.0" ]
null
null
null
csv2bufr/__init__.py
tomkralidis/CSV2BUFR
ba7ce4ed2bb41e42fcb9d03f10049ffc6a2073f8
[ "Apache-2.0" ]
null
null
null
############################################################################### # # 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. # ############################################################################### __version__ = "0.1.0" import csv from datetime import timezone, datetime import hashlib from io import StringIO, BytesIO import json import logging import os.path from typing import Any, Iterator, Union from eccodes import (codes_bufr_new_from_samples, codes_set_array, codes_set, codes_get_native_type, codes_write, codes_release, codes_get, codes_bufr_keys_iterator_new, codes_bufr_keys_iterator_next, codes_bufr_keys_iterator_delete, codes_bufr_keys_iterator_get_name, CodesInternalError) from jsonpath_ng.ext import parser from jsonschema import validate # some 'constants' SUCCESS = True NUMBERS = (float, int, complex) MISSING = ("NA", "NaN", "NAN", "None") NULLIFY_INVALID = True # TODO: move to env. variable LOGGER = logging.getLogger(__name__) THISDIR = os.path.dirname(os.path.realpath(__file__)) MAPPINGS = f"{THISDIR}{os.sep}resources{os.sep}mappings" BUFR_TABLE_VERSION = 36 # default BUFR table version # list of BUFR attributes ATTRIBUTES = ['code', 'units', 'scale', 'reference', 'width'] # list of ecCodes keys for BUFR headers HEADERS = ["edition", "masterTableNumber", "bufrHeaderCentre", "bufrHeaderSubCentre", "updateSequenceNumber", "dataCategory", "internationalDataSubCategory", "dataSubCategory", "masterTablesVersionNumber", "localTablesVersionNumber", "typicalYear", "typicalMonth", "typicalDay", "typicalHour", "typicalMinute", "typicalSecond", "typicalDate", "typicalTime", "numberOfSubsets", "observedData", "compressedData", "unexpandedDescriptors", "subsetNumber"] # dictionary to store jsonpath parsers, these are compiled the first time that # they are used. jsonpath_parsers = dict() # custom error handlers class MappingError(Exception): pass def parse_wigos_id(wigos_id: str) -> dict: """ Returns the WIGOS Identifier (wigos_id) in string representation as the individual components in a dictionary. The WIGOS Identifier takes the following form: <WIGOS identifier series>-<issuer>-<issue number>-<local identifier> See https://community.wmo.int/wigos-station-identifier for more information. :param wigos_id: WIGOS Station Identifier (WSI) as a string, e.g. "0-20000-0-ABCD123" :returns: `dict` containing components of the WIGOS identifier: "wid_series", "wid_issuer", "wid_issue_number" and "local_identifier" """ tokens = wigos_id.split("-") assert len(tokens) == 4 result = { "wid_series": int(tokens[0]), "wid_issuer": int(tokens[1]), "wid_issue_number": int(tokens[2]), "wid_local": tokens[3] } return result def validate_mapping(mapping: dict) -> bool: """ Validates dictionary containing mapping to BUFR against internal schema. Returns True if the dictionary passes and raises an error otherwise. :param mapping: dictionary containing mappings to specified BUFR sequence using ecCodes key. :returns: `bool` of validation result """ # load internal file schema for mappings file_schema = f"{MAPPINGS}{os.sep}mapping_schema.json" with open(file_schema) as fh: schema = json.load(fh) # now validate try: validate(mapping, schema) except MappingError as e: message = "Invalid mapping dictionary" LOGGER.error(message) raise e return SUCCESS def apply_scaling(value: Union[NUMBERS], scale: Union[NUMBERS], offset: Union[NUMBERS]) -> Union[NUMBERS]: """ Applies a simple scaling and offset to the input data value. Scaling follows the BUFR conventions, e.g. .. math:: \\mbox{scaled\\_value} = \\mbox{value} \\times 10^{\\mbox{scale}} + \\mbox{offset} :param value: The input value to have scaling and offset applied to :param scale: The scale factor to use :param offset: The offset factor to use :returns: scaled value """ if isinstance(value, NUMBERS): if None not in [scale, offset]: try: value = value * pow(10, scale) + offset except Exception as e: LOGGER.error(e.message) raise e return value def validate_value(key: str, value: Union[NUMBERS], valid_min: Union[NUMBERS], valid_max: Union[NUMBERS], nullify_on_fail: bool = False) -> Union[NUMBERS]: """ Check numeric values lie within specified range (if specified) :param key: ECCODES key used when giving feedback / logging :param value: The value to validate :param valid_min: Valid minimum value :param valid_max: Valid maximum value :param nullify_on_fail: Action to take on fail, either set to None (nullify_on_fail=True) or through an error (default) :returns: validated value """ # TODO move this function to the class as part of set value if value is None: return value if not isinstance(value, NUMBERS): # TODO: add checking against code / flag table here? return value if None not in [valid_min, valid_max]: if value > valid_max or value < valid_min: e = ValueError(f"{key}: Value ({value}) out of valid range ({valid_min} - {valid_max}).") # noqa if nullify_on_fail: message = f"{e} Element set to missing" LOGGER.debug(message) return None else: LOGGER.error(str(e)) raise e return value class BUFRMessage: def __init__(self, descriptors: list, delayed_replications: list = list(), table_version: int = BUFR_TABLE_VERSION) -> None: """ Constructor :param descriptors: list of BUFR descriptors to use in this instance e.g. descriptors=[301150, 307014] :param delayed_replications: delayed replicators to use in the sequence if not set ECCODES sets the delayed replicators to 1. Omit if unsure of value :param table_version: version of Master Table 0 to use, default 36 """ # ================================ # first create empty bufr messages # ================================ bufr_msg = codes_bufr_new_from_samples("BUFR4") # =============================== # set delayed replication factors # =============================== if len(delayed_replications) > 0: codes_set_array(bufr_msg, "inputDelayedDescriptorReplicationFactor", delayed_replications) # =============================== # set master table version number # =============================== codes_set(bufr_msg, "masterTablesVersionNumber", table_version) # now set unexpanded descriptors codes_set_array(bufr_msg, "unexpandedDescriptors", descriptors) # ================================================ # now iterator over and add to internal dictionary # ================================================ self.dict = dict() # need a more descriptive name iterator = codes_bufr_keys_iterator_new(bufr_msg) while codes_bufr_keys_iterator_next(iterator): key = codes_bufr_keys_iterator_get_name(iterator) # place holder for data self.dict[key] = dict() self.dict[key]["value"] = None # add native type, used when encoding later native_type = codes_get_native_type(bufr_msg, key) self.dict[key]["type"] = native_type.__name__ # now add attributes (excl. BUFR header elements) if key not in HEADERS: for attr in ATTRIBUTES: try: self.dict[key][attr] = \ codes_get(bufr_msg, f"{key}->{attr}") except Exception as e: raise e codes_bufr_keys_iterator_delete(iterator) # ============================================ # now release the BUFR message back to eccodes # ============================================ codes_release(bufr_msg) # ============================================ # finally add last few items to class # ============================================ self.descriptors = descriptors self.delayed_replications = delayed_replications # used when encoding self.bufr = None # placeholder for BUFR bytes # ============================================ def create_template(self) -> None: template = {} template["inputDelayedDescriptorReplicationFactor"] = \ self.delayed_replications template["number_header_rows"] = 1 template["names_on_row"] = 1 template["header"] = [] # create header section for element in HEADERS: value = None if element == "unexpandedDescriptors": value = self.descriptors entry = { "eccodes_key": element, "value": value, "csv_column": None, "jsonpath": None, "valid_min": None, "valid_max": None, "scale": None, "offset": None } template["header"].append(entry) # now create data section template["data"] = [] for element in self.dict: if element not in HEADERS: entry = { "eccodes_key": element, "value": None, "csv_column": None, "jsonpath": None, "valid_min": None, "valid_max": None, "scale": None, "offset": None } template["data"].append(entry) # add WIGOS identifier template["wigos_identifier"] = { "value": None, "jsonpath": None, "csv_column": None } print(json.dumps(template, indent=4)) def reset(self) -> None: """ Function resets BUFRMessage :returns: `None` """ for key in self.dict: self.dict[key]["value"] = None self.bufr = None def set_element(self, key: str, value: object) -> None: """ Function to set element in BUFR message :param key: the key of the element to set (using ECCODES keys) :param value: the value of the element :returns: `None` """ # TODO move value validation here if value is not None and not isinstance(value, list): expected_type = self.dict[key]["type"] if expected_type == "int" and not isinstance(value, int): LOGGER.debug(f"int expected for {key} but received {type(value)} ({value})") # noqa if isinstance(value, float): value = int(round(value)) else: try: value = int(value) except Exception as e: if NULLIFY_INVALID: value = None LOGGER.debug(f"{e}: Unable to convert value to int, set to None") # noqa else: raise e LOGGER.debug(f"value converted to int ({value})") elif expected_type == "float" and not isinstance(value, float): LOGGER.debug(f"float expected for {key} but received {type(value)} ({value})") # noqa value = float(value) LOGGER.debug(f"value converted to float ({value})") else: value = value self.dict[key]["value"] = value def get_element(self, key: str) -> Any: """ Function to retrieve value from BUFR message :param key: the key of the element to set (using ECCODES keys) :returns: value of the element """ # check if we want value or an attribute (indicated by ->) if "->" in key: tokens = key.split("->") result = self.dict[tokens[0]][tokens[1]] else: result = self.dict[key]["value"] return result def as_bufr(self, use_cached: bool = False) -> bytes: """ Function to get BUFR message encoded into bytes. Once called the bytes are cached and the cached value returned unless specified otherwise. :param use_cached: Boolean indicating whether to use cached value :returns: bytes containing BUFR data """ if use_cached and (self.bufr is not None): return self.bufr # =========================== # initialise new BUFR message # =========================== bufr_msg = codes_bufr_new_from_samples("BUFR4") # set delayed replications, this is needed again as we only used it the # first time to set the keys if len(self.delayed_replications) > 0: codes_set_array(bufr_msg, "inputDelayedDescriptorReplicationFactor", self.delayed_replications) # ============================ # iterate over keys and encode # ============================ for eccodes_key in self.dict: value = self.dict[eccodes_key]["value"] if value is not None: LOGGER.debug(f"setting value {value} for element {eccodes_key}.") # noqa if isinstance(value, list): try: LOGGER.debug("calling codes_set_array") codes_set_array(bufr_msg, eccodes_key, value) except Exception as e: LOGGER.error(f"error calling codes_set_array({bufr_msg}, {eccodes_key}, {value}): {e}") # noqa raise e else: try: codes_set(bufr_msg, eccodes_key, value) except Exception as e: LOGGER.error(f"error calling codes_set({bufr_msg}, {eccodes_key}, {value}): {e}") # noqa raise e # ============================== # Message now ready to be packed # ============================== try: codes_set(bufr_msg, "pack", True) except CodesInternalError as e: LOGGER.debug(f"error calling codes_set({bufr_msg}, 'pack', True): {e}") # noqa LOGGER.debug(json.dumps(self.dict, indent=4)) LOGGER.debug("null message returned") codes_release(bufr_msg) return self.bufr except Exception as e: LOGGER.error(f"error calling codes_set({bufr_msg}, 'pack', True): {e}") # noqa raise e # ======================================================= # now write to in memory file and return bytes to caller # ======================================================= try: fh = BytesIO() codes_write(bufr_msg, fh) codes_release(bufr_msg) fh.seek(0) except Exception as e: LOGGER.error(f"error writing to internal BytesIO object, {e}") raise e # ============================================= # Return BUFR message bytes # ============================================= self.bufr = fh.read() return self.bufr def md5(self) -> str: """ Calculates and returns md5 of BUFR message :returns: md5 of BUFR message """ bufr = self.as_bufr(use_cached=True) if bufr is not None: return hashlib.md5(bufr).hexdigest() else: return None def parse(self, data: dict, metadata: dict, mappings: dict) -> None: """ Function to parse observation data and station metadata, mapping to the specified BUFR sequence. :param data: dictionary of key value pairs containing the data to be encoded. :param metadata: dictionary containing the metadata for the station from OSCAR surface :param mappings: dictionary containing list of BUFR elements to encode (specified using ECCODES key) and whether to get the value from (fixed, csv or metadata) :returns: `None` """ # ================================================== # extract wigos ID from metadata # Is this the right place for this? # ================================================== try: wigosID = metadata["wigosIds"][0]["wid"] tokens = parse_wigos_id(wigosID) for token in tokens: metadata["wigosIds"][0][token] = tokens[token] except (Exception, AssertionError): LOGGER.warning("WigosID not parsed automatically. wigosID element not in metadata?") # noqa # ================================================== # now parse the data. # ================================================== for section in ("header", "data"): for element in mappings[section]: eccodes_key = element["eccodes_key"] # first identify source of data value = None column = None jsonpath = None if "value" in element: value = element["value"] if "csv_column" in element: column = element["csv_column"] if "jsonpath" in element: jsonpath = element["jsonpath"] # now get value from indicated source if value is not None: value = element["value"] elif column is not None: # get column name # make sure column is in data if column not in data: message = f"column '{column}' not found in data dictionary" # noqa raise ValueError(message) value = data[column] elif jsonpath is not None: if jsonpath not in jsonpath_parsers: jsonpath_parsers[jsonpath] = parser.parse(jsonpath) p = jsonpath_parsers[jsonpath] query = p.find(metadata) assert len(query) == 1 value = query[0].value else: LOGGER.debug(f"value and column both None for element {element['eccodes_key']}") # noqa # =============================== # apply specified scaling to data # =============================== if value in MISSING: value = None else: scale = None offset = None if "scale" in element: scale = element["scale"] if "offset" in element: offset = element["offset"] value = apply_scaling(value, scale, offset) # ================== # now validate value # ================== valid_min = None valid_max = None if "valid_min" in element: valid_min = element["valid_min"] if "valid_max" in element: valid_max = element["valid_max"] LOGGER.debug(f"validating value {value} for element {element['eccodes_key']} against range") # noqa try: value = validate_value(element["eccodes_key"], value, valid_min, valid_max, NULLIFY_INVALID) LOGGER.debug(f"value {value} validated for element {element['eccodes_key']}") # noqa except Exception as e: if NULLIFY_INVALID: LOGGER.debug(f"Error raised whilst validating {element['eccodes_key']}, value set to None") # noqa value = None else: raise e # ================================================== # at this point we should have the eccodes key and a # validated value to use, add to dict # ================================================== self.set_element(eccodes_key, value) LOGGER.debug(f"value {value} updated for element {element['eccodes_key']}") # noqa def get_datetime(self) -> datetime: """ Function to extract characteristic date and time from the BUFR message :returns: `datetime.datetime` of ISO8601 representation of the characteristic date/time """ return datetime( self.get_element("typicalYear"), self.get_element("typicalMonth"), self.get_element("typicalDay"), self.get_element("typicalHour"), self.get_element("typicalMinute") ) def transform(data: str, metadata: dict, mappings: dict) -> Iterator[dict]: """ This function returns an iterator to process each line in the input CSV string. On each iteration a dictionary is returned containing the BUFR encoded data and, if specified, a geojson representation. The mapping to BUFR is specified by the "mappings" dictionary using the ecCodes keys. For more information and a list of the keys see the tables at: https://confluence.ecmwf.int/display/ECC/WMO%3D37+element+table The dictionary returned by the iterator contains the following keys: - ["bufr4"] = data encoded into BUFR; - ["_meta"] = metadata on the data. The ["_meta"] element includes the following: - ["identifier"] = identifier for report (WIGOS_<WSI>_<ISO8601>); - ["md5"] = md5 checksum of BUFR encoded data; - ["wigos_id"] = WIGOS identifier; - ["data_date"] = characteristic date of data; - ["originating_centre"] = Originating centre (see Common code table C11); # noqa - ["data_category"] = Category of data, see BUFR Table A. :param data: string containing csv separated data. First line should contain the column headers, second line the data :param metadata: dictionary containing the metadata for the station from OSCAR surface :param mappings: dictionary containing list of BUFR elements to encode (specified using ecCodes key) and whether to get the value from (fixed, csv or metadata) :param template: dictionary containing mapping from BUFR to geoJSON :returns: iterator """ # ====================== # validate mapping files # ====================== e = validate_mapping(mappings) if e is not SUCCESS: raise ValueError("Invalid mappings") # ========================================================== # Now extract descriptors and replications from mapping file # ========================================================== delayed_replications = mappings["inputDelayedDescriptorReplicationFactor"] path = "$.header[?(@.eccodes_key=='unexpandedDescriptors')]" unexpanded_descriptors = \ parser.parse(path).find(mappings)[0].value["value"] path = "$.header[?(@.eccodes_key=='masterTablesVersionNumber')]" table_version = parser.parse(path).find(mappings)[0].value["value"] if "number_header_rows" in mappings: nheaders = mappings["number_header_rows"] else: nheaders = 1 if "names_on_row" in mappings: names = mappings["names_on_row"] else: names = 1 # ========================================= # Now we need to convert string back to CSV # and iterate over rows # ========================================= fh = StringIO(data) reader = csv.reader(fh, delimiter=',', quoting=csv.QUOTE_NONNUMERIC) # counter to keep track rows_read = 0 # first read in and process header rows while rows_read < nheaders: row = next(reader) if rows_read == names - 1: col_names = row rows_read += 1 continue # initialise new BUFRMessage (and reuse later) LOGGER.debug("Initializing new BUFR message") message = BUFRMessage(unexpanded_descriptors, delayed_replications, table_version) # now iterate over remaining rows for row in reader: result = dict() LOGGER.debug(f"Processing row {rows_read}") # check and make sure we have ascii data for val in row: if isinstance(val, str): if not val.isascii(): if NULLIFY_INVALID: LOGGER.debug(f"csv read error, non ASCII data detected ({val}), skipping row") # noqa LOGGER.debug(row) continue else: raise ValueError # valid data row, make dictionary data_dict = dict(zip(col_names, row)) # reset BUFR message to clear data message.reset() # parse to BUFR sequence LOGGER.debug("Parsing data") message.parse(data_dict, metadata, mappings) # encode to BUFR LOGGER.debug("Parsing data") try: result["bufr4"] = message.as_bufr() except Exception as e: LOGGER.error("Error encoding BUFR, null returned") LOGGER.error(e) result["bufr4"] = None # now identifier based on WSI and observation date as identifier wsi = metadata['wigosIds'][0]['wid'] if 'wigosIds' in metadata else "N/A" # noqa isodate = message.get_datetime().strftime('%Y%m%dT%H%M%S') rmk = f"WIGOS_{wsi}_{isodate}" # now additional metadata elements LOGGER.debug("Adding metadata elements") result["_meta"] = { "identifier": rmk, "md5": message.md5(), "wigos_id": wsi, "data_date": message.get_datetime(), "originating_centre": message.get_element("bufrHeaderCentre"), "data_category": message.get_element("dataCategory") } time_ = datetime.now(timezone.utc).isoformat() LOGGER.info(f"{time_}|{result['_meta']}") # increment ticker rows_read += 1 # now yield result back to caller yield result
39.161111
123
0.533586
t, "value": None, "csv_column": None, "jsonpath": None, "valid_min": None, "valid_max": None, "scale": None, "offset": None } template["data"].append(entry) template["wigos_identifier"] = { "value": None, "jsonpath": None, "csv_column": None } print(json.dumps(template, indent=4)) def reset(self) -> None: for key in self.dict: self.dict[key]["value"] = None self.bufr = None def set_element(self, key: str, value: object) -> None: if value is not None and not isinstance(value, list): expected_type = self.dict[key]["type"] if expected_type == "int" and not isinstance(value, int): LOGGER.debug(f"int expected for {key} but received {type(value)} ({value})") if isinstance(value, float): value = int(round(value)) else: try: value = int(value) except Exception as e: if NULLIFY_INVALID: value = None LOGGER.debug(f"{e}: Unable to convert value to int, set to None") else: raise e LOGGER.debug(f"value converted to int ({value})") elif expected_type == "float" and not isinstance(value, float): LOGGER.debug(f"float expected for {key} but received {type(value)} ({value})") value = float(value) LOGGER.debug(f"value converted to float ({value})") else: value = value self.dict[key]["value"] = value def get_element(self, key: str) -> Any: if "->" in key: tokens = key.split("->") result = self.dict[tokens[0]][tokens[1]] else: result = self.dict[key]["value"] return result def as_bufr(self, use_cached: bool = False) -> bytes: if use_cached and (self.bufr is not None): return self.bufr bufr_msg = codes_bufr_new_from_samples("BUFR4") if len(self.delayed_replications) > 0: codes_set_array(bufr_msg, "inputDelayedDescriptorReplicationFactor", self.delayed_replications) for eccodes_key in self.dict: value = self.dict[eccodes_key]["value"] if value is not None: LOGGER.debug(f"setting value {value} for element {eccodes_key}.") if isinstance(value, list): try: LOGGER.debug("calling codes_set_array") codes_set_array(bufr_msg, eccodes_key, value) except Exception as e: LOGGER.error(f"error calling codes_set_array({bufr_msg}, {eccodes_key}, {value}): {e}") raise e else: try: codes_set(bufr_msg, eccodes_key, value) except Exception as e: LOGGER.error(f"error calling codes_set({bufr_msg}, {eccodes_key}, {value}): {e}") raise e try: codes_set(bufr_msg, "pack", True) except CodesInternalError as e: LOGGER.debug(f"error calling codes_set({bufr_msg}, 'pack', True): {e}") LOGGER.debug(json.dumps(self.dict, indent=4)) LOGGER.debug("null message returned") codes_release(bufr_msg) return self.bufr except Exception as e: LOGGER.error(f"error calling codes_set({bufr_msg}, 'pack', True): {e}") raise e try: fh = BytesIO() codes_write(bufr_msg, fh) codes_release(bufr_msg) fh.seek(0) except Exception as e: LOGGER.error(f"error writing to internal BytesIO object, {e}") raise e self.bufr = fh.read() return self.bufr def md5(self) -> str: bufr = self.as_bufr(use_cached=True) if bufr is not None: return hashlib.md5(bufr).hexdigest() else: return None def parse(self, data: dict, metadata: dict, mappings: dict) -> None: try: wigosID = metadata["wigosIds"][0]["wid"] tokens = parse_wigos_id(wigosID) for token in tokens: metadata["wigosIds"][0][token] = tokens[token] except (Exception, AssertionError): LOGGER.warning("WigosID not parsed automatically. wigosID element not in metadata?") for section in ("header", "data"): for element in mappings[section]: eccodes_key = element["eccodes_key"] value = None column = None jsonpath = None if "value" in element: value = element["value"] if "csv_column" in element: column = element["csv_column"] if "jsonpath" in element: jsonpath = element["jsonpath"] if value is not None: value = element["value"] elif column is not None: if column not in data: message = f"column '{column}' not found in data dictionary" raise ValueError(message) value = data[column] elif jsonpath is not None: if jsonpath not in jsonpath_parsers: jsonpath_parsers[jsonpath] = parser.parse(jsonpath) p = jsonpath_parsers[jsonpath] query = p.find(metadata) assert len(query) == 1 value = query[0].value else: LOGGER.debug(f"value and column both None for element {element['eccodes_key']}") if value in MISSING: value = None else: scale = None offset = None if "scale" in element: scale = element["scale"] if "offset" in element: offset = element["offset"] value = apply_scaling(value, scale, offset) valid_min = None valid_max = None if "valid_min" in element: valid_min = element["valid_min"] if "valid_max" in element: valid_max = element["valid_max"] LOGGER.debug(f"validating value {value} for element {element['eccodes_key']} against range") try: value = validate_value(element["eccodes_key"], value, valid_min, valid_max, NULLIFY_INVALID) LOGGER.debug(f"value {value} validated for element {element['eccodes_key']}") except Exception as e: if NULLIFY_INVALID: LOGGER.debug(f"Error raised whilst validating {element['eccodes_key']}, value set to None") value = None else: raise e self.set_element(eccodes_key, value) LOGGER.debug(f"value {value} updated for element {element['eccodes_key']}") def get_datetime(self) -> datetime: return datetime( self.get_element("typicalYear"), self.get_element("typicalMonth"), self.get_element("typicalDay"), self.get_element("typicalHour"), self.get_element("typicalMinute") ) def transform(data: str, metadata: dict, mappings: dict) -> Iterator[dict]: e = validate_mapping(mappings) if e is not SUCCESS: raise ValueError("Invalid mappings") delayed_replications = mappings["inputDelayedDescriptorReplicationFactor"] path = "$.header[?(@.eccodes_key=='unexpandedDescriptors')]" unexpanded_descriptors = \ parser.parse(path).find(mappings)[0].value["value"] path = "$.header[?(@.eccodes_key=='masterTablesVersionNumber')]" table_version = parser.parse(path).find(mappings)[0].value["value"] if "number_header_rows" in mappings: nheaders = mappings["number_header_rows"] else: nheaders = 1 if "names_on_row" in mappings: names = mappings["names_on_row"] else: names = 1 fh = StringIO(data) reader = csv.reader(fh, delimiter=',', quoting=csv.QUOTE_NONNUMERIC) rows_read = 0 while rows_read < nheaders: row = next(reader) if rows_read == names - 1: col_names = row rows_read += 1 continue LOGGER.debug("Initializing new BUFR message") message = BUFRMessage(unexpanded_descriptors, delayed_replications, table_version) for row in reader: result = dict() LOGGER.debug(f"Processing row {rows_read}") for val in row: if isinstance(val, str): if not val.isascii(): if NULLIFY_INVALID: LOGGER.debug(f"csv read error, non ASCII data detected ({val}), skipping row") LOGGER.debug(row) continue else: raise ValueError data_dict = dict(zip(col_names, row)) message.reset() LOGGER.debug("Parsing data") message.parse(data_dict, metadata, mappings) LOGGER.debug("Parsing data") try: result["bufr4"] = message.as_bufr() except Exception as e: LOGGER.error("Error encoding BUFR, null returned") LOGGER.error(e) result["bufr4"] = None wsi = metadata['wigosIds'][0]['wid'] if 'wigosIds' in metadata else "N/A" isodate = message.get_datetime().strftime('%Y%m%dT%H%M%S') rmk = f"WIGOS_{wsi}_{isodate}" LOGGER.debug("Adding metadata elements") result["_meta"] = { "identifier": rmk, "md5": message.md5(), "wigos_id": wsi, "data_date": message.get_datetime(), "originating_centre": message.get_element("bufrHeaderCentre"), "data_category": message.get_element("dataCategory") } time_ = datetime.now(timezone.utc).isoformat() LOGGER.info(f"{time_}|{result['_meta']}") rows_read += 1 yield result
true
true
1c39ea212f29f4b670366b9a6e4ef3ba23026a48
2,112
py
Python
tests/models/symbol/alarm_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
5
2016-08-23T17:52:22.000Z
2019-05-16T08:45:30.000Z
tests/models/symbol/alarm_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
2
2016-11-10T05:30:21.000Z
2019-04-05T15:03:37.000Z
tests/models/symbol/alarm_test.py
NetApp/santricity-webapi-pythonsdk
1d3df4a00561192f4cdcdd1890f4d27547ed2de2
[ "BSD-3-Clause-Clear" ]
7
2016-08-25T16:11:44.000Z
2021-02-22T05:31:25.000Z
#!/usr/bin/env python # coding: utf-8 """ The Clear BSD License Copyright (c) – 2016, NetApp, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NetApp, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import unittest from netapp.santricity.models.symbol.alarm import Alarm class AlarmTest(unittest.TestCase): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ # Try instantiating the model def test_alarm(self): alarm_obj = Alarm() self.assertNotEqual(alarm_obj, None)
55.578947
845
0.766098
import unittest from netapp.santricity.models.symbol.alarm import Alarm class AlarmTest(unittest.TestCase): def test_alarm(self): alarm_obj = Alarm() self.assertNotEqual(alarm_obj, None)
true
true
1c39eb03b62b8f90c8a9a5f1726780d591b4195b
3,416
py
Python
tests/test_optimizers.py
Javicadserres/dnetworks
ff648a24dbc6d882c0986feb9c23549d30a9c1e8
[ "MIT" ]
1
2021-02-07T22:47:11.000Z
2021-02-07T22:47:11.000Z
tests/test_optimizers.py
Javicadserres/dnetworks
ff648a24dbc6d882c0986feb9c23549d30a9c1e8
[ "MIT" ]
1
2021-01-30T23:37:24.000Z
2021-02-07T21:06:30.000Z
tests/test_optimizers.py
Javicadserres/DNet
173f9dfa35ae1cff8dbeec3c1d24cb00990b41a6
[ "MIT" ]
null
null
null
import numpy as np import dnetworks from dnetworks import SGD, RMSprop, Adam from .test_utils import test_parameters_optimizers def test_sgd(): """ Tests Stochastic gradient descent optimization class. """ weights, bias, dW, db = test_parameters_optimizers() expected_weights = np.array( [[-0.17310385, -0.87734562, 0.04230592], [ 0.58351704, -1.10041826, 1.14432594]] ) expected_bias = np.array([[0.90210947], [0.50279191]]) expected_vdw = np.array( [[ 0.09008559, -0.06837279, -0.01228902], [-0.09357694, -0.02678881, 0.05303555]] ) expected_vdb = np.array([[-0.06916607], [-0.03967535]]) optimicer = SGD() ( obtained_weigths, obtained_bias, (obtained_V_dW, obtained_V_db) ) = optimicer.optim(weights, bias, dW, db) np.testing.assert_almost_equal(expected_weights, obtained_weigths) np.testing.assert_almost_equal(expected_bias, obtained_bias) np.testing.assert_almost_equal(expected_vdw, obtained_V_dW) np.testing.assert_almost_equal(expected_vdb, obtained_V_db) def test_rmsprop(): """ Tests RMSpropo optimization class. """ weights, bias, dW, db = test_parameters_optimizers() expected_weights = np.array( [[-0.19614529, -0.85414134, 0.06593083], [ 0.60653229, -1.0769021 , 1.12100663]] ) expected_bias = np.array([[0.9253078], [0.52621142]]) expected_sdw = np.array( [[0.08115414, 0.04674838, 0.0015102], [0.08756644, 0.0071764 , 0.02812769]] ) expected_sdb = np.array([[0.04783946], [0.01574134]]) optimicer = RMSprop() ( obtained_weigths, obtained_bias, (obtained_S_dW, obtained_S_db) ) = optimicer.optim(weights, bias, dW, db) np.testing.assert_almost_equal(expected_weights, obtained_weigths) np.testing.assert_almost_equal(expected_bias, obtained_bias) np.testing.assert_almost_equal(expected_sdw, obtained_S_dW) np.testing.assert_almost_equal(expected_sdb, obtained_S_db) def test_adam(): """ Tests Adam optimization class. """ weights, bias, dW, db = test_parameters_optimizers() expected_weights = np.array( [[-0.17799666, -0.87228997, 0.0477822 ], [ 0.58838366, -1.09505073, 1.13915526]] ) expected_bias = np.array([[0.90715917], [0.50806279]]) expected_vdw = np.array( [[ 0.09008559, -0.06837279, -0.01228902], [-0.09357694, -0.02678881, 0.05303555]] ) expected_vdb = np.array([[-0.06916607], [-0.03967535]]) expected_sdw = np.array( [[0.00811541, 0.00467484, 0.00015102], [0.00875664, 0.00071764, 0.00281277]] ) expected_sdb = np.array( [[0.00478395], [0.00157413]] ) optimicer = Adam() ( obtained_weigths, obtained_bias, (obtained_V_dW, obtained_V_db, obtained_S_dW, obtained_S_db, epoch) ) = optimicer.optim(weights, bias, dW, db, vel_square=(0, 0, 0, 0, 2)) np.testing.assert_almost_equal(expected_weights, obtained_weigths) np.testing.assert_almost_equal(expected_bias, obtained_bias) np.testing.assert_almost_equal(expected_vdw, obtained_V_dW) np.testing.assert_almost_equal(expected_vdb, obtained_V_db) np.testing.assert_almost_equal(expected_sdw, obtained_S_dW) np.testing.assert_almost_equal(expected_sdb, obtained_S_db)
32.533333
75
0.661007
import numpy as np import dnetworks from dnetworks import SGD, RMSprop, Adam from .test_utils import test_parameters_optimizers def test_sgd(): weights, bias, dW, db = test_parameters_optimizers() expected_weights = np.array( [[-0.17310385, -0.87734562, 0.04230592], [ 0.58351704, -1.10041826, 1.14432594]] ) expected_bias = np.array([[0.90210947], [0.50279191]]) expected_vdw = np.array( [[ 0.09008559, -0.06837279, -0.01228902], [-0.09357694, -0.02678881, 0.05303555]] ) expected_vdb = np.array([[-0.06916607], [-0.03967535]]) optimicer = SGD() ( obtained_weigths, obtained_bias, (obtained_V_dW, obtained_V_db) ) = optimicer.optim(weights, bias, dW, db) np.testing.assert_almost_equal(expected_weights, obtained_weigths) np.testing.assert_almost_equal(expected_bias, obtained_bias) np.testing.assert_almost_equal(expected_vdw, obtained_V_dW) np.testing.assert_almost_equal(expected_vdb, obtained_V_db) def test_rmsprop(): weights, bias, dW, db = test_parameters_optimizers() expected_weights = np.array( [[-0.19614529, -0.85414134, 0.06593083], [ 0.60653229, -1.0769021 , 1.12100663]] ) expected_bias = np.array([[0.9253078], [0.52621142]]) expected_sdw = np.array( [[0.08115414, 0.04674838, 0.0015102], [0.08756644, 0.0071764 , 0.02812769]] ) expected_sdb = np.array([[0.04783946], [0.01574134]]) optimicer = RMSprop() ( obtained_weigths, obtained_bias, (obtained_S_dW, obtained_S_db) ) = optimicer.optim(weights, bias, dW, db) np.testing.assert_almost_equal(expected_weights, obtained_weigths) np.testing.assert_almost_equal(expected_bias, obtained_bias) np.testing.assert_almost_equal(expected_sdw, obtained_S_dW) np.testing.assert_almost_equal(expected_sdb, obtained_S_db) def test_adam(): weights, bias, dW, db = test_parameters_optimizers() expected_weights = np.array( [[-0.17799666, -0.87228997, 0.0477822 ], [ 0.58838366, -1.09505073, 1.13915526]] ) expected_bias = np.array([[0.90715917], [0.50806279]]) expected_vdw = np.array( [[ 0.09008559, -0.06837279, -0.01228902], [-0.09357694, -0.02678881, 0.05303555]] ) expected_vdb = np.array([[-0.06916607], [-0.03967535]]) expected_sdw = np.array( [[0.00811541, 0.00467484, 0.00015102], [0.00875664, 0.00071764, 0.00281277]] ) expected_sdb = np.array( [[0.00478395], [0.00157413]] ) optimicer = Adam() ( obtained_weigths, obtained_bias, (obtained_V_dW, obtained_V_db, obtained_S_dW, obtained_S_db, epoch) ) = optimicer.optim(weights, bias, dW, db, vel_square=(0, 0, 0, 0, 2)) np.testing.assert_almost_equal(expected_weights, obtained_weigths) np.testing.assert_almost_equal(expected_bias, obtained_bias) np.testing.assert_almost_equal(expected_vdw, obtained_V_dW) np.testing.assert_almost_equal(expected_vdb, obtained_V_db) np.testing.assert_almost_equal(expected_sdw, obtained_S_dW) np.testing.assert_almost_equal(expected_sdb, obtained_S_db)
true
true
1c39eb79a723b7c27a77ce7f7e120981453c52eb
4,175
py
Python
venv/lib/python3.8/site-packages/tests/test.py
julio9246/hg-poker-api
56805601bc26bf8bb80e05235ae22a59a174af09
[ "Apache-2.0" ]
null
null
null
venv/lib/python3.8/site-packages/tests/test.py
julio9246/hg-poker-api
56805601bc26bf8bb80e05235ae22a59a174af09
[ "Apache-2.0" ]
null
null
null
venv/lib/python3.8/site-packages/tests/test.py
julio9246/hg-poker-api
56805601bc26bf8bb80e05235ae22a59a174af09
[ "Apache-2.0" ]
null
null
null
from py_postgresql_wrapper.configuration import Configuration from py_postgresql_wrapper.database import Database, Page Configuration.instance(configuration_file='configuration.json') def test_create_table(): with Database() as database: database.execute(''' drop table if exists test ''') database.execute(''' create table test ( id int primary key, description varchar(255) ) ''') def test_delete_by_id(): with Database() as database: database.delete('test').where('id', 1).execute() assert len(database.execute('select id, description from test').fetch_all()) == 3 def test_delete_with_like(): with Database() as database: database.delete('test').where('description', 'Test%', operator='like').execute() assert len(database.execute("select id, description from test").fetch_all()) == 0 def test_find_all(): with Database() as database: data = database.execute('select id, description from test').fetch_all() assert len(data) == 4 assert data[0].id == 1 assert data[0].description == 'Test 1' def test_find_by_file(): with Database() as database: data = database.execute('find_test_by_id', {'id': 1}).fetch_one() assert data.id == 1 assert data.description == 'Test 1' def test_find_by_id(): with Database() as database: data = database.execute('select id, description from test where id = %(id)s', {'id': 1}).fetch_one() assert data.id == 1 def test_find_by_select(): with Database() as database: data = database.select('test').where('description', 'Test%', operator='like').execute().fetch_all() assert len(data) == 4 def test_find_by_select_without_where(): with Database() as database: data = database.select('test').execute().fetch_all() print(data) assert len(data) == 4 def test_find_many(): with Database() as database: data = database.execute('select id, description from test').fetch_many(2) assert len(data) == 2 def test_find_paging_by_select(): with Database() as database: data = database.select('test').fields('id', 'description').where('id', 3, operator='<').order_by('id').paging(0, 2) assert type(data) == Page assert len(data.data) == 2 assert data.data[0].id == 1 assert data.data[0].description == 'Test 1' def test_find_paging_by_select_without_where(): with Database() as database: data = database.select('test').paging(0, 2) assert type(data) == Page assert len(data.data) == 2 def test_find_without_result(): with Database() as database: data = database.select('test').where('1', '0', constant=True).execute().fetch_one() assert data is None def test_insert(): with Database() as database: database.insert('test').set('id', 1).set('description', 'Test 1').execute() database.insert('test').set('id', 2).set('description', 'Test 2').execute() database.insert('test').set('id', 3).set('description', 'Test 3').execute() database.insert('test').set('id', 4).set('description', 'Test 4').execute() def test_rollback(): try: with Database() as database: database.insert('test').set('id', 10).set('description', 'Test 10').execute() raise Exception() except(): with Database() as database: assert database.select('test').where('id', 10).execute().fetch_one() is None def test_truncate_table(): with Database() as database: database.execute(''' truncate table test ''') def test_update(): with Database() as database: data = database.update('test').set('description', 'New Test 1').where('id', 1).execute() assert data.cursor.rowcount == 1 def test_update_where_all(): try: with Database() as database: database.update('test').set('description', 'New Test 1').where_all({'id': 1, 'description': 'Test 1'}).execute() except() as e: assert e is None
31.870229
124
0.621078
from py_postgresql_wrapper.configuration import Configuration from py_postgresql_wrapper.database import Database, Page Configuration.instance(configuration_file='configuration.json') def test_create_table(): with Database() as database: database.execute(''' drop table if exists test ''') database.execute(''' create table test ( id int primary key, description varchar(255) ) ''') def test_delete_by_id(): with Database() as database: database.delete('test').where('id', 1).execute() assert len(database.execute('select id, description from test').fetch_all()) == 3 def test_delete_with_like(): with Database() as database: database.delete('test').where('description', 'Test%', operator='like').execute() assert len(database.execute("select id, description from test").fetch_all()) == 0 def test_find_all(): with Database() as database: data = database.execute('select id, description from test').fetch_all() assert len(data) == 4 assert data[0].id == 1 assert data[0].description == 'Test 1' def test_find_by_file(): with Database() as database: data = database.execute('find_test_by_id', {'id': 1}).fetch_one() assert data.id == 1 assert data.description == 'Test 1' def test_find_by_id(): with Database() as database: data = database.execute('select id, description from test where id = %(id)s', {'id': 1}).fetch_one() assert data.id == 1 def test_find_by_select(): with Database() as database: data = database.select('test').where('description', 'Test%', operator='like').execute().fetch_all() assert len(data) == 4 def test_find_by_select_without_where(): with Database() as database: data = database.select('test').execute().fetch_all() print(data) assert len(data) == 4 def test_find_many(): with Database() as database: data = database.execute('select id, description from test').fetch_many(2) assert len(data) == 2 def test_find_paging_by_select(): with Database() as database: data = database.select('test').fields('id', 'description').where('id', 3, operator='<').order_by('id').paging(0, 2) assert type(data) == Page assert len(data.data) == 2 assert data.data[0].id == 1 assert data.data[0].description == 'Test 1' def test_find_paging_by_select_without_where(): with Database() as database: data = database.select('test').paging(0, 2) assert type(data) == Page assert len(data.data) == 2 def test_find_without_result(): with Database() as database: data = database.select('test').where('1', '0', constant=True).execute().fetch_one() assert data is None def test_insert(): with Database() as database: database.insert('test').set('id', 1).set('description', 'Test 1').execute() database.insert('test').set('id', 2).set('description', 'Test 2').execute() database.insert('test').set('id', 3).set('description', 'Test 3').execute() database.insert('test').set('id', 4).set('description', 'Test 4').execute() def test_rollback(): try: with Database() as database: database.insert('test').set('id', 10).set('description', 'Test 10').execute() raise Exception() except(): with Database() as database: assert database.select('test').where('id', 10).execute().fetch_one() is None def test_truncate_table(): with Database() as database: database.execute(''' truncate table test ''') def test_update(): with Database() as database: data = database.update('test').set('description', 'New Test 1').where('id', 1).execute() assert data.cursor.rowcount == 1 def test_update_where_all(): try: with Database() as database: database.update('test').set('description', 'New Test 1').where_all({'id': 1, 'description': 'Test 1'}).execute() except() as e: assert e is None
true
true
1c39ebdbdc6d584b05bc200ab2e7204acc597dc9
14,241
py
Python
discovery-infra/start_discovery.py
nmagnezi/assisted-test-infra
a31dc4350d77681038a16c05d9a1e09fa992578a
[ "Apache-2.0" ]
null
null
null
discovery-infra/start_discovery.py
nmagnezi/assisted-test-infra
a31dc4350d77681038a16c05d9a1e09fa992578a
[ "Apache-2.0" ]
null
null
null
discovery-infra/start_discovery.py
nmagnezi/assisted-test-infra
a31dc4350d77681038a16c05d9a1e09fa992578a
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python3 # -*- coding: utf-8 -*- import argparse import dns.resolver import ipaddress import json import os import pprint import time import uuid from distutils.dir_util import copy_tree from pathlib import Path import bm_inventory_api import consts import install_cluster import utils import waiting from logger import log # Creates ip list, if will be needed in any other place, please move to utils def _create_ip_address_list(node_count, starting_ip_addr): return [str(ipaddress.ip_address(starting_ip_addr) + i) for i in range(node_count)] # Filling tfvars json files with terraform needed variables to spawn vms def fill_tfvars(image_path, storage_path, master_count, nodes_details): if not os.path.exists(consts.TFVARS_JSON_FILE): Path(consts.TF_FOLDER).mkdir(parents=True, exist_ok=True) copy_tree(consts.TF_TEMPLATE, consts.TF_FOLDER) with open(consts.TFVARS_JSON_FILE) as _file: tfvars = json.load(_file) master_starting_ip = str( ipaddress.ip_address( ipaddress.IPv4Network(nodes_details["machine_cidr"]).network_address ) + 10 ) worker_starting_ip = str( ipaddress.ip_address( ipaddress.IPv4Network(nodes_details["machine_cidr"]).network_address ) + 10 + int(tfvars["master_count"]) ) tfvars["image_path"] = image_path tfvars["master_count"] = min(master_count, consts.NUMBER_OF_MASTERS) tfvars["libvirt_master_ips"] = _create_ip_address_list( min(master_count, consts.NUMBER_OF_MASTERS), starting_ip_addr=master_starting_ip ) tfvars["api_vip"] = _get_vips_ips()[0] tfvars["libvirt_worker_ips"] = _create_ip_address_list( nodes_details["worker_count"], starting_ip_addr=worker_starting_ip ) tfvars["libvirt_storage_pool_path"] = storage_path tfvars.update(nodes_details) with open(consts.TFVARS_JSON_FILE, "w") as _file: json.dump(tfvars, _file) # Run make run terraform -> creates vms def create_nodes(image_path, storage_path, master_count, nodes_details): log.info("Creating tfvars") fill_tfvars(image_path, storage_path, master_count, nodes_details) log.info("Start running terraform") cmd = "make _run_terraform" return utils.run_command(cmd) # Starts terraform nodes creation, waits till all nodes will get ip and will move to known status def create_nodes_and_wait_till_registered( inventory_client, cluster, image_path, storage_path, master_count, nodes_details ): nodes_count = master_count + nodes_details["worker_count"] create_nodes( image_path, storage_path=storage_path, master_count=master_count, nodes_details=nodes_details, ) # TODO: Check for only new nodes utils.wait_till_nodes_are_ready( nodes_count=nodes_count, network_name=nodes_details["libvirt_network_name"] ) if not inventory_client: log.info("No inventory url, will not wait till nodes registration") return log.info("Wait till nodes will be registered") waiting.wait( lambda: utils.are_all_libvirt_nodes_in_cluster_hosts( inventory_client, cluster.id, nodes_details["libvirt_network_name"] ), timeout_seconds=consts.NODES_REGISTERED_TIMEOUT, sleep_seconds=10, waiting_for="Nodes to be registered in inventory service", ) log.info("Registered nodes are:") pprint.pprint(inventory_client.get_cluster_hosts(cluster.id)) # Set nodes roles by vm name # If master in name -> role will be master, same for worker def set_hosts_roles(client, cluster_id, network_name): added_hosts = [] libvirt_nodes = utils.get_libvirt_nodes_mac_role_ip_and_name(network_name) inventory_hosts = client.get_cluster_hosts(cluster_id) for libvirt_mac, libvirt_metadata in libvirt_nodes.items(): for host in inventory_hosts: inventory = json.loads(host["inventory"]) if libvirt_mac.lower() in map( lambda interface: interface["mac_address"].lower(), inventory["interfaces"], ): added_hosts.append({"id": host["id"], "role": libvirt_metadata["role"]}) assert len(libvirt_nodes) == len( added_hosts ), "All nodes should have matching inventory hosts" client.set_hosts_roles(cluster_id=cluster_id, hosts_with_roles=added_hosts) def set_cluster_vips(client, cluster_id): cluster_info = client.cluster_get(cluster_id) api_vip, ingress_vip = _get_vips_ips() cluster_info.api_vip = api_vip cluster_info.ingress_vip = ingress_vip client.update_cluster(cluster_id, cluster_info) def _get_vips_ips(): network_subnet_starting_ip = str( ipaddress.ip_address( ipaddress.IPv4Network(args.vm_network_cidr).network_address ) + 100 ) ips = _create_ip_address_list( 2, starting_ip_addr=str(ipaddress.ip_address(network_subnet_starting_ip)) ) return ips[0], ips[1] # TODO add config file # Converts params from args to bm-inventory cluster params def _cluster_create_params(): params = { "openshift_version": args.openshift_version, "base_dns_domain": args.base_dns_domain, "cluster_network_cidr": args.cluster_network, "cluster_network_host_prefix": args.host_prefix, "service_network_cidr": args.service_network, "pull_secret": args.pull_secret, } return params # convert params from args to terraform tfvars def _create_node_details(cluster_name): return { "libvirt_worker_memory": args.worker_memory, "libvirt_master_memory": args.master_memory, "worker_count": args.number_of_workers, "cluster_name": cluster_name, "cluster_domain": args.base_dns_domain, "machine_cidr": args.vm_network_cidr, "libvirt_network_name": args.network_name, "libvirt_network_if": args.network_bridge, } def validate_dns(client, cluster_id): if not args.managed_dns_domains: # 'set_dns' (using dnsmasq) is invoked after nodes_flow return cluster = client.cluster_get(cluster_id) api_address = "api.{}.{}".format(cluster.name, cluster.base_dns_domain) ingress_address = "ingress.apps.{}.{}".format(cluster.name, cluster.base_dns_domain) log.info( "Validating resolvability of the following domains: %s -> %s, %s -> %s", api_address, cluster.api_vip, ingress_address, cluster.ingress_vip, ) try: api_answers = dns.resolver.query(api_address, "A") ingress_answers = dns.resolver.query(ingress_address, "A") api_vip = str(api_answers[0]) ingress_vip = str(ingress_answers[0]) if api_vip != cluster.api_vip or ingress_vip != cluster.ingress_vip: raise Exception("DNS domains are not resolvable") log.info("DNS domains are resolvable") except Exception as e: log.error("Failed to resolve DNS domains") raise e # Create vms from downloaded iso that will connect to bm-inventory and register # If install cluster is set , it will run install cluster command and wait till all nodes will be in installing status def nodes_flow(client, cluster_name, cluster): nodes_details = _create_node_details(cluster_name) if cluster: nodes_details["cluster_inventory_id"] = cluster.id create_nodes_and_wait_till_registered( inventory_client=client, cluster=cluster, image_path=args.image or consts.IMAGE_PATH, storage_path=args.storage_path, master_count=args.master_count, nodes_details=nodes_details, ) if client: cluster_info = client.cluster_get(cluster.id) macs = utils.get_libvirt_nodes_macs(nodes_details["libvirt_network_name"]) if not (cluster_info.api_vip and cluster_info.ingress_vip): utils.wait_till_hosts_with_macs_are_in_status( client=client, cluster_id=cluster.id, macs=macs, statuses=[ consts.NodesStatus.INSUFFICIENT, consts.NodesStatus.PENDING_FOR_INPUT, ], ) set_cluster_vips(client, cluster.id) else: log.info("VIPs already configured") set_hosts_roles(client, cluster.id, nodes_details["libvirt_network_name"]) utils.wait_till_hosts_with_macs_are_in_status( client=client, cluster_id=cluster.id, macs=macs, statuses=[consts.NodesStatus.KNOWN], ) log.info("Printing after setting roles") pprint.pprint(client.get_cluster_hosts(cluster.id)) if args.install_cluster: time.sleep(10) install_cluster.run_install_flow( client=client, cluster_id=cluster.id, kubeconfig_path=consts.DEFAULT_CLUSTER_KUBECONFIG_PATH, pull_secret=args.pull_secret, ) # Validate DNS domains resolvability validate_dns(client, cluster.id) def main(): client = None cluster = {} random_postfix = str(uuid.uuid4())[:8] cluster_name = args.cluster_name or consts.CLUSTER_PREFIX + random_postfix if args.managed_dns_domains: args.base_dns_domain = args.managed_dns_domains.split(":")[0] if args.cluster_name: cluster_name = "%s-%s" % (args.cluster_name, random_postfix) # If image is passed, there is no need to create cluster and download image, need only to spawn vms with is image if not args.image: utils.recreate_folder(consts.IMAGE_FOLDER) client = bm_inventory_api.create_client(args.inventory_url) if args.cluster_id: cluster = client.cluster_get(cluster_id=args.cluster_id) else: cluster = client.create_cluster( cluster_name, ssh_public_key=args.ssh_key, **_cluster_create_params() ) client.generate_and_download_image( cluster_id=cluster.id, image_path=consts.IMAGE_PATH, ssh_key=args.ssh_key, proxy_url=args.proxy_url, ) # Iso only, cluster will be up and iso downloaded but vm will not be created if not args.iso_only: nodes_flow(client, cluster_name, cluster) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run discovery flow") parser.add_argument( "-i", "--image", help="Run terraform with given image", type=str, default="" ) parser.add_argument( "-n", "--master-count", help="Masters count to spawn", type=int, default=3 ) parser.add_argument( "-p", "--storage-path", help="Path to storage pool", type=str, default=consts.STORAGE_PATH, ) parser.add_argument( "-si", "--skip-inventory", help="Node count to spawn", action="store_true" ) parser.add_argument("-k", "--ssh-key", help="Path to ssh key", type=str, default="") parser.add_argument( "-mm", "--master-memory", help="Master memory (ram) in mb", type=int, default=8192, ) parser.add_argument( "-wm", "--worker-memory", help="Worker memory (ram) in mb", type=int, default=8192, ) parser.add_argument( "-nw", "--number-of-workers", help="Workers count to spawn", type=int, default=0 ) parser.add_argument( "-cn", "--cluster-network", help="Cluster network with cidr", type=str, default="10.128.0.0/14", ) parser.add_argument( "-hp", "--host-prefix", help="Host prefix to use", type=int, default=23 ) parser.add_argument( "-sn", "--service-network", help="Network for services", type=str, default="172.30.0.0/16", ) parser.add_argument( "-ps", "--pull-secret", help="Pull secret", type=str, default="" ) parser.add_argument( "-ov", "--openshift-version", help="Openshift version", type=str, default="4.5" ) parser.add_argument( "-bd", "--base-dns-domain", help="Base dns domain", type=str, default="redhat.com", ) parser.add_argument( "-mD", "--managed-dns-domains", help="DNS domains that are managaed by bm-inventory, format: domain_name:domain_id/provider_type.", type=str, default="", ) parser.add_argument( "-cN", "--cluster-name", help="Cluster name", type=str, default="" ) parser.add_argument( "-vN", "--vm-network-cidr", help="Vm network cidr", type=str, default="192.168.126.0/24", ) parser.add_argument( "-nN", "--network-name", help="Network name", type=str, default="test-infra-net" ) parser.add_argument( "-in", "--install-cluster", help="Install cluster, will take latest id", action="store_true", ) parser.add_argument( "-nB", "--network-bridge", help="Network bridge to use", type=str, default="tt0" ) parser.add_argument( "-iO", "--iso-only", help="Create cluster and download iso, no need to spawn cluster", action="store_true", ) parser.add_argument( "-pU", "--proxy-url", help="Proxy url to pass to inventory cluster", type=str, default="", ) parser.add_argument( "-rv", "--run-with-vips", help="Run cluster create with adding vips " "from the same subnet as vms", type=str, default="no", ) parser.add_argument( "-iU", "--inventory-url", help="Full url of remote inventory", type=str, default="", ) parser.add_argument( "-id", "--cluster-id", help="Cluster id to install", type=str, default=None ) args = parser.parse_args() if not args.pull_secret and args.install_cluster: raise Exception("Can't install cluster without pull secret, please provide one") main()
33.508235
118
0.649884
import argparse import dns.resolver import ipaddress import json import os import pprint import time import uuid from distutils.dir_util import copy_tree from pathlib import Path import bm_inventory_api import consts import install_cluster import utils import waiting from logger import log def _create_ip_address_list(node_count, starting_ip_addr): return [str(ipaddress.ip_address(starting_ip_addr) + i) for i in range(node_count)] def fill_tfvars(image_path, storage_path, master_count, nodes_details): if not os.path.exists(consts.TFVARS_JSON_FILE): Path(consts.TF_FOLDER).mkdir(parents=True, exist_ok=True) copy_tree(consts.TF_TEMPLATE, consts.TF_FOLDER) with open(consts.TFVARS_JSON_FILE) as _file: tfvars = json.load(_file) master_starting_ip = str( ipaddress.ip_address( ipaddress.IPv4Network(nodes_details["machine_cidr"]).network_address ) + 10 ) worker_starting_ip = str( ipaddress.ip_address( ipaddress.IPv4Network(nodes_details["machine_cidr"]).network_address ) + 10 + int(tfvars["master_count"]) ) tfvars["image_path"] = image_path tfvars["master_count"] = min(master_count, consts.NUMBER_OF_MASTERS) tfvars["libvirt_master_ips"] = _create_ip_address_list( min(master_count, consts.NUMBER_OF_MASTERS), starting_ip_addr=master_starting_ip ) tfvars["api_vip"] = _get_vips_ips()[0] tfvars["libvirt_worker_ips"] = _create_ip_address_list( nodes_details["worker_count"], starting_ip_addr=worker_starting_ip ) tfvars["libvirt_storage_pool_path"] = storage_path tfvars.update(nodes_details) with open(consts.TFVARS_JSON_FILE, "w") as _file: json.dump(tfvars, _file) def create_nodes(image_path, storage_path, master_count, nodes_details): log.info("Creating tfvars") fill_tfvars(image_path, storage_path, master_count, nodes_details) log.info("Start running terraform") cmd = "make _run_terraform" return utils.run_command(cmd) def create_nodes_and_wait_till_registered( inventory_client, cluster, image_path, storage_path, master_count, nodes_details ): nodes_count = master_count + nodes_details["worker_count"] create_nodes( image_path, storage_path=storage_path, master_count=master_count, nodes_details=nodes_details, ) utils.wait_till_nodes_are_ready( nodes_count=nodes_count, network_name=nodes_details["libvirt_network_name"] ) if not inventory_client: log.info("No inventory url, will not wait till nodes registration") return log.info("Wait till nodes will be registered") waiting.wait( lambda: utils.are_all_libvirt_nodes_in_cluster_hosts( inventory_client, cluster.id, nodes_details["libvirt_network_name"] ), timeout_seconds=consts.NODES_REGISTERED_TIMEOUT, sleep_seconds=10, waiting_for="Nodes to be registered in inventory service", ) log.info("Registered nodes are:") pprint.pprint(inventory_client.get_cluster_hosts(cluster.id)) def set_hosts_roles(client, cluster_id, network_name): added_hosts = [] libvirt_nodes = utils.get_libvirt_nodes_mac_role_ip_and_name(network_name) inventory_hosts = client.get_cluster_hosts(cluster_id) for libvirt_mac, libvirt_metadata in libvirt_nodes.items(): for host in inventory_hosts: inventory = json.loads(host["inventory"]) if libvirt_mac.lower() in map( lambda interface: interface["mac_address"].lower(), inventory["interfaces"], ): added_hosts.append({"id": host["id"], "role": libvirt_metadata["role"]}) assert len(libvirt_nodes) == len( added_hosts ), "All nodes should have matching inventory hosts" client.set_hosts_roles(cluster_id=cluster_id, hosts_with_roles=added_hosts) def set_cluster_vips(client, cluster_id): cluster_info = client.cluster_get(cluster_id) api_vip, ingress_vip = _get_vips_ips() cluster_info.api_vip = api_vip cluster_info.ingress_vip = ingress_vip client.update_cluster(cluster_id, cluster_info) def _get_vips_ips(): network_subnet_starting_ip = str( ipaddress.ip_address( ipaddress.IPv4Network(args.vm_network_cidr).network_address ) + 100 ) ips = _create_ip_address_list( 2, starting_ip_addr=str(ipaddress.ip_address(network_subnet_starting_ip)) ) return ips[0], ips[1] def _cluster_create_params(): params = { "openshift_version": args.openshift_version, "base_dns_domain": args.base_dns_domain, "cluster_network_cidr": args.cluster_network, "cluster_network_host_prefix": args.host_prefix, "service_network_cidr": args.service_network, "pull_secret": args.pull_secret, } return params def _create_node_details(cluster_name): return { "libvirt_worker_memory": args.worker_memory, "libvirt_master_memory": args.master_memory, "worker_count": args.number_of_workers, "cluster_name": cluster_name, "cluster_domain": args.base_dns_domain, "machine_cidr": args.vm_network_cidr, "libvirt_network_name": args.network_name, "libvirt_network_if": args.network_bridge, } def validate_dns(client, cluster_id): if not args.managed_dns_domains: return cluster = client.cluster_get(cluster_id) api_address = "api.{}.{}".format(cluster.name, cluster.base_dns_domain) ingress_address = "ingress.apps.{}.{}".format(cluster.name, cluster.base_dns_domain) log.info( "Validating resolvability of the following domains: %s -> %s, %s -> %s", api_address, cluster.api_vip, ingress_address, cluster.ingress_vip, ) try: api_answers = dns.resolver.query(api_address, "A") ingress_answers = dns.resolver.query(ingress_address, "A") api_vip = str(api_answers[0]) ingress_vip = str(ingress_answers[0]) if api_vip != cluster.api_vip or ingress_vip != cluster.ingress_vip: raise Exception("DNS domains are not resolvable") log.info("DNS domains are resolvable") except Exception as e: log.error("Failed to resolve DNS domains") raise e def nodes_flow(client, cluster_name, cluster): nodes_details = _create_node_details(cluster_name) if cluster: nodes_details["cluster_inventory_id"] = cluster.id create_nodes_and_wait_till_registered( inventory_client=client, cluster=cluster, image_path=args.image or consts.IMAGE_PATH, storage_path=args.storage_path, master_count=args.master_count, nodes_details=nodes_details, ) if client: cluster_info = client.cluster_get(cluster.id) macs = utils.get_libvirt_nodes_macs(nodes_details["libvirt_network_name"]) if not (cluster_info.api_vip and cluster_info.ingress_vip): utils.wait_till_hosts_with_macs_are_in_status( client=client, cluster_id=cluster.id, macs=macs, statuses=[ consts.NodesStatus.INSUFFICIENT, consts.NodesStatus.PENDING_FOR_INPUT, ], ) set_cluster_vips(client, cluster.id) else: log.info("VIPs already configured") set_hosts_roles(client, cluster.id, nodes_details["libvirt_network_name"]) utils.wait_till_hosts_with_macs_are_in_status( client=client, cluster_id=cluster.id, macs=macs, statuses=[consts.NodesStatus.KNOWN], ) log.info("Printing after setting roles") pprint.pprint(client.get_cluster_hosts(cluster.id)) if args.install_cluster: time.sleep(10) install_cluster.run_install_flow( client=client, cluster_id=cluster.id, kubeconfig_path=consts.DEFAULT_CLUSTER_KUBECONFIG_PATH, pull_secret=args.pull_secret, ) validate_dns(client, cluster.id) def main(): client = None cluster = {} random_postfix = str(uuid.uuid4())[:8] cluster_name = args.cluster_name or consts.CLUSTER_PREFIX + random_postfix if args.managed_dns_domains: args.base_dns_domain = args.managed_dns_domains.split(":")[0] if args.cluster_name: cluster_name = "%s-%s" % (args.cluster_name, random_postfix) if not args.image: utils.recreate_folder(consts.IMAGE_FOLDER) client = bm_inventory_api.create_client(args.inventory_url) if args.cluster_id: cluster = client.cluster_get(cluster_id=args.cluster_id) else: cluster = client.create_cluster( cluster_name, ssh_public_key=args.ssh_key, **_cluster_create_params() ) client.generate_and_download_image( cluster_id=cluster.id, image_path=consts.IMAGE_PATH, ssh_key=args.ssh_key, proxy_url=args.proxy_url, ) if not args.iso_only: nodes_flow(client, cluster_name, cluster) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run discovery flow") parser.add_argument( "-i", "--image", help="Run terraform with given image", type=str, default="" ) parser.add_argument( "-n", "--master-count", help="Masters count to spawn", type=int, default=3 ) parser.add_argument( "-p", "--storage-path", help="Path to storage pool", type=str, default=consts.STORAGE_PATH, ) parser.add_argument( "-si", "--skip-inventory", help="Node count to spawn", action="store_true" ) parser.add_argument("-k", "--ssh-key", help="Path to ssh key", type=str, default="") parser.add_argument( "-mm", "--master-memory", help="Master memory (ram) in mb", type=int, default=8192, ) parser.add_argument( "-wm", "--worker-memory", help="Worker memory (ram) in mb", type=int, default=8192, ) parser.add_argument( "-nw", "--number-of-workers", help="Workers count to spawn", type=int, default=0 ) parser.add_argument( "-cn", "--cluster-network", help="Cluster network with cidr", type=str, default="10.128.0.0/14", ) parser.add_argument( "-hp", "--host-prefix", help="Host prefix to use", type=int, default=23 ) parser.add_argument( "-sn", "--service-network", help="Network for services", type=str, default="172.30.0.0/16", ) parser.add_argument( "-ps", "--pull-secret", help="Pull secret", type=str, default="" ) parser.add_argument( "-ov", "--openshift-version", help="Openshift version", type=str, default="4.5" ) parser.add_argument( "-bd", "--base-dns-domain", help="Base dns domain", type=str, default="redhat.com", ) parser.add_argument( "-mD", "--managed-dns-domains", help="DNS domains that are managaed by bm-inventory, format: domain_name:domain_id/provider_type.", type=str, default="", ) parser.add_argument( "-cN", "--cluster-name", help="Cluster name", type=str, default="" ) parser.add_argument( "-vN", "--vm-network-cidr", help="Vm network cidr", type=str, default="192.168.126.0/24", ) parser.add_argument( "-nN", "--network-name", help="Network name", type=str, default="test-infra-net" ) parser.add_argument( "-in", "--install-cluster", help="Install cluster, will take latest id", action="store_true", ) parser.add_argument( "-nB", "--network-bridge", help="Network bridge to use", type=str, default="tt0" ) parser.add_argument( "-iO", "--iso-only", help="Create cluster and download iso, no need to spawn cluster", action="store_true", ) parser.add_argument( "-pU", "--proxy-url", help="Proxy url to pass to inventory cluster", type=str, default="", ) parser.add_argument( "-rv", "--run-with-vips", help="Run cluster create with adding vips " "from the same subnet as vms", type=str, default="no", ) parser.add_argument( "-iU", "--inventory-url", help="Full url of remote inventory", type=str, default="", ) parser.add_argument( "-id", "--cluster-id", help="Cluster id to install", type=str, default=None ) args = parser.parse_args() if not args.pull_secret and args.install_cluster: raise Exception("Can't install cluster without pull secret, please provide one") main()
true
true
1c39ed4d45a3b5b0ec6dda5a6a04cced4f458431
4,998
py
Python
functions/get_Proposals.py
GuillaumeBalezo/SOD-python
c54566d25e01b252815fbc613a8d0af1c77818b6
[ "MIT" ]
null
null
null
functions/get_Proposals.py
GuillaumeBalezo/SOD-python
c54566d25e01b252815fbc613a8d0af1c77818b6
[ "MIT" ]
null
null
null
functions/get_Proposals.py
GuillaumeBalezo/SOD-python
c54566d25e01b252815fbc613a8d0af1c77818b6
[ "MIT" ]
null
null
null
# Functions for generating the proposal set for optimization # # Jianming Zhang, Stan Sclaroff, Zhe Lin, Xiaohui Shen, # Brian Price and Radomír Mech. "Unconstrained Salient # Object Detection via Proposal Subset Optimization." # CVPR, 2016. # Code written by Guillaume Balezo, 2020 import numpy as np from scipy import cluster import cv2 from tensorflow.keras.applications.vgg16 import preprocess_input from tensorflow.keras.preprocessing.image import load_img from functions.utils import get_iou_float, get_roi_bbox def get_proposals(I_batch, net, param): """ Generate the proposal set for optimization. Args: I_batch: Images of the batch. net: CNN model. param: parameters of the model. Returns: P_batch: Prediction over the batch. S_batch: Scores associated with the predictions: """ Ip = prepare_image(I_batch, param) scores_batch = net.predict(Ip) P_batch = [] S_batch = [] for idx_batch in range(len(I_batch)): scores = scores_batch[idx_batch] I = I_batch[idx_batch] imsz = np.array([I.shape[0], I.shape[1]]) top_idxs = np.argsort(-scores) scores = np.take(scores, top_idxs) BB = param['center'][:, top_idxs] P = BB[:, : param['masterImgPropN']].copy() S = scores[: param['masterImgPropN']].copy() # extract ROIs ROI = BB[:, : param['roiN']].copy() ROI = post_proc(ROI, imsz, param) ROI = cluster_boxes(ROI, param) # merge some ROI if needed # process ROIs Ip = crop_imgs_and_prepare(I.copy(), ROI, param) if Ip.size == 0: P_batch.append(P) S_batch.append(S) continue scores = net.predict(Ip) top_idxs = np.argsort(-scores, axis = 1) scores = np.take_along_axis(scores, top_idxs, axis = 1) for i in range(Ip.shape[0]): B = param['center'][:, top_idxs[i, : param['subImgPropN']]] roi = ROI[:, i] / np.tile(np.roll(imsz, 1), 2) B = get_roi_bbox(B.copy(), roi) P = np.hstack((P, B)) S = np.hstack((S, scores[i, : param['subImgPropN']])) P_batch.append(P) S_batch.append(S) return P_batch, S_batch def prepare_image(I_batch, param): """ Preprocess the images before the CNN predictions. Args: I_batch: Images of the batch. param: parameters of the model. Returns: Ip: Images of the batch preprocessed """ Ip = np.zeros((len(I_batch), param['width'], param['height'], 3)) for i in range(len(I_batch)): img = I_batch[i] img = preprocess_input(img, mode='caffe') Ip[i] = np.expand_dims(cv2.resize(img, (param['width'], param['height']), interpolation = cv2.INTER_LINEAR), axis = 0) return Ip def cluster_boxes(BB, param): if BB.shape[1] < 2: ROI = np.copy(BB) return ROI D = [] for i in range(BB.shape[1]): for j in range(i + 1, BB.shape[1]): D.append(1 - get_iou_float(BB[:, j].reshape(-1, 1).T, BB[:, i])) Z = cluster.hierarchy.linkage(D) T = cluster.hierarchy.fcluster(Z, param['roiClusterCutoff'], criterion = 'distance') ROI = np.vstack((BB[:2, T == 1].min(axis = 1, keepdims=True), BB[2:, T == 1].max(axis = 1, keepdims=True))) # initialisation for the for loop for i in range(2, T.max() + 1): ROI = np.hstack((ROI, np.vstack((BB[:2, T == i].min(axis = 1, keepdims=True), BB[2:, T == i].max(axis = 1, keepdims=True))))) return ROI def post_proc(ROI, imsz, param): """ Post processing of the CNN predictions. Args: ROI: Region of interest. imsz: Image size. param: parameters of the model. Returns: ROI: Post-processed CNN predictions """ # expand w = ROI[2] - ROI[0] h = ROI[3] - ROI[1] ROI[0] = ROI[0] - 0.5 * w * param['roiExpand'] ROI[1] = ROI[1] - 0.5 * h * param['roiExpand'] ROI[2] = ROI[0] + w * (1 + param['roiExpand']) ROI[3] = ROI[1] + h * (1 + param['roiExpand']) ROI = ROI * np.tile(np.roll(imsz, 1), 2).reshape(-1, 1) ROI[:2] = np.maximum(ROI[:2], 0) ROI[2] = np.minimum(ROI[2], imsz[1]) ROI[3] = np.minimum(ROI[3], imsz[0]) # removing area = (ROI[2] - ROI[0] + 1) * (ROI[3] - ROI[1] + 1) ROI = ROI[:, area < (0.9 * imsz[0] * imsz[1])] return ROI def crop_imgs_and_prepare(img, roilist, param): """ Crop the image on the region of interest and preprocess the crops before the CNN network. The function is used in get_proposals, during the refinement step. Args: img: image. roilist: Regions of interest. param: parameters of the model. Returns: Ip: Preprocessed crops of the image """ Ip = [] if len(roilist.shape) == 1: roilist = roilist.reshape(-1, 1) for i in range(roilist.shape[1]): roi = roilist[:, i] img_cropped = img[int(roi[1]) : int(roi[3]) + 1, int(roi[0]) : int(roi[2]) + 1, :] img_cropped = preprocess_input(img_cropped, mode = 'caffe') Ip.append(cv2.resize(img_cropped, (param['height'], param['width']), interpolation = cv2.INTER_LINEAR)) return np.array(Ip)
35.956835
143
0.622449
# Object Detection via Proposal Subset Optimization." import numpy as np from scipy import cluster import cv2 from tensorflow.keras.applications.vgg16 import preprocess_input from tensorflow.keras.preprocessing.image import load_img from functions.utils import get_iou_float, get_roi_bbox def get_proposals(I_batch, net, param): Ip = prepare_image(I_batch, param) scores_batch = net.predict(Ip) P_batch = [] S_batch = [] for idx_batch in range(len(I_batch)): scores = scores_batch[idx_batch] I = I_batch[idx_batch] imsz = np.array([I.shape[0], I.shape[1]]) top_idxs = np.argsort(-scores) scores = np.take(scores, top_idxs) BB = param['center'][:, top_idxs] P = BB[:, : param['masterImgPropN']].copy() S = scores[: param['masterImgPropN']].copy() ROI = BB[:, : param['roiN']].copy() ROI = post_proc(ROI, imsz, param) ROI = cluster_boxes(ROI, param) Ip = crop_imgs_and_prepare(I.copy(), ROI, param) if Ip.size == 0: P_batch.append(P) S_batch.append(S) continue scores = net.predict(Ip) top_idxs = np.argsort(-scores, axis = 1) scores = np.take_along_axis(scores, top_idxs, axis = 1) for i in range(Ip.shape[0]): B = param['center'][:, top_idxs[i, : param['subImgPropN']]] roi = ROI[:, i] / np.tile(np.roll(imsz, 1), 2) B = get_roi_bbox(B.copy(), roi) P = np.hstack((P, B)) S = np.hstack((S, scores[i, : param['subImgPropN']])) P_batch.append(P) S_batch.append(S) return P_batch, S_batch def prepare_image(I_batch, param): Ip = np.zeros((len(I_batch), param['width'], param['height'], 3)) for i in range(len(I_batch)): img = I_batch[i] img = preprocess_input(img, mode='caffe') Ip[i] = np.expand_dims(cv2.resize(img, (param['width'], param['height']), interpolation = cv2.INTER_LINEAR), axis = 0) return Ip def cluster_boxes(BB, param): if BB.shape[1] < 2: ROI = np.copy(BB) return ROI D = [] for i in range(BB.shape[1]): for j in range(i + 1, BB.shape[1]): D.append(1 - get_iou_float(BB[:, j].reshape(-1, 1).T, BB[:, i])) Z = cluster.hierarchy.linkage(D) T = cluster.hierarchy.fcluster(Z, param['roiClusterCutoff'], criterion = 'distance') ROI = np.vstack((BB[:2, T == 1].min(axis = 1, keepdims=True), BB[2:, T == 1].max(axis = 1, keepdims=True))) for i in range(2, T.max() + 1): ROI = np.hstack((ROI, np.vstack((BB[:2, T == i].min(axis = 1, keepdims=True), BB[2:, T == i].max(axis = 1, keepdims=True))))) return ROI def post_proc(ROI, imsz, param): w = ROI[2] - ROI[0] h = ROI[3] - ROI[1] ROI[0] = ROI[0] - 0.5 * w * param['roiExpand'] ROI[1] = ROI[1] - 0.5 * h * param['roiExpand'] ROI[2] = ROI[0] + w * (1 + param['roiExpand']) ROI[3] = ROI[1] + h * (1 + param['roiExpand']) ROI = ROI * np.tile(np.roll(imsz, 1), 2).reshape(-1, 1) ROI[:2] = np.maximum(ROI[:2], 0) ROI[2] = np.minimum(ROI[2], imsz[1]) ROI[3] = np.minimum(ROI[3], imsz[0]) area = (ROI[2] - ROI[0] + 1) * (ROI[3] - ROI[1] + 1) ROI = ROI[:, area < (0.9 * imsz[0] * imsz[1])] return ROI def crop_imgs_and_prepare(img, roilist, param): Ip = [] if len(roilist.shape) == 1: roilist = roilist.reshape(-1, 1) for i in range(roilist.shape[1]): roi = roilist[:, i] img_cropped = img[int(roi[1]) : int(roi[3]) + 1, int(roi[0]) : int(roi[2]) + 1, :] img_cropped = preprocess_input(img_cropped, mode = 'caffe') Ip.append(cv2.resize(img_cropped, (param['height'], param['width']), interpolation = cv2.INTER_LINEAR)) return np.array(Ip)
true
true
1c39ee0d09d309601976177d3ee3b77136688f28
598
gyp
Python
Dependencies/gyp-master/test/link-objects/link-objects.gyp
knight666/exlibris
b21b46e0c84e5c4f81f8048022cda88e7bb3dca2
[ "MIT" ]
null
null
null
Dependencies/gyp-master/test/link-objects/link-objects.gyp
knight666/exlibris
b21b46e0c84e5c4f81f8048022cda88e7bb3dca2
[ "MIT" ]
null
null
null
Dependencies/gyp-master/test/link-objects/link-objects.gyp
knight666/exlibris
b21b46e0c84e5c4f81f8048022cda88e7bb3dca2
[ "MIT" ]
null
null
null
# Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'link-objects', 'type': 'executable', 'actions': [ { 'action_name': 'build extra object', 'inputs': ['extra.c'], 'outputs': ['extra.o'], 'action': ['gcc', '-o', 'extra.o', '-c', 'extra.c'], 'process_outputs_as_sources': 1, }, ], 'sources': [ 'base.c', ], }, ], }
23.92
73
0.4699
{ 'targets': [ { 'target_name': 'link-objects', 'type': 'executable', 'actions': [ { 'action_name': 'build extra object', 'inputs': ['extra.c'], 'outputs': ['extra.o'], 'action': ['gcc', '-o', 'extra.o', '-c', 'extra.c'], 'process_outputs_as_sources': 1, }, ], 'sources': [ 'base.c', ], }, ], }
true
true
1c39ee4c86ec9922e58fdf773cb6aa7bd3757d51
26
py
Python
btd6_memory_info/generated/UnityEngine/PlayerLoop/Initialization/initialization.py
56kyle/bloons_auto
419d55b51d1cddc49099593970adf1c67985b389
[ "MIT" ]
null
null
null
btd6_memory_info/generated/UnityEngine/PlayerLoop/Initialization/initialization.py
56kyle/bloons_auto
419d55b51d1cddc49099593970adf1c67985b389
[ "MIT" ]
null
null
null
btd6_memory_info/generated/UnityEngine/PlayerLoop/Initialization/initialization.py
56kyle/bloons_auto
419d55b51d1cddc49099593970adf1c67985b389
[ "MIT" ]
null
null
null
class Initialization: pass
26
26
0.884615
class Initialization: pass
true
true
1c39eff48d75c5db6921826a3a317ebc0b7bbe05
8,176
py
Python
test/functional/feature_part_smsgpaidfee.py
empower-network/empower
3b63fbfe394574855d176262d604060f49ad77c1
[ "MIT" ]
2
2019-06-26T23:49:53.000Z
2019-08-13T06:49:56.000Z
test/functional/feature_part_smsgpaidfee.py
empower-network/empower
3b63fbfe394574855d176262d604060f49ad77c1
[ "MIT" ]
null
null
null
test/functional/feature_part_smsgpaidfee.py
empower-network/empower
3b63fbfe394574855d176262d604060f49ad77c1
[ "MIT" ]
4
2019-08-07T04:36:40.000Z
2021-07-07T03:21:31.000Z
#!/usr/bin/env python3 # Copyright (c) 2017-2019 The Particl Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import struct import copy from test_framework.test_empower import EmpowerTestFramework from test_framework.util import connect_nodes, assert_raises_rpc_error def getvarint(bb, ofs=0): i = bb[ofs] & 0x7F nb = 1 ofs += 1 while (bb[ofs-1] & 0x80): i += (bb[ofs] & 0x7F) << (7 * nb) ofs += 1 nb += 1 return i, nb def putvarint(i): bb = bytearray() b = i & 0x7F i = i >> 7 while i > 0: bb += bytes([b | 0x80,]) b = i & 0x7F i = i >> 7 bb += bytes([b,]) return bb class SmsgPaidFeeTest(EmpowerTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [['-debug', '-nocheckblockindex', '-noacceptnonstdtxn', '-reservebalance=10000000'] for i in range(self.num_nodes)] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def setup_network(self, split=False): self.add_nodes(self.num_nodes, extra_args=self.extra_args) self.start_nodes() connect_nodes(self.nodes[0], 1) self.sync_all() def run_test(self): tmpdir = self.options.tmpdir nodes = self.nodes nodes[0].extkeyimportmaster('abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb') assert(nodes[0].getwalletinfo()['total_balance'] == 100000) nodes[1].extkeyimportmaster('pact mammal barrel matrix local final lecture chunk wasp survey bid various book strong spread fall ozone daring like topple door fatigue limb olympic', '', 'true') nodes[1].getnewextaddress('lblExtTest') nodes[1].rescanblockchain() assert(nodes[1].getwalletinfo()['total_balance'] == 25000) assert(nodes[0].smsggetfeerate() == 50000) self.stakeBlocks(1, fSync=False) ro = nodes[0].getblock(nodes[0].getblockhash(1), 2) assert(float(ro['tx'][0]['vout'][0]['smsgfeerate']) == 0.0005) ro = nodes[0].walletsettings('stakingoptions', {'smsgfeeratetarget' : 0.001}) assert(float(ro['stakingoptions']['smsgfeeratetarget']) == 0.001) blk1_hex = nodes[0].getblock(nodes[0].getblockhash(1), 0) ro = nodes[2].submitblock(blk1_hex) assert(ro is None) self.stakeBlocks(1, fSync=False) ro = nodes[0].getblock(nodes[0].getblockhash(2), 2) stakedaddress = ro['tx'][0]['vout'][1]['scriptPubKey']['addresses'][0] coinstaketx = ro['tx'][0]['hex'] assert(float(ro['tx'][0]['vout'][0]['smsgfeerate']) == 0.00050215) blk2_hex = nodes[0].getblock(nodes[0].getblockhash(2), 0) assert(nodes[0].getblockchaininfo()['blocks'] == 2) nodes[0].rewindchain(1) nodes[1].rewindchain(1) ro = nodes[0].getblockchaininfo() assert(ro['blocks'] == 1) txb = bytearray.fromhex(coinstaketx) assert(txb[0] == 0xa0) # tx version assert(txb[1] == 0x02) # tx type (coinstake) assert(txb[6] == 0x01) # nInputs assert(txb[43] == 0x00) # scriptSig assert(txb[48] == 0x03) # num outputs assert(txb[49] == 0x04) # OUTPUT_DATA assert(txb[50] == 0x0d) # length of data vector block_height = struct.unpack('<i', txb[51:55])[0] assert(block_height == 2) assert(txb[55] == 0x09) # DO_SMSG i, nb = getvarint(txb, 56) assert(i == 50215) varint_bb = txb[56:56 + nb] varint = putvarint(50215) assert(varint_bb == varint) diff_o = 59 assert(txb[diff_o] == 0xa) # DO_SMSG_DIFFICULTY smsgdifficulty = struct.unpack('<i', txb[diff_o+1:diff_o+5])[0] assert(smsgdifficulty == 0x1f0fffff) base_txb = copy.deepcopy(txb) txb[50] -= nb + 1 txb = txb[:55] + txb[55 + nb + 1:] ro = nodes[0].decoderawtransaction(txb.hex()) assert(len(ro['vout'][0]['data_hex']) == 18) ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-fee' == nodes[2].submitblock(block_hex)) self.log.info('Increase too large') varint = putvarint(50216) txb[50] += len(varint) + 1 txb = txb[:55] + bytes([0x09, ]) + varint + txb[55:] ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-fee' == nodes[2].submitblock(block_hex)) self.log.info('Decrease too large') varint = putvarint(49784) txb[50] += len(varint) + 1 txb = txb[:55] + bytes([0x09, ]) + varint + txb[55:] ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-fee' == nodes[2].submitblock(block_hex)) self.log.info('Missing difficulty') txb2 = copy.deepcopy(base_txb) txb2[50] -= 5 txb2 = txb2[:59] + txb2[59+5:] ro = nodes[0].signrawtransactionwithwallet(txb2.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-diff' == nodes[2].submitblock(block_hex)) self.log.info('Low difficulty') txb2 = copy.deepcopy(base_txb) txb2 = txb2[:60] + struct.pack("i", 0x1f00ffff) + txb2[60+4:] ro = nodes[0].signrawtransactionwithwallet(txb2.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-diff' == nodes[2].submitblock(block_hex)) self.log.info('Above max difficulty') txb2 = copy.deepcopy(base_txb) txb2 = txb2[:60] + struct.pack("i", 0x1fffffff) + txb2[60+4:] ro = nodes[0].signrawtransactionwithwallet(txb2.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-diff' == nodes[2].submitblock(block_hex)) # Should verify varint = putvarint(49785) txb[50] += len(varint) + 1 txb = txb[:55] + bytes([0x09, ]) + varint + txb[55:] ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, '', [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-block-signature' == nodes[0].submitblock(block_hex)) block_hex = self.nodes[0].rehashblock(block_hex, stakedaddress) assert(nodes[2].submitblock(block_hex) is None) ro = nodes[2].getblockchaininfo() assert(ro['blocks'] == 2) self.log.info('submitmsg false') address0 = nodes[0].getnewaddress() address1 = nodes[1].getnewaddress() nodes[0].smsgaddlocaladdress(address0) nodes[1].smsgaddaddress(address0, nodes[0].smsglocalkeys()['wallet_keys'][0]['public_key']) text = 'Some text to test smsg' assert(int(nodes[1].smsgoutbox()['result']) == 0) assert(int(nodes[0].smsginbox()['result']) == 0) ro = nodes[1].smsgsend(address1, address0, text, False, 10, False, False, False, False, False) assert('msg' in ro) msg = ro['msg'] msg_id = ro['msgid'] assert(int(nodes[1].smsgoutbox()['result']) == 0) assert_raises_rpc_error(-1, "Import failed: Message not received.", nodes[1].smsgimport, msg) ro = nodes[0].smsgimport(msg) assert(ro['msgid'] == msg_id) ro = nodes[0].smsginbox() assert(ro['messages'][0]['msgid'] == msg_id) assert(ro['messages'][0]['text'] == text) assert(nodes[0].smsggetdifficulty() > 0.06) if __name__ == '__main__': SmsgPaidFeeTest().main()
38.566038
201
0.603229
import struct import copy from test_framework.test_empower import EmpowerTestFramework from test_framework.util import connect_nodes, assert_raises_rpc_error def getvarint(bb, ofs=0): i = bb[ofs] & 0x7F nb = 1 ofs += 1 while (bb[ofs-1] & 0x80): i += (bb[ofs] & 0x7F) << (7 * nb) ofs += 1 nb += 1 return i, nb def putvarint(i): bb = bytearray() b = i & 0x7F i = i >> 7 while i > 0: bb += bytes([b | 0x80,]) b = i & 0x7F i = i >> 7 bb += bytes([b,]) return bb class SmsgPaidFeeTest(EmpowerTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 3 self.extra_args = [['-debug', '-nocheckblockindex', '-noacceptnonstdtxn', '-reservebalance=10000000'] for i in range(self.num_nodes)] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def setup_network(self, split=False): self.add_nodes(self.num_nodes, extra_args=self.extra_args) self.start_nodes() connect_nodes(self.nodes[0], 1) self.sync_all() def run_test(self): tmpdir = self.options.tmpdir nodes = self.nodes nodes[0].extkeyimportmaster('abandon baby cabbage dad eager fabric gadget habit ice kangaroo lab absorb') assert(nodes[0].getwalletinfo()['total_balance'] == 100000) nodes[1].extkeyimportmaster('pact mammal barrel matrix local final lecture chunk wasp survey bid various book strong spread fall ozone daring like topple door fatigue limb olympic', '', 'true') nodes[1].getnewextaddress('lblExtTest') nodes[1].rescanblockchain() assert(nodes[1].getwalletinfo()['total_balance'] == 25000) assert(nodes[0].smsggetfeerate() == 50000) self.stakeBlocks(1, fSync=False) ro = nodes[0].getblock(nodes[0].getblockhash(1), 2) assert(float(ro['tx'][0]['vout'][0]['smsgfeerate']) == 0.0005) ro = nodes[0].walletsettings('stakingoptions', {'smsgfeeratetarget' : 0.001}) assert(float(ro['stakingoptions']['smsgfeeratetarget']) == 0.001) blk1_hex = nodes[0].getblock(nodes[0].getblockhash(1), 0) ro = nodes[2].submitblock(blk1_hex) assert(ro is None) self.stakeBlocks(1, fSync=False) ro = nodes[0].getblock(nodes[0].getblockhash(2), 2) stakedaddress = ro['tx'][0]['vout'][1]['scriptPubKey']['addresses'][0] coinstaketx = ro['tx'][0]['hex'] assert(float(ro['tx'][0]['vout'][0]['smsgfeerate']) == 0.00050215) blk2_hex = nodes[0].getblock(nodes[0].getblockhash(2), 0) assert(nodes[0].getblockchaininfo()['blocks'] == 2) nodes[0].rewindchain(1) nodes[1].rewindchain(1) ro = nodes[0].getblockchaininfo() assert(ro['blocks'] == 1) txb = bytearray.fromhex(coinstaketx) assert(txb[0] == 0xa0) assert(txb[1] == 0x02) assert(txb[6] == 0x01) assert(txb[43] == 0x00) assert(txb[48] == 0x03) assert(txb[49] == 0x04) assert(txb[50] == 0x0d) block_height = struct.unpack('<i', txb[51:55])[0] assert(block_height == 2) assert(txb[55] == 0x09) i, nb = getvarint(txb, 56) assert(i == 50215) varint_bb = txb[56:56 + nb] varint = putvarint(50215) assert(varint_bb == varint) diff_o = 59 assert(txb[diff_o] == 0xa) smsgdifficulty = struct.unpack('<i', txb[diff_o+1:diff_o+5])[0] assert(smsgdifficulty == 0x1f0fffff) base_txb = copy.deepcopy(txb) txb[50] -= nb + 1 txb = txb[:55] + txb[55 + nb + 1:] ro = nodes[0].decoderawtransaction(txb.hex()) assert(len(ro['vout'][0]['data_hex']) == 18) ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-fee' == nodes[2].submitblock(block_hex)) self.log.info('Increase too large') varint = putvarint(50216) txb[50] += len(varint) + 1 txb = txb[:55] + bytes([0x09, ]) + varint + txb[55:] ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-fee' == nodes[2].submitblock(block_hex)) self.log.info('Decrease too large') varint = putvarint(49784) txb[50] += len(varint) + 1 txb = txb[:55] + bytes([0x09, ]) + varint + txb[55:] ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-fee' == nodes[2].submitblock(block_hex)) self.log.info('Missing difficulty') txb2 = copy.deepcopy(base_txb) txb2[50] -= 5 txb2 = txb2[:59] + txb2[59+5:] ro = nodes[0].signrawtransactionwithwallet(txb2.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-diff' == nodes[2].submitblock(block_hex)) self.log.info('Low difficulty') txb2 = copy.deepcopy(base_txb) txb2 = txb2[:60] + struct.pack("i", 0x1f00ffff) + txb2[60+4:] ro = nodes[0].signrawtransactionwithwallet(txb2.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-diff' == nodes[2].submitblock(block_hex)) self.log.info('Above max difficulty') txb2 = copy.deepcopy(base_txb) txb2 = txb2[:60] + struct.pack("i", 0x1fffffff) + txb2[60+4:] ro = nodes[0].signrawtransactionwithwallet(txb2.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, stakedaddress, [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-cs-smsg-diff' == nodes[2].submitblock(block_hex)) varint = putvarint(49785) txb[50] += len(varint) + 1 txb = txb[:55] + bytes([0x09, ]) + varint + txb[55:] ro = nodes[0].signrawtransactionwithwallet(txb.hex()) block_hex = self.nodes[0].rehashblock(blk2_hex, '', [{'txn': ro['hex'], 'pos': 0, 'replace': True}]) assert('bad-block-signature' == nodes[0].submitblock(block_hex)) block_hex = self.nodes[0].rehashblock(block_hex, stakedaddress) assert(nodes[2].submitblock(block_hex) is None) ro = nodes[2].getblockchaininfo() assert(ro['blocks'] == 2) self.log.info('submitmsg false') address0 = nodes[0].getnewaddress() address1 = nodes[1].getnewaddress() nodes[0].smsgaddlocaladdress(address0) nodes[1].smsgaddaddress(address0, nodes[0].smsglocalkeys()['wallet_keys'][0]['public_key']) text = 'Some text to test smsg' assert(int(nodes[1].smsgoutbox()['result']) == 0) assert(int(nodes[0].smsginbox()['result']) == 0) ro = nodes[1].smsgsend(address1, address0, text, False, 10, False, False, False, False, False) assert('msg' in ro) msg = ro['msg'] msg_id = ro['msgid'] assert(int(nodes[1].smsgoutbox()['result']) == 0) assert_raises_rpc_error(-1, "Import failed: Message not received.", nodes[1].smsgimport, msg) ro = nodes[0].smsgimport(msg) assert(ro['msgid'] == msg_id) ro = nodes[0].smsginbox() assert(ro['messages'][0]['msgid'] == msg_id) assert(ro['messages'][0]['text'] == text) assert(nodes[0].smsggetdifficulty() > 0.06) if __name__ == '__main__': SmsgPaidFeeTest().main()
true
true
1c39f11b3ba73675d5f201c56b4c1885141547f8
1,668
py
Python
googlevoice/tests.py
nathanhere/pygooglevoice
d5662f6d9fb2e023e75553044bc5bfae0be61815
[ "BSD-3-Clause" ]
156
2015-01-07T00:34:33.000Z
2022-03-13T01:14:53.000Z
googlevoice/tests.py
nathanhere/pygooglevoice
d5662f6d9fb2e023e75553044bc5bfae0be61815
[ "BSD-3-Clause" ]
51
2015-02-06T14:58:39.000Z
2021-10-01T23:00:13.000Z
googlevoice/tests.py
nathanhere/pygooglevoice
d5662f6d9fb2e023e75553044bc5bfae0be61815
[ "BSD-3-Clause" ]
94
2015-02-06T18:44:48.000Z
2022-02-10T01:29:34.000Z
import os from unittest import TestCase, main from six.moves import input from googlevoice import Voice from googlevoice import conf class VoiceTest(TestCase): voice = Voice() voice.login() outgoing = input('Outgoing number (blank to ignore call tests): ') forwarding = None if outgoing: forwarding = input('Forwarding number [optional]: ') or None if outgoing: def test_1call(self): self.voice.call(self.outgoing, self.forwarding) def test_sms(self): self.voice.send_sms(self.outgoing, 'i sms u') def test_2cancel(self): self.voice.cancel(self.outgoing, self.forwarding) def test_special(self): self.assert_(self.voice.special) def test_inbox(self): self.assert_(self.voice.inbox) def test_balance(self): self.assert_(self.voice.settings['credits']) def test_search(self): self.assert_(len(self.voice.search('joe'))) def test_disable_enable(self): self.voice.phones[0].disable() self.voice.phones[0].enable() def test_download(self): msg = list(self.voice.voicemail().messages)[0] fn = '%s.mp3' % msg.id if os.path.isfile(fn): os.remove(fn) self.voice.download(msg) self.assert_(os.path.isfile(fn)) def test_zlogout(self): self.voice.logout() self.assert_(self.voice.special is None) def test_config(self): self.assert_(conf.config.forwardingNumber) self.assert_(str(conf.config.phoneType) in '1237') self.assertEqual(conf.config.get('wtf'), None) if __name__ == '__main__': main()
26.0625
70
0.63789
import os from unittest import TestCase, main from six.moves import input from googlevoice import Voice from googlevoice import conf class VoiceTest(TestCase): voice = Voice() voice.login() outgoing = input('Outgoing number (blank to ignore call tests): ') forwarding = None if outgoing: forwarding = input('Forwarding number [optional]: ') or None if outgoing: def test_1call(self): self.voice.call(self.outgoing, self.forwarding) def test_sms(self): self.voice.send_sms(self.outgoing, 'i sms u') def test_2cancel(self): self.voice.cancel(self.outgoing, self.forwarding) def test_special(self): self.assert_(self.voice.special) def test_inbox(self): self.assert_(self.voice.inbox) def test_balance(self): self.assert_(self.voice.settings['credits']) def test_search(self): self.assert_(len(self.voice.search('joe'))) def test_disable_enable(self): self.voice.phones[0].disable() self.voice.phones[0].enable() def test_download(self): msg = list(self.voice.voicemail().messages)[0] fn = '%s.mp3' % msg.id if os.path.isfile(fn): os.remove(fn) self.voice.download(msg) self.assert_(os.path.isfile(fn)) def test_zlogout(self): self.voice.logout() self.assert_(self.voice.special is None) def test_config(self): self.assert_(conf.config.forwardingNumber) self.assert_(str(conf.config.phoneType) in '1237') self.assertEqual(conf.config.get('wtf'), None) if __name__ == '__main__': main()
true
true
1c39f121bfc197bc668023b153d241ed81092a0a
1,090
py
Python
Wardies/urls.py
HabeshaQueen/Awards
956fad404d9910660266eb8e1819418b78a788b6
[ "Unlicense" ]
null
null
null
Wardies/urls.py
HabeshaQueen/Awards
956fad404d9910660266eb8e1819418b78a788b6
[ "Unlicense" ]
2
2021-03-19T00:53:00.000Z
2021-06-08T19:56:23.000Z
Wardies/urls.py
HabeshaQueen/Awards
956fad404d9910660266eb8e1819418b78a788b6
[ "Unlicense" ]
null
null
null
"""Wardies URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url,include from django.contrib import admin from django.contrib.auth import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('Wards.urls')), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^logout/$', views.logout, {"next_page": '/'}), url(r'^api-token-auth/', obtain_auth_token) ]
35.16129
79
0.700917
from django.conf.urls import url,include from django.contrib import admin from django.contrib.auth import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('Wards.urls')), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^logout/$', views.logout, {"next_page": '/'}), url(r'^api-token-auth/', obtain_auth_token) ]
true
true
1c39f1537f68410a285118d7a096bbcbbb42619e
1,357
py
Python
CONFidence CTF 2014/Main event/Crypto Machine/solution/exploit.py
IMULMUL/ctf-tasks
9c1549c71aa5fc876f3a46751de226320dc879af
[ "Apache-2.0" ]
581
2019-02-20T08:53:36.000Z
2022-03-20T13:29:29.000Z
CONFidence CTF 2014/Main event/Crypto Machine/solution/exploit.py
Ma3k4H3d/ctf-tasks
67b3564307a20a9175bcf695ce9643fb80d4652f
[ "Apache-2.0" ]
null
null
null
CONFidence CTF 2014/Main event/Crypto Machine/solution/exploit.py
Ma3k4H3d/ctf-tasks
67b3564307a20a9175bcf695ce9643fb80d4652f
[ "Apache-2.0" ]
61
2019-02-20T10:57:42.000Z
2021-07-02T06:53:09.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Filename: exploit.py # Author: Mateusz Jurczyk # Task: Crypto Machine # Competition: CONFidence CTF 2014 # Category: Software exploitation # Scoring: 200 pts (medium difficulty) # Number of solves: 0 out of 11 participants import struct import socket import telnetlib import time def dw(x): return struct.pack("<H", x) def dd(x): return struct.pack("<I", x) def dq(x): return struct.pack("<Q", x) def main(): # Connect to the service. s = socket.socket() s.connect(("127.0.0.1", 1337)) # Call the HMAC function (id #0). data = "Hello world" s.send(dq(0x8000000000000000)) s.send(dd(len(data))) s.send(data) # Send the length of the key as 2 bytes, to bypass the sanity check. key_length = 1024 + 8 + 2 s.send(dw(key_length)) # Wait for the partial key length to be received. time.sleep(1) # Send the key overwriting the stack-based buffer, setting the lower # 16 bits of the function pointer to the address of system("/bin/sh"), # with the highest nibble of the value guessed as 0x1. s.send("A" * (key_length - 2) + dw(0x1460)) # Switch to interactive mode. t = telnetlib.Telnet() t.sock = s t.interact() if __name__ == "__main__": main()
24.232143
73
0.619749
import struct import socket import telnetlib import time def dw(x): return struct.pack("<H", x) def dd(x): return struct.pack("<I", x) def dq(x): return struct.pack("<Q", x) def main(): s = socket.socket() s.connect(("127.0.0.1", 1337)) ta = "Hello world" s.send(dq(0x8000000000000000)) s.send(dd(len(data))) s.send(data) key_length = 1024 + 8 + 2 s.send(dw(key_length)) time.sleep(1) s.send("A" * (key_length - 2) + dw(0x1460)) t = telnetlib.Telnet() t.sock = s t.interact() if __name__ == "__main__": main()
true
true
1c39f1f3573625b65fb6b63b7c9c5f1b016fc439
1,838
py
Python
package/spack-r-affycontam/package.py
ctuning/ck-spack
307934efce1be2d4f104251275c82fbc70127105
[ "BSD-3-Clause" ]
1
2018-07-17T07:45:09.000Z
2018-07-17T07:45:09.000Z
package/spack-r-affycontam/package.py
ctuning/ck-spack
307934efce1be2d4f104251275c82fbc70127105
[ "BSD-3-Clause" ]
null
null
null
package/spack-r-affycontam/package.py
ctuning/ck-spack
307934efce1be2d4f104251275c82fbc70127105
[ "BSD-3-Clause" ]
null
null
null
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RAffycontam(RPackage): """structured corruption of cel file data to demonstrate QA effectiveness.""" homepage = "https://www.bioconductor.org/packages/affyContam/" url = "https://git.bioconductor.org/packages/affyContam" version('1.34.0', git='https://git.bioconductor.org/packages/affyContam', commit='03529f26d059c19e069cdda358dbf7789b6d4c40') depends_on('r@3.4.0:3.4.9', when=('@1.34.0')) depends_on('r-biobase', type=('build', 'run')) depends_on('r-affy', type=('build', 'run')) depends_on('r-affydata', type=('build', 'run'))
44.829268
128
0.673014
true
true
1c39f2d3d02b95bc196458142e48edfd8407d931
7,545
py
Python
policy/td3.py
dkkim93/gumbel-rl-gridworld
902352ed3e10b551472f5c28933864ca17f82e12
[ "MIT" ]
4
2019-07-20T02:46:54.000Z
2021-03-09T13:07:27.000Z
policy/td3.py
Nedaned/gumbel-marl-gridworld
2ec86bc6cf7c16d5ef0368c9dc4a83062d3d86e3
[ "MIT" ]
null
null
null
policy/td3.py
Nedaned/gumbel-marl-gridworld
2ec86bc6cf7c16d5ef0368c9dc4a83062d3d86e3
[ "MIT" ]
2
2020-09-28T16:05:32.000Z
2021-03-15T13:15:14.000Z
"""Modified Twin Delayed Deep Deterministic Policy Gradients (TD3) TD3 Ref: https://github.com/sfujim/TD3 """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from misc.utils import onehot_from_logits, gumbel_softmax device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class Actor(nn.Module): def __init__(self, actor_input_dim, actor_output_dim, n_hidden, n_action, name): super(Actor, self).__init__() setattr(self, name + "_l1", nn.Linear(actor_input_dim, n_hidden)) setattr(self, name + "_l2", nn.Linear(n_hidden, n_hidden)) setattr(self, name + "_l3", nn.Linear(n_hidden, n_action)) self.name = name def forward(self, x): x = F.relu(getattr(self, self.name + "_l1")(x)) x = F.relu(getattr(self, self.name + "_l2")(x)) x = getattr(self, self.name + "_l3")(x) return x class Critic(nn.Module): def __init__(self, critic_input_dim, n_hidden, name): super(Critic, self).__init__() # Q1 architecture setattr(self, name + "_l1", nn.Linear(critic_input_dim, n_hidden)) setattr(self, name + "_l2", nn.Linear(n_hidden, n_hidden)) setattr(self, name + "_l3", nn.Linear(n_hidden, 1)) # Q2 architecture setattr(self, name + "_l4", nn.Linear(critic_input_dim, n_hidden)) setattr(self, name + "_l5", nn.Linear(n_hidden, n_hidden)) setattr(self, name + "_l6", nn.Linear(n_hidden, 1)) self.name = name def forward(self, x, u): xu = torch.cat([x, u], 1) x1 = F.relu(getattr(self, self.name + "_l1")(xu)) x1 = F.relu(getattr(self, self.name + "_l2")(x1)) x1 = getattr(self, self.name + "_l3")(x1) x2 = F.relu(getattr(self, self.name + "_l4")(xu)) x2 = F.relu(getattr(self, self.name + "_l5")(x2)) x2 = getattr(self, self.name + "_l6")(x2) return x1, x2 def Q1(self, x, u): xu = torch.cat([x, u], 1) x1 = F.relu(getattr(self, self.name + "_l1")(xu)) x1 = F.relu(getattr(self, self.name + "_l2")(x1)) x1 = getattr(self, self.name + "_l3")(x1) return x1 class TD3(object): def __init__(self, actor_input_dim, actor_output_dim, critic_input_dim, n_hidden, name, args): self.actor = Actor( actor_input_dim, actor_output_dim, n_hidden, args.n_action, name=name + "_actor").to(device) self.actor_target = Actor( actor_input_dim, actor_output_dim, n_hidden, args.n_action, name=name + "_actor").to(device) self.actor_target.load_state_dict(self.actor.state_dict()) self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=args.actor_lr) self.critic = Critic(critic_input_dim, n_hidden, name=name + "_critic").to(device) self.critic_target = Critic(critic_input_dim, n_hidden, name=name + "_critic").to(device) self.critic_target.load_state_dict(self.critic.state_dict()) self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=args.critic_lr) self.name = name self.args = args def select_action(self, state): state = torch.FloatTensor(state.reshape(1, -1)).to(device) action = self.actor(state) action = onehot_from_logits(logits=action) action = action.cpu().data.numpy() action = np.squeeze(action, axis=0) return action def train(self, replay_buffer, iterations, batch_size, discount, tau, policy_freq): debug = {} debug["critic_loss"] = 0. debug["actor_loss"] = 0. for it in range(iterations): # Sample replay buffer x, y, u, r, d = replay_buffer.sample(batch_size) state = torch.FloatTensor(x).to(device) action = torch.FloatTensor(u).to(device) next_state = torch.FloatTensor(y).to(device) done = torch.FloatTensor(1 - d).to(device) reward = torch.FloatTensor(r).to(device) # Select next action according to policy next_action = self.actor_target(next_state) next_action = onehot_from_logits(next_action) # Compute the target Q value target_Q1, target_Q2 = self.critic_target(next_state, next_action) target_Q = torch.min(target_Q1, target_Q2) target_Q = reward + (done * discount * target_Q).detach() # Get current Q estimates current_Q1, current_Q2 = self.critic(state, action) # Compute critic loss critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q) # Optimize the critic self.critic_optimizer.zero_grad() critic_loss.backward() torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 0.5) self.critic_optimizer.step() debug["critic_loss"] += critic_loss.cpu().data.numpy().flatten() # Delayed policy updates if it % policy_freq == 0: # Compute actor loss action = self.actor(state) action = gumbel_softmax(action, hard=True) actor_loss = -self.critic.Q1(state, action).mean() # Optimize the actor self.actor_optimizer.zero_grad() actor_loss.backward() torch.nn.utils.clip_grad_norm_(self.actor.parameters(), 0.5) self.actor_optimizer.step() debug["actor_loss"] += actor_loss.cpu().data.numpy().flatten() # Update the frozen target models for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) return debug def save(self, filename, directory): torch.save(self.actor.state_dict(), '%s/%s_actor.pth' % (directory, filename)) if "worker" not in self.name: torch.save(self.critic.state_dict(), '%s/%s_critic.pth' % (directory, filename)) def load(self, filename, directory): from collections import OrderedDict actor_weight = torch.load('%s/%s_actor.pth' % (directory, filename), map_location='cpu') actor_weight_fixed = OrderedDict() for k, v in actor_weight.items(): name_fixed = self.name for i_name, name in enumerate(k.split("_")): if i_name > 0: name_fixed += "_" + name actor_weight_fixed[name_fixed] = v self.actor.load_state_dict(actor_weight_fixed) if "worker" not in self.name: critic_weight = torch.load('%s/%s_critic.pth' % (directory, filename), map_location='cpu') critic_weight_fixed = OrderedDict() for k, v in critic_weight.items(): name_fixed = self.name for i_name, name in enumerate(k.split("_")): if i_name > 0: name_fixed += "_" + name critic_weight_fixed[name_fixed] = v self.critic.load_state_dict(critic_weight_fixed) self.actor_target.load_state_dict(self.actor.state_dict()) self.critic_target.load_state_dict(self.critic.state_dict())
39.502618
106
0.60729
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from misc.utils import onehot_from_logits, gumbel_softmax device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class Actor(nn.Module): def __init__(self, actor_input_dim, actor_output_dim, n_hidden, n_action, name): super(Actor, self).__init__() setattr(self, name + "_l1", nn.Linear(actor_input_dim, n_hidden)) setattr(self, name + "_l2", nn.Linear(n_hidden, n_hidden)) setattr(self, name + "_l3", nn.Linear(n_hidden, n_action)) self.name = name def forward(self, x): x = F.relu(getattr(self, self.name + "_l1")(x)) x = F.relu(getattr(self, self.name + "_l2")(x)) x = getattr(self, self.name + "_l3")(x) return x class Critic(nn.Module): def __init__(self, critic_input_dim, n_hidden, name): super(Critic, self).__init__() setattr(self, name + "_l1", nn.Linear(critic_input_dim, n_hidden)) setattr(self, name + "_l2", nn.Linear(n_hidden, n_hidden)) setattr(self, name + "_l3", nn.Linear(n_hidden, 1)) setattr(self, name + "_l4", nn.Linear(critic_input_dim, n_hidden)) setattr(self, name + "_l5", nn.Linear(n_hidden, n_hidden)) setattr(self, name + "_l6", nn.Linear(n_hidden, 1)) self.name = name def forward(self, x, u): xu = torch.cat([x, u], 1) x1 = F.relu(getattr(self, self.name + "_l1")(xu)) x1 = F.relu(getattr(self, self.name + "_l2")(x1)) x1 = getattr(self, self.name + "_l3")(x1) x2 = F.relu(getattr(self, self.name + "_l4")(xu)) x2 = F.relu(getattr(self, self.name + "_l5")(x2)) x2 = getattr(self, self.name + "_l6")(x2) return x1, x2 def Q1(self, x, u): xu = torch.cat([x, u], 1) x1 = F.relu(getattr(self, self.name + "_l1")(xu)) x1 = F.relu(getattr(self, self.name + "_l2")(x1)) x1 = getattr(self, self.name + "_l3")(x1) return x1 class TD3(object): def __init__(self, actor_input_dim, actor_output_dim, critic_input_dim, n_hidden, name, args): self.actor = Actor( actor_input_dim, actor_output_dim, n_hidden, args.n_action, name=name + "_actor").to(device) self.actor_target = Actor( actor_input_dim, actor_output_dim, n_hidden, args.n_action, name=name + "_actor").to(device) self.actor_target.load_state_dict(self.actor.state_dict()) self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), lr=args.actor_lr) self.critic = Critic(critic_input_dim, n_hidden, name=name + "_critic").to(device) self.critic_target = Critic(critic_input_dim, n_hidden, name=name + "_critic").to(device) self.critic_target.load_state_dict(self.critic.state_dict()) self.critic_optimizer = torch.optim.Adam(self.critic.parameters(), lr=args.critic_lr) self.name = name self.args = args def select_action(self, state): state = torch.FloatTensor(state.reshape(1, -1)).to(device) action = self.actor(state) action = onehot_from_logits(logits=action) action = action.cpu().data.numpy() action = np.squeeze(action, axis=0) return action def train(self, replay_buffer, iterations, batch_size, discount, tau, policy_freq): debug = {} debug["critic_loss"] = 0. debug["actor_loss"] = 0. for it in range(iterations): x, y, u, r, d = replay_buffer.sample(batch_size) state = torch.FloatTensor(x).to(device) action = torch.FloatTensor(u).to(device) next_state = torch.FloatTensor(y).to(device) done = torch.FloatTensor(1 - d).to(device) reward = torch.FloatTensor(r).to(device) next_action = self.actor_target(next_state) next_action = onehot_from_logits(next_action) target_Q1, target_Q2 = self.critic_target(next_state, next_action) target_Q = torch.min(target_Q1, target_Q2) target_Q = reward + (done * discount * target_Q).detach() current_Q1, current_Q2 = self.critic(state, action) critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(current_Q2, target_Q) self.critic_optimizer.zero_grad() critic_loss.backward() torch.nn.utils.clip_grad_norm_(self.critic.parameters(), 0.5) self.critic_optimizer.step() debug["critic_loss"] += critic_loss.cpu().data.numpy().flatten() if it % policy_freq == 0: action = self.actor(state) action = gumbel_softmax(action, hard=True) actor_loss = -self.critic.Q1(state, action).mean() self.actor_optimizer.zero_grad() actor_loss.backward() torch.nn.utils.clip_grad_norm_(self.actor.parameters(), 0.5) self.actor_optimizer.step() debug["actor_loss"] += actor_loss.cpu().data.numpy().flatten() for param, target_param in zip(self.critic.parameters(), self.critic_target.parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) for param, target_param in zip(self.actor.parameters(), self.actor_target.parameters()): target_param.data.copy_(tau * param.data + (1 - tau) * target_param.data) return debug def save(self, filename, directory): torch.save(self.actor.state_dict(), '%s/%s_actor.pth' % (directory, filename)) if "worker" not in self.name: torch.save(self.critic.state_dict(), '%s/%s_critic.pth' % (directory, filename)) def load(self, filename, directory): from collections import OrderedDict actor_weight = torch.load('%s/%s_actor.pth' % (directory, filename), map_location='cpu') actor_weight_fixed = OrderedDict() for k, v in actor_weight.items(): name_fixed = self.name for i_name, name in enumerate(k.split("_")): if i_name > 0: name_fixed += "_" + name actor_weight_fixed[name_fixed] = v self.actor.load_state_dict(actor_weight_fixed) if "worker" not in self.name: critic_weight = torch.load('%s/%s_critic.pth' % (directory, filename), map_location='cpu') critic_weight_fixed = OrderedDict() for k, v in critic_weight.items(): name_fixed = self.name for i_name, name in enumerate(k.split("_")): if i_name > 0: name_fixed += "_" + name critic_weight_fixed[name_fixed] = v self.critic.load_state_dict(critic_weight_fixed) self.actor_target.load_state_dict(self.actor.state_dict()) self.critic_target.load_state_dict(self.critic.state_dict())
true
true
1c39f33f152b69d3caa02ce9ce7545ca11e23004
1,814
py
Python
setup.py
OpenPeerPower/supervisor
39a3226041caa34b2dabb54f76d8e88c06d50155
[ "Apache-2.0" ]
1
2021-11-19T12:03:03.000Z
2021-11-19T12:03:03.000Z
setup.py
OpenPeerPower/supervisor
39a3226041caa34b2dabb54f76d8e88c06d50155
[ "Apache-2.0" ]
null
null
null
setup.py
OpenPeerPower/supervisor
39a3226041caa34b2dabb54f76d8e88c06d50155
[ "Apache-2.0" ]
null
null
null
"""Open Peer Power Supervisor setup.""" from setuptools import setup from supervisor.const import SUPERVISOR_VERSION setup( name="Supervisor", version=SUPERVISOR_VERSION, license="BSD License", author="The Open Peer Power Authors", author_email="hello@openpeerpower.io", url="https://openpeerpower.io/", description=("Open-source private cloud os for Open-Peer-Power" " based on OppOS"), long_description=( "A maintainless private cloud operator system that" "setup a Open-Peer-Power instance. Based on OppOS" ), classifiers=[ "Intended Audience :: End Users/Desktop", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Home Automation", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Scientific/Engineering :: Atmospheric Science", "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 3.8", ], keywords=["docker", "openpeerpower", "api"], zip_safe=False, platforms="any", packages=[ "supervisor", "supervisor.docker", "supervisor.addons", "supervisor.api", "supervisor.dbus", "supervisor.dbus.payloads", "supervisor.dbus.network", "supervisor.discovery", "supervisor.discovery.services", "supervisor.services", "supervisor.services.modules", "supervisor.openpeerpower", "supervisor.host", "supervisor.misc", "supervisor.utils", "supervisor.plugins", "supervisor.snapshots", "supervisor.store", ], include_package_data=True, )
32.981818
87
0.627343
from setuptools import setup from supervisor.const import SUPERVISOR_VERSION setup( name="Supervisor", version=SUPERVISOR_VERSION, license="BSD License", author="The Open Peer Power Authors", author_email="hello@openpeerpower.io", url="https://openpeerpower.io/", description=("Open-source private cloud os for Open-Peer-Power" " based on OppOS"), long_description=( "A maintainless private cloud operator system that" "setup a Open-Peer-Power instance. Based on OppOS" ), classifiers=[ "Intended Audience :: End Users/Desktop", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Topic :: Home Automation", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Scientific/Engineering :: Atmospheric Science", "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Programming Language :: Python :: 3.8", ], keywords=["docker", "openpeerpower", "api"], zip_safe=False, platforms="any", packages=[ "supervisor", "supervisor.docker", "supervisor.addons", "supervisor.api", "supervisor.dbus", "supervisor.dbus.payloads", "supervisor.dbus.network", "supervisor.discovery", "supervisor.discovery.services", "supervisor.services", "supervisor.services.modules", "supervisor.openpeerpower", "supervisor.host", "supervisor.misc", "supervisor.utils", "supervisor.plugins", "supervisor.snapshots", "supervisor.store", ], include_package_data=True, )
true
true
1c39f57ebadec3283331504a168a0ad14f3c8d8c
2,055
py
Python
src/source_wkpd/wiki_source_obj.py
Aluriak/24hducode2016
629a3225c5a426d3deb472d67f0e0091904d1547
[ "Unlicense" ]
null
null
null
src/source_wkpd/wiki_source_obj.py
Aluriak/24hducode2016
629a3225c5a426d3deb472d67f0e0091904d1547
[ "Unlicense" ]
null
null
null
src/source_wkpd/wiki_source_obj.py
Aluriak/24hducode2016
629a3225c5a426d3deb472d67f0e0091904d1547
[ "Unlicense" ]
null
null
null
""" Definition of a source than adds Wikipédia data. """ from src.default import * from src.source import Source #import src.wkpd.wikipedia_parse as wkp from src.source_wkpd import wikipedia_parse as wkp class WikiSource(Source): """docstring de class""" def __init__(self): self.funny_keys = set() def enrichment(self, data_dict): # Initialize linked_elems # data_dict['linked_elems'] = list() # Update data according to GPS coords # if FIELD_LATITUDE in data_dict: # # print("Processing: Coordinates") # data_dict['linked_elems'] += wkp.get_wikipedia_data_near_coords( # data_dict[FIELD_LATITUDE], # data_dict[FIELD_LONGITUDE] # ) # print(data_dict['linked_elems']) # # [self.funny_keys.update(elem.keys()) for elem # in data_dict['linked_elems']] # Update data according to a SyndicObjectName if FIELD_NAME in data_dict: # print("Processing:", FIELD_NAME) try: payload = wkp.get_wikipedia_data(data_dict[FIELD_NAME])[0] data_dict[FIELD_DESCRIPTION] = payload[FIELD_DESCRIPTION] data_dict[FIELD_URL] = payload[FIELD_URL] except IndexError: data_dict[FIELD_DESCRIPTION] = None data_dict[FIELD_URL] = None # print('PAYLOAD:', payload.__class__, payload) # [self.funny_keys.update(elem.keys()) for elem # in data_dict['linked_elems']] # print("RETURNED KEYS", self.funny_keys) return data_dict def keywords(self): return {FIELD_URL, FIELD_DESCRIPTION} if __name__ == "__main__": obj = dict() obj[FIELD_COORDINATES] = (48.515079, 4.298639) obj[FIELD_NAME] = "Europajazz" wk_src = WikiSource() print(wk_src.enrichment(obj))
31.136364
77
0.569343
from src.default import * from src.source import Source from src.source_wkpd import wikipedia_parse as wkp class WikiSource(Source): def __init__(self): self.funny_keys = set() def enrichment(self, data_dict): if FIELD_NAME in data_dict: try: payload = wkp.get_wikipedia_data(data_dict[FIELD_NAME])[0] data_dict[FIELD_DESCRIPTION] = payload[FIELD_DESCRIPTION] data_dict[FIELD_URL] = payload[FIELD_URL] except IndexError: data_dict[FIELD_DESCRIPTION] = None data_dict[FIELD_URL] = None return data_dict def keywords(self): return {FIELD_URL, FIELD_DESCRIPTION} if __name__ == "__main__": obj = dict() obj[FIELD_COORDINATES] = (48.515079, 4.298639) obj[FIELD_NAME] = "Europajazz" wk_src = WikiSource() print(wk_src.enrichment(obj))
true
true
1c39f727dd39651a1793e6825b30540d3352e9a7
26,609
py
Python
koku/masu/database/aws_report_db_accessor.py
bsquizz/koku
386dd6ca4a4fd1b50790a929acc81d2dc245a91c
[ "Apache-2.0" ]
null
null
null
koku/masu/database/aws_report_db_accessor.py
bsquizz/koku
386dd6ca4a4fd1b50790a929acc81d2dc245a91c
[ "Apache-2.0" ]
null
null
null
koku/masu/database/aws_report_db_accessor.py
bsquizz/koku
386dd6ca4a4fd1b50790a929acc81d2dc245a91c
[ "Apache-2.0" ]
null
null
null
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Database accessor for report data.""" import json import logging import pkgutil import uuid from dateutil.parser import parse from django.conf import settings from django.db import connection from django.db.models import F from jinjasql import JinjaSql from tenant_schemas.utils import schema_context from trino.exceptions import TrinoExternalError from api.utils import DateHelper from koku.database import get_model from koku.database import SQLScriptAtomicExecutorMixin from masu.config import Config from masu.database import AWS_CUR_TABLE_MAP from masu.database.report_db_accessor_base import ReportDBAccessorBase from masu.external.date_accessor import DateAccessor from reporting.models import OCP_ON_ALL_PERSPECTIVES from reporting.models import OCP_ON_AWS_PERSPECTIVES from reporting.models import OCPAllCostLineItemDailySummaryP from reporting.models import OCPAllCostLineItemProjectDailySummaryP from reporting.models import OCPAWSCostLineItemDailySummaryP from reporting.provider.aws.models import AWSCostEntry from reporting.provider.aws.models import AWSCostEntryBill from reporting.provider.aws.models import AWSCostEntryLineItem from reporting.provider.aws.models import AWSCostEntryLineItemDaily from reporting.provider.aws.models import AWSCostEntryLineItemDailySummary from reporting.provider.aws.models import AWSCostEntryPricing from reporting.provider.aws.models import AWSCostEntryProduct from reporting.provider.aws.models import AWSCostEntryReservation from reporting.provider.aws.models import PRESTO_LINE_ITEM_DAILY_TABLE from reporting.provider.aws.models import UI_SUMMARY_TABLES from reporting.provider.aws.openshift.models import UI_SUMMARY_TABLES as OCPAWS_UI_SUMMARY_TABLES LOG = logging.getLogger(__name__) class AWSReportDBAccessor(SQLScriptAtomicExecutorMixin, ReportDBAccessorBase): """Class to interact with customer reporting tables.""" def __init__(self, schema): """Establish the database connection. Args: schema (str): The customer schema to associate with """ super().__init__(schema) self._datetime_format = Config.AWS_DATETIME_STR_FORMAT self.date_accessor = DateAccessor() self.jinja_sql = JinjaSql() self._table_map = AWS_CUR_TABLE_MAP @property def line_item_daily_summary_table(self): return AWSCostEntryLineItemDailySummary @property def ocpall_line_item_daily_summary_table(self): return get_model("OCPAllCostLineItemDailySummaryP") @property def ocpall_line_item_project_daily_summary_table(self): return get_model("OCPAllCostLineItemProjectDailySummaryP") @property def line_item_table(self): return AWSCostEntryLineItem @property def cost_entry_table(self): return AWSCostEntry @property def line_item_daily_table(self): return AWSCostEntryLineItemDaily def get_cost_entry_bills(self): """Get all cost entry bill objects.""" table_name = AWSCostEntryBill with schema_context(self.schema): columns = ["id", "bill_type", "payer_account_id", "billing_period_start", "provider_id"] bills = self._get_db_obj_query(table_name).values(*columns) return { (bill["bill_type"], bill["payer_account_id"], bill["billing_period_start"], bill["provider_id"]): bill[ "id" ] for bill in bills } def get_cost_entry_bills_by_date(self, start_date): """Return a cost entry bill for the specified start date.""" table_name = AWSCostEntryBill with schema_context(self.schema): return self._get_db_obj_query(table_name).filter(billing_period_start=start_date) def get_cost_entry_bills_query_by_provider(self, provider_uuid): """Return all cost entry bills for the specified provider.""" table_name = AWSCostEntryBill with schema_context(self.schema): return self._get_db_obj_query(table_name).filter(provider_id=provider_uuid) def bills_for_provider_uuid(self, provider_uuid, start_date=None): """Return all cost entry bills for provider_uuid on date.""" bills = self.get_cost_entry_bills_query_by_provider(provider_uuid) if start_date: if isinstance(start_date, str): start_date = parse(start_date) bill_date = start_date.replace(day=1) bills = bills.filter(billing_period_start=bill_date) return bills def get_bill_query_before_date(self, date, provider_uuid=None): """Get the cost entry bill objects with billing period before provided date.""" table_name = AWSCostEntryBill with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) if provider_uuid: cost_entry_bill_query = base_query.filter(billing_period_start__lte=date, provider_id=provider_uuid) else: cost_entry_bill_query = base_query.filter(billing_period_start__lte=date) return cost_entry_bill_query def get_lineitem_query_for_billid(self, bill_id): """Get the AWS cost entry line item for a given bill query.""" table_name = AWSCostEntryLineItem with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) line_item_query = base_query.filter(cost_entry_bill_id=bill_id) return line_item_query def get_daily_query_for_billid(self, bill_id): """Get the AWS cost daily item for a given bill query.""" table_name = AWSCostEntryLineItemDaily with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) daily_item_query = base_query.filter(cost_entry_bill_id=bill_id) return daily_item_query def get_summary_query_for_billid(self, bill_id): """Get the AWS cost summary item for a given bill query.""" table_name = AWSCostEntryLineItemDailySummary with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) summary_item_query = base_query.filter(cost_entry_bill_id=bill_id) return summary_item_query def get_ocp_aws_summary_query_for_billid(self, bill_id): """Get the OCP-on-AWS report summary item for a given bill query.""" table_name = self._table_map["ocp_on_aws_daily_summary"] base_query = self._get_db_obj_query(table_name) summary_item_query = base_query.filter(cost_entry_bill_id=bill_id) return summary_item_query def get_ocp_aws_project_summary_query_for_billid(self, bill_id): """Get the OCP-on-AWS report project summary item for a given bill query.""" table_name = self._table_map["ocp_on_aws_project_daily_summary"] base_query = self._get_db_obj_query(table_name) summary_item_query = base_query.filter(cost_entry_bill_id=bill_id) return summary_item_query def get_cost_entry_query_for_billid(self, bill_id): """Get the AWS cost entry data for a given bill query.""" table_name = AWSCostEntry with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) line_item_query = base_query.filter(bill_id=bill_id) return line_item_query def get_cost_entries(self): """Make a mapping of cost entries by start time.""" table_name = AWSCostEntry with schema_context(self.schema): cost_entries = self._get_db_obj_query(table_name).all() return {(ce.bill_id, ce.interval_start.strftime(self._datetime_format)): ce.id for ce in cost_entries} def get_products(self): """Make a mapping of product sku to product objects.""" table_name = AWSCostEntryProduct with schema_context(self.schema): columns = ["id", "sku", "product_name", "region"] products = self._get_db_obj_query(table_name, columns=columns).all() return { (product["sku"], product["product_name"], product["region"]): product["id"] for product in products } def get_pricing(self): """Make a mapping of pricing values string to pricing objects.""" table_name = AWSCostEntryPricing with schema_context(self.schema): pricing = self._get_db_obj_query(table_name).all() return {f"{p.term}-{p.unit}": p.id for p in pricing} def get_reservations(self): """Make a mapping of reservation ARN to reservation objects.""" table_name = AWSCostEntryReservation with schema_context(self.schema): columns = ["id", "reservation_arn"] reservs = self._get_db_obj_query(table_name, columns=columns).all() return {res["reservation_arn"]: res["id"] for res in reservs} def populate_line_item_daily_table(self, start_date, end_date, bill_ids): """Populate the daily aggregate of line items table. Args: start_date (datetime.date) The date to start populating the table. end_date (datetime.date) The date to end on. bill_ids (list) Returns (None) """ table_name = self._table_map["line_item_daily"] daily_sql = pkgutil.get_data("masu.database", "sql/reporting_awscostentrylineitem_daily.sql") daily_sql = daily_sql.decode("utf-8") daily_sql_params = { "uuid": str(uuid.uuid4()).replace("-", "_"), "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } daily_sql, daily_sql_params = self.jinja_sql.prepare_query(daily_sql, daily_sql_params) self._execute_raw_sql_query(table_name, daily_sql, start_date, end_date, bind_params=list(daily_sql_params)) def populate_line_item_daily_summary_table(self, start_date, end_date, bill_ids): """Populate the daily aggregated summary of line items table. Args: start_date (datetime.date) The date to start populating the table. end_date (datetime.date) The date to end on. Returns (None) """ table_name = self._table_map["line_item_daily_summary"] summary_sql = pkgutil.get_data("masu.database", "sql/reporting_awscostentrylineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "uuid": str(uuid.uuid4()).replace("-", "_"), "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def populate_ui_summary_tables(self, start_date, end_date, source_uuid, tables=UI_SUMMARY_TABLES): """Populate our UI summary tables (formerly materialized views).""" for table_name in tables: summary_sql = pkgutil.get_data("masu.database", f"sql/aws/{table_name}.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "start_date": start_date, "end_date": end_date, "schema": self.schema, "source_uuid": source_uuid, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def populate_line_item_daily_summary_table_presto(self, start_date, end_date, source_uuid, bill_id, markup_value): """Populate the daily aggregated summary of line items table. Args: start_date (datetime.date) The date to start populating the table. end_date (datetime.date) The date to end on. Returns (None) """ summary_sql = pkgutil.get_data("masu.database", "presto_sql/reporting_awscostentrylineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") uuid_str = str(uuid.uuid4()).replace("-", "_") summary_sql_params = { "uuid": uuid_str, "start_date": start_date, "end_date": end_date, "schema": self.schema, "table": PRESTO_LINE_ITEM_DAILY_TABLE, "source_uuid": source_uuid, "year": start_date.strftime("%Y"), "month": start_date.strftime("%m"), "markup": markup_value if markup_value else 0, "bill_id": bill_id, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) LOG.info(f"Summary SQL: {str(summary_sql)}") self._execute_presto_raw_sql_query(self.schema, summary_sql) def mark_bill_as_finalized(self, bill_id): """Mark a bill in the database as finalized.""" table_name = AWSCostEntryBill with schema_context(self.schema): bill = self._get_db_obj_query(table_name).get(id=bill_id) if bill.finalized_datetime is None: bill.finalized_datetime = self.date_accessor.today_with_timezone("UTC") bill.save() def populate_tags_summary_table(self, bill_ids, start_date, end_date): """Populate the line item aggregated totals data table.""" table_name = self._table_map["tags_summary"] agg_sql = pkgutil.get_data("masu.database", "sql/reporting_awstags_summary.sql") agg_sql = agg_sql.decode("utf-8") agg_sql_params = {"schema": self.schema, "bill_ids": bill_ids, "start_date": start_date, "end_date": end_date} agg_sql, agg_sql_params = self.jinja_sql.prepare_query(agg_sql, agg_sql_params) self._execute_raw_sql_query(table_name, agg_sql, bind_params=list(agg_sql_params)) def populate_ocp_on_aws_cost_daily_summary(self, start_date, end_date, cluster_id, bill_ids, markup_value): """Populate the daily cost aggregated summary for OCP on AWS. Args: start_date (datetime.date) The date to start populating the table. end_date (datetime.date) The date to end on. Returns (None) """ table_name = self._table_map["ocp_on_aws_daily_summary"] summary_sql = pkgutil.get_data("masu.database", "sql/reporting_ocpawscostlineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "uuid": str(uuid.uuid4()).replace("-", "_"), "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "cluster_id": cluster_id, "schema": self.schema, "markup": markup_value, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def populate_ocp_on_aws_ui_summary_tables(self, sql_params, tables=OCPAWS_UI_SUMMARY_TABLES): """Populate our UI summary tables (formerly materialized views).""" for table_name in tables: summary_sql = pkgutil.get_data("masu.database", f"sql/aws/openshift/{table_name}.sql") summary_sql = summary_sql.decode("utf-8") summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, sql_params) self._execute_raw_sql_query(table_name, summary_sql, bind_params=list(summary_sql_params)) def delete_ocp_on_aws_hive_partition_by_day(self, days, aws_source, ocp_source, year, month): """Deletes partitions individually for each day in days list.""" table = self._table_map["ocp_on_aws_project_daily_summary"] retries = settings.HIVE_PARTITION_DELETE_RETRIES if self.table_exists_trino(table): LOG.info( "Deleting partitions for the following: \n\tSchema: %s " "\n\tOCP Source: %s \n\tAWS Source: %s \n\tTable: %s \n\tYear-Month: %s-%s \n\tDays: %s", self.schema, ocp_source, aws_source, table, year, month, days, ) for day in days: for i in range(retries): try: sql = f""" DELETE FROM hive.{self.schema}.{table} WHERE aws_source = '{aws_source}' AND ocp_source = '{ocp_source}' AND year = '{year}' AND (month = replace(ltrim(replace('{month}', '0', ' ')),' ', '0') OR month = '{month}') AND day = '{day}'""" self._execute_presto_raw_sql_query(self.schema, sql) break except TrinoExternalError as err: if err.error_name == "HIVE_METASTORE_ERROR" and i < (retries - 1): continue else: raise err def populate_ocp_on_aws_cost_daily_summary_presto( self, start_date, end_date, openshift_provider_uuid, aws_provider_uuid, report_period_id, bill_id, markup_value, distribution, ): """Populate the daily cost aggregated summary for OCP on AWS. Args: start_date (datetime.date) The date to start populating the table. end_date (datetime.date) The date to end on. Returns (None) """ # Default to cpu distribution year = start_date.strftime("%Y") month = start_date.strftime("%m") days = DateHelper().list_days(start_date, end_date) days_str = "','".join([str(day.day) for day in days]) days_list = [str(day.day) for day in days] self.delete_ocp_on_aws_hive_partition_by_day( days_list, aws_provider_uuid, openshift_provider_uuid, year, month ) pod_column = "pod_effective_usage_cpu_core_hours" cluster_column = "cluster_capacity_cpu_core_hours" if distribution == "memory": pod_column = "pod_effective_usage_memory_gigabyte_hours" cluster_column = "cluster_capacity_memory_gigabyte_hours" summary_sql = pkgutil.get_data("masu.database", "presto_sql/reporting_ocpawscostlineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "schema": self.schema, "start_date": start_date, "year": year, "month": month, "days": days_str, "end_date": end_date, "aws_source_uuid": aws_provider_uuid, "ocp_source_uuid": openshift_provider_uuid, "bill_id": bill_id, "report_period_id": report_period_id, "markup": markup_value, "pod_column": pod_column, "cluster_column": cluster_column, } self._execute_presto_multipart_sql_query(self.schema, summary_sql, bind_params=summary_sql_params) def back_populate_ocp_on_aws_daily_summary(self, start_date, end_date, report_period_id): """Populate the OCP on AWS and OCP daily summary tables. after populating the project table via trino.""" table_name = AWS_CUR_TABLE_MAP["ocp_on_aws_daily_summary"] sql = pkgutil.get_data( "masu.database", "sql/reporting_ocpawscostentrylineitem_daily_summary_back_populate.sql" ) sql = sql.decode("utf-8") sql_params = { "schema": self.schema, "start_date": start_date, "end_date": end_date, "report_period_id": report_period_id, } sql, sql_params = self.jinja_sql.prepare_query(sql, sql_params) self._execute_raw_sql_query(table_name, sql, bind_params=list(sql_params)) def populate_ocp_on_aws_tags_summary_table(self, bill_ids, start_date, end_date): """Populate the line item aggregated totals data table.""" table_name = self._table_map["ocp_on_aws_tags_summary"] agg_sql = pkgutil.get_data("masu.database", "sql/reporting_ocpawstags_summary.sql") agg_sql = agg_sql.decode("utf-8") agg_sql_params = {"schema": self.schema, "bill_ids": bill_ids, "start_date": start_date, "end_date": end_date} agg_sql, agg_sql_params = self.jinja_sql.prepare_query(agg_sql, agg_sql_params) self._execute_raw_sql_query(table_name, agg_sql, bind_params=list(agg_sql_params)) def populate_markup_cost(self, provider_uuid, markup, start_date, end_date, bill_ids=None): """Set markup costs in the database.""" with schema_context(self.schema): if bill_ids and start_date and end_date: date_filters = {"usage_start__gte": start_date, "usage_start__lte": end_date} else: date_filters = {} OCPALL_MARKUP = (OCPAllCostLineItemDailySummaryP, *OCP_ON_ALL_PERSPECTIVES) for bill_id in bill_ids: AWSCostEntryLineItemDailySummary.objects.filter(cost_entry_bill_id=bill_id, **date_filters).update( markup_cost=(F("unblended_cost") * markup), markup_cost_blended=(F("blended_cost") * markup), markup_cost_savingsplan=(F("savingsplan_effective_cost") * markup), ) OCPAWSCostLineItemDailySummaryP.objects.filter(cost_entry_bill_id=bill_id, **date_filters).update( markup_cost=(F("unblended_cost") * markup) ) for ocpaws_model in OCP_ON_AWS_PERSPECTIVES: ocpaws_model.objects.filter(source_uuid=provider_uuid, **date_filters).update( markup_cost=(F("unblended_cost") * markup) ) OCPAllCostLineItemProjectDailySummaryP.objects.filter( source_uuid=provider_uuid, source_type="AWS", **date_filters ).update(project_markup_cost=(F("pod_cost") * markup)) for markup_model in OCPALL_MARKUP: markup_model.objects.filter(source_uuid=provider_uuid, source_type="AWS", **date_filters).update( markup_cost=(F("unblended_cost") * markup) ) def populate_enabled_tag_keys(self, start_date, end_date, bill_ids): """Populate the enabled tag key table. Args: start_date (datetime.date) The date to start populating the table. end_date (datetime.date) The date to end on. bill_ids (list) A list of bill IDs. Returns (None) """ table_name = self._table_map["enabled_tag_keys"] summary_sql = pkgutil.get_data("masu.database", "sql/reporting_awsenabledtagkeys.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def update_line_item_daily_summary_with_enabled_tags(self, start_date, end_date, bill_ids): """Populate the enabled tag key table. Args: start_date (datetime.date) The date to start populating the table. end_date (datetime.date) The date to end on. bill_ids (list) A list of bill IDs. Returns (None) """ table_name = self._table_map["line_item_daily_summary"] summary_sql = pkgutil.get_data( "masu.database", "sql/reporting_awscostentryline_item_daily_summary_update_enabled_tags.sql" ) summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def get_openshift_on_cloud_matched_tags(self, aws_bill_id, ocp_report_period_id): """Return a list of matched tags.""" sql = pkgutil.get_data("masu.database", "sql/reporting_ocpaws_matched_tags.sql") sql = sql.decode("utf-8") sql_params = {"bill_id": aws_bill_id, "report_period_id": ocp_report_period_id, "schema": self.schema} sql, bind_params = self.jinja_sql.prepare_query(sql, sql_params) with connection.cursor() as cursor: cursor.db.set_schema(self.schema) cursor.execute(sql, params=bind_params) results = cursor.fetchall() return [json.loads(result[0]) for result in results] def get_openshift_on_cloud_matched_tags_trino(self, aws_source_uuid, ocp_source_uuid, start_date, end_date): """Return a list of matched tags.""" sql = pkgutil.get_data("masu.database", "presto_sql/reporting_ocpaws_matched_tags.sql") sql = sql.decode("utf-8") sql_params = { "start_date": start_date, "end_date": end_date, "schema": self.schema, "aws_source_uuid": aws_source_uuid, "ocp_source_uuid": ocp_source_uuid, "year": start_date.strftime("%Y"), "month": start_date.strftime("%m"), } sql, sql_params = self.jinja_sql.prepare_query(sql, sql_params) results = self._execute_presto_raw_sql_query(self.schema, sql, bind_params=sql_params) return [json.loads(result[0]) for result in results]
44.127695
120
0.655605
import json import logging import pkgutil import uuid from dateutil.parser import parse from django.conf import settings from django.db import connection from django.db.models import F from jinjasql import JinjaSql from tenant_schemas.utils import schema_context from trino.exceptions import TrinoExternalError from api.utils import DateHelper from koku.database import get_model from koku.database import SQLScriptAtomicExecutorMixin from masu.config import Config from masu.database import AWS_CUR_TABLE_MAP from masu.database.report_db_accessor_base import ReportDBAccessorBase from masu.external.date_accessor import DateAccessor from reporting.models import OCP_ON_ALL_PERSPECTIVES from reporting.models import OCP_ON_AWS_PERSPECTIVES from reporting.models import OCPAllCostLineItemDailySummaryP from reporting.models import OCPAllCostLineItemProjectDailySummaryP from reporting.models import OCPAWSCostLineItemDailySummaryP from reporting.provider.aws.models import AWSCostEntry from reporting.provider.aws.models import AWSCostEntryBill from reporting.provider.aws.models import AWSCostEntryLineItem from reporting.provider.aws.models import AWSCostEntryLineItemDaily from reporting.provider.aws.models import AWSCostEntryLineItemDailySummary from reporting.provider.aws.models import AWSCostEntryPricing from reporting.provider.aws.models import AWSCostEntryProduct from reporting.provider.aws.models import AWSCostEntryReservation from reporting.provider.aws.models import PRESTO_LINE_ITEM_DAILY_TABLE from reporting.provider.aws.models import UI_SUMMARY_TABLES from reporting.provider.aws.openshift.models import UI_SUMMARY_TABLES as OCPAWS_UI_SUMMARY_TABLES LOG = logging.getLogger(__name__) class AWSReportDBAccessor(SQLScriptAtomicExecutorMixin, ReportDBAccessorBase): def __init__(self, schema): super().__init__(schema) self._datetime_format = Config.AWS_DATETIME_STR_FORMAT self.date_accessor = DateAccessor() self.jinja_sql = JinjaSql() self._table_map = AWS_CUR_TABLE_MAP @property def line_item_daily_summary_table(self): return AWSCostEntryLineItemDailySummary @property def ocpall_line_item_daily_summary_table(self): return get_model("OCPAllCostLineItemDailySummaryP") @property def ocpall_line_item_project_daily_summary_table(self): return get_model("OCPAllCostLineItemProjectDailySummaryP") @property def line_item_table(self): return AWSCostEntryLineItem @property def cost_entry_table(self): return AWSCostEntry @property def line_item_daily_table(self): return AWSCostEntryLineItemDaily def get_cost_entry_bills(self): table_name = AWSCostEntryBill with schema_context(self.schema): columns = ["id", "bill_type", "payer_account_id", "billing_period_start", "provider_id"] bills = self._get_db_obj_query(table_name).values(*columns) return { (bill["bill_type"], bill["payer_account_id"], bill["billing_period_start"], bill["provider_id"]): bill[ "id" ] for bill in bills } def get_cost_entry_bills_by_date(self, start_date): table_name = AWSCostEntryBill with schema_context(self.schema): return self._get_db_obj_query(table_name).filter(billing_period_start=start_date) def get_cost_entry_bills_query_by_provider(self, provider_uuid): table_name = AWSCostEntryBill with schema_context(self.schema): return self._get_db_obj_query(table_name).filter(provider_id=provider_uuid) def bills_for_provider_uuid(self, provider_uuid, start_date=None): bills = self.get_cost_entry_bills_query_by_provider(provider_uuid) if start_date: if isinstance(start_date, str): start_date = parse(start_date) bill_date = start_date.replace(day=1) bills = bills.filter(billing_period_start=bill_date) return bills def get_bill_query_before_date(self, date, provider_uuid=None): table_name = AWSCostEntryBill with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) if provider_uuid: cost_entry_bill_query = base_query.filter(billing_period_start__lte=date, provider_id=provider_uuid) else: cost_entry_bill_query = base_query.filter(billing_period_start__lte=date) return cost_entry_bill_query def get_lineitem_query_for_billid(self, bill_id): table_name = AWSCostEntryLineItem with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) line_item_query = base_query.filter(cost_entry_bill_id=bill_id) return line_item_query def get_daily_query_for_billid(self, bill_id): table_name = AWSCostEntryLineItemDaily with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) daily_item_query = base_query.filter(cost_entry_bill_id=bill_id) return daily_item_query def get_summary_query_for_billid(self, bill_id): table_name = AWSCostEntryLineItemDailySummary with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) summary_item_query = base_query.filter(cost_entry_bill_id=bill_id) return summary_item_query def get_ocp_aws_summary_query_for_billid(self, bill_id): table_name = self._table_map["ocp_on_aws_daily_summary"] base_query = self._get_db_obj_query(table_name) summary_item_query = base_query.filter(cost_entry_bill_id=bill_id) return summary_item_query def get_ocp_aws_project_summary_query_for_billid(self, bill_id): table_name = self._table_map["ocp_on_aws_project_daily_summary"] base_query = self._get_db_obj_query(table_name) summary_item_query = base_query.filter(cost_entry_bill_id=bill_id) return summary_item_query def get_cost_entry_query_for_billid(self, bill_id): table_name = AWSCostEntry with schema_context(self.schema): base_query = self._get_db_obj_query(table_name) line_item_query = base_query.filter(bill_id=bill_id) return line_item_query def get_cost_entries(self): table_name = AWSCostEntry with schema_context(self.schema): cost_entries = self._get_db_obj_query(table_name).all() return {(ce.bill_id, ce.interval_start.strftime(self._datetime_format)): ce.id for ce in cost_entries} def get_products(self): table_name = AWSCostEntryProduct with schema_context(self.schema): columns = ["id", "sku", "product_name", "region"] products = self._get_db_obj_query(table_name, columns=columns).all() return { (product["sku"], product["product_name"], product["region"]): product["id"] for product in products } def get_pricing(self): table_name = AWSCostEntryPricing with schema_context(self.schema): pricing = self._get_db_obj_query(table_name).all() return {f"{p.term}-{p.unit}": p.id for p in pricing} def get_reservations(self): table_name = AWSCostEntryReservation with schema_context(self.schema): columns = ["id", "reservation_arn"] reservs = self._get_db_obj_query(table_name, columns=columns).all() return {res["reservation_arn"]: res["id"] for res in reservs} def populate_line_item_daily_table(self, start_date, end_date, bill_ids): table_name = self._table_map["line_item_daily"] daily_sql = pkgutil.get_data("masu.database", "sql/reporting_awscostentrylineitem_daily.sql") daily_sql = daily_sql.decode("utf-8") daily_sql_params = { "uuid": str(uuid.uuid4()).replace("-", "_"), "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } daily_sql, daily_sql_params = self.jinja_sql.prepare_query(daily_sql, daily_sql_params) self._execute_raw_sql_query(table_name, daily_sql, start_date, end_date, bind_params=list(daily_sql_params)) def populate_line_item_daily_summary_table(self, start_date, end_date, bill_ids): table_name = self._table_map["line_item_daily_summary"] summary_sql = pkgutil.get_data("masu.database", "sql/reporting_awscostentrylineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "uuid": str(uuid.uuid4()).replace("-", "_"), "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def populate_ui_summary_tables(self, start_date, end_date, source_uuid, tables=UI_SUMMARY_TABLES): for table_name in tables: summary_sql = pkgutil.get_data("masu.database", f"sql/aws/{table_name}.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "start_date": start_date, "end_date": end_date, "schema": self.schema, "source_uuid": source_uuid, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def populate_line_item_daily_summary_table_presto(self, start_date, end_date, source_uuid, bill_id, markup_value): summary_sql = pkgutil.get_data("masu.database", "presto_sql/reporting_awscostentrylineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") uuid_str = str(uuid.uuid4()).replace("-", "_") summary_sql_params = { "uuid": uuid_str, "start_date": start_date, "end_date": end_date, "schema": self.schema, "table": PRESTO_LINE_ITEM_DAILY_TABLE, "source_uuid": source_uuid, "year": start_date.strftime("%Y"), "month": start_date.strftime("%m"), "markup": markup_value if markup_value else 0, "bill_id": bill_id, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) LOG.info(f"Summary SQL: {str(summary_sql)}") self._execute_presto_raw_sql_query(self.schema, summary_sql) def mark_bill_as_finalized(self, bill_id): table_name = AWSCostEntryBill with schema_context(self.schema): bill = self._get_db_obj_query(table_name).get(id=bill_id) if bill.finalized_datetime is None: bill.finalized_datetime = self.date_accessor.today_with_timezone("UTC") bill.save() def populate_tags_summary_table(self, bill_ids, start_date, end_date): table_name = self._table_map["tags_summary"] agg_sql = pkgutil.get_data("masu.database", "sql/reporting_awstags_summary.sql") agg_sql = agg_sql.decode("utf-8") agg_sql_params = {"schema": self.schema, "bill_ids": bill_ids, "start_date": start_date, "end_date": end_date} agg_sql, agg_sql_params = self.jinja_sql.prepare_query(agg_sql, agg_sql_params) self._execute_raw_sql_query(table_name, agg_sql, bind_params=list(agg_sql_params)) def populate_ocp_on_aws_cost_daily_summary(self, start_date, end_date, cluster_id, bill_ids, markup_value): table_name = self._table_map["ocp_on_aws_daily_summary"] summary_sql = pkgutil.get_data("masu.database", "sql/reporting_ocpawscostlineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "uuid": str(uuid.uuid4()).replace("-", "_"), "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "cluster_id": cluster_id, "schema": self.schema, "markup": markup_value, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def populate_ocp_on_aws_ui_summary_tables(self, sql_params, tables=OCPAWS_UI_SUMMARY_TABLES): for table_name in tables: summary_sql = pkgutil.get_data("masu.database", f"sql/aws/openshift/{table_name}.sql") summary_sql = summary_sql.decode("utf-8") summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, sql_params) self._execute_raw_sql_query(table_name, summary_sql, bind_params=list(summary_sql_params)) def delete_ocp_on_aws_hive_partition_by_day(self, days, aws_source, ocp_source, year, month): table = self._table_map["ocp_on_aws_project_daily_summary"] retries = settings.HIVE_PARTITION_DELETE_RETRIES if self.table_exists_trino(table): LOG.info( "Deleting partitions for the following: \n\tSchema: %s " "\n\tOCP Source: %s \n\tAWS Source: %s \n\tTable: %s \n\tYear-Month: %s-%s \n\tDays: %s", self.schema, ocp_source, aws_source, table, year, month, days, ) for day in days: for i in range(retries): try: sql = f""" DELETE FROM hive.{self.schema}.{table} WHERE aws_source = '{aws_source}' AND ocp_source = '{ocp_source}' AND year = '{year}' AND (month = replace(ltrim(replace('{month}', '0', ' ')),' ', '0') OR month = '{month}') AND day = '{day}'""" self._execute_presto_raw_sql_query(self.schema, sql) break except TrinoExternalError as err: if err.error_name == "HIVE_METASTORE_ERROR" and i < (retries - 1): continue else: raise err def populate_ocp_on_aws_cost_daily_summary_presto( self, start_date, end_date, openshift_provider_uuid, aws_provider_uuid, report_period_id, bill_id, markup_value, distribution, ): year = start_date.strftime("%Y") month = start_date.strftime("%m") days = DateHelper().list_days(start_date, end_date) days_str = "','".join([str(day.day) for day in days]) days_list = [str(day.day) for day in days] self.delete_ocp_on_aws_hive_partition_by_day( days_list, aws_provider_uuid, openshift_provider_uuid, year, month ) pod_column = "pod_effective_usage_cpu_core_hours" cluster_column = "cluster_capacity_cpu_core_hours" if distribution == "memory": pod_column = "pod_effective_usage_memory_gigabyte_hours" cluster_column = "cluster_capacity_memory_gigabyte_hours" summary_sql = pkgutil.get_data("masu.database", "presto_sql/reporting_ocpawscostlineitem_daily_summary.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "schema": self.schema, "start_date": start_date, "year": year, "month": month, "days": days_str, "end_date": end_date, "aws_source_uuid": aws_provider_uuid, "ocp_source_uuid": openshift_provider_uuid, "bill_id": bill_id, "report_period_id": report_period_id, "markup": markup_value, "pod_column": pod_column, "cluster_column": cluster_column, } self._execute_presto_multipart_sql_query(self.schema, summary_sql, bind_params=summary_sql_params) def back_populate_ocp_on_aws_daily_summary(self, start_date, end_date, report_period_id): table_name = AWS_CUR_TABLE_MAP["ocp_on_aws_daily_summary"] sql = pkgutil.get_data( "masu.database", "sql/reporting_ocpawscostentrylineitem_daily_summary_back_populate.sql" ) sql = sql.decode("utf-8") sql_params = { "schema": self.schema, "start_date": start_date, "end_date": end_date, "report_period_id": report_period_id, } sql, sql_params = self.jinja_sql.prepare_query(sql, sql_params) self._execute_raw_sql_query(table_name, sql, bind_params=list(sql_params)) def populate_ocp_on_aws_tags_summary_table(self, bill_ids, start_date, end_date): table_name = self._table_map["ocp_on_aws_tags_summary"] agg_sql = pkgutil.get_data("masu.database", "sql/reporting_ocpawstags_summary.sql") agg_sql = agg_sql.decode("utf-8") agg_sql_params = {"schema": self.schema, "bill_ids": bill_ids, "start_date": start_date, "end_date": end_date} agg_sql, agg_sql_params = self.jinja_sql.prepare_query(agg_sql, agg_sql_params) self._execute_raw_sql_query(table_name, agg_sql, bind_params=list(agg_sql_params)) def populate_markup_cost(self, provider_uuid, markup, start_date, end_date, bill_ids=None): with schema_context(self.schema): if bill_ids and start_date and end_date: date_filters = {"usage_start__gte": start_date, "usage_start__lte": end_date} else: date_filters = {} OCPALL_MARKUP = (OCPAllCostLineItemDailySummaryP, *OCP_ON_ALL_PERSPECTIVES) for bill_id in bill_ids: AWSCostEntryLineItemDailySummary.objects.filter(cost_entry_bill_id=bill_id, **date_filters).update( markup_cost=(F("unblended_cost") * markup), markup_cost_blended=(F("blended_cost") * markup), markup_cost_savingsplan=(F("savingsplan_effective_cost") * markup), ) OCPAWSCostLineItemDailySummaryP.objects.filter(cost_entry_bill_id=bill_id, **date_filters).update( markup_cost=(F("unblended_cost") * markup) ) for ocpaws_model in OCP_ON_AWS_PERSPECTIVES: ocpaws_model.objects.filter(source_uuid=provider_uuid, **date_filters).update( markup_cost=(F("unblended_cost") * markup) ) OCPAllCostLineItemProjectDailySummaryP.objects.filter( source_uuid=provider_uuid, source_type="AWS", **date_filters ).update(project_markup_cost=(F("pod_cost") * markup)) for markup_model in OCPALL_MARKUP: markup_model.objects.filter(source_uuid=provider_uuid, source_type="AWS", **date_filters).update( markup_cost=(F("unblended_cost") * markup) ) def populate_enabled_tag_keys(self, start_date, end_date, bill_ids): table_name = self._table_map["enabled_tag_keys"] summary_sql = pkgutil.get_data("masu.database", "sql/reporting_awsenabledtagkeys.sql") summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def update_line_item_daily_summary_with_enabled_tags(self, start_date, end_date, bill_ids): table_name = self._table_map["line_item_daily_summary"] summary_sql = pkgutil.get_data( "masu.database", "sql/reporting_awscostentryline_item_daily_summary_update_enabled_tags.sql" ) summary_sql = summary_sql.decode("utf-8") summary_sql_params = { "start_date": start_date, "end_date": end_date, "bill_ids": bill_ids, "schema": self.schema, } summary_sql, summary_sql_params = self.jinja_sql.prepare_query(summary_sql, summary_sql_params) self._execute_raw_sql_query( table_name, summary_sql, start_date, end_date, bind_params=list(summary_sql_params) ) def get_openshift_on_cloud_matched_tags(self, aws_bill_id, ocp_report_period_id): sql = pkgutil.get_data("masu.database", "sql/reporting_ocpaws_matched_tags.sql") sql = sql.decode("utf-8") sql_params = {"bill_id": aws_bill_id, "report_period_id": ocp_report_period_id, "schema": self.schema} sql, bind_params = self.jinja_sql.prepare_query(sql, sql_params) with connection.cursor() as cursor: cursor.db.set_schema(self.schema) cursor.execute(sql, params=bind_params) results = cursor.fetchall() return [json.loads(result[0]) for result in results] def get_openshift_on_cloud_matched_tags_trino(self, aws_source_uuid, ocp_source_uuid, start_date, end_date): sql = pkgutil.get_data("masu.database", "presto_sql/reporting_ocpaws_matched_tags.sql") sql = sql.decode("utf-8") sql_params = { "start_date": start_date, "end_date": end_date, "schema": self.schema, "aws_source_uuid": aws_source_uuid, "ocp_source_uuid": ocp_source_uuid, "year": start_date.strftime("%Y"), "month": start_date.strftime("%m"), } sql, sql_params = self.jinja_sql.prepare_query(sql, sql_params) results = self._execute_presto_raw_sql_query(self.schema, sql, bind_params=sql_params) return [json.loads(result[0]) for result in results]
true
true
1c39f85d98024e1f191b3e92b15dd3b3e349b5e1
8,767
py
Python
tests/providers_test.py
Asjidkalam/studio
5a4f2bbd6a2e3508d740404b0177f21c0c412f6e
[ "Apache-2.0" ]
null
null
null
tests/providers_test.py
Asjidkalam/studio
5a4f2bbd6a2e3508d740404b0177f21c0c412f6e
[ "Apache-2.0" ]
1
2021-02-08T15:42:00.000Z
2021-02-08T15:42:00.000Z
tests/providers_test.py
Asjidkalam/studio
5a4f2bbd6a2e3508d740404b0177f21c0c412f6e
[ "Apache-2.0" ]
1
2021-02-08T15:38:56.000Z
2021-02-08T15:38:56.000Z
import unittest import inspect import yaml import uuid import os import time import six import shutil from studio import model from studio.firebase_provider import FirebaseProvider from studio.postgres_provider import PostgresProvider from studio.s3_provider import S3Provider from studio.auth import remove_all_keys from studio.util import has_aws_credentials from env_detect import on_gcp, on_aws from model_test import get_test_experiment def get_methods(cls): methods = inspect.getmembers(cls, predicate=inspect.ismethod) return set([name for name, _ in methods if not name.startswith('_')]) class ProvidersTest(unittest.TestCase): def test_providers_compatible(self): # Check that all available providers are compatible. firebase_methods = get_methods(FirebaseProvider) postgres_methods = get_methods(PostgresProvider) s3_methods = get_methods(S3Provider) self.assertEqual(firebase_methods, postgres_methods) self.assertEqual(firebase_methods, s3_methods) class KeyValueProviderTest(object): def get_default_config_name(self): return 'test_config.yaml' def get_provider(self, config_name=None): config_name = config_name if config_name else \ self.get_default_config_name() config_file = os.path.join( os.path.dirname( os.path.realpath(__file__)), config_name) with open(config_file) as f: config = yaml.load(f, Loader=yaml.SafeLoader) return model.get_db_provider(config) def test_get_set(self): with self.get_provider() as fb: fb._set("test/hello", "world") response = fb._get("test/hello") self.assertEqual(response, "world") random_str = str(uuid.uuid4()) key_path = 'test/randomKey' fb._set(key_path, random_str) self.assertTrue(fb._get(key_path) == random_str) fb._delete(key_path) def test_get_user_keybase(self): with self.get_provider() as fb: keybase = fb._get_user_keybase() self.assertTrue(keybase == 'users/guest/') def test_get_experiments_keybase(self): with self.get_provider() as fb: keybase = fb._get_experiments_keybase() self.assertTrue(keybase == 'experiments/') def test_get_projects_keybase(self): with self.get_provider() as fb: keybase = fb._get_projects_keybase() self.assertTrue(keybase == 'projects/') def test_add_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _ = get_test_experiment() fb._delete(fb._get_experiments_keybase() + experiment_name) fb.add_experiment(experiment) self.assertTrue(experiment.status == 'waiting') self.assertTrue(experiment.time_added <= time.time()) actual_experiment_dict = fb._get( fb._get_experiments_keybase() + experiment_name) self._compare_experiment_data(experiment, actual_experiment_dict) fb.finish_experiment(experiment) fb.delete_experiment(experiment) def test_start_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _ = get_test_experiment() fb._delete(fb._get_experiments_keybase() + experiment_name) fb.add_experiment(experiment) fb.start_experiment(experiment) self.assertTrue(experiment.status == 'running') self.assertTrue(experiment.time_added <= time.time()) self.assertTrue(experiment.time_started <= time.time()) actual_experiment_dict = fb._get( fb._get_experiments_keybase() + experiment_name) self._compare_experiment_data(experiment, actual_experiment_dict) fb.finish_experiment(experiment) fb.delete_experiment(experiment) def test_finish_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _ = get_test_experiment() fb._delete(fb._get_experiments_keybase() + experiment_name) fb.add_experiment(experiment) fb.start_experiment(experiment) fb.finish_experiment(experiment) self.assertTrue(experiment.status == 'finished') self.assertTrue(experiment.time_added <= time.time()) self.assertTrue(experiment.time_started <= time.time()) self.assertTrue(experiment.time_finished <= time.time()) actual_experiment_dict = fb._get( fb._get_experiments_keybase() + experiment_name) self._compare_experiment_data(experiment, actual_experiment_dict) fb.delete_experiment(experiment) def test_checkpoint_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _, = get_test_experiment() modeldir = experiment.artifacts['modeldir'].local_path if os.path.exists(modeldir): shutil.rmtree(modeldir) os.makedirs(modeldir) try: fb.delete_experiment(experiment_name) except BaseException: pass fb.add_experiment(experiment) fb.start_experiment(experiment) file_in_modeldir = os.path.join(modeldir, str(uuid.uuid4())) random_str = str(uuid.uuid4()) with open(file_in_modeldir, 'w') as f: f.write(random_str) checkpoint_threads = fb.checkpoint_experiment(experiment) if checkpoint_threads: for t in checkpoint_threads: t.join() shutil.rmtree(modeldir) fb.store.get_artifact( fb.get_experiment( experiment_name, getinfo=False).artifacts['modeldir']) with open(file_in_modeldir, 'r') as f: line = f.read() self.assertTrue(line == random_str) fb.delete_experiment(experiment) def _compare_experiment_data(self, experiment, actual_experiment_dict): for key, value in experiment.__dict__.items(): if value: if key != 'artifacts': self.assertTrue( actual_experiment_dict[key] == value) else: for art_name, art in value.items(): self.assertTrue( actual_experiment_dict[key][art_name] == value[art_name].to_dict()) @unittest.skipIf(True, "Firebase is not expected to be used.") class FirebaseProviderTest(unittest.TestCase, KeyValueProviderTest): _multiprocess_shared_ = True def test_get_set_auth_firebase(self): remove_all_keys() with self.get_provider('test_config_auth.yaml') as fb: response = fb._get("authtest/hello") self.assertEquals(response, "world") random_str = str(uuid.uuid4()) key_path = 'authtest/randomKey' fb._set(key_path, random_str) self.assertTrue(fb._get(key_path) == random_str) fb._delete(key_path) remove_all_keys() def test_get_set_noauth_firebase(self): remove_all_keys() with self.get_provider('test_config.yaml') as fb: response = fb._get("authtest/hello") self.assertTrue(response is None) random_str = str(uuid.uuid4()) key_path = 'authtest/randomKey' fb._set(key_path, random_str) self.assertTrue(fb._get(key_path) is None) remove_all_keys() def test_get_set_firebase_bad(self): # smoke test to make sure access to a database at wrong # url is reported, but does not crash the system with self.get_provider('test_bad_config.yaml') as fb: response = fb._get("test/hello") self.assertTrue(response is None) fb._set("test/hello", "bla") @unittest.skipIf( not on_aws(), 'User indicated not on aws') class UserIndicatedOnAWSTest(unittest.TestCase): def test_on_enviornment(self): self.assertTrue(has_aws_credentials()) @unittest.skipIf( not isinstance(KeyValueProviderTest().get_provider(), S3Provider), 'Skipping due to provider is not S3Provider') class S3ProviderTest(unittest.TestCase, KeyValueProviderTest): _multiprocess_shared_ = True def get_default_config_name(self): return 'test_config.yaml' if __name__ == "__main__": KeyValueProviderTest().get_provider(config_name=None) unittest.main()
34.789683
77
0.639557
import unittest import inspect import yaml import uuid import os import time import six import shutil from studio import model from studio.firebase_provider import FirebaseProvider from studio.postgres_provider import PostgresProvider from studio.s3_provider import S3Provider from studio.auth import remove_all_keys from studio.util import has_aws_credentials from env_detect import on_gcp, on_aws from model_test import get_test_experiment def get_methods(cls): methods = inspect.getmembers(cls, predicate=inspect.ismethod) return set([name for name, _ in methods if not name.startswith('_')]) class ProvidersTest(unittest.TestCase): def test_providers_compatible(self): firebase_methods = get_methods(FirebaseProvider) postgres_methods = get_methods(PostgresProvider) s3_methods = get_methods(S3Provider) self.assertEqual(firebase_methods, postgres_methods) self.assertEqual(firebase_methods, s3_methods) class KeyValueProviderTest(object): def get_default_config_name(self): return 'test_config.yaml' def get_provider(self, config_name=None): config_name = config_name if config_name else \ self.get_default_config_name() config_file = os.path.join( os.path.dirname( os.path.realpath(__file__)), config_name) with open(config_file) as f: config = yaml.load(f, Loader=yaml.SafeLoader) return model.get_db_provider(config) def test_get_set(self): with self.get_provider() as fb: fb._set("test/hello", "world") response = fb._get("test/hello") self.assertEqual(response, "world") random_str = str(uuid.uuid4()) key_path = 'test/randomKey' fb._set(key_path, random_str) self.assertTrue(fb._get(key_path) == random_str) fb._delete(key_path) def test_get_user_keybase(self): with self.get_provider() as fb: keybase = fb._get_user_keybase() self.assertTrue(keybase == 'users/guest/') def test_get_experiments_keybase(self): with self.get_provider() as fb: keybase = fb._get_experiments_keybase() self.assertTrue(keybase == 'experiments/') def test_get_projects_keybase(self): with self.get_provider() as fb: keybase = fb._get_projects_keybase() self.assertTrue(keybase == 'projects/') def test_add_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _ = get_test_experiment() fb._delete(fb._get_experiments_keybase() + experiment_name) fb.add_experiment(experiment) self.assertTrue(experiment.status == 'waiting') self.assertTrue(experiment.time_added <= time.time()) actual_experiment_dict = fb._get( fb._get_experiments_keybase() + experiment_name) self._compare_experiment_data(experiment, actual_experiment_dict) fb.finish_experiment(experiment) fb.delete_experiment(experiment) def test_start_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _ = get_test_experiment() fb._delete(fb._get_experiments_keybase() + experiment_name) fb.add_experiment(experiment) fb.start_experiment(experiment) self.assertTrue(experiment.status == 'running') self.assertTrue(experiment.time_added <= time.time()) self.assertTrue(experiment.time_started <= time.time()) actual_experiment_dict = fb._get( fb._get_experiments_keybase() + experiment_name) self._compare_experiment_data(experiment, actual_experiment_dict) fb.finish_experiment(experiment) fb.delete_experiment(experiment) def test_finish_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _ = get_test_experiment() fb._delete(fb._get_experiments_keybase() + experiment_name) fb.add_experiment(experiment) fb.start_experiment(experiment) fb.finish_experiment(experiment) self.assertTrue(experiment.status == 'finished') self.assertTrue(experiment.time_added <= time.time()) self.assertTrue(experiment.time_started <= time.time()) self.assertTrue(experiment.time_finished <= time.time()) actual_experiment_dict = fb._get( fb._get_experiments_keybase() + experiment_name) self._compare_experiment_data(experiment, actual_experiment_dict) fb.delete_experiment(experiment) def test_checkpoint_experiment(self): with self.get_provider() as fb: experiment, experiment_name, _, _, = get_test_experiment() modeldir = experiment.artifacts['modeldir'].local_path if os.path.exists(modeldir): shutil.rmtree(modeldir) os.makedirs(modeldir) try: fb.delete_experiment(experiment_name) except BaseException: pass fb.add_experiment(experiment) fb.start_experiment(experiment) file_in_modeldir = os.path.join(modeldir, str(uuid.uuid4())) random_str = str(uuid.uuid4()) with open(file_in_modeldir, 'w') as f: f.write(random_str) checkpoint_threads = fb.checkpoint_experiment(experiment) if checkpoint_threads: for t in checkpoint_threads: t.join() shutil.rmtree(modeldir) fb.store.get_artifact( fb.get_experiment( experiment_name, getinfo=False).artifacts['modeldir']) with open(file_in_modeldir, 'r') as f: line = f.read() self.assertTrue(line == random_str) fb.delete_experiment(experiment) def _compare_experiment_data(self, experiment, actual_experiment_dict): for key, value in experiment.__dict__.items(): if value: if key != 'artifacts': self.assertTrue( actual_experiment_dict[key] == value) else: for art_name, art in value.items(): self.assertTrue( actual_experiment_dict[key][art_name] == value[art_name].to_dict()) @unittest.skipIf(True, "Firebase is not expected to be used.") class FirebaseProviderTest(unittest.TestCase, KeyValueProviderTest): _multiprocess_shared_ = True def test_get_set_auth_firebase(self): remove_all_keys() with self.get_provider('test_config_auth.yaml') as fb: response = fb._get("authtest/hello") self.assertEquals(response, "world") random_str = str(uuid.uuid4()) key_path = 'authtest/randomKey' fb._set(key_path, random_str) self.assertTrue(fb._get(key_path) == random_str) fb._delete(key_path) remove_all_keys() def test_get_set_noauth_firebase(self): remove_all_keys() with self.get_provider('test_config.yaml') as fb: response = fb._get("authtest/hello") self.assertTrue(response is None) random_str = str(uuid.uuid4()) key_path = 'authtest/randomKey' fb._set(key_path, random_str) self.assertTrue(fb._get(key_path) is None) remove_all_keys() def test_get_set_firebase_bad(self): with self.get_provider('test_bad_config.yaml') as fb: response = fb._get("test/hello") self.assertTrue(response is None) fb._set("test/hello", "bla") @unittest.skipIf( not on_aws(), 'User indicated not on aws') class UserIndicatedOnAWSTest(unittest.TestCase): def test_on_enviornment(self): self.assertTrue(has_aws_credentials()) @unittest.skipIf( not isinstance(KeyValueProviderTest().get_provider(), S3Provider), 'Skipping due to provider is not S3Provider') class S3ProviderTest(unittest.TestCase, KeyValueProviderTest): _multiprocess_shared_ = True def get_default_config_name(self): return 'test_config.yaml' if __name__ == "__main__": KeyValueProviderTest().get_provider(config_name=None) unittest.main()
true
true
1c39fa63b000568faf65b90c206d0fb5ea691a09
784
py
Python
services/backend/app/api/auth.py
miguelalb/resume-portal-fastapi
286f732510925c5ad3760ca2af82098ed78e0dd9
[ "BSD-3-Clause" ]
1
2022-02-28T02:29:02.000Z
2022-02-28T02:29:02.000Z
services/backend/app/api/auth.py
miguelalb/resume-portal-fastapi
286f732510925c5ad3760ca2af82098ed78e0dd9
[ "BSD-3-Clause" ]
null
null
null
services/backend/app/api/auth.py
miguelalb/resume-portal-fastapi
286f732510925c5ad3760ca2af82098ed78e0dd9
[ "BSD-3-Clause" ]
null
null
null
from app import crud, schemas from app.dependencies import get_db from app.security import authenticate_user, create_access_token from fastapi import APIRouter, Depends, status from sqlalchemy.orm import Session router = APIRouter() @router.post("/login") async def login(user_in: schemas.UserLogin, db: Session = Depends(get_db)): user = authenticate_user(db, user_in.username, user_in.password) token = create_access_token({"id": str(user.id)}) return schemas.Token(access_token=token, token_type="Bearer") @router.post( "/register", response_model=schemas.User, status_code=status.HTTP_201_CREATED ) async def register(user_in: schemas.UserCreate, db: Session = Depends(get_db)): user = crud.create_user(db, user_in) return schemas.User.from_orm(user)
34.086957
81
0.769133
from app import crud, schemas from app.dependencies import get_db from app.security import authenticate_user, create_access_token from fastapi import APIRouter, Depends, status from sqlalchemy.orm import Session router = APIRouter() @router.post("/login") async def login(user_in: schemas.UserLogin, db: Session = Depends(get_db)): user = authenticate_user(db, user_in.username, user_in.password) token = create_access_token({"id": str(user.id)}) return schemas.Token(access_token=token, token_type="Bearer") @router.post( "/register", response_model=schemas.User, status_code=status.HTTP_201_CREATED ) async def register(user_in: schemas.UserCreate, db: Session = Depends(get_db)): user = crud.create_user(db, user_in) return schemas.User.from_orm(user)
true
true
1c39fa755029bf8e012024a8e85eda8529fb046e
8,984
py
Python
dataset/clip_generator.py
yuananf/Voice-Cloning-App
5996f971232fd8056cd2514b196df44bffef0d34
[ "BSD-3-Clause" ]
null
null
null
dataset/clip_generator.py
yuananf/Voice-Cloning-App
5996f971232fd8056cd2514b196df44bffef0d34
[ "BSD-3-Clause" ]
null
null
null
dataset/clip_generator.py
yuananf/Voice-Cloning-App
5996f971232fd8056cd2514b196df44bffef0d34
[ "BSD-3-Clause" ]
1
2021-07-22T08:29:12.000Z
2021-07-22T08:29:12.000Z
import argparse import os import logging import json import uuid import shutil from pathlib import Path from pydub import AudioSegment import dataset.forced_alignment.align as align from dataset.forced_alignment.search import FuzzySearch from dataset.forced_alignment.audio import DEFAULT_RATE from dataset.audio_processing import change_sample_rate, add_silence MIN_LENGTH = 1.0 MAX_LENGTH = 10.0 def clip_generator( audio_path, script_path, forced_alignment_path, output_path, label_path, logging=logging, min_length=MIN_LENGTH, max_length=MAX_LENGTH, silence_padding=0.1, min_confidence=0.85, ): """ Generates dataset clips & label file. Parameters ---------- audio_path : str Path to audio file (must have been converted using convert_audio) script_path : str Path to source text forced_alignment_path : str Path to save alignment JSON to output_path : str Path to save audio clips to label_path : str Path to save label file to logging : logging (optional) Logging object to write logs to min_length : float (optional) Minimum duration of a clip in seconds max_length : float (optional) Maximum duration of a clip in seconds silence_padding : float (optional) Padding of silence at the end of each clip in seconds min_confidence : float (optional) Minimum confidence score to generate a clip for Raises ------- AssertionError If given paths are invalid or clips could not be produced Returns ------- list List of clip lengths in seconds """ assert not os.path.isdir(output_path), "Output directory already exists" os.makedirs(output_path, exist_ok=False) assert os.path.isfile(audio_path), "Audio file not found" assert os.path.isfile(script_path), "Script file not found" assert audio_path.endswith(".wav"), "Must be a WAV file" logging.info(f"Loading script from {script_path}...") with open(script_path, "r", encoding="utf-8") as script_file: clean_text = script_file.read().lower().strip().replace("\n", " ").replace(" ", " ") logging.info("Searching text for matching fragments...") search = FuzzySearch(clean_text) logging.info("Changing sample rate...") new_audio_path = change_sample_rate(audio_path, DEFAULT_RATE) # Produce segments logging.info("Fetching segments...") segments = align.get_segments(new_audio_path) # Match with text logging.info("Matching segments...") min_length_ms = min_length * 1000 max_length_ms = max_length * 1000 processed_segments = align.process_segments( audio_path, output_path, segments, min_length_ms, max_length_ms, logging ) matched_segments = align.split_match(processed_segments, search) matched_segments = list(filter(lambda f: f is not None, matched_segments)) logging.info(f"Matched {len(matched_segments)} segments") # Generate final clips silence = AudioSegment.silent(duration=int(silence_padding * 1000)) result_fragments = [] clip_lengths = [] for fragment in matched_segments: if ( fragment["transcript"] and fragment["score"] >= min_confidence and "match-start" in fragment and "match-end" in fragment and fragment["match-end"] - fragment["match-start"] > 0 ): fragment_matched = clean_text[fragment["match-start"] : fragment["match-end"]] if fragment_matched: fragment["aligned"] = fragment_matched clip_lengths.append((fragment["end"] - fragment["start"]) // 1000) add_silence(os.path.join(output_path, fragment["name"]), silence) result_fragments.append(fragment) # Delete unused clips fragment_names = [fragment["name"] for fragment in result_fragments] for filename in os.listdir(output_path): if filename not in fragment_names: os.remove(os.path.join(output_path, filename)) os.remove(new_audio_path) assert result_fragments, "No audio clips could be generated" # Produce alignment file logging.info(f"Produced {len(result_fragments)} final fragments") with open(forced_alignment_path, "w", encoding="utf-8") as result_file: result_file.write(json.dumps(result_fragments, ensure_ascii=False, indent=4)) # Produce metadata file with open(label_path, "w", encoding="utf-8") as f: for fragment in result_fragments: f.write(f"{fragment['name']}|{fragment['aligned']}\n") logging.info("Generated clips") return clip_lengths def get_filename(filename, suffix): """ Adds a suffix to a filename. Parameters ---------- filename : str Current filename suffix : str String to add to the filename Returns ------- str New filename """ name_without_filetype = filename.split(".")[0] return filename.replace(name_without_filetype, name_without_filetype + "-" + suffix) def extend_dataset( audio_path, script_path, forced_alignment_path, output_path, label_path, suffix=str(uuid.uuid4()), logging=logging, min_confidence=0.85, ): """ Extends an existing dataset. Uses temporary filenames and then combines files with the existing dataset. Parameters ---------- audio_path : str Path to audio file (must have been converted using convert_audio) script_path : str Path to source text forced_alignment_path : str Path to save alignment JSON to output_path : str Path to save audio clips to label_path : str Path to save label file to suffix : str String suffix to add to filenames logging : logging (optional) Logging object to write logs to min_confidence : float (optional) Minimum confidence score to generate a clip for Raises ------- AssertionError If given paths are invalid or clips could not be produced """ assert os.path.isdir(output_path), "Existing wavs folder not found" assert os.path.isfile(label_path), "Existing metadata file not found" temp_label_path = label_path.replace(Path(label_path).name, "temp.csv") temp_wavs_folder = output_path.replace(Path(output_path).name, "temp_wavs") clip_generator( audio_path, script_path, forced_alignment_path, temp_wavs_folder, temp_label_path, logging, min_confidence=min_confidence, ) with open(temp_label_path) as f: new_labels = f.readlines() with open(label_path, "a+") as f: for line in new_labels: filename, text = line.split("|") new_filename = get_filename(filename, suffix) f.write(f"{new_filename}|{text}") for filename in os.listdir(temp_wavs_folder): new_filename = get_filename(filename, suffix) shutil.copyfile(os.path.join(temp_wavs_folder, filename), os.path.join(output_path, new_filename)) os.remove(temp_label_path) shutil.rmtree(temp_wavs_folder) logging.info("Combined dataset") if __name__ == "__main__": """Generate clips""" parser = argparse.ArgumentParser(description="Split audio into snippets using forced align timings") parser.add_argument("-a", "--audio_path", help="Path to WAV file", type=str, required=True) parser.add_argument("-s", "--script_path", help="Path to text file", type=str, required=True) parser.add_argument( "-f", "--forced_alignment_path", help="Path to forced alignment JSON", type=str, default="align.json" ) parser.add_argument("-o", "--output_path", help="Path to save snippets", type=str, default="wavs") parser.add_argument( "-l", "--label_path", help="Path to save snippet labelling text file", type=str, default="metadata.csv" ) parser.add_argument("--min_length", help="Minumum snippet length", type=float, default=1.0) parser.add_argument("--max_length", help="Maximum snippet length", type=float, default=10.0) parser.add_argument("--silence_padding", help="Silence padding on the end of the clip", type=int, default=0.1) parser.add_argument("--min_confidence", help="Minimum clip confidendence", type=float, default=0.85) args = parser.parse_args() clip_lengths = clip_generator(**vars(args)) total_audio = sum(clip_lengths) total_clips = len(clip_lengths) minutes = int(total_audio / 60) seconds = total_audio - (minutes * 60) print(f"Total clips = {total_clips} (average of {total_audio/total_clips} seconds per clip)") print(f"Total audio = {minutes} minutes, {seconds} seconds") print(f"Audio saved to {args.output_path}. Text file save to {args.label_path}") import matplotlib.pyplot as plt plt.hist(clip_lengths, bins=10) plt.show()
33.901887
114
0.675534
import argparse import os import logging import json import uuid import shutil from pathlib import Path from pydub import AudioSegment import dataset.forced_alignment.align as align from dataset.forced_alignment.search import FuzzySearch from dataset.forced_alignment.audio import DEFAULT_RATE from dataset.audio_processing import change_sample_rate, add_silence MIN_LENGTH = 1.0 MAX_LENGTH = 10.0 def clip_generator( audio_path, script_path, forced_alignment_path, output_path, label_path, logging=logging, min_length=MIN_LENGTH, max_length=MAX_LENGTH, silence_padding=0.1, min_confidence=0.85, ): assert not os.path.isdir(output_path), "Output directory already exists" os.makedirs(output_path, exist_ok=False) assert os.path.isfile(audio_path), "Audio file not found" assert os.path.isfile(script_path), "Script file not found" assert audio_path.endswith(".wav"), "Must be a WAV file" logging.info(f"Loading script from {script_path}...") with open(script_path, "r", encoding="utf-8") as script_file: clean_text = script_file.read().lower().strip().replace("\n", " ").replace(" ", " ") logging.info("Searching text for matching fragments...") search = FuzzySearch(clean_text) logging.info("Changing sample rate...") new_audio_path = change_sample_rate(audio_path, DEFAULT_RATE) logging.info("Fetching segments...") segments = align.get_segments(new_audio_path) logging.info("Matching segments...") min_length_ms = min_length * 1000 max_length_ms = max_length * 1000 processed_segments = align.process_segments( audio_path, output_path, segments, min_length_ms, max_length_ms, logging ) matched_segments = align.split_match(processed_segments, search) matched_segments = list(filter(lambda f: f is not None, matched_segments)) logging.info(f"Matched {len(matched_segments)} segments") silence = AudioSegment.silent(duration=int(silence_padding * 1000)) result_fragments = [] clip_lengths = [] for fragment in matched_segments: if ( fragment["transcript"] and fragment["score"] >= min_confidence and "match-start" in fragment and "match-end" in fragment and fragment["match-end"] - fragment["match-start"] > 0 ): fragment_matched = clean_text[fragment["match-start"] : fragment["match-end"]] if fragment_matched: fragment["aligned"] = fragment_matched clip_lengths.append((fragment["end"] - fragment["start"]) // 1000) add_silence(os.path.join(output_path, fragment["name"]), silence) result_fragments.append(fragment) fragment_names = [fragment["name"] for fragment in result_fragments] for filename in os.listdir(output_path): if filename not in fragment_names: os.remove(os.path.join(output_path, filename)) os.remove(new_audio_path) assert result_fragments, "No audio clips could be generated" logging.info(f"Produced {len(result_fragments)} final fragments") with open(forced_alignment_path, "w", encoding="utf-8") as result_file: result_file.write(json.dumps(result_fragments, ensure_ascii=False, indent=4)) with open(label_path, "w", encoding="utf-8") as f: for fragment in result_fragments: f.write(f"{fragment['name']}|{fragment['aligned']}\n") logging.info("Generated clips") return clip_lengths def get_filename(filename, suffix): name_without_filetype = filename.split(".")[0] return filename.replace(name_without_filetype, name_without_filetype + "-" + suffix) def extend_dataset( audio_path, script_path, forced_alignment_path, output_path, label_path, suffix=str(uuid.uuid4()), logging=logging, min_confidence=0.85, ): assert os.path.isdir(output_path), "Existing wavs folder not found" assert os.path.isfile(label_path), "Existing metadata file not found" temp_label_path = label_path.replace(Path(label_path).name, "temp.csv") temp_wavs_folder = output_path.replace(Path(output_path).name, "temp_wavs") clip_generator( audio_path, script_path, forced_alignment_path, temp_wavs_folder, temp_label_path, logging, min_confidence=min_confidence, ) with open(temp_label_path) as f: new_labels = f.readlines() with open(label_path, "a+") as f: for line in new_labels: filename, text = line.split("|") new_filename = get_filename(filename, suffix) f.write(f"{new_filename}|{text}") for filename in os.listdir(temp_wavs_folder): new_filename = get_filename(filename, suffix) shutil.copyfile(os.path.join(temp_wavs_folder, filename), os.path.join(output_path, new_filename)) os.remove(temp_label_path) shutil.rmtree(temp_wavs_folder) logging.info("Combined dataset") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Split audio into snippets using forced align timings") parser.add_argument("-a", "--audio_path", help="Path to WAV file", type=str, required=True) parser.add_argument("-s", "--script_path", help="Path to text file", type=str, required=True) parser.add_argument( "-f", "--forced_alignment_path", help="Path to forced alignment JSON", type=str, default="align.json" ) parser.add_argument("-o", "--output_path", help="Path to save snippets", type=str, default="wavs") parser.add_argument( "-l", "--label_path", help="Path to save snippet labelling text file", type=str, default="metadata.csv" ) parser.add_argument("--min_length", help="Minumum snippet length", type=float, default=1.0) parser.add_argument("--max_length", help="Maximum snippet length", type=float, default=10.0) parser.add_argument("--silence_padding", help="Silence padding on the end of the clip", type=int, default=0.1) parser.add_argument("--min_confidence", help="Minimum clip confidendence", type=float, default=0.85) args = parser.parse_args() clip_lengths = clip_generator(**vars(args)) total_audio = sum(clip_lengths) total_clips = len(clip_lengths) minutes = int(total_audio / 60) seconds = total_audio - (minutes * 60) print(f"Total clips = {total_clips} (average of {total_audio/total_clips} seconds per clip)") print(f"Total audio = {minutes} minutes, {seconds} seconds") print(f"Audio saved to {args.output_path}. Text file save to {args.label_path}") import matplotlib.pyplot as plt plt.hist(clip_lengths, bins=10) plt.show()
true
true
1c39fba6acb33be18e0143c0ffd889f24a117da6
4,404
py
Python
src/pymortests/sylvester.py
weslowrie/pymor
badb5078b2394162d04a1ebfefe9034b889dac64
[ "Unlicense" ]
1
2020-12-31T18:45:48.000Z
2020-12-31T18:45:48.000Z
src/pymortests/sylvester.py
TreeerT/pymor
e8b18d2d4c4b5998f0bd84f6728e365e0693b753
[ "Unlicense" ]
4
2022-03-17T10:07:38.000Z
2022-03-30T12:41:06.000Z
src/pymortests/sylvester.py
TreeerT/pymor
e8b18d2d4c4b5998f0bd84f6728e365e0693b753
[ "Unlicense" ]
null
null
null
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2020 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) import numpy as np import scipy.linalg as spla import scipy.sparse as sps from pymor.algorithms.sylvester import solve_sylv_schur from pymor.operators.numpy import NumpyMatrixOperator import pytest n_list = [100, 1000] r_list = [1, 10, 20] m_list = [1, 2] p_list = [1, 2] def fro_norm(A): if not sps.issparse(A): return spla.norm(A) else: return sps.linalg.norm(A) def diff_conv_1d_fd(n, a, b): diagonals = [-a * 2 * (n + 1) ** 2 * np.ones((n,)), (a * (n + 1) ** 2 + b * (n + 1) / 2) * np.ones((n - 1,)), (a * (n + 1) ** 2 - b * (n + 1) / 2) * np.ones((n - 1,))] A = sps.diags(diagonals, [0, -1, 1]) return A def diff_conv_1d_fem(n, a, b): diagonals = [-a * 2 * (n + 1) ** 2 * np.ones((n,)), (a * (n + 1) ** 2 + b * (n + 1) / 2) * np.ones((n - 1,)), (a * (n + 1) ** 2 - b * (n + 1) / 2) * np.ones((n - 1,))] A = sps.diags(diagonals, [0, -1, 1]) diagonals = [2 / 3 * np.ones((n,)), 1 / 6 * np.ones((n - 1,)), 1 / 6 * np.ones((n - 1,))] E = sps.diags(diagonals, [0, -1, 1]) return A, E @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('m', m_list) def test_sylv_schur_V(n, r, m): np.random.seed(0) A = diff_conv_1d_fd(n, 1, 1) B = np.random.randn(n, m) Ar = np.random.randn(r, r) - r * np.eye(r) Br = np.random.randn(r, m) Aop = NumpyMatrixOperator(A) Bop = NumpyMatrixOperator(B) Arop = NumpyMatrixOperator(Ar) Brop = NumpyMatrixOperator(Br) Vva = solve_sylv_schur(Aop, Arop, B=Bop, Br=Brop) V = Vva.to_numpy().T AV = A.dot(V) VArT = V.dot(Ar.T) BBrT = B.dot(Br.T) assert fro_norm(AV + VArT + BBrT) / fro_norm(BBrT) < 1e-10 @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('m', m_list) def test_sylv_schur_V_E(n, r, m): np.random.seed(0) A, E = diff_conv_1d_fem(n, 1, 1) B = np.random.randn(n, m) Ar = np.random.randn(r, r) - r * np.eye(r) Er = np.random.randn(r, r) Er = (Er + Er.T) / 2 Er += r * np.eye(r) Br = np.random.randn(r, m) Aop = NumpyMatrixOperator(A) Eop = NumpyMatrixOperator(E) Bop = NumpyMatrixOperator(B) Arop = NumpyMatrixOperator(Ar) Erop = NumpyMatrixOperator(Er) Brop = NumpyMatrixOperator(Br) Vva = solve_sylv_schur(Aop, Arop, E=Eop, Er=Erop, B=Bop, Br=Brop) V = Vva.to_numpy().T AVErT = A.dot(V.dot(Er.T)) EVArT = E.dot(V.dot(Ar.T)) BBrT = B.dot(Br.T) assert fro_norm(AVErT + EVArT + BBrT) / fro_norm(BBrT) < 1e-10 @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('p', p_list) def test_sylv_schur_W(n, r, p): np.random.seed(0) A = diff_conv_1d_fd(n, 1, 1) C = np.random.randn(p, n) Ar = np.random.randn(r, r) - r * np.eye(r) Cr = np.random.randn(p, r) Aop = NumpyMatrixOperator(A) Cop = NumpyMatrixOperator(C) Arop = NumpyMatrixOperator(Ar) Crop = NumpyMatrixOperator(Cr) Wva = solve_sylv_schur(Aop, Arop, C=Cop, Cr=Crop) W = Wva.to_numpy().T ATW = A.T.dot(W) WAr = W.dot(Ar) CTCr = C.T.dot(Cr) assert fro_norm(ATW + WAr + CTCr) / fro_norm(CTCr) < 1e-10 @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('p', p_list) def test_sylv_schur_W_E(n, r, p): np.random.seed(0) A, E = diff_conv_1d_fem(n, 1, 1) C = np.random.randn(p, n) Ar = np.random.randn(r, r) - r * np.eye(r) Er = np.random.randn(r, r) Er = (Er + Er.T) / 2 Er += r * np.eye(r) Cr = np.random.randn(p, r) Aop = NumpyMatrixOperator(A) Eop = NumpyMatrixOperator(E) Cop = NumpyMatrixOperator(C) Arop = NumpyMatrixOperator(Ar) Erop = NumpyMatrixOperator(Er) Crop = NumpyMatrixOperator(Cr) Wva = solve_sylv_schur(Aop, Arop, E=Eop, Er=Erop, C=Cop, Cr=Crop) W = Wva.to_numpy().T ATWEr = A.T.dot(W.dot(Er)) ETWAr = E.T.dot(W.dot(Ar)) CTCr = C.T.dot(Cr) assert fro_norm(ATWEr + ETWAr + CTCr) / fro_norm(CTCr) < 1e-10
26.214286
77
0.585831
import numpy as np import scipy.linalg as spla import scipy.sparse as sps from pymor.algorithms.sylvester import solve_sylv_schur from pymor.operators.numpy import NumpyMatrixOperator import pytest n_list = [100, 1000] r_list = [1, 10, 20] m_list = [1, 2] p_list = [1, 2] def fro_norm(A): if not sps.issparse(A): return spla.norm(A) else: return sps.linalg.norm(A) def diff_conv_1d_fd(n, a, b): diagonals = [-a * 2 * (n + 1) ** 2 * np.ones((n,)), (a * (n + 1) ** 2 + b * (n + 1) / 2) * np.ones((n - 1,)), (a * (n + 1) ** 2 - b * (n + 1) / 2) * np.ones((n - 1,))] A = sps.diags(diagonals, [0, -1, 1]) return A def diff_conv_1d_fem(n, a, b): diagonals = [-a * 2 * (n + 1) ** 2 * np.ones((n,)), (a * (n + 1) ** 2 + b * (n + 1) / 2) * np.ones((n - 1,)), (a * (n + 1) ** 2 - b * (n + 1) / 2) * np.ones((n - 1,))] A = sps.diags(diagonals, [0, -1, 1]) diagonals = [2 / 3 * np.ones((n,)), 1 / 6 * np.ones((n - 1,)), 1 / 6 * np.ones((n - 1,))] E = sps.diags(diagonals, [0, -1, 1]) return A, E @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('m', m_list) def test_sylv_schur_V(n, r, m): np.random.seed(0) A = diff_conv_1d_fd(n, 1, 1) B = np.random.randn(n, m) Ar = np.random.randn(r, r) - r * np.eye(r) Br = np.random.randn(r, m) Aop = NumpyMatrixOperator(A) Bop = NumpyMatrixOperator(B) Arop = NumpyMatrixOperator(Ar) Brop = NumpyMatrixOperator(Br) Vva = solve_sylv_schur(Aop, Arop, B=Bop, Br=Brop) V = Vva.to_numpy().T AV = A.dot(V) VArT = V.dot(Ar.T) BBrT = B.dot(Br.T) assert fro_norm(AV + VArT + BBrT) / fro_norm(BBrT) < 1e-10 @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('m', m_list) def test_sylv_schur_V_E(n, r, m): np.random.seed(0) A, E = diff_conv_1d_fem(n, 1, 1) B = np.random.randn(n, m) Ar = np.random.randn(r, r) - r * np.eye(r) Er = np.random.randn(r, r) Er = (Er + Er.T) / 2 Er += r * np.eye(r) Br = np.random.randn(r, m) Aop = NumpyMatrixOperator(A) Eop = NumpyMatrixOperator(E) Bop = NumpyMatrixOperator(B) Arop = NumpyMatrixOperator(Ar) Erop = NumpyMatrixOperator(Er) Brop = NumpyMatrixOperator(Br) Vva = solve_sylv_schur(Aop, Arop, E=Eop, Er=Erop, B=Bop, Br=Brop) V = Vva.to_numpy().T AVErT = A.dot(V.dot(Er.T)) EVArT = E.dot(V.dot(Ar.T)) BBrT = B.dot(Br.T) assert fro_norm(AVErT + EVArT + BBrT) / fro_norm(BBrT) < 1e-10 @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('p', p_list) def test_sylv_schur_W(n, r, p): np.random.seed(0) A = diff_conv_1d_fd(n, 1, 1) C = np.random.randn(p, n) Ar = np.random.randn(r, r) - r * np.eye(r) Cr = np.random.randn(p, r) Aop = NumpyMatrixOperator(A) Cop = NumpyMatrixOperator(C) Arop = NumpyMatrixOperator(Ar) Crop = NumpyMatrixOperator(Cr) Wva = solve_sylv_schur(Aop, Arop, C=Cop, Cr=Crop) W = Wva.to_numpy().T ATW = A.T.dot(W) WAr = W.dot(Ar) CTCr = C.T.dot(Cr) assert fro_norm(ATW + WAr + CTCr) / fro_norm(CTCr) < 1e-10 @pytest.mark.parametrize('n', n_list) @pytest.mark.parametrize('r', r_list) @pytest.mark.parametrize('p', p_list) def test_sylv_schur_W_E(n, r, p): np.random.seed(0) A, E = diff_conv_1d_fem(n, 1, 1) C = np.random.randn(p, n) Ar = np.random.randn(r, r) - r * np.eye(r) Er = np.random.randn(r, r) Er = (Er + Er.T) / 2 Er += r * np.eye(r) Cr = np.random.randn(p, r) Aop = NumpyMatrixOperator(A) Eop = NumpyMatrixOperator(E) Cop = NumpyMatrixOperator(C) Arop = NumpyMatrixOperator(Ar) Erop = NumpyMatrixOperator(Er) Crop = NumpyMatrixOperator(Cr) Wva = solve_sylv_schur(Aop, Arop, E=Eop, Er=Erop, C=Cop, Cr=Crop) W = Wva.to_numpy().T ATWEr = A.T.dot(W.dot(Er)) ETWAr = E.T.dot(W.dot(Ar)) CTCr = C.T.dot(Cr) assert fro_norm(ATWEr + ETWAr + CTCr) / fro_norm(CTCr) < 1e-10
true
true
1c39fe76c1f399b2f771ca5be27723a225538a27
8,347
py
Python
docs/source/conf.py
GabrielFritz/DTCR-Retail
e961cb5230c940318eb022a7fee2f0058780e284
[ "MIT" ]
null
null
null
docs/source/conf.py
GabrielFritz/DTCR-Retail
e961cb5230c940318eb022a7fee2f0058780e284
[ "MIT" ]
null
null
null
docs/source/conf.py
GabrielFritz/DTCR-Retail
e961cb5230c940318eb022a7fee2f0058780e284
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2018-2019 QuantumBlack Visual Analytics Limited # # 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 # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND # NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS # BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo # (either separately or in combination, "QuantumBlack Trademarks") are # trademarks of QuantumBlack. The License does not grant you any right or # license to the QuantumBlack Trademarks. You may not use the QuantumBlack # Trademarks or any confusingly similar mark as a trademark for your product, # or use the QuantumBlack Trademarks in any other manner that might cause # confusion in the marketplace, including but not limited to in advertising, # on websites, or on software. # # See the License for the specific language governing permissions and # limitations under the License. # ts_clustering documentation build # configuration file, created by sphinx-quickstart. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import re from kedro.cli.utils import find_stylesheets from recommonmark.transform import AutoStructify from ts_clustering import __version__ as release # -- Project information ----------------------------------------------------- project = "ts_clustering" copyright = "2018-2019, QuantumBlack Visual Analytics Limited" author = "QuantumBlack" # The short X.Y version. version = re.match(r"^([0-9]+\.[0-9]+).*", release).group(1) # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx_autodoc_typehints", "sphinx.ext.doctest", "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.mathjax", "sphinx.ext.ifconfig", "sphinx.ext.viewcode", "sphinx.ext.mathjax", "nbsphinx", "recommonmark", "sphinx_copybutton", ] # enable autosummary plugin (table of contents for modules/classes/class # methods) autosummary_generate = True # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = {".rst": "restructuredtext", ".md": "markdown"} # The master toctree document. master_doc = "index" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = ["_build", "**.ipynb_checkpoints"] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "sphinx_rtd_theme" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {"collapse_navigation": False, "style_external_links": True} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ["_static"] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} html_show_sourcelink = False # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = "ts_clusteringdoc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # # Additional stuff for the LaTeX preamble. # # 'preamble': '', # # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "ts_clustering.tex", "ts_clustering Documentation", "QuantumBlack", "manual", ) ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( master_doc, "ts_clustering", "ts_clustering Documentation", [author], 1, ) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "ts_clustering", "ts_clustering Documentation", author, "ts_clustering", "Project ts_clustering codebase.", "Data-Science", ) ] # -- Options for todo extension ---------------------------------------------- # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Extension configuration ------------------------------------------------- # nbsphinx_prolog = """ # see here for prolog/epilog details: # https://nbsphinx.readthedocs.io/en/0.3.1/prolog-and-epilog.html # """ # -- NBconvert kernel config ------------------------------------------------- nbsphinx_kernel_name = "python3" def remove_arrows_in_examples(lines): for i, line in enumerate(lines): lines[i] = line.replace(">>>", "") def autodoc_process_docstring(app, what, name, obj, options, lines): remove_arrows_in_examples(lines) def skip(app, what, name, obj, skip, options): if name == "__init__": return False return skip def setup(app): app.connect("autodoc-process-docstring", autodoc_process_docstring) app.connect("autodoc-skip-member", skip) # add Kedro stylesheets for stylesheet in find_stylesheets(): app.add_stylesheet(stylesheet) # enable rendering RST tables in Markdown app.add_config_value("recommonmark_config", {"enable_eval_rst": True}, True) app.add_transform(AutoStructify)
32.352713
81
0.677848
import re from kedro.cli.utils import find_stylesheets from recommonmark.transform import AutoStructify from ts_clustering import __version__ as release project = "ts_clustering" copyright = "2018-2019, QuantumBlack Visual Analytics Limited" author = "QuantumBlack" version = re.match(r"^([0-9]+\.[0-9]+).*", release).group(1) extensions = [ "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx_autodoc_typehints", "sphinx.ext.doctest", "sphinx.ext.todo", "sphinx.ext.coverage", "sphinx.ext.mathjax", "sphinx.ext.ifconfig", "sphinx.ext.viewcode", "sphinx.ext.mathjax", "nbsphinx", "recommonmark", "sphinx_copybutton", ] autosummary_generate = True templates_path = ["_templates"] source_suffix = {".rst": "restructuredtext", ".md": "markdown"} master_doc = "index" language = None exclude_patterns = ["_build", "**.ipynb_checkpoints"] pygments_style = "sphinx" html_theme = "sphinx_rtd_theme" html_theme_options = {"collapse_navigation": False, "style_external_links": True} html_static_path = ["_static"] # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} html_show_sourcelink = False # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = "ts_clusteringdoc" # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # # Additional stuff for the LaTeX preamble. # # 'preamble': '', # # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "ts_clustering.tex", "ts_clustering Documentation", "QuantumBlack", "manual", ) ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( master_doc, "ts_clustering", "ts_clustering Documentation", [author], 1, ) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "ts_clustering", "ts_clustering Documentation", author, "ts_clustering", "Project ts_clustering codebase.", "Data-Science", ) ] # -- Options for todo extension ---------------------------------------------- # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Extension configuration ------------------------------------------------- # nbsphinx_prolog = """ # see here for prolog/epilog details: # https://nbsphinx.readthedocs.io/en/0.3.1/prolog-and-epilog.html # """ # -- NBconvert kernel config ------------------------------------------------- nbsphinx_kernel_name = "python3" def remove_arrows_in_examples(lines): for i, line in enumerate(lines): lines[i] = line.replace(">>>", "") def autodoc_process_docstring(app, what, name, obj, options, lines): remove_arrows_in_examples(lines) def skip(app, what, name, obj, skip, options): if name == "__init__": return False return skip def setup(app): app.connect("autodoc-process-docstring", autodoc_process_docstring) app.connect("autodoc-skip-member", skip) # add Kedro stylesheets for stylesheet in find_stylesheets(): app.add_stylesheet(stylesheet) # enable rendering RST tables in Markdown app.add_config_value("recommonmark_config", {"enable_eval_rst": True}, True) app.add_transform(AutoStructify)
true
true
1c39feaeae94c0bc499563a7804647f96374a2a2
1,905
py
Python
pyeto/_check.py
gcamargo1/PyETo
2dbbdecad04fdd25976beefe3953062cb3f04064
[ "BSD-3-Clause" ]
1
2018-12-17T10:57:05.000Z
2018-12-17T10:57:05.000Z
pyeto/_check.py
mwheels/PyETo
fa4f78ada2b1de9f7e8c10648f0a58baa6d79bd3
[ "BSD-3-Clause" ]
null
null
null
pyeto/_check.py
mwheels/PyETo
fa4f78ada2b1de9f7e8c10648f0a58baa6d79bd3
[ "BSD-3-Clause" ]
null
null
null
""" Internal validation functions. :copyright: (c) 2015 by Mark Richards. :license: BSD 3-Clause, see LICENSE.txt for more details. """ from pyeto.convert import deg2rad # Internal constants # Latitude _MINLAT_RADIANS = deg2rad(-90.0) _MAXLAT_RADIANS = deg2rad(90.0) # Solar declination _MINSOLDEC_RADIANS = deg2rad(-23.5) _MAXSOLDEC_RADIANS = deg2rad(23.5) # Sunset hour angle _MINSHA_RADIANS = 0.0 _MAXSHA_RADIANS = deg2rad(180) def check_day_hours(hours, arg_name): """ Check that *hours* is in the range 1 to 24. """ if not 0 <= hours <= 24: raise ValueError( '{0} should be in range 0-24: {1!r}'.format(arg_name, hours)) def check_doy(doy): """ Check day of the year is valid. """ if not 1 <= doy <= 366: raise ValueError( 'Day of the year (doy) must be in range 1-366: {0!r}'.format(doy)) def check_latitude_rad(latitude): if not _MINLAT_RADIANS <= latitude <= _MAXLAT_RADIANS: raise ValueError( 'latitude outside valid range {0!r} to {1!r} rad: {2!r}' .format(_MINLAT_RADIANS, _MAXLAT_RADIANS, latitude)) def check_sol_dec_rad(sd): """ Solar declination can vary between -23.5 and +23.5 degrees. See http://mypages.iit.edu/~maslanka/SolarGeo.pdf """ if not _MINSOLDEC_RADIANS <= sd <= _MAXSOLDEC_RADIANS: raise ValueError( 'solar declination outside valid range {0!r} to {1!r} rad: {2!r}' .format(_MINSOLDEC_RADIANS, _MAXSOLDEC_RADIANS, sd)) def check_sunset_hour_angle_rad(sha): """ Sunset hour angle has the range 0 to 180 degrees. See http://mypages.iit.edu/~maslanka/SolarGeo.pdf """ if not _MINSHA_RADIANS <= sha <= _MAXSHA_RADIANS: raise ValueError( 'sunset hour angle outside valid range {0!r} to {1!r} rad: {2!r}' .format(_MINSHA_RADIANS, _MAXSHA_RADIANS, sha))
27.214286
78
0.649344
from pyeto.convert import deg2rad _MINLAT_RADIANS = deg2rad(-90.0) _MAXLAT_RADIANS = deg2rad(90.0) _MINSOLDEC_RADIANS = deg2rad(-23.5) _MAXSOLDEC_RADIANS = deg2rad(23.5) _MINSHA_RADIANS = 0.0 _MAXSHA_RADIANS = deg2rad(180) def check_day_hours(hours, arg_name): if not 0 <= hours <= 24: raise ValueError( '{0} should be in range 0-24: {1!r}'.format(arg_name, hours)) def check_doy(doy): if not 1 <= doy <= 366: raise ValueError( 'Day of the year (doy) must be in range 1-366: {0!r}'.format(doy)) def check_latitude_rad(latitude): if not _MINLAT_RADIANS <= latitude <= _MAXLAT_RADIANS: raise ValueError( 'latitude outside valid range {0!r} to {1!r} rad: {2!r}' .format(_MINLAT_RADIANS, _MAXLAT_RADIANS, latitude)) def check_sol_dec_rad(sd): if not _MINSOLDEC_RADIANS <= sd <= _MAXSOLDEC_RADIANS: raise ValueError( 'solar declination outside valid range {0!r} to {1!r} rad: {2!r}' .format(_MINSOLDEC_RADIANS, _MAXSOLDEC_RADIANS, sd)) def check_sunset_hour_angle_rad(sha): if not _MINSHA_RADIANS <= sha <= _MAXSHA_RADIANS: raise ValueError( 'sunset hour angle outside valid range {0!r} to {1!r} rad: {2!r}' .format(_MINSHA_RADIANS, _MAXSHA_RADIANS, sha))
true
true
1c39ffe2f7f5a6174766372a64e6a4f384c8b2d1
6,931
py
Python
salted/input_handler.py
RuedigerVoigt/salted
97886014b7a582d943758d65307db2bc03197f6e
[ "Apache-2.0" ]
4
2020-11-24T09:18:36.000Z
2022-01-13T20:32:21.000Z
salted/input_handler.py
RuedigerVoigt/salted
97886014b7a582d943758d65307db2bc03197f6e
[ "Apache-2.0" ]
11
2020-11-30T23:11:48.000Z
2022-02-25T23:47:44.000Z
salted/input_handler.py
RuedigerVoigt/salted
97886014b7a582d943758d65307db2bc03197f6e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Input Handler for salted ~~~~~~~~~~~~~~~~~~~~~ Source: https://github.com/RuedigerVoigt/salted (c) 2020-2021: Rüdiger Voigt Released under the Apache License 2.0 """ from collections import Counter import logging import pathlib from typing import List, Optional import urllib.parse import userprovided from tqdm.asyncio import tqdm # type: ignore from salted import database_io from salted import parser class InputHandler: """read files and extract the hyperlinks inside them.""" def __init__(self, db: database_io.DatabaseIO): self.db = db self.cnt: Counter = Counter() self.parser = parser.Parser() def read_file_content(self, path_to_file: pathlib.Path) -> Optional[str]: "Return the file content or log an error if file cannot be accessed." content: Optional[str] = None try: with open(path_to_file, 'r') as code: content = code.read() except FileNotFoundError: self.db.log_file_access_error( str(path_to_file), 'file not found') except PermissionError: self.db.log_file_access_error( str(path_to_file), 'permission error') except TimeoutError: self.db.log_file_access_error( str(path_to_file), 'system timeout') except BlockingIOError: self.db.log_file_access_error( str(path_to_file), 'blocking IO') except Exception as unexpected: # pylint: disable=W0703 self.db.log_file_access_error( str(path_to_file), str(unexpected)) finally: # pylint: disable=W0150 return content def handle_found_urls(self, file_path: pathlib.Path, url_list: list) -> None: """Extract all hyperlinks from url_list, normalize them and add them to test queue.""" links_found: list = [] mailto_found: list = [] for link in url_list: url = link[0] linktext = link[1] if url.startswith('http'): # It may be that multiple links point to the same resource. # Normalizing them means they only need to be tested once. # The non-normalized version is stored anyway, because in case # the link is broken, that version is used to show the user # the broken links on a specific page. try: normalized_url = userprovided.url.normalize_url(url) except userprovided.err.QueryKeyConflict: normalized_url = userprovided.url.normalize_url( url, do_not_change_query_part=True) parsed_url = urllib.parse.urlparse(url) links_found.append([str(file_path), parsed_url.hostname, url, normalized_url, linktext]) self.cnt['links_found'] += 1 elif url.startswith('mailto:'): logging.debug("Checking mailto Links is not implemented yet") # TO DO # mail_addresses = self.parser.extract_mails_from_mailto(url) # if not mail_addresses: # continue # for address in mail_addresses: # if userprovided.mail.is_email(address): # host = address.split('@')[1] # # TO DO: ... # else: # # Invalid email # # TO DO: ... # pass else: # cannot check this kind of link self.cnt['unsupported_scheme'] += 1 # Push the found links once for each file instead for all files # at once. The latter would kill performance for large document # collections. if links_found: self.db.save_found_links(links_found) if mailto_found: pass def handle_found_dois(self, file_path: pathlib.Path, doi_list: list) -> None: """Change the DOI list into the needed format and send it piecewise to the database.""" if not doi_list: return None # The parser generated a list in the format [[doi, text], [doi, text]] # - text being the key-value of the bibtex-entry and the field in # which the DOI was found. dois_found = list() for entry in doi_list: dois_found.append([str(file_path), entry[0], entry[1]]) # In case of a bibliography taht can be a very long list. # So feed it to sqlite in little pieces first = 0 step = 50 last = first + step if len(dois_found) < step: self.db.save_found_dois(dois_found) else: while last <= (len(dois_found) - 1): self.db.save_found_dois(dois_found[first:last]) first += step last += step return None def scan_files(self, files_to_check: List[pathlib.Path]) -> None: """Scan each file within a list of paths for hyperlinks and DOIs. Write those to the SQLite database. """ if not files_to_check: logging.warning('No files to check') return None # Reset counter as check_links might be used multiple times and this # should be per run: self.cnt['links_found'] = 0 print("Scanning files for links:") for file_path in tqdm(files_to_check): content = self.read_file_content(file_path) if not content: # If for any reason this file could not be read, try the next. continue # only one function returns two values doi_list: Optional[list] = None if file_path.suffix in {".htm", ".html"}: url_list = self.parser.extract_links_from_html(content) elif file_path.suffix in {".md"}: url_list = self.parser.extract_links_from_markdown(content) elif file_path.suffix in {".tex"}: url_list = self.parser.extract_links_from_tex(content) elif file_path.suffix in {".bib"}: url_list, doi_list = self.parser.extract_links_from_bib(content) else: raise RuntimeError('Invalid extension. Should never happen.') if url_list: self.handle_found_urls(file_path, url_list) if doi_list: self.handle_found_dois(file_path, doi_list) return None
37.874317
80
0.553023
from collections import Counter import logging import pathlib from typing import List, Optional import urllib.parse import userprovided from tqdm.asyncio import tqdm from salted import database_io from salted import parser class InputHandler: def __init__(self, db: database_io.DatabaseIO): self.db = db self.cnt: Counter = Counter() self.parser = parser.Parser() def read_file_content(self, path_to_file: pathlib.Path) -> Optional[str]: content: Optional[str] = None try: with open(path_to_file, 'r') as code: content = code.read() except FileNotFoundError: self.db.log_file_access_error( str(path_to_file), 'file not found') except PermissionError: self.db.log_file_access_error( str(path_to_file), 'permission error') except TimeoutError: self.db.log_file_access_error( str(path_to_file), 'system timeout') except BlockingIOError: self.db.log_file_access_error( str(path_to_file), 'blocking IO') except Exception as unexpected: self.db.log_file_access_error( str(path_to_file), str(unexpected)) finally: return content def handle_found_urls(self, file_path: pathlib.Path, url_list: list) -> None: links_found: list = [] mailto_found: list = [] for link in url_list: url = link[0] linktext = link[1] if url.startswith('http'): try: normalized_url = userprovided.url.normalize_url(url) except userprovided.err.QueryKeyConflict: normalized_url = userprovided.url.normalize_url( url, do_not_change_query_part=True) parsed_url = urllib.parse.urlparse(url) links_found.append([str(file_path), parsed_url.hostname, url, normalized_url, linktext]) self.cnt['links_found'] += 1 elif url.startswith('mailto:'): logging.debug("Checking mailto Links is not implemented yet") else: self.cnt['unsupported_scheme'] += 1 if links_found: self.db.save_found_links(links_found) if mailto_found: pass def handle_found_dois(self, file_path: pathlib.Path, doi_list: list) -> None: if not doi_list: return None dois_found = list() for entry in doi_list: dois_found.append([str(file_path), entry[0], entry[1]]) first = 0 step = 50 last = first + step if len(dois_found) < step: self.db.save_found_dois(dois_found) else: while last <= (len(dois_found) - 1): self.db.save_found_dois(dois_found[first:last]) first += step last += step return None def scan_files(self, files_to_check: List[pathlib.Path]) -> None: if not files_to_check: logging.warning('No files to check') return None self.cnt['links_found'] = 0 print("Scanning files for links:") for file_path in tqdm(files_to_check): content = self.read_file_content(file_path) if not content: continue doi_list: Optional[list] = None if file_path.suffix in {".htm", ".html"}: url_list = self.parser.extract_links_from_html(content) elif file_path.suffix in {".md"}: url_list = self.parser.extract_links_from_markdown(content) elif file_path.suffix in {".tex"}: url_list = self.parser.extract_links_from_tex(content) elif file_path.suffix in {".bib"}: url_list, doi_list = self.parser.extract_links_from_bib(content) else: raise RuntimeError('Invalid extension. Should never happen.') if url_list: self.handle_found_urls(file_path, url_list) if doi_list: self.handle_found_dois(file_path, doi_list) return None
true
true
1c3a012eff61b3f8dc43f89b7561938c442c0588
2,196
py
Python
lib/node_modules/@stdlib/math/base/special/sincos/benchmark/python/benchmark.py
ghalimi/stdlib
88f50b88aa945875ef053e2f89d26f9150a18c12
[ "BSL-1.0" ]
3,428
2016-07-14T13:48:46.000Z
2022-03-31T22:32:13.000Z
lib/node_modules/@stdlib/math/base/special/sincos/benchmark/python/benchmark.py
ghalimi/stdlib
88f50b88aa945875ef053e2f89d26f9150a18c12
[ "BSL-1.0" ]
435
2016-04-07T18:12:45.000Z
2022-03-22T15:43:17.000Z
lib/node_modules/@stdlib/math/base/special/sincos/benchmark/python/benchmark.py
sthagen/stdlib
042b6215818db0e2a784e72c7e054167dcefcd2a
[ "BSL-1.0" ]
188
2016-11-29T22:58:11.000Z
2022-03-17T06:46:43.000Z
#!/usr/bin/env python # # @license Apache-2.0 # # Copyright (c) 2018 The Stdlib 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. """Benchmark sincos.""" from __future__ import print_function import timeit NAME = "sincos" REPEATS = 3 ITERATIONS = 1000000 def print_version(): """Print the TAP version.""" print("TAP version 13") def print_summary(total, passing): """Print the benchmark summary. # Arguments * `total`: total number of tests * `passing`: number of passing tests """ print("#") print("1.." + str(total)) # TAP plan print("# total " + str(total)) print("# pass " + str(passing)) print("#") print("# ok") def print_results(elapsed): """Print benchmark results. # Arguments * `elapsed`: elapsed time (in seconds) # Examples ``` python python> print_results(0.131009101868) ``` """ rate = ITERATIONS / elapsed print(" ---") print(" iterations: " + str(ITERATIONS)) print(" elapsed: " + str(elapsed)) print(" rate: " + str(rate)) print(" ...") def benchmark(): """Run the benchmark and print benchmark results.""" setup = "from math import sin, cos; from random import random;" stmt = "x = 20.0*random() - 10.0; y = [ sin( x ), cos( x ) ]" t = timeit.Timer(stmt, setup=setup) print_version() for i in range(REPEATS): print("# python::" + NAME) elapsed = t.timeit(number=ITERATIONS) print_results(elapsed) print("ok " + str(i+1) + " benchmark finished") print_summary(REPEATS, REPEATS) def main(): """Run the benchmark.""" benchmark() if __name__ == "__main__": main()
22.408163
74
0.631603
from __future__ import print_function import timeit NAME = "sincos" REPEATS = 3 ITERATIONS = 1000000 def print_version(): print("TAP version 13") def print_summary(total, passing): print("#") print("1.." + str(total)) print("# total " + str(total)) print("# pass " + str(passing)) print("#") print("# ok") def print_results(elapsed): rate = ITERATIONS / elapsed print(" ---") print(" iterations: " + str(ITERATIONS)) print(" elapsed: " + str(elapsed)) print(" rate: " + str(rate)) print(" ...") def benchmark(): setup = "from math import sin, cos; from random import random;" stmt = "x = 20.0*random() - 10.0; y = [ sin( x ), cos( x ) ]" t = timeit.Timer(stmt, setup=setup) print_version() for i in range(REPEATS): print("# python::" + NAME) elapsed = t.timeit(number=ITERATIONS) print_results(elapsed) print("ok " + str(i+1) + " benchmark finished") print_summary(REPEATS, REPEATS) def main(): benchmark() if __name__ == "__main__": main()
true
true
1c3a01509c43b5982a2e565f209bb2f980cd1989
932
py
Python
py/desisim/test/test_top_level.py
HiramHerrera/desisim
3ae76e4c921f72b71ff7522462740e904136f428
[ "BSD-3-Clause" ]
15
2015-12-16T22:01:53.000Z
2022-01-14T07:31:55.000Z
py/desisim/test/test_top_level.py
HiramHerrera/desisim
3ae76e4c921f72b71ff7522462740e904136f428
[ "BSD-3-Clause" ]
455
2015-04-06T03:11:27.000Z
2022-02-28T18:11:16.000Z
py/desisim/test/test_top_level.py
HiramHerrera/desisim
3ae76e4c921f72b71ff7522462740e904136f428
[ "BSD-3-Clause" ]
21
2015-01-26T17:45:04.000Z
2022-02-22T19:46:20.000Z
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """ test top-level desisim functions """ # from __future__ import absolute_import, division, print_function # import unittest import re from .. import __version__ as theVersion # class TestTopLevel(unittest.TestCase): @classmethod def setUpClass(cls): cls.versionre = re.compile(r'([0-9]+!)?([0-9]+)(\.[0-9]+)*((a|b|rc|\.post|\.dev)[0-9]+)?') @classmethod def tearDownClass(cls): pass def test_version(self): """Ensure the version conforms to PEP386/PEP440. """ #- python 3.5 has assertRegexpMatches but has deprecated it in favor #- of assertRegexp, but that doesn't exist in python 2.7. Keep #- assertRegexMatches for now until we've fully transitioned to py3.5 self.assertRegex(theVersion,self.versionre) if __name__ == '__main__': unittest.main()
28.242424
98
0.660944
from __future__ import absolute_import, division, print_function import unittest import re from .. import __version__ as theVersion class TestTopLevel(unittest.TestCase): @classmethod def setUpClass(cls): cls.versionre = re.compile(r'([0-9]+!)?([0-9]+)(\.[0-9]+)*((a|b|rc|\.post|\.dev)[0-9]+)?') @classmethod def tearDownClass(cls): pass def test_version(self): #- assertRegexMatches for now until we've fully transitioned to py3.5 self.assertRegex(theVersion,self.versionre) if __name__ == '__main__': unittest.main()
true
true
1c3a035bbccea8366fcfa766c69145e4ec0d73ca
64,359
py
Python
python/paddle/nn/functional/pooling.py
joey12300/Paddle
59102c6dcd2def3091f5c37816354ac69d669809
[ "Apache-2.0" ]
1
2021-03-11T13:16:50.000Z
2021-03-11T13:16:50.000Z
python/paddle/nn/functional/pooling.py
AFLee/Paddle
311b3b44fc7d51d4d66d90ab8a3fc0d42231afda
[ "Apache-2.0" ]
null
null
null
python/paddle/nn/functional/pooling.py
AFLee/Paddle
311b3b44fc7d51d4d66d90ab8a3fc0d42231afda
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2020 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. # TODO: define pooling functions from ...fluid import core from ...fluid.framework import in_dygraph_mode from ...fluid.layers import utils, LayerHelper, unsqueeze, squeeze from ...fluid.data_feeder import check_type, check_variable_and_dtype __all__ = [ 'avg_pool1d', 'avg_pool2d', 'avg_pool3d', 'max_pool1d', 'max_pool2d', 'max_pool3d', 'adaptive_avg_pool1d', 'adaptive_avg_pool2d', 'adaptive_avg_pool3d', 'adaptive_max_pool1d', 'adaptive_max_pool2d', 'adaptive_max_pool3d', ] def _is_list_or_tuple(input): return isinstance(input, (list, tuple)) def _check_input(x, dimension): if len(x.shape) != dimension: raise ValueError( "Excepted Input X is {}-D tensor, but received {}-D {}".format( dimension, len(x.shape), type(x))) def _check_instance(x, x_name, types=(int, float)): if not isinstance(x, types): raise ValueError("Excepted {} type for {} but received type: {}. ". format(types, x_name, type(x))) def _zero_padding_in_batch_and_channel(padding, channel_last): if channel_last: return list(padding[0]) == [0, 0] and list(padding[-1]) == [0, 0] else: return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0] def _exclude_padding_in_batch_and_channel(padding, channel_last): padding_ = padding[1:-1] if channel_last else padding[2:] padding_ = [elem for pad_a_dim in padding_ for elem in pad_a_dim] return padding_ def _channel_last(data_format, num_dims): if num_dims == 1: if data_format not in ['NCL', 'NLC']: raise ValueError( "Attr(data_format) should be 'NCL' or 'NLC'. Received " "Attr(data_format): %s" % str(data_format)) else: return True if data_format == "NLC" else False if num_dims == 2: if data_format not in ['NCHW', 'NHWC']: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s" % str(data_format)) else: return True if data_format == "NHWC" else False if num_dims == 3: if data_format not in ['NCDHW', 'NDHWC']: raise ValueError( "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " "Attr(data_format): %s" % str(data_format)) else: return True if data_format == "NDHWC" else False def _update_padding_nd(padding, num_dims, channel_last=False, ceil_mode=False): if isinstance(padding, str): padding = padding.upper() if padding not in ["SAME", "VALID"]: raise ValueError( "Unknown padding: '{}'. It can only be 'SAME' or 'VALID'.". format(padding)) if padding == "VALID": if ceil_mode != False: raise ValueError( "When Attr(padding) is \"VALID\", Attr(ceil_mode) must be False. " "Received ceil_mode: True.") padding_algorithm = "VALID" padding = [0] * num_dims else: padding_algorithm = "SAME" padding = [0] * num_dims elif _is_list_or_tuple(padding): # for padding like # [(pad_before, pad_after), (pad_before, pad_after), ...] # padding for batch_dim and channel_dim included if len(padding) == 2 + num_dims and _is_list_or_tuple(padding[0]): if not _zero_padding_in_batch_and_channel(padding, channel_last): raise ValueError( "Non-zero padding({}) in the batch or channel dimensions " "is not supported.".format(padding)) padding_algorithm = "EXPLICIT" padding = _exclude_padding_in_batch_and_channel(padding, channel_last) if utils._is_symmetric_padding(padding, num_dims): padding = padding[0::2] # for padding like [pad_before, pad_after, pad_before, pad_after, ...] elif len(padding) == 2 * num_dims and isinstance(padding[0], int): padding_algorithm = "EXPLICIT" padding = utils.convert_to_list(padding, 2 * num_dims, 'padding') if utils._is_symmetric_padding(padding, num_dims): padding = padding[0::2] # for padding like [pad_d1, pad_d2, ...] elif len(padding) == num_dims and isinstance(padding[0], int): padding_algorithm = "EXPLICIT" padding = utils.convert_to_list(padding, num_dims, 'padding') else: raise ValueError("Invalid padding: {}".format(padding)) # for integer padding else: padding_algorithm = "EXPLICIT" padding = utils.convert_to_list(padding, num_dims, 'padding') return padding, padding_algorithm def _expand_low_nd_padding(padding): #1d to 2d fake input if len(padding) == 2: padding = [0] * 2 + padding elif len(padding) == 1: padding = [0] + padding else: raise ValueError( "The size of padding's dimmention should be 1 or 2. But got padding={}". format(padding)) return padding def avg_pool1d(x, kernel_size, stride=None, padding=0, exclusive=True, ceil_mode=False, name=None): """ This API implements average pooling 1d operation, See more details in :ref:`api_nn_pooling_AvgPool1d` . Args: x (Tensor): The input tensor of pooling operator which is a 3-D tensor with shape [N, C, L]. where `N` is batch size, `C` is the number of channels, `L` is the length of the feature. The data type is float32 or float64. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain an integer. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, it must contain an integer. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. 1. A string in ['valid', 'same']. 2. An int, which means the feature map is zero padded by size of `padding` on every sides. 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides. 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after]. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). The default value is 0. exclusive (bool): Whether to exclude padding points in average pooling mode, default is `True`. ceil_mode (bool): ${ceil_mode_comment}Whether to use the ceil function to calculate output height and width. If it is set to False, the floor function will be used. The default value is False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is "VALID", but `ceil_mode` is True. ValueError: If `padding` is a list or tuple but its length is greater than 1. ShapeError: If the input is not a 3-D tensor. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle import paddle.nn.functional as F data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32)) out = F.avg_pool1d(data, kernel_size=2, stride=2, padding=0) # out shape: [1, 3, 16] """ """NCL to NCHW""" data_format = "NCHW" check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool1d') _check_input(x, 3) x = unsqueeze(x, [2]) kernel_size = utils.convert_to_list(kernel_size, 1, 'kernel_size') kernel_size = [1] + kernel_size if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 1, 'pool_stride') stride = [1] + stride channel_last = _channel_last("NCL", 1) padding, padding_algorithm = _update_padding_nd( padding, 1, channel_last=channel_last, ceil_mode=ceil_mode) # use 2d to implenment 1d should expand padding in advance. padding = _expand_low_nd_padding(padding) if in_dygraph_mode(): output = core.ops.pool2d( x, 'pooling_type', 'avg', 'ksize', kernel_size, 'global_pooling', False, 'strides', stride, 'paddings', padding, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', exclusive, 'data_format', data_format) return squeeze(output, [2]) op_type = 'pool2d' helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type=op_type, inputs={"X": x}, outputs={"Out": pool_out}, attrs={ "pooling_type": 'avg', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) return squeeze(pool_out, [2]) def avg_pool2d(x, kernel_size, stride=None, padding=0, ceil_mode=False, exclusive=True, divisor_override=None, data_format="NCHW", name=None): """ This API implements average pooling 2d operation. See more details in :ref:`api_nn_pooling_AvgPool2d` . Args: x (Tensor): The input tensor of pooling operator which is a 4-D tensor with shape [N, C, H, W]. The format of input tensor is `"NCHW"` or `"NHWC"`, where `N` is batch size, `C` is the number of channels, `H` is the height of the feature, and `W` is the width of the feature. The data type if float32 or float64. kernel_size (int|list|tuple): The pool kernel size. If it is a tuple or list, it must contain two integers, (kernel_size_Height, kernel_size_Width). Otherwise, the pool kernel size will be a square of an int. stride (int|list|tuple): The stride size. If it is a tuple or list, it must contain two integers, (stride_Height, stride_Width). Otherwise, the stride size will be a square of an int. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. 1. A string in ['valid', 'same']. 2. An int, which means the feature map is zero padded by size of `padding` on every sides. 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension. 4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). The default value is 0. ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape exclusive (bool): Whether to exclude padding points in average pooling mode, default is `true`. divisor_override (float): if specified, it will be used as divisor, otherwise kernel_size will be used. Default None. data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is "VALID", but `ceil_mode` is True. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle import paddle.nn.functional as F import numpy as np # avg pool2d x = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32]).astype(np.float32)) out = F.avg_pool2d(x, kernel_size=2, stride=2, padding=0) # out.shape [1, 3, 16, 16] """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool2d') kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 2, 'pool_stride') channel_last = _channel_last(data_format, 2) padding, padding_algorithm = _update_padding_nd( padding, 2, channel_last, ceil_mode=ceil_mode) if in_dygraph_mode(): output = core.ops.pool2d( x, 'pooling_type', 'avg', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', exclusive, 'data_format', data_format) if divisor_override is None: return output else: _check_instance(divisor_override, "divisor_override") return output * (kernel_size[0] * kernel_size[1]) / divisor_override op_type = 'pool2d' helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type=op_type, inputs={"X": x}, outputs={"Out": pool_out}, attrs={ "pooling_type": "avg", "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) if divisor_override is None: return pool_out else: _check_instance(divisor_override, "divisor_override") return pool_out * (kernel_size[0] * kernel_size[1]) / divisor_override def avg_pool3d(x, kernel_size, stride=None, padding=0, ceil_mode=False, exclusive=True, divisor_override=None, data_format="NCDHW", name=None): """ This API implements average pooling 3d operation. See more details in :ref:`api_nn_pooling_AvgPool3d` . Args: x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with shape [N, C, D, H, W], where `N` represents the batch size, `C` represents the number of channels, `D`, `H` and `W` represent the depth, height and width of the feature respectively. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three integers, (kernel_size_Depth, kernel_size_Height, kernel_size_Width). Otherwise, the pool kernel size will be the cube of an int. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, it must contain three integers, [stride_Depth, stride_Height, stride_Width). Otherwise, the pool stride size will be a cube of an int. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. 1. A string in ['valid', 'same']. 2. An int, which means the feature map is zero padded by size of `padding` on every sides. 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). The default value is 0. ceil_mode (bool): ${ceil_mode_comment} exclusive (bool): Whether to exclude padding points in average pooling mode, default is True. divisor_override (int|float) if specified, it will be used as divisor, otherwise kernel_size will be used. Default None. data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is "VALID", but `ceil_mode` is True. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle.fluid as fluid import paddle x = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32, 32]).astype(np.float32)) # avg pool3d out = paddle.nn.functional.avg_pool3d( x, kernel_size = 2, stride = 2, padding=0) # out.shape: [1, 3, 16, 16, 16] """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d') kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 3, 'pool_stride') channel_last = _channel_last(data_format, 3) padding, padding_algorithm = _update_padding_nd( padding, 3, channel_last=channel_last, ceil_mode=ceil_mode) if in_dygraph_mode(): output = core.ops.pool3d( x, 'pooling_type', 'avg', 'ksize', kernel_size, 'strides', stride, 'paddings', padding, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', exclusive, 'data_format', data_format) if divisor_override is None: return output else: _check_instance(divisor_override, "divisor_override") return output * (kernel_size[0] * kernel_size[1] * kernel_size[2]) / divisor_override op_type = "pool3d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'avg', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) if divisor_override is None: return pool_out else: _check_instance(divisor_override, "divisor_override") return pool_out * (kernel_size[0] * kernel_size[1] * kernel_size[2]) / divisor_override def max_pool1d(x, kernel_size, stride=None, padding=0, return_mask=False, ceil_mode=False, name=None): """ This API implements max pooling 1d opereation. See more details in :ref:`api_nn_pooling_MaxPool1d` . Args: x (Tensor): The input tensor of pooling operator which is a 3-D tensor with shape [N, C, L], where `N` is batch size, `C` is the number of channels, `L` is the length of the feature. The data type if float32 or float64. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain an integer. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, it must contain an integer. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. 1. A string in ['valid', 'same']. 2. An integer, which means the feature map is zero padded by size of `padding` on every sides. 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides. 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after]. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). The default value is 0. return_mask (bool): Whether return the max indices along with the outputs. default is `False`. ceil_mode (bool): Whether to use the ceil function to calculate output height and width. False is the default. If it is set to False, the floor function will be used. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is "VALID", but `ceil_mode` is True. ShapeError: If the input is not a 3-D tensor. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle import paddle.nn.functional as F data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32)) pool_out = F.max_pool1d(data, kernel_size=2, stride=2, padding=0) # pool_out shape: [1, 3, 16] pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True) # pool_out shape: [1, 3, 16], indices shape: [1, 3, 16] """ """NCL to NCHW""" data_format = "NCHW" check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool1d') _check_input(x, 3) x = unsqueeze(x, [2]) kernel_size = [1] + utils.convert_to_list(kernel_size, 1, 'pool_size') if stride is None: stride = kernel_size else: stride = [1] + utils.convert_to_list(stride, 1, 'pool_stride') padding, padding_algorithm = _update_padding_nd( padding, 1, ceil_mode=ceil_mode) # use 2d to implenment 1d should expand padding in advance. padding = _expand_low_nd_padding(padding) if in_dygraph_mode(): if return_mask: pool_out = core.ops.max_pool2d_with_index( x, 'ksize', kernel_size, 'global_pooling', False, 'strides', stride, 'paddings', padding, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2])) if return_mask else squeeze(pool_out[0], [2]) else: pool_out = core.ops.pool2d( x, 'pooling_type', 'max', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return squeeze(pool_out, [2]) op_type = 'max_pool2d_with_index' if return_mask else "pool2d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": True, "data_format": data_format, }) return (squeeze(pool_out, [2]), squeeze(mask, [2])) if return_mask else squeeze(pool_out, [2]) def max_pool2d(x, kernel_size, stride=None, padding=0, return_mask=False, ceil_mode=False, data_format="NCHW", name=None): """ This API implements max pooling 2d operation. See more details in :ref:`api_nn_pooling_MaxPool2d` . Args: x (Tensor): The input tensor of pooling operator which is a 4-D tensor with shape [N, C, H, W]. The format of input tensor is `"NCHW"` or `"NHWC"`, where `N` is batch size, `C` is the number of channels, `H` is the height of the feature, and `W` is the width of the feature. The data type if float32 or float64. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two integers, (kernel_size_Height, kernel_size_Width). Otherwise, the pool kernel size will be a square of an int. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, it must contain two integers, (stride_Height, stride_Width). Otherwise, the pool stride size will be a square of an int. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. 1. A string in ['valid', 'same']. 2. An int, which means the feature map is zero padded by size of `padding` on every sides. 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension. 4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). The default value is 0. ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape return_mask (bool): Whether to return the max indices along with the outputs. Default False, only support `"NCHW"` data format data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of: `[batch_size, input_channels, input_height, input_width]`. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is "VALID", but `ceil_mode` is True. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle import paddle.nn.functional as F import numpy as np # max pool2d x = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32]).astype(np.float32)) out = F.max_pool2d(x, kernel_size=2, stride=2, padding=0) # output.shape [1, 3, 16, 16] # for return_mask=True out, max_indices = F.max_pool2d(x, kernel_size=2, stride=2, padding=0, return_mask=True) # out.shape [1, 3, 16, 16], max_indices.shape [1, 3, 16, 16], """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool2d') kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 2, 'pool_stride') if data_format not in ["NCHW", "NHWC"]: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s." % str(data_format)) channel_last = True if data_format == "NHWC" else False padding, padding_algorithm = _update_padding_nd( padding, num_dims=2, channel_last=channel_last, ceil_mode=ceil_mode) if data_format == "NHWC" and return_mask: raise ValueError( "When setting return_mask to true, data_format must be set to NCHW in API:max_pool2d" ) if in_dygraph_mode(): if return_mask: output = core.ops.max_pool2d_with_index( x, 'ksize', kernel_size, 'global_pooling', False, 'strides', stride, 'paddings', padding, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output if return_mask else output[0] else: output = core.ops.pool2d( x, 'pooling_type', 'max', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output op_type = 'max_pool2d_with_index' if return_mask else "pool2d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": True, "data_format": data_format, }) return (pool_out, mask) if return_mask else pool_out def max_pool3d(x, kernel_size, stride=None, padding=0, return_mask=False, ceil_mode=False, data_format="NCDHW", name=None): """ This API implements max pooling 2d operation. See more details in :ref:`api_nn_pooling_MaxPool3d` . Args: x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` or `"NDHWC"`, where N represents batch size, C represents the number of channels, D, H and W represent the depth, height and width of the feature respectively. kernel_size (int|list|tuple): The pool kernel size. If the kernel size is a tuple or list, it must contain three integers, (kernel_size_Depth, kernel_size_Height, kernel_size_Width). Otherwise, the pool kernel size will be the cube of an int. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list, it must contain three integers, [stride_Depth, stride_Height, stride_Width). Otherwise, the pool stride size will be a cube of an int. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms. 1. A string in ['valid', 'same']. 2. An int, which means the feature map is zero padded by size of `padding` on every sides. 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension. 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0). The default value is 0. ceil_mode (bool): ${ceil_mode_comment} return_mask (bool): Whether to return the max indices along with the outputs. Default False. Only support "NDCHW" data_format. data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of pooling result. The data type is same as input tensor. Raises: ValueError: If `padding` is a string, but not "SAME" or "VALID". ValueError: If `padding` is "VALID", but `ceil_mode` is True. ShapeError: If the output's shape calculated is not greater than 0. Examples: .. code-block:: python import paddle import paddle.nn.functional as F import numpy as np # max pool3d x = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32, 32]).astype(np.float32)) output = F.max_pool2d(x, kernel_size=2, stride=2, padding=0) output.shape [1, 3, 16, 16, 16] # for return_mask=True x = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32, 32, 32]).astype(np.float32)) output, max_indices = paddle.nn.functional.max_pool3d(x, kernel_size = 2, stride = 2, padding=0, return_mask=True) # output.shape [None, 3, 16, 16, 16], max_indices.shape [None, 3, 16, 16, 16], """ check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d') kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 3, 'pool_stride') channel_last = _channel_last(data_format, 3) padding, padding_algorithm = _update_padding_nd( padding, 3, channel_last=channel_last, ceil_mode=ceil_mode) if data_format == "NDHWC" and return_mask: raise ValueError( "When setting return_mask to true, data_format must be set to NCDHW in API:max_pool3d" ) if in_dygraph_mode(): if return_mask: output = core.ops.max_pool3d_with_index( x, 'pooling_type', 'max', 'ksize', kernel_size, 'strides', stride, 'paddings', padding, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output if return_mask else output[0] else: output = core.ops.pool3d( x, 'pooling_type', 'max', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output op_type = "max_pool3d_with_index" if return_mask else "pool3d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": False, "data_format": data_format, }) return (pool_out, mask) if return_mask else pool_out def adaptive_avg_pool1d(x, output_size, name=None): """ This API implements adaptive average pooling 1d operation. See more details in :ref:`api_nn_pooling_AdaptiveAvgPool1d` . Args: x (Tensor): The input tensor of pooling operator, which is a 3-D tensor with shape [N, C, L]. The format of input tensor is NCL, where N is batch size, C is the number of channels, L is the length of the feature. The data type is float32 or float64. output_size (int): The target output size. It must be an integer. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive average pooling result. The data type is same as input tensor. Raises: ValueError: 'output_size' should be an integer. Examples: .. code-block:: python # average adaptive pool1d # suppose input data in shape of [N, C, L], `output_size` is m or [m], # output shape is [N, C, m], adaptive pool divide L dimension # of input data into m grids averagely and performs poolings in each # grid to get output. # adaptive max pool performs calculations as follow: # # for i in range(m): # lstart = floor(i * L / m) # lend = ceil((i + 1) * L / m) # output[:, :, i] = sum(input[:, :, lstart: lend])/(lstart - lend) # import paddle import paddle.nn.functional as F data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32)) pool_out = F.adaptive_average_pool1d(data, output_size=16) # pool_out shape: [1, 3, 16]) """ pool_type = 'avg' check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_pool2d') _check_input(x, 3) check_type(output_size, 'pool_size', (int), 'adaptive_pool1d') pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size') l_type = "pool2d" x = unsqueeze(x, [2]) if in_dygraph_mode(): pool_out = core.ops.pool2d(x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True) return squeeze(pool_out, [2]) helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": pool_type, "ksize": pool_size, "adaptive": True, }) return squeeze(pool_out, [2]) def adaptive_avg_pool2d(x, output_size, data_format='NCHW', name=None): """ This API implements adaptive average pooling 2d operation. See more details in :ref:`api_nn_pooling_AdaptiveAvgPool2d` . Args: x (Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor. The data type can be float32 or float64. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two element, (H, W). H and W can be either a int, or None which means the size will be the same as that of the input. data_format (str): The data format of the input and output data. An optional string from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of avg adaptive pool2d result. The data type is same as input tensor. Raises: ValueError: If `data_format` is not "NCHW" or "NHWC". Examples: .. code-block:: python # adaptive avg pool2d # suppose input data in shape of [N, C, H, W], `output_size` is [m, n], # output shape is [N, C, m, n], adaptive pool divide H and W dimensions # of input data into m * n grids averagely and performs poolings in each # grid to get output. # adaptive avg pool performs calculations as follow: # # for i in range(m): # for j in range(n): # hstart = floor(i * H / m) # hend = ceil((i + 1) * H / m) # wstart = floor(i * W / n) # wend = ceil((i + 1) * W / n) # output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend]) # import paddle import numpy as np input_data = np.random.rand(2, 3, 32, 32) x = paddle.to_tensor(input_data) # x.shape is [2, 3, 32, 32] out = paddle.nn.functional.adaptive_avg_pool2d( x = x, output_size=[3, 3]) # out.shape is [2, 3, 3, 3] """ if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_avg_pool2d') check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d') if data_format not in ["NCHW", "NHWC"]: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s." % str(data_format)) if data_format == "NCHW": in_h, in_w = x.shape[2:4] else: in_h, in_w = x.shape[1:3] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 2, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_h if output_size[1] == None: output_size[1] = in_w if in_dygraph_mode(): output = core.ops.pool2d(x, 'pooling_type', 'avg', 'ksize', output_size, 'global_pooling', False, 'adaptive', True, 'data_format', data_format) return output l_type = 'pool2d' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": "avg", "ksize": output_size, "adaptive": True, "data_format": data_format, }) return pool_out def adaptive_avg_pool3d(x, output_size, data_format='NCDHW', name=None): """ This API implements adaptive average pooling 3d operation. See more details in :ref:`api_nn_pooling_AdaptiveAvgPool3d` . Args: x (Tensor): The input tensor of adaptive avg pool3d operator, which is a 5-D tensor. The data type can be float32, float64. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three elements, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as that of the input. data_format (str): The data format of the input and output data. An optional string from: "NCDHW", "NDHWC". The default is "NCDHW". When it is "NCDHW", the data is stored in the order of: [batch_size, input_channels, input_depth, input_height, input_width]. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of avg adaptive pool3d result. The data type is same as input tensor. Raises: ValueError: If `data_format` is not "NCDHW" or "NDHWC". Examples: .. code-block:: python # adaptive avg pool3d # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n], # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions # of input data into l * m * n grids averagely and performs poolings in each # grid to get output. # adaptive avg pool performs calculations as follow: # # for i in range(l): # for j in range(m): # for k in range(n): # dstart = floor(i * D / l) # dend = ceil((i + 1) * D / l) # hstart = floor(j * H / m) # hend = ceil((j + 1) * H / m) # wstart = floor(k * W / n) # wend = ceil((k + 1) * W / n) # output[:, :, i, j, k] = # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend]) import paddle import numpy as np input_data = np.random.rand(2, 3, 8, 32, 32) x = paddle.to_tensor(input_data) # x.shape is [2, 3, 8, 32, 32] out = paddle.nn.functional.adaptive_avg_pool3d( x = x, output_size=[3, 3, 3]) # out.shape is [2, 3, 3, 3, 3] """ if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_avg_pool3d') check_type(data_format, 'data_format', str, 'adaptive_avg_pool3d') if data_format not in ["NCDHW", "NDHWC"]: raise ValueError( "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " "Attr(data_format): %s." % str(data_format)) if data_format == "NCDHW": in_l, in_h, in_w = x.shape[2:5] else: in_l, in_h, in_w = x.shape[1:4] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 3, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_l if output_size[1] == None: output_size[1] = in_h if output_size[2] == None: output_size[2] = in_w if in_dygraph_mode(): output = core.ops.pool3d(x, 'pooling_type', 'avg', 'ksize', output_size, 'global_pooling', False, 'adaptive', True, 'data_format', data_format) return output l_type = 'pool3d' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": "avg", "ksize": output_size, "adaptive": True, "data_format": data_format, }) return pool_out def adaptive_max_pool1d(x, output_size, return_mask=False, name=None): """ This API implements adaptive max pooling 1d operation. See more details in :ref:`api_nn_pooling_AdaptiveMaxPool1d` . Args: x (Tensor): The input tensor of pooling operator, which is a 3-D tensor with shape [N, C, L]. The format of input tensor is NCL, where N is batch size, C is the number of channels, L is the length of the feature. The data type is float32 or float64. output_size (int): The pool kernel size. The value should be an integer. return_mask (bool): If true, the index of max pooling point will be returned along with outputs. It cannot be set in average pooling type. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive pooling result. The data type is same as input tensor. Raises: ValueError: 'output_size' should be an integer. Examples: .. code-block:: python # max adaptive pool1d # suppose input data in shape of [N, C, L], `output_size` is m or [m], # output shape is [N, C, m], adaptive pool divide L dimension # of input data into m grids averagely and performs poolings in each # grid to get output. # adaptive max pool performs calculations as follow: # # for i in range(m): # lstart = floor(i * L / m) # lend = ceil((i + 1) * L / m) # output[:, :, i] = max(input[:, :, lstart: lend]) # import paddle import paddle.nn.functional as F data = paddle.to_tensor(np.random.uniform(-1, 1, [1, 3, 32]).astype(np.float32)) pool_out = F.adaptive_max_pool1d(data, output_size=16) # pool_out shape: [1, 3, 16]) pool_out, indices = F.adaptive_max_pool1d(data, output_size=16, return_mask=True) # pool_out shape: [1, 3, 16] indices shape: [1, 3, 16] """ pool_type = 'max' check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_max_pool1d') _check_input(x, 3) check_type(output_size, 'pool_size', int, 'adaptive_max_pool1d') check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool1d') pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size') l_type = 'max_pool2d_with_index' x = unsqueeze(x, [2]) if in_dygraph_mode(): pool_out = core.ops.max_pool2d_with_index( x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True) return (squeeze(pool_out[0], [2]), squeeze( pool_out[1], [2])) if return_mask else squeeze(pool_out[0], [2]) helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": pool_type, "ksize": pool_size, "adaptive": True, }) return (squeeze(pool_out, [2]), squeeze(mask, [2])) if return_mask else squeeze(pool_out, [2]) def adaptive_max_pool2d(x, output_size, return_mask=False, name=None): """ This operation applies a 2D adaptive max pooling on input tensor. See more details in :ref:`api_nn_pooling_AdaptiveMaxPool2d` . Args: x (Tensor): The input tensor of adaptive max pool2d operator, which is a 4-D tensor. The data type can be float16, float32, float64, int32 or int64. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two elements, (H, W). H and W can be either a int, or None which means the size will be the same as that of the input. return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive max pool2d result. The data type is same as input tensor. Examples: .. code-block:: python # max adaptive pool2d # suppose input data in the shape of [N, C, H, W], `output_size` is [m, n] # output shape is [N, C, m, n], adaptive pool divide H and W dimensions # of input data into m*n grids averagely and performs poolings in each # grid to get output. # adaptive max pool performs calculations as follow: # # for i in range(m): # for j in range(n): # hstart = floor(i * H / m) # hend = ceil((i + 1) * H / m) # wstart = floor(i * W / n) # wend = ceil((i + 1) * W / n) # output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend]) # import paddle import numpy as np input_data = np.random.rand(2, 3, 32, 32) x = paddle.to_tensor(input_data) # x.shape is [2, 3, 32, 32] out = paddle.nn.functional.adaptive_max_pool2d( x = x, output_size=[3, 3]) # out.shape is [2, 3, 3, 3] """ if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_max_pool2d') _check_input(x, 4) #check_type(output_size, 'pool_size', (int), 'adaptive_max_pool2d') check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool2d') in_h, in_w = x.shape[2:4] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 2, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_h if output_size[1] == None: output_size[1] = in_w if in_dygraph_mode(): pool_out = core.ops.max_pool2d_with_index( x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True) return pool_out if return_mask else pool_out[0] l_type = 'max_pool2d_with_index' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": output_size, "adaptive": True, }) #return (pool_out, mask) if return_mask else pool_out return pool_out def adaptive_max_pool3d(x, output_size, return_mask=False, name=None): """ This operation applies a 3D adaptive max pooling on input tensor. See more details in :ref:`api_nn_pooling_AdaptiveMaxPool3d` . Args: x (Tensor): The input tensor of adaptive max pool3d operator, which is a 5-D tensor. The data type can be float32, float64. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three elements, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as that of the input. return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default. Returns: Tensor: The output tensor of adaptive max pool3d result. The data type is same as input tensor. Examples: .. code-block:: python # adaptive max pool3d # suppose input data in the shape of [N, C, D, H, W], `output_size` is [l, m, n] # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions # of input data into m*n grids averagely and performs poolings in each # grid to get output. # adaptive max pool performs calculations as follow: # # for i in range(l): # for j in range(m): # for k in range(n): # dstart = floor(i * D / l) # dend = ceil((i + 1) * D / l) # hstart = floor(i * H / m) # hend = ceil((i + 1) * H / m) # wstart = floor(i * W / n) # wend = ceil((i + 1) * W / n) # output[:, :, i, j, k] = max(input[:, :, dstart: dend, hstart: hend, wstart: wend]) # import paddle import numpy as np input_data = np.random.rand(2, 3, 8, 32, 32) x = paddle.to_tensor(input_data) # x.shape is [2, 3, 8, 32, 32] out = paddle.nn.functional.adaptive_max_pool3d( x = x, output_size=[3, 3, 3]) # out.shape is [2, 3, 3, 3, 3] """ if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_max_pool3d') _check_input(x, 5) #check_type(output_size, 'pool_size', (int), 'adaptive_max_pool3d') check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool3d') in_l, in_h, in_w = x.shape[2:5] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 3, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_l if output_size[1] == None: output_size[1] = in_h if output_size[2] == None: output_size[2] = in_w if in_dygraph_mode(): pool_out = core.ops.max_pool3d_with_index( x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True) return pool_out if return_mask else pool_out[0] l_type = 'max_pool3d_with_index' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": output_size, "adaptive": True, }) return (pool_out, mask) if return_mask else pool_out
45.515559
248
0.582234
from ...fluid import core from ...fluid.framework import in_dygraph_mode from ...fluid.layers import utils, LayerHelper, unsqueeze, squeeze from ...fluid.data_feeder import check_type, check_variable_and_dtype __all__ = [ 'avg_pool1d', 'avg_pool2d', 'avg_pool3d', 'max_pool1d', 'max_pool2d', 'max_pool3d', 'adaptive_avg_pool1d', 'adaptive_avg_pool2d', 'adaptive_avg_pool3d', 'adaptive_max_pool1d', 'adaptive_max_pool2d', 'adaptive_max_pool3d', ] def _is_list_or_tuple(input): return isinstance(input, (list, tuple)) def _check_input(x, dimension): if len(x.shape) != dimension: raise ValueError( "Excepted Input X is {}-D tensor, but received {}-D {}".format( dimension, len(x.shape), type(x))) def _check_instance(x, x_name, types=(int, float)): if not isinstance(x, types): raise ValueError("Excepted {} type for {} but received type: {}. ". format(types, x_name, type(x))) def _zero_padding_in_batch_and_channel(padding, channel_last): if channel_last: return list(padding[0]) == [0, 0] and list(padding[-1]) == [0, 0] else: return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0] def _exclude_padding_in_batch_and_channel(padding, channel_last): padding_ = padding[1:-1] if channel_last else padding[2:] padding_ = [elem for pad_a_dim in padding_ for elem in pad_a_dim] return padding_ def _channel_last(data_format, num_dims): if num_dims == 1: if data_format not in ['NCL', 'NLC']: raise ValueError( "Attr(data_format) should be 'NCL' or 'NLC'. Received " "Attr(data_format): %s" % str(data_format)) else: return True if data_format == "NLC" else False if num_dims == 2: if data_format not in ['NCHW', 'NHWC']: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s" % str(data_format)) else: return True if data_format == "NHWC" else False if num_dims == 3: if data_format not in ['NCDHW', 'NDHWC']: raise ValueError( "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " "Attr(data_format): %s" % str(data_format)) else: return True if data_format == "NDHWC" else False def _update_padding_nd(padding, num_dims, channel_last=False, ceil_mode=False): if isinstance(padding, str): padding = padding.upper() if padding not in ["SAME", "VALID"]: raise ValueError( "Unknown padding: '{}'. It can only be 'SAME' or 'VALID'.". format(padding)) if padding == "VALID": if ceil_mode != False: raise ValueError( "When Attr(padding) is \"VALID\", Attr(ceil_mode) must be False. " "Received ceil_mode: True.") padding_algorithm = "VALID" padding = [0] * num_dims else: padding_algorithm = "SAME" padding = [0] * num_dims elif _is_list_or_tuple(padding): if len(padding) == 2 + num_dims and _is_list_or_tuple(padding[0]): if not _zero_padding_in_batch_and_channel(padding, channel_last): raise ValueError( "Non-zero padding({}) in the batch or channel dimensions " "is not supported.".format(padding)) padding_algorithm = "EXPLICIT" padding = _exclude_padding_in_batch_and_channel(padding, channel_last) if utils._is_symmetric_padding(padding, num_dims): padding = padding[0::2] elif len(padding) == 2 * num_dims and isinstance(padding[0], int): padding_algorithm = "EXPLICIT" padding = utils.convert_to_list(padding, 2 * num_dims, 'padding') if utils._is_symmetric_padding(padding, num_dims): padding = padding[0::2] elif len(padding) == num_dims and isinstance(padding[0], int): padding_algorithm = "EXPLICIT" padding = utils.convert_to_list(padding, num_dims, 'padding') else: raise ValueError("Invalid padding: {}".format(padding)) else: padding_algorithm = "EXPLICIT" padding = utils.convert_to_list(padding, num_dims, 'padding') return padding, padding_algorithm def _expand_low_nd_padding(padding): if len(padding) == 2: padding = [0] * 2 + padding elif len(padding) == 1: padding = [0] + padding else: raise ValueError( "The size of padding's dimmention should be 1 or 2. But got padding={}". format(padding)) return padding def avg_pool1d(x, kernel_size, stride=None, padding=0, exclusive=True, ceil_mode=False, name=None): data_format = "NCHW" check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool1d') _check_input(x, 3) x = unsqueeze(x, [2]) kernel_size = utils.convert_to_list(kernel_size, 1, 'kernel_size') kernel_size = [1] + kernel_size if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 1, 'pool_stride') stride = [1] + stride channel_last = _channel_last("NCL", 1) padding, padding_algorithm = _update_padding_nd( padding, 1, channel_last=channel_last, ceil_mode=ceil_mode) # use 2d to implenment 1d should expand padding in advance. padding = _expand_low_nd_padding(padding) if in_dygraph_mode(): output = core.ops.pool2d( x, 'pooling_type', 'avg', 'ksize', kernel_size, 'global_pooling', False, 'strides', stride, 'paddings', padding, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', exclusive, 'data_format', data_format) return squeeze(output, [2]) op_type = 'pool2d' helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type=op_type, inputs={"X": x}, outputs={"Out": pool_out}, attrs={ "pooling_type": 'avg', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) return squeeze(pool_out, [2]) def avg_pool2d(x, kernel_size, stride=None, padding=0, ceil_mode=False, exclusive=True, divisor_override=None, data_format="NCHW", name=None): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'avg_pool2d') kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 2, 'pool_stride') channel_last = _channel_last(data_format, 2) padding, padding_algorithm = _update_padding_nd( padding, 2, channel_last, ceil_mode=ceil_mode) if in_dygraph_mode(): output = core.ops.pool2d( x, 'pooling_type', 'avg', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', exclusive, 'data_format', data_format) if divisor_override is None: return output else: _check_instance(divisor_override, "divisor_override") return output * (kernel_size[0] * kernel_size[1]) / divisor_override op_type = 'pool2d' helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) helper.append_op( type=op_type, inputs={"X": x}, outputs={"Out": pool_out}, attrs={ "pooling_type": "avg", "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) if divisor_override is None: return pool_out else: _check_instance(divisor_override, "divisor_override") return pool_out * (kernel_size[0] * kernel_size[1]) / divisor_override def avg_pool3d(x, kernel_size, stride=None, padding=0, ceil_mode=False, exclusive=True, divisor_override=None, data_format="NCDHW", name=None): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d') kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 3, 'pool_stride') channel_last = _channel_last(data_format, 3) padding, padding_algorithm = _update_padding_nd( padding, 3, channel_last=channel_last, ceil_mode=ceil_mode) if in_dygraph_mode(): output = core.ops.pool3d( x, 'pooling_type', 'avg', 'ksize', kernel_size, 'strides', stride, 'paddings', padding, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', exclusive, 'data_format', data_format) if divisor_override is None: return output else: _check_instance(divisor_override, "divisor_override") return output * (kernel_size[0] * kernel_size[1] * kernel_size[2]) / divisor_override op_type = "pool3d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'avg', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": exclusive, "data_format": data_format, }) if divisor_override is None: return pool_out else: _check_instance(divisor_override, "divisor_override") return pool_out * (kernel_size[0] * kernel_size[1] * kernel_size[2]) / divisor_override def max_pool1d(x, kernel_size, stride=None, padding=0, return_mask=False, ceil_mode=False, name=None): data_format = "NCHW" check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool1d') _check_input(x, 3) x = unsqueeze(x, [2]) kernel_size = [1] + utils.convert_to_list(kernel_size, 1, 'pool_size') if stride is None: stride = kernel_size else: stride = [1] + utils.convert_to_list(stride, 1, 'pool_stride') padding, padding_algorithm = _update_padding_nd( padding, 1, ceil_mode=ceil_mode) # use 2d to implenment 1d should expand padding in advance. padding = _expand_low_nd_padding(padding) if in_dygraph_mode(): if return_mask: pool_out = core.ops.max_pool2d_with_index( x, 'ksize', kernel_size, 'global_pooling', False, 'strides', stride, 'paddings', padding, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2])) if return_mask else squeeze(pool_out[0], [2]) else: pool_out = core.ops.pool2d( x, 'pooling_type', 'max', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return squeeze(pool_out, [2]) op_type = 'max_pool2d_with_index' if return_mask else "pool2d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": True, "data_format": data_format, }) return (squeeze(pool_out, [2]), squeeze(mask, [2])) if return_mask else squeeze(pool_out, [2]) def max_pool2d(x, kernel_size, stride=None, padding=0, return_mask=False, ceil_mode=False, data_format="NCHW", name=None): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool2d') kernel_size = utils.convert_to_list(kernel_size, 2, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 2, 'pool_stride') if data_format not in ["NCHW", "NHWC"]: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s." % str(data_format)) channel_last = True if data_format == "NHWC" else False padding, padding_algorithm = _update_padding_nd( padding, num_dims=2, channel_last=channel_last, ceil_mode=ceil_mode) if data_format == "NHWC" and return_mask: raise ValueError( "When setting return_mask to true, data_format must be set to NCHW in API:max_pool2d" ) if in_dygraph_mode(): if return_mask: output = core.ops.max_pool2d_with_index( x, 'ksize', kernel_size, 'global_pooling', False, 'strides', stride, 'paddings', padding, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output if return_mask else output[0] else: output = core.ops.pool2d( x, 'pooling_type', 'max', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output op_type = 'max_pool2d_with_index' if return_mask else "pool2d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": True, "data_format": data_format, }) return (pool_out, mask) if return_mask else pool_out def max_pool3d(x, kernel_size, stride=None, padding=0, return_mask=False, ceil_mode=False, data_format="NCDHW", name=None): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool3d') kernel_size = utils.convert_to_list(kernel_size, 3, 'pool_size') if stride is None: stride = kernel_size else: stride = utils.convert_to_list(stride, 3, 'pool_stride') channel_last = _channel_last(data_format, 3) padding, padding_algorithm = _update_padding_nd( padding, 3, channel_last=channel_last, ceil_mode=ceil_mode) if data_format == "NDHWC" and return_mask: raise ValueError( "When setting return_mask to true, data_format must be set to NCDHW in API:max_pool3d" ) if in_dygraph_mode(): if return_mask: output = core.ops.max_pool3d_with_index( x, 'pooling_type', 'max', 'ksize', kernel_size, 'strides', stride, 'paddings', padding, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output if return_mask else output[0] else: output = core.ops.pool3d( x, 'pooling_type', 'max', 'ksize', kernel_size, 'global_pooling', False, 'padding_algorithm', padding_algorithm, 'strides', stride, 'paddings', padding, 'use_cudnn', True, 'ceil_mode', ceil_mode, 'use_mkldnn', False, 'exclusive', True, 'data_format', data_format) return output op_type = "max_pool3d_with_index" if return_mask else "pool3d" helper = LayerHelper(op_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=op_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": kernel_size, "global_pooling": False, "strides": stride, "paddings": padding, "padding_algorithm": padding_algorithm, "use_cudnn": True, "ceil_mode": ceil_mode, "use_mkldnn": False, "exclusive": False, "data_format": data_format, }) return (pool_out, mask) if return_mask else pool_out def adaptive_avg_pool1d(x, output_size, name=None): pool_type = 'avg' check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_pool2d') _check_input(x, 3) check_type(output_size, 'pool_size', (int), 'adaptive_pool1d') pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size') l_type = "pool2d" x = unsqueeze(x, [2]) if in_dygraph_mode(): pool_out = core.ops.pool2d(x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True) return squeeze(pool_out, [2]) helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": pool_type, "ksize": pool_size, "adaptive": True, }) return squeeze(pool_out, [2]) def adaptive_avg_pool2d(x, output_size, data_format='NCHW', name=None): if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_avg_pool2d') check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d') if data_format not in ["NCHW", "NHWC"]: raise ValueError( "Attr(data_format) should be 'NCHW' or 'NHWC'. Received " "Attr(data_format): %s." % str(data_format)) if data_format == "NCHW": in_h, in_w = x.shape[2:4] else: in_h, in_w = x.shape[1:3] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 2, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_h if output_size[1] == None: output_size[1] = in_w if in_dygraph_mode(): output = core.ops.pool2d(x, 'pooling_type', 'avg', 'ksize', output_size, 'global_pooling', False, 'adaptive', True, 'data_format', data_format) return output l_type = 'pool2d' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": "avg", "ksize": output_size, "adaptive": True, "data_format": data_format, }) return pool_out def adaptive_avg_pool3d(x, output_size, data_format='NCDHW', name=None): if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_avg_pool3d') check_type(data_format, 'data_format', str, 'adaptive_avg_pool3d') if data_format not in ["NCDHW", "NDHWC"]: raise ValueError( "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received " "Attr(data_format): %s." % str(data_format)) if data_format == "NCDHW": in_l, in_h, in_w = x.shape[2:5] else: in_l, in_h, in_w = x.shape[1:4] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 3, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_l if output_size[1] == None: output_size[1] = in_h if output_size[2] == None: output_size[2] = in_w if in_dygraph_mode(): output = core.ops.pool3d(x, 'pooling_type', 'avg', 'ksize', output_size, 'global_pooling', False, 'adaptive', True, 'data_format', data_format) return output l_type = 'pool3d' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": "avg", "ksize": output_size, "adaptive": True, "data_format": data_format, }) return pool_out def adaptive_max_pool1d(x, output_size, return_mask=False, name=None): pool_type = 'max' check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_max_pool1d') _check_input(x, 3) check_type(output_size, 'pool_size', int, 'adaptive_max_pool1d') check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool1d') pool_size = [1] + utils.convert_to_list(output_size, 1, 'pool_size') l_type = 'max_pool2d_with_index' x = unsqueeze(x, [2]) if in_dygraph_mode(): pool_out = core.ops.max_pool2d_with_index( x, 'pooling_type', pool_type, 'ksize', pool_size, 'adaptive', True) return (squeeze(pool_out[0], [2]), squeeze( pool_out[1], [2])) if return_mask else squeeze(pool_out[0], [2]) helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": pool_type, "ksize": pool_size, "adaptive": True, }) return (squeeze(pool_out, [2]), squeeze(mask, [2])) if return_mask else squeeze(pool_out, [2]) def adaptive_max_pool2d(x, output_size, return_mask=False, name=None): if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_max_pool2d') _check_input(x, 4) #check_type(output_size, 'pool_size', (int), 'adaptive_max_pool2d') check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool2d') in_h, in_w = x.shape[2:4] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 2, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_h if output_size[1] == None: output_size[1] = in_w if in_dygraph_mode(): pool_out = core.ops.max_pool2d_with_index( x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True) return pool_out if return_mask else pool_out[0] l_type = 'max_pool2d_with_index' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": output_size, "adaptive": True, }) #return (pool_out, mask) if return_mask else pool_out return pool_out def adaptive_max_pool3d(x, output_size, return_mask=False, name=None): if not in_dygraph_mode(): check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'adaptive_max_pool3d') _check_input(x, 5) #check_type(output_size, 'pool_size', (int), 'adaptive_max_pool3d') check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool3d') in_l, in_h, in_w = x.shape[2:5] if isinstance(output_size, int): output_size = utils.convert_to_list(output_size, 3, 'output_size') else: output_size = list(output_size) if output_size[0] == None: output_size[0] = in_l if output_size[1] == None: output_size[1] = in_h if output_size[2] == None: output_size[2] = in_w if in_dygraph_mode(): pool_out = core.ops.max_pool3d_with_index( x, 'pooling_type', 'max', 'ksize', output_size, 'adaptive', True) return pool_out if return_mask else pool_out[0] l_type = 'max_pool3d_with_index' helper = LayerHelper(l_type, **locals()) dtype = helper.input_dtype(input_param_name='x') pool_out = helper.create_variable_for_type_inference(dtype) mask = helper.create_variable_for_type_inference(dtype) outputs = {"Out": pool_out, "Mask": mask} helper.append_op( type=l_type, inputs={"X": x}, outputs=outputs, attrs={ "pooling_type": 'max', "ksize": output_size, "adaptive": True, }) return (pool_out, mask) if return_mask else pool_out
true
true