hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
725fc5d0654e9d1d83314649f9273961d6a4bec3
820
py
Python
h5axeconfig/grism/base.py
Russell-Ryan/aXeConfig
ff52e1981b825a075372c682cb6034cfeec58213
[ "MIT" ]
null
null
null
h5axeconfig/grism/base.py
Russell-Ryan/aXeConfig
ff52e1981b825a075372c682cb6034cfeec58213
[ "MIT" ]
null
null
null
h5axeconfig/grism/base.py
Russell-Ryan/aXeConfig
ff52e1981b825a075372c682cb6034cfeec58213
[ "MIT" ]
1
2019-09-25T14:51:04.000Z
2019-09-25T14:51:04.000Z
import numpy as np import os ''' Base class for h5axeconfig package. Code is based on the standard aXe configuration polynomials, but repackaged in the h5 format by Russell Ryan. This format works better (than the ascii-based system) for dealing with instruments with multiple detectors (e.g. WFIRST). ''' class Base(object): """ Base class for h5axeconfig objects. """ def __init__(self,h5): ''' Load the h5axeconfig module Parameters ---------- h5 : h5-like dictionary This establishes the name of the base class ''' self.beam=os.path.split(h5.name)[1] def __str__(self): ''' Simple overloading of the print function ''' return '{} for beam: {}'.format(self.__class__.__name__,self.beam)
24.117647
75
0.626829
103
820
4.834951
0.621359
0.054217
0.048193
0.092369
0
0
0
0
0
0
0
0.015126
0.27439
820
33
76
24.848485
0.821849
0.242683
0
0
0
0
0.055556
0
0
0
0
0
0
1
0.285714
false
0
0.285714
0
0.857143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
72668c971ba350475634e6fb3e0a2a97c7dc73cb
744
py
Python
synthesizer/layers/custom_layers.py
puppyapple/Real-Time-Voice-Cloning
d1e1481e18ee7d604372025f3b751663d8dda37b
[ "MIT" ]
null
null
null
synthesizer/layers/custom_layers.py
puppyapple/Real-Time-Voice-Cloning
d1e1481e18ee7d604372025f3b751663d8dda37b
[ "MIT" ]
null
null
null
synthesizer/layers/custom_layers.py
puppyapple/Real-Time-Voice-Cloning
d1e1481e18ee7d604372025f3b751663d8dda37b
[ "MIT" ]
null
null
null
# coding: utf-8 # import torch # from torch import nn # class StopProjection(nn.Module): # r""" Simple projection layer to predict the "stop token" # Args: # in_features (int): size of the input vector # out_features (int or list): size of each output vector. aka number # of predicted frames. # """ # def __init__(self, in_features, out_features): # super(StopProjection, self).__init__() # self.linear = nn.Linear(in_features, out_features) # self.dropout = nn.Dropout(0.5) # self.sigmoid = nn.Sigmoid() # def forward(self, inputs): # out = self.dropout(inputs) # out = self.linear(out) # out = self.sigmoid(out) # return out
29.76
76
0.603495
93
744
4.677419
0.516129
0.068966
0.05977
0.096552
0
0
0
0
0
0
0
0.005597
0.27957
744
24
77
31
0.80597
0.939516
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
726703a91da7fb75a65e5f9dd98b2a1049e974fa
116
py
Python
ChildProject/__init__.py
FrancisTembo/ChildProject
5d42bd102ba1e827ec913146e21cee6be7babff4
[ "MIT" ]
5
2021-07-01T21:52:06.000Z
2022-01-25T14:47:44.000Z
ChildProject/__init__.py
FrancisTembo/ChildProject
5d42bd102ba1e827ec913146e21cee6be7babff4
[ "MIT" ]
101
2020-10-15T12:39:36.000Z
2021-04-04T09:39:24.000Z
ChildProject/__init__.py
FrancisTembo/ChildProject
5d42bd102ba1e827ec913146e21cee6be7babff4
[ "MIT" ]
2
2021-07-09T09:43:03.000Z
2022-03-16T11:36:17.000Z
__all__= [ 'table', 'projects', 'annotations', 'converters', 'metrics' ] __version__ = '0.0.3'
11.6
21
0.534483
10
116
5.4
0.9
0
0
0
0
0
0
0
0
0
0
0.035714
0.275862
116
9
22
12.888889
0.607143
0
0
0
0
0
0.396552
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
726b649f30e93aa3c595581dc2ce07bec82a116b
1,135
py
Python
miniGithub/migrations/0011_change_code.py
stefan096/UKS
aeabe6a9995143c006ad4143e8e876a102e9d69b
[ "MIT" ]
null
null
null
miniGithub/migrations/0011_change_code.py
stefan096/UKS
aeabe6a9995143c006ad4143e8e876a102e9d69b
[ "MIT" ]
36
2020-01-12T17:00:23.000Z
2020-03-21T13:25:28.000Z
miniGithub/migrations/0011_change_code.py
stefan096/UKS
aeabe6a9995143c006ad4143e8e876a102e9d69b
[ "MIT" ]
null
null
null
# Generated by Django 3.0.2 on 2020-02-11 19:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('miniGithub', '0010_change_milestone'), ] operations = [ migrations.CreateModel( name='Change_Code', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('commit_url', models.CharField(max_length=100)), ('commit_id', models.CharField(max_length=100)), ('message', models.CharField(max_length=100)), ('created_time', models.DateTimeField()), ('creator', models.CharField(max_length=100)), ('creator_email', models.CharField(max_length=100)), ('problem', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='miniGithub.Problem')), ('project', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='miniGithub.Project')), ], ), ]
39.137931
128
0.610573
120
1,135
5.633333
0.483333
0.110947
0.133136
0.177515
0.41568
0.215976
0.215976
0.215976
0.215976
0.215976
0
0.039859
0.248458
1,135
28
129
40.535714
0.752638
0.039648
0
0
1
0
0.141544
0.019301
0
0
0
0
0
1
0
false
0
0.090909
0
0.227273
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
72800f4cf07c1ade02e8f22e23c65237121f8da1
321
py
Python
restd.py
rbaylon/py-openbsdb-rest
a14a8cdb2b47c9e3520582e230c9b97cf2c5818f
[ "0BSD" ]
null
null
null
restd.py
rbaylon/py-openbsdb-rest
a14a8cdb2b47c9e3520582e230c9b97cf2c5818f
[ "0BSD" ]
null
null
null
restd.py
rbaylon/py-openbsdb-rest
a14a8cdb2b47c9e3520582e230c9b97cf2c5818f
[ "0BSD" ]
null
null
null
from views import app def main(): print(" * ** Warning this is running in debug mode. For production deployment refer to https://flask.palletsprojects.com/en/1.1.x/deploying/wsgi-standalone/#twisted-web .") app.run(host='0.0.0.0',port=app.config['LISTEN_PORT'],debug=True) if __name__ == '__main__': main()
35.666667
176
0.70405
50
321
4.34
0.8
0.02765
0.02765
0
0
0
0
0
0
0
0
0.021583
0.133956
321
8
177
40.125
0.758993
0
0
0
0
0.166667
0.588785
0
0
0
0
0
0
1
0.166667
true
0
0.166667
0
0.333333
0.166667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
72830b6dbfcd18713d01adfc0295fe9ecf134e7a
159
py
Python
test/resources/python/main.py
Manu343726/biicode-common
91b32c6fd1e4a72ce5451183f1766d313cd0e420
[ "MIT" ]
17
2015-04-15T09:40:23.000Z
2017-05-17T20:34:49.000Z
test/resources/python/main.py
Manu343726/biicode-common
91b32c6fd1e4a72ce5451183f1766d313cd0e420
[ "MIT" ]
2
2015-04-22T11:29:36.000Z
2018-09-25T09:31:09.000Z
test/resources/python/main.py
bowlofstew/common
45e9ca902be7bbbdd73dafe3ab8957bc4a006020
[ "MIT" ]
22
2015-04-15T09:46:00.000Z
2020-09-29T17:03:31.000Z
from functions import * A=leerLista() imprimirLista(A,"A") print ("Promedio = " + str(promediarLista(A))) print("//bii://mhernando/testpython/functions.py")
19.875
50
0.710692
19
159
5.947368
0.736842
0.106195
0
0
0
0
0
0
0
0
0
0
0.09434
159
7
51
22.714286
0.784722
0
0
0
0
0
0.333333
0.257862
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0.4
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
728439aa018979311ec649a68cd3bbc9f2653515
4,101
py
Python
conduit/hydra/conduit/data/datasets/conf.py
wearepal/conduit
a16e575181c0464aa63ee4c029eac19021ce79ba
[ "MIT" ]
null
null
null
conduit/hydra/conduit/data/datasets/conf.py
wearepal/conduit
a16e575181c0464aa63ee4c029eac19021ce79ba
[ "MIT" ]
5
2022-03-18T12:54:45.000Z
2022-03-30T19:14:16.000Z
conduit/hydra/conduit/data/datasets/conf.py
wearepal/conduit
a16e575181c0464aa63ee4c029eac19021ce79ba
[ "MIT" ]
1
2022-03-24T03:52:44.000Z
2022-03-24T03:52:44.000Z
# Generated by configen, do not edit. # See https://github.com/facebookresearch/hydra/tree/master/tools/configen # fmt: off # isort:skip_file # flake8: noqa from dataclasses import dataclass, field from conduit.data.datasets.audio.ecoacoustics import SoundscapeAttr from conduit.data.datasets.vision.camelyon17 import Camelyon17Attr from conduit.data.datasets.vision.camelyon17 import Camelyon17SplitScheme from conduit.data.datasets.vision.celeba import CelebAttr from conduit.data.datasets.vision.isic import IsicAttr from conduit.data.datasets.vision.nico import NicoSuperclass from conduit.data.datasets.vision.ssrp import SSRPSplit from omegaconf import MISSING from typing import Any from typing import Dict from typing import List from typing import Optional @dataclass class CelebAConf: _target_: str = "conduit.data.datasets.CelebA" root: Any = MISSING # Union[str, Path] download: bool = True superclass: Any = CelebAttr.Smiling # Union[CelebAttr, str] subclass: Any = CelebAttr.Male # Union[CelebAttr, str] transform: Any = None # Union[Compose, BasicTransform, Callable[[Image], Any], NoneType] split: Any = None # Union[CelebASplit, str, NoneType] @dataclass class ColoredMNISTConf: _target_: str = "conduit.data.datasets.ColoredMNIST" root: Any = MISSING # Union[str, Path] download: bool = True transform: Any = None # Union[Compose, BasicTransform, Callable[[Image], Any], NoneType] label_map: Optional[Dict[str, int]] = None colors: Optional[List[int]] = None num_colors: int = 10 scale: float = 0.2 correlation: Optional[float] = None binarize: bool = False greyscale: bool = False background: bool = False black: bool = True split: Any = None # Union[ColoredMNISTSplit, str, NoneType] seed: Optional[int] = 42 @dataclass class ISICConf: _target_: str = "conduit.data.datasets.ISIC" root: Any = MISSING # Union[str, Path] download: bool = True max_samples: int = 25000 context_attr: IsicAttr = IsicAttr.histo target_attr: IsicAttr = IsicAttr.malignant transform: Any = None # Union[Compose, BasicTransform, Callable[[Image], Any], NoneType] @dataclass class NICOConf: _target_: str = "conduit.data.datasets.NICO" root: Any = MISSING # Union[str, Path] download: bool = True transform: Any = None # Union[Compose, BasicTransform, Callable[[Image], Any], NoneType] superclass: Any = NicoSuperclass.animals # Union[NicoSuperclass, str, NoneType] @dataclass class SSRPConf: _target_: str = "conduit.data.datasets.SSRP" root: Any = MISSING # Union[str, Path] split: Any = SSRPSplit.pretrain # Union[SSRPSplit, str] download: bool = True transform: Any = None # Union[Compose, BasicTransform, Callable[[Image], Any], NoneType] @dataclass class WaterbirdsConf: _target_: str = "conduit.data.datasets.Waterbirds" root: Any = MISSING # Union[str, Path] download: bool = True transform: Any = None # Union[Compose, BasicTransform, Callable[[Image], Any], NoneType] split: Any = None # Union[WaterbirdsSplit, str, NoneType] @dataclass class Camelyon17Conf: _target_: str = "conduit.data.datasets.Camelyon17" root: Any = MISSING # Union[str, Path] download: bool = True transform: Any = None # Union[Compose, BasicTransform, Callable[[Image], Any], NoneType] split: Any = None # Union[Camelyon17Split, str, NoneType] split_scheme: Any = Camelyon17SplitScheme.official # Union[Camelyon17SplitScheme, str] superclass: Any = Camelyon17Attr.tumor # Union[Camelyon17Attr, str] subclass: Any = Camelyon17Attr.center # Union[Camelyon17Attr, str] @dataclass class EcoacousticsConf: _target_: str = "conduit.data.datasets.Ecoacoustics" root: Any = MISSING # Union[str, Path] transform: Any = None # Optional[Callable[[Tensor], Tensor]] download: bool = True target_attrs: Any = SoundscapeAttr.habitat # Union[SoundscapeAttr, str, List[Union[SoundscapeAttr, str]]] segment_len: Optional[float] = 15 preprocess: bool = False
36.945946
110
0.719581
478
4,101
6.121339
0.261506
0.056391
0.097403
0.054682
0.441217
0.325017
0.307245
0.276487
0.276487
0.247779
0
0.011848
0.176786
4,101
110
111
37.281818
0.854858
0.286759
0
0.409091
1
0
0.082324
0.082324
0
0
0
0
0
1
0
true
0
0.147727
0
0.909091
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
728467b57090013d52b926e9ee033ae932849f38
461
py
Python
projects/mymod.py
jonaslindemann/compute-course-public
b8f55595ebbd790d79b525efdff17b8517154796
[ "MIT" ]
4
2021-09-12T12:07:01.000Z
2021-09-29T17:38:34.000Z
projects/mymod.py
jonaslindemann/compute-course-public
b8f55595ebbd790d79b525efdff17b8517154796
[ "MIT" ]
null
null
null
projects/mymod.py
jonaslindemann/compute-course-public
b8f55595ebbd790d79b525efdff17b8517154796
[ "MIT" ]
5
2020-10-24T16:02:31.000Z
2021-09-28T20:57:46.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 14 14:14:47 2017 @author: bmjl """ class Point: """This is Point class""" def __init__(self): """This is the Point constructur""" print("Point created") def hello(self): """Hello method""" print("Hello") def hello_module(): """Hello function""" print("Hello from mymod.") if __name__ == "__main__": print("My module")
18.44
43
0.557484
57
461
4.280702
0.631579
0.032787
0
0
0
0
0
0
0
0
0
0.041543
0.26898
461
25
44
18.44
0.682493
0.373102
0
0
0
0
0.199234
0
0
0
0
0
0
1
0.333333
false
0
0
0
0.444444
0.444444
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
1
0
2
72880e7198eae24e6724dff6ea95e3bacc422415
38,279
py
Python
python/machinetalk/protobuf/motcmds_pb2.py
luminize/machinetalk-protobuf
6ca7c99806401179ece164b07dc87852bfa8df9c
[ "MIT" ]
null
null
null
python/machinetalk/protobuf/motcmds_pb2.py
luminize/machinetalk-protobuf
6ca7c99806401179ece164b07dc87852bfa8df9c
[ "MIT" ]
null
null
null
python/machinetalk/protobuf/motcmds_pb2.py
luminize/machinetalk-protobuf
6ca7c99806401179ece164b07dc87852bfa8df9c
[ "MIT" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: machinetalk/protobuf/motcmds.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from machinetalk.protobuf import emcclass_pb2 as machinetalk_dot_protobuf_dot_emcclass__pb2 from machinetalk.protobuf import nanopb_pb2 as machinetalk_dot_protobuf_dot_nanopb__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='machinetalk/protobuf/motcmds.proto', package='machinetalk', syntax='proto2', serialized_pb=_b('\n\"machinetalk/protobuf/motcmds.proto\x12\x0bmachinetalk\x1a#machinetalk/protobuf/emcclass.proto\x1a!machinetalk/protobuf/nanopb.proto\"\xa7\x07\n\rMotionCommand\x12(\n\x07\x63ommand\x18\n \x02(\x0e\x32\x17.machinetalk.cmd_code_t\x12\x12\n\ncommandNum\x18\x14 \x02(\x07\x12\x14\n\x0cmotor_offset\x18\x1e \x01(\x01\x12\x10\n\x08maxLimit\x18( \x01(\x01\x12\x10\n\x08minLimit\x18\x32 \x01(\x01\x12!\n\x03pos\x18< \x01(\x0b\x32\x14.machinetalk.EmcPose\x12(\n\x06\x63\x65nter\x18\x46 \x01(\x0b\x32\x18.machinetalk.PmCartesian\x12(\n\x06normal\x18P \x01(\x0b\x32\x18.machinetalk.PmCartesian\x12\x0c\n\x04turn\x18Z \x01(\x07\x12\x0b\n\x03vel\x18\x64 \x01(\x01\x12\x12\n\nini_maxvel\x18n \x01(\x01\x12,\n\x0bmotion_type\x18x \x01(\x0e\x32\x17.machinetalk.MotionType\x12\x14\n\x0bspindlesync\x18\x82\x01 \x01(\x01\x12\x0c\n\x03\x61\x63\x63\x18\x8c\x01 \x01(\x01\x12\x11\n\x08\x62\x61\x63klash\x18\x96\x01 \x01(\x01\x12\x0b\n\x02id\x18\xa0\x01 \x01(\x07\x12\x11\n\x08termCond\x18\xaa\x01 \x01(\x07\x12\x12\n\ttolerance\x18\xb4\x01 \x01(\x01\x12\r\n\x04\x61xis\x18\xbe\x01 \x01(\x07\x12\x0e\n\x05scale\x18\xc8\x01 \x01(\x01\x12\x0f\n\x06offset\x18\xd2\x01 \x01(\x01\x12\r\n\x04home\x18\xdc\x01 \x01(\x01\x12\x17\n\x0ehome_final_vel\x18\xe6\x01 \x01(\x01\x12\x13\n\nsearch_vel\x18\xf0\x01 \x01(\x01\x12\x12\n\tlatch_vel\x18\xfa\x01 \x01(\x01\x12\x0e\n\x05\x66lags\x18\x84\x02 \x01(\x07\x12\x16\n\rhome_sequence\x18\x8e\x02 \x01(\x07\x12\x16\n\rvolatile_home\x18\x98\x02 \x01(\x07\x12\x12\n\tminFerror\x18\xa2\x02 \x01(\x01\x12\x12\n\tmaxFerror\x18\xac\x02 \x01(\x01\x12\x0f\n\x06wdWait\x18\xb6\x02 \x01(\x07\x12\x0e\n\x05\x64\x65\x62ug\x18\xc0\x02 \x01(\x07\x12\x0c\n\x03now\x18\xca\x02 \x01(\x05\x12\x0c\n\x03out\x18\xd4\x02 \x01(\x05\x12\x0e\n\x05start\x18\xde\x02 \x01(\x05\x12\x0c\n\x03\x65nd\x18\xe8\x02 \x01(\x05\x12\r\n\x04mode\x18\xf2\x02 \x01(\x05\x12\x15\n\x0c\x63omp_nominal\x18\xfc\x02 \x01(\x01\x12\x15\n\x0c\x63omp_forward\x18\x86\x03 \x01(\x01\x12\x15\n\x0c\x63omp_reverse\x18\x90\x03 \x01(\x01\x12\x13\n\nprobe_type\x18\x9a\x03 \x01(\x05\x12*\n\x0btool_offset\x18\xa4\x03 \x01(\x0b\x32\x14.machinetalk.EmcPose:\x06\x92?\x03H\xd8\x04\"\xba\x01\n\x0cMotionStatus\x12,\n\x0b\x63ommandEcho\x18\n \x02(\x0e\x32\x17.machinetalk.cmd_code_t\x12\x16\n\x0e\x63ommandNumEcho\x18\x14 \x02(\x07\x12\x30\n\rcommandStatus\x18\x1e \x02(\x0e\x32\x19.machinetalk.cmd_status_t\x12*\n\x0c\x63\x61rte_pos_fb\x18( \x01(\x0b\x32\x14.machinetalk.EmcPose:\x06\x92?\x03H\xd9\x04*\xdc\x01\n\nMotionType\x12\x19\n\x15_EMC_MOTION_TYPE_NONE\x10\x00\x12\x1d\n\x19_EMC_MOTION_TYPE_TRAVERSE\x10\x01\x12\x19\n\x15_EMC_MOTION_TYPE_FEED\x10\x02\x12\x18\n\x14_EMC_MOTION_TYPE_ARC\x10\x03\x12\x1f\n\x1b_EMC_MOTION_TYPE_TOOLCHANGE\x10\x04\x12\x1c\n\x18_EMC_MOTION_TYPE_PROBING\x10\x05\x12 \n\x1c_EMC_MOTION_TYPE_INDEXROTARY\x10\x06*\xfb\x0b\n\ncmd_code_t\x12\x11\n\x0c\x45MCMOT_ABORT\x10\xa0\x1f\x12\x16\n\x11\x45MCMOT_AXIS_ABORT\x10\xa1\x1f\x12\x12\n\rEMCMOT_ENABLE\x10\xa2\x1f\x12\x13\n\x0e\x45MCMOT_DISABLE\x10\xa3\x1f\x12\x1c\n\x17\x45MCMOT_ENABLE_AMPLIFIER\x10\xa4\x1f\x12\x1d\n\x18\x45MCMOT_DISABLE_AMPLIFIER\x10\xa5\x1f\x12\x1b\n\x16\x45MCMOT_ENABLE_WATCHDOG\x10\xa6\x1f\x12\x1c\n\x17\x45MCMOT_DISABLE_WATCHDOG\x10\xa7\x1f\x12\x1a\n\x15\x45MCMOT_ACTIVATE_JOINT\x10\xa8\x1f\x12\x1c\n\x17\x45MCMOT_DEACTIVATE_JOINT\x10\xa9\x1f\x12\x11\n\x0c\x45MCMOT_PAUSE\x10\xaa\x1f\x12\x12\n\rEMCMOT_RESUME\x10\xab\x1f\x12\x10\n\x0b\x45MCMOT_STEP\x10\xac\x1f\x12\x10\n\x0b\x45MCMOT_FREE\x10\xad\x1f\x12\x11\n\x0c\x45MCMOT_COORD\x10\xae\x1f\x12\x12\n\rEMCMOT_TELEOP\x10\xaf\x1f\x12\x19\n\x14\x45MCMOT_SPINDLE_SCALE\x10\xb0\x1f\x12\x15\n\x10\x45MCMOT_SS_ENABLE\x10\xb1\x1f\x12\x16\n\x11\x45MCMOT_FEED_SCALE\x10\xb2\x1f\x12\x15\n\x10\x45MCMOT_FS_ENABLE\x10\xb3\x1f\x12\x15\n\x10\x45MCMOT_FH_ENABLE\x10\xb4\x1f\x12\x15\n\x10\x45MCMOT_AF_ENABLE\x10\xb5\x1f\x12\x1b\n\x16\x45MCMOT_OVERRIDE_LIMITS\x10\xb6\x1f\x12\x10\n\x0b\x45MCMOT_HOME\x10\xb7\x1f\x12\x12\n\rEMCMOT_UNHOME\x10\xb8\x1f\x12\x14\n\x0f\x45MCMOT_JOG_CONT\x10\xb9\x1f\x12\x14\n\x0f\x45MCMOT_JOG_INCR\x10\xba\x1f\x12\x13\n\x0e\x45MCMOT_JOG_ABS\x10\xbb\x1f\x12\x14\n\x0f\x45MCMOT_SET_LINE\x10\xbc\x1f\x12\x16\n\x11\x45MCMOT_SET_CIRCLE\x10\xbd\x1f\x12\x1d\n\x18\x45MCMOT_SET_TELEOP_VECTOR\x10\xbe\x1f\x12\x1d\n\x18\x45MCMOT_CLEAR_PROBE_FLAGS\x10\xbf\x1f\x12\x11\n\x0c\x45MCMOT_PROBE\x10\xc0\x1f\x12\x15\n\x10\x45MCMOT_RIGID_TAP\x10\xc1\x1f\x12\x1f\n\x1a\x45MCMOT_SET_POSITION_LIMITS\x10\xc2\x1f\x12\x18\n\x13\x45MCMOT_SET_BACKLASH\x10\xc3\x1f\x12\x1a\n\x15\x45MCMOT_SET_MIN_FERROR\x10\xc4\x1f\x12\x1a\n\x15\x45MCMOT_SET_MAX_FERROR\x10\xc5\x1f\x12\x13\n\x0e\x45MCMOT_SET_VEL\x10\xc6\x1f\x12\x19\n\x14\x45MCMOT_SET_VEL_LIMIT\x10\xc7\x1f\x12\x1f\n\x1a\x45MCMOT_SET_JOINT_VEL_LIMIT\x10\xc8\x1f\x12\x1f\n\x1a\x45MCMOT_SET_JOINT_ACC_LIMIT\x10\xc9\x1f\x12\x13\n\x0e\x45MCMOT_SET_ACC\x10\xca\x1f\x12\x19\n\x14\x45MCMOT_SET_TERM_COND\x10\xcb\x1f\x12\x18\n\x13\x45MCMOT_SET_NUM_AXES\x10\xcc\x1f\x12\x1a\n\x15\x45MCMOT_SET_WORLD_HOME\x10\xcd\x1f\x12\x1d\n\x18\x45MCMOT_SET_HOMING_PARAMS\x10\xce\x1f\x12\x15\n\x10\x45MCMOT_SET_DEBUG\x10\xcf\x1f\x12\x14\n\x0f\x45MCMOT_SET_DOUT\x10\xd0\x1f\x12\x14\n\x0f\x45MCMOT_SET_AOUT\x10\xd1\x1f\x12\x1b\n\x16\x45MCMOT_SET_SPINDLESYNC\x10\xd2\x1f\x12\x16\n\x11\x45MCMOT_SPINDLE_ON\x10\xd3\x1f\x12\x17\n\x12\x45MCMOT_SPINDLE_OFF\x10\xd4\x1f\x12\x1c\n\x17\x45MCMOT_SPINDLE_INCREASE\x10\xd5\x1f\x12\x1c\n\x17\x45MCMOT_SPINDLE_DECREASE\x10\xd6\x1f\x12 \n\x1b\x45MCMOT_SPINDLE_BRAKE_ENGAGE\x10\xd7\x1f\x12!\n\x1c\x45MCMOT_SPINDLE_BRAKE_RELEASE\x10\xd8\x1f\x12\x1c\n\x17\x45MCMOT_SET_MOTOR_OFFSET\x10\xd9\x1f\x12\x1a\n\x15\x45MCMOT_SET_JOINT_COMP\x10\xda\x1f\x12\x16\n\x11\x45MCMOT_SET_OFFSET\x10\xdb\x1f*\xad\x01\n\x0c\x63md_status_t\x12\x15\n\x11\x45MCMOT_COMMAND_OK\x10\x00\x12\"\n\x1e\x45MCMOT_COMMAND_UNKNOWN_COMMAND\x10\x01\x12\"\n\x1e\x45MCMOT_COMMAND_INVALID_COMMAND\x10\x02\x12!\n\x1d\x45MCMOT_COMMAND_INVALID_PARAMS\x10\x03\x12\x1b\n\x17\x45MCMOT_COMMAND_BAD_EXEC\x10\x04') , dependencies=[machinetalk_dot_protobuf_dot_emcclass__pb2.DESCRIPTOR,machinetalk_dot_protobuf_dot_nanopb__pb2.DESCRIPTOR,]) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _MOTIONTYPE = _descriptor.EnumDescriptor( name='MotionType', full_name='machinetalk.MotionType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='_EMC_MOTION_TYPE_NONE', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='_EMC_MOTION_TYPE_TRAVERSE', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='_EMC_MOTION_TYPE_FEED', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='_EMC_MOTION_TYPE_ARC', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='_EMC_MOTION_TYPE_TOOLCHANGE', index=4, number=4, options=None, type=None), _descriptor.EnumValueDescriptor( name='_EMC_MOTION_TYPE_PROBING', index=5, number=5, options=None, type=None), _descriptor.EnumValueDescriptor( name='_EMC_MOTION_TYPE_INDEXROTARY', index=6, number=6, options=None, type=None), ], containing_type=None, options=None, serialized_start=1251, serialized_end=1471, ) _sym_db.RegisterEnumDescriptor(_MOTIONTYPE) MotionType = enum_type_wrapper.EnumTypeWrapper(_MOTIONTYPE) _CMD_CODE_T = _descriptor.EnumDescriptor( name='cmd_code_t', full_name='machinetalk.cmd_code_t', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='EMCMOT_ABORT', index=0, number=4000, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_AXIS_ABORT', index=1, number=4001, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_ENABLE', index=2, number=4002, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_DISABLE', index=3, number=4003, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_ENABLE_AMPLIFIER', index=4, number=4004, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_DISABLE_AMPLIFIER', index=5, number=4005, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_ENABLE_WATCHDOG', index=6, number=4006, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_DISABLE_WATCHDOG', index=7, number=4007, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_ACTIVATE_JOINT', index=8, number=4008, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_DEACTIVATE_JOINT', index=9, number=4009, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_PAUSE', index=10, number=4010, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_RESUME', index=11, number=4011, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_STEP', index=12, number=4012, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_FREE', index=13, number=4013, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_COORD', index=14, number=4014, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_TELEOP', index=15, number=4015, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SPINDLE_SCALE', index=16, number=4016, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SS_ENABLE', index=17, number=4017, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_FEED_SCALE', index=18, number=4018, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_FS_ENABLE', index=19, number=4019, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_FH_ENABLE', index=20, number=4020, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_AF_ENABLE', index=21, number=4021, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_OVERRIDE_LIMITS', index=22, number=4022, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_HOME', index=23, number=4023, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_UNHOME', index=24, number=4024, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_JOG_CONT', index=25, number=4025, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_JOG_INCR', index=26, number=4026, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_JOG_ABS', index=27, number=4027, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_LINE', index=28, number=4028, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_CIRCLE', index=29, number=4029, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_TELEOP_VECTOR', index=30, number=4030, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_CLEAR_PROBE_FLAGS', index=31, number=4031, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_PROBE', index=32, number=4032, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_RIGID_TAP', index=33, number=4033, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_POSITION_LIMITS', index=34, number=4034, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_BACKLASH', index=35, number=4035, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_MIN_FERROR', index=36, number=4036, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_MAX_FERROR', index=37, number=4037, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_VEL', index=38, number=4038, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_VEL_LIMIT', index=39, number=4039, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_JOINT_VEL_LIMIT', index=40, number=4040, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_JOINT_ACC_LIMIT', index=41, number=4041, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_ACC', index=42, number=4042, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_TERM_COND', index=43, number=4043, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_NUM_AXES', index=44, number=4044, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_WORLD_HOME', index=45, number=4045, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_HOMING_PARAMS', index=46, number=4046, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_DEBUG', index=47, number=4047, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_DOUT', index=48, number=4048, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_AOUT', index=49, number=4049, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_SPINDLESYNC', index=50, number=4050, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SPINDLE_ON', index=51, number=4051, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SPINDLE_OFF', index=52, number=4052, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SPINDLE_INCREASE', index=53, number=4053, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SPINDLE_DECREASE', index=54, number=4054, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SPINDLE_BRAKE_ENGAGE', index=55, number=4055, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SPINDLE_BRAKE_RELEASE', index=56, number=4056, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_MOTOR_OFFSET', index=57, number=4057, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_JOINT_COMP', index=58, number=4058, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_SET_OFFSET', index=59, number=4059, options=None, type=None), ], containing_type=None, options=None, serialized_start=1474, serialized_end=3005, ) _sym_db.RegisterEnumDescriptor(_CMD_CODE_T) cmd_code_t = enum_type_wrapper.EnumTypeWrapper(_CMD_CODE_T) _CMD_STATUS_T = _descriptor.EnumDescriptor( name='cmd_status_t', full_name='machinetalk.cmd_status_t', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='EMCMOT_COMMAND_OK', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_COMMAND_UNKNOWN_COMMAND', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_COMMAND_INVALID_COMMAND', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_COMMAND_INVALID_PARAMS', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='EMCMOT_COMMAND_BAD_EXEC', index=4, number=4, options=None, type=None), ], containing_type=None, options=None, serialized_start=3008, serialized_end=3181, ) _sym_db.RegisterEnumDescriptor(_CMD_STATUS_T) cmd_status_t = enum_type_wrapper.EnumTypeWrapper(_CMD_STATUS_T) _EMC_MOTION_TYPE_NONE = 0 _EMC_MOTION_TYPE_TRAVERSE = 1 _EMC_MOTION_TYPE_FEED = 2 _EMC_MOTION_TYPE_ARC = 3 _EMC_MOTION_TYPE_TOOLCHANGE = 4 _EMC_MOTION_TYPE_PROBING = 5 _EMC_MOTION_TYPE_INDEXROTARY = 6 EMCMOT_ABORT = 4000 EMCMOT_AXIS_ABORT = 4001 EMCMOT_ENABLE = 4002 EMCMOT_DISABLE = 4003 EMCMOT_ENABLE_AMPLIFIER = 4004 EMCMOT_DISABLE_AMPLIFIER = 4005 EMCMOT_ENABLE_WATCHDOG = 4006 EMCMOT_DISABLE_WATCHDOG = 4007 EMCMOT_ACTIVATE_JOINT = 4008 EMCMOT_DEACTIVATE_JOINT = 4009 EMCMOT_PAUSE = 4010 EMCMOT_RESUME = 4011 EMCMOT_STEP = 4012 EMCMOT_FREE = 4013 EMCMOT_COORD = 4014 EMCMOT_TELEOP = 4015 EMCMOT_SPINDLE_SCALE = 4016 EMCMOT_SS_ENABLE = 4017 EMCMOT_FEED_SCALE = 4018 EMCMOT_FS_ENABLE = 4019 EMCMOT_FH_ENABLE = 4020 EMCMOT_AF_ENABLE = 4021 EMCMOT_OVERRIDE_LIMITS = 4022 EMCMOT_HOME = 4023 EMCMOT_UNHOME = 4024 EMCMOT_JOG_CONT = 4025 EMCMOT_JOG_INCR = 4026 EMCMOT_JOG_ABS = 4027 EMCMOT_SET_LINE = 4028 EMCMOT_SET_CIRCLE = 4029 EMCMOT_SET_TELEOP_VECTOR = 4030 EMCMOT_CLEAR_PROBE_FLAGS = 4031 EMCMOT_PROBE = 4032 EMCMOT_RIGID_TAP = 4033 EMCMOT_SET_POSITION_LIMITS = 4034 EMCMOT_SET_BACKLASH = 4035 EMCMOT_SET_MIN_FERROR = 4036 EMCMOT_SET_MAX_FERROR = 4037 EMCMOT_SET_VEL = 4038 EMCMOT_SET_VEL_LIMIT = 4039 EMCMOT_SET_JOINT_VEL_LIMIT = 4040 EMCMOT_SET_JOINT_ACC_LIMIT = 4041 EMCMOT_SET_ACC = 4042 EMCMOT_SET_TERM_COND = 4043 EMCMOT_SET_NUM_AXES = 4044 EMCMOT_SET_WORLD_HOME = 4045 EMCMOT_SET_HOMING_PARAMS = 4046 EMCMOT_SET_DEBUG = 4047 EMCMOT_SET_DOUT = 4048 EMCMOT_SET_AOUT = 4049 EMCMOT_SET_SPINDLESYNC = 4050 EMCMOT_SPINDLE_ON = 4051 EMCMOT_SPINDLE_OFF = 4052 EMCMOT_SPINDLE_INCREASE = 4053 EMCMOT_SPINDLE_DECREASE = 4054 EMCMOT_SPINDLE_BRAKE_ENGAGE = 4055 EMCMOT_SPINDLE_BRAKE_RELEASE = 4056 EMCMOT_SET_MOTOR_OFFSET = 4057 EMCMOT_SET_JOINT_COMP = 4058 EMCMOT_SET_OFFSET = 4059 EMCMOT_COMMAND_OK = 0 EMCMOT_COMMAND_UNKNOWN_COMMAND = 1 EMCMOT_COMMAND_INVALID_COMMAND = 2 EMCMOT_COMMAND_INVALID_PARAMS = 3 EMCMOT_COMMAND_BAD_EXEC = 4 _MOTIONCOMMAND = _descriptor.Descriptor( name='MotionCommand', full_name='machinetalk.MotionCommand', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='command', full_name='machinetalk.MotionCommand.command', index=0, number=10, type=14, cpp_type=8, label=2, has_default_value=False, default_value=4000, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='commandNum', full_name='machinetalk.MotionCommand.commandNum', index=1, number=20, type=7, cpp_type=3, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='motor_offset', full_name='machinetalk.MotionCommand.motor_offset', index=2, number=30, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='maxLimit', full_name='machinetalk.MotionCommand.maxLimit', index=3, number=40, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='minLimit', full_name='machinetalk.MotionCommand.minLimit', index=4, number=50, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='pos', full_name='machinetalk.MotionCommand.pos', index=5, number=60, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='center', full_name='machinetalk.MotionCommand.center', index=6, number=70, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='normal', full_name='machinetalk.MotionCommand.normal', index=7, number=80, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='turn', full_name='machinetalk.MotionCommand.turn', index=8, number=90, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='vel', full_name='machinetalk.MotionCommand.vel', index=9, number=100, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='ini_maxvel', full_name='machinetalk.MotionCommand.ini_maxvel', index=10, number=110, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='motion_type', full_name='machinetalk.MotionCommand.motion_type', index=11, number=120, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='spindlesync', full_name='machinetalk.MotionCommand.spindlesync', index=12, number=130, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='acc', full_name='machinetalk.MotionCommand.acc', index=13, number=140, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='backlash', full_name='machinetalk.MotionCommand.backlash', index=14, number=150, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='id', full_name='machinetalk.MotionCommand.id', index=15, number=160, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='termCond', full_name='machinetalk.MotionCommand.termCond', index=16, number=170, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='tolerance', full_name='machinetalk.MotionCommand.tolerance', index=17, number=180, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='axis', full_name='machinetalk.MotionCommand.axis', index=18, number=190, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='scale', full_name='machinetalk.MotionCommand.scale', index=19, number=200, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='offset', full_name='machinetalk.MotionCommand.offset', index=20, number=210, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='home', full_name='machinetalk.MotionCommand.home', index=21, number=220, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='home_final_vel', full_name='machinetalk.MotionCommand.home_final_vel', index=22, number=230, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='search_vel', full_name='machinetalk.MotionCommand.search_vel', index=23, number=240, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='latch_vel', full_name='machinetalk.MotionCommand.latch_vel', index=24, number=250, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='flags', full_name='machinetalk.MotionCommand.flags', index=25, number=260, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='home_sequence', full_name='machinetalk.MotionCommand.home_sequence', index=26, number=270, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='volatile_home', full_name='machinetalk.MotionCommand.volatile_home', index=27, number=280, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='minFerror', full_name='machinetalk.MotionCommand.minFerror', index=28, number=290, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='maxFerror', full_name='machinetalk.MotionCommand.maxFerror', index=29, number=300, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='wdWait', full_name='machinetalk.MotionCommand.wdWait', index=30, number=310, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='debug', full_name='machinetalk.MotionCommand.debug', index=31, number=320, type=7, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='now', full_name='machinetalk.MotionCommand.now', index=32, number=330, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='out', full_name='machinetalk.MotionCommand.out', index=33, number=340, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='start', full_name='machinetalk.MotionCommand.start', index=34, number=350, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='end', full_name='machinetalk.MotionCommand.end', index=35, number=360, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='mode', full_name='machinetalk.MotionCommand.mode', index=36, number=370, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='comp_nominal', full_name='machinetalk.MotionCommand.comp_nominal', index=37, number=380, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='comp_forward', full_name='machinetalk.MotionCommand.comp_forward', index=38, number=390, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='comp_reverse', full_name='machinetalk.MotionCommand.comp_reverse', index=39, number=400, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='probe_type', full_name='machinetalk.MotionCommand.probe_type', index=40, number=410, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='tool_offset', full_name='machinetalk.MotionCommand.tool_offset', index=41, number=420, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('\222?\003H\330\004')), is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=124, serialized_end=1059, ) _MOTIONSTATUS = _descriptor.Descriptor( name='MotionStatus', full_name='machinetalk.MotionStatus', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='commandEcho', full_name='machinetalk.MotionStatus.commandEcho', index=0, number=10, type=14, cpp_type=8, label=2, has_default_value=False, default_value=4000, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='commandNumEcho', full_name='machinetalk.MotionStatus.commandNumEcho', index=1, number=20, type=7, cpp_type=3, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='commandStatus', full_name='machinetalk.MotionStatus.commandStatus', index=2, number=30, type=14, cpp_type=8, label=2, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='carte_pos_fb', full_name='machinetalk.MotionStatus.carte_pos_fb', index=3, number=40, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('\222?\003H\331\004')), is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=1062, serialized_end=1248, ) _MOTIONCOMMAND.fields_by_name['command'].enum_type = _CMD_CODE_T _MOTIONCOMMAND.fields_by_name['pos'].message_type = machinetalk_dot_protobuf_dot_emcclass__pb2._EMCPOSE _MOTIONCOMMAND.fields_by_name['center'].message_type = machinetalk_dot_protobuf_dot_emcclass__pb2._PMCARTESIAN _MOTIONCOMMAND.fields_by_name['normal'].message_type = machinetalk_dot_protobuf_dot_emcclass__pb2._PMCARTESIAN _MOTIONCOMMAND.fields_by_name['motion_type'].enum_type = _MOTIONTYPE _MOTIONCOMMAND.fields_by_name['tool_offset'].message_type = machinetalk_dot_protobuf_dot_emcclass__pb2._EMCPOSE _MOTIONSTATUS.fields_by_name['commandEcho'].enum_type = _CMD_CODE_T _MOTIONSTATUS.fields_by_name['commandStatus'].enum_type = _CMD_STATUS_T _MOTIONSTATUS.fields_by_name['carte_pos_fb'].message_type = machinetalk_dot_protobuf_dot_emcclass__pb2._EMCPOSE DESCRIPTOR.message_types_by_name['MotionCommand'] = _MOTIONCOMMAND DESCRIPTOR.message_types_by_name['MotionStatus'] = _MOTIONSTATUS DESCRIPTOR.enum_types_by_name['MotionType'] = _MOTIONTYPE DESCRIPTOR.enum_types_by_name['cmd_code_t'] = _CMD_CODE_T DESCRIPTOR.enum_types_by_name['cmd_status_t'] = _CMD_STATUS_T MotionCommand = _reflection.GeneratedProtocolMessageType('MotionCommand', (_message.Message,), dict( DESCRIPTOR = _MOTIONCOMMAND, __module__ = 'machinetalk.protobuf.motcmds_pb2' # @@protoc_insertion_point(class_scope:machinetalk.MotionCommand) )) _sym_db.RegisterMessage(MotionCommand) MotionStatus = _reflection.GeneratedProtocolMessageType('MotionStatus', (_message.Message,), dict( DESCRIPTOR = _MOTIONSTATUS, __module__ = 'machinetalk.protobuf.motcmds_pb2' # @@protoc_insertion_point(class_scope:machinetalk.MotionStatus) )) _sym_db.RegisterMessage(MotionStatus) _MOTIONCOMMAND.has_options = True _MOTIONCOMMAND._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('\222?\003H\330\004')) _MOTIONSTATUS.has_options = True _MOTIONSTATUS._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('\222?\003H\331\004')) # @@protoc_insertion_point(module_scope)
45.461995
5,932
0.740145
5,246
38,279
5.127335
0.107701
0.064838
0.088334
0.050859
0.643059
0.592721
0.556398
0.525764
0.477099
0.39304
0
0.078335
0.138927
38,279
841
5,933
45.516052
0.73772
0.007811
0
0.617178
1
0.001227
0.257262
0.222026
0
0
0
0
0
1
0
false
0
0.011043
0
0.011043
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
7294d1181530285bddeaf8f07673356f400020ff
165
py
Python
ex2_openVideo.py
Yasir323/Image-Processing
1301492444182ee89eb20f37571e2f18b58de8eb
[ "MIT" ]
null
null
null
ex2_openVideo.py
Yasir323/Image-Processing
1301492444182ee89eb20f37571e2f18b58de8eb
[ "MIT" ]
null
null
null
ex2_openVideo.py
Yasir323/Image-Processing
1301492444182ee89eb20f37571e2f18b58de8eb
[ "MIT" ]
null
null
null
import cv2 cap = cv2.VideoCapture("data/video.mp4") while True: success, img = cap.read() cv2.imshow("Video", img) if cv2.waitKey(1) & 0xFF == ord('q'): break
18.333333
40
0.654545
26
165
4.153846
0.769231
0
0
0
0
0
0
0
0
0
0
0.05036
0.157576
165
9
41
18.333333
0.726619
0
0
0
0
0
0.120482
0
0
0
0.024096
0
0
1
0
false
0
0.142857
0
0.142857
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
72a17854a9b4eb18bf677c7d5d99ee524ea883d7
93
py
Python
pyctm/memory/kafka/k_distributed_memory_behavior.py
CST-Group/PyCTM
c42b6141fb0488a7ec16d7e7563184c4859f02a3
[ "MIT" ]
null
null
null
pyctm/memory/kafka/k_distributed_memory_behavior.py
CST-Group/PyCTM
c42b6141fb0488a7ec16d7e7563184c4859f02a3
[ "MIT" ]
null
null
null
pyctm/memory/kafka/k_distributed_memory_behavior.py
CST-Group/PyCTM
c42b6141fb0488a7ec16d7e7563184c4859f02a3
[ "MIT" ]
null
null
null
import enum class KDistributedMemoryBehavior(enum.Enum): TRIGGERED = 0, PULLED = 1
13.285714
44
0.709677
10
93
6.6
0.8
0
0
0
0
0
0
0
0
0
0
0.027397
0.215054
93
6
45
15.5
0.876712
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.25
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
72a92a68a1303a86e463f38ae9012a703ac97f63
841
py
Python
provision/Config/action-env.py
AzureAppDev/aks-demos
4714c11860007df549abfab72aa5b712dba3e7bc
[ "MIT" ]
null
null
null
provision/Config/action-env.py
AzureAppDev/aks-demos
4714c11860007df549abfab72aa5b712dba3e7bc
[ "MIT" ]
null
null
null
provision/Config/action-env.py
AzureAppDev/aks-demos
4714c11860007df549abfab72aa5b712dba3e7bc
[ "MIT" ]
null
null
null
import sys environment = sys.argv[1] region_name = sys.argv[2] app_code = sys.argv[3] version = sys.argv[4] def regionCode(region_name): return f"{region_name[0:1]}{region_name[-1:]}" def resourceEnv(app_code, version, env): return f"{app_code}-env{version}-{env}" def resourceEnvCompact(app_code, version, env): return f"{app_code}env{version}{env}" def outputVariable(output_name, value): print(f"::set-output name={output_name}::{value}") key_vault_name = f"kv-{resourceEnv(app_code, version, environment)}" registry_name = f"acr{resourceEnvCompact(app_code, version, environment)}" registry_group_name = f"rg-{resourceEnv(app_code, version, environment)}" outputVariable("key_vault_name", key_vault_name) outputVariable("registry_name", registry_name) outputVariable("registry_group_name", registry_group_name)
28.033333
74
0.757432
120
841
5.066667
0.275
0.092105
0.115132
0.123355
0.340461
0.154605
0.154605
0.154605
0.154605
0.154605
0
0.009223
0.097503
841
29
75
29
0.791831
0
0
0
0
0
0.392601
0.239857
0
0
0
0
0
1
0.210526
false
0
0.052632
0.157895
0.421053
0.052632
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
72ae7de07f0bd276d094c56045f7d626074e2179
990
py
Python
src/cdpy/cdpy.py
rch/cdpy
3cb9bad11ac08d5dc546a9bf91a2836067fa042c
[ "Apache-2.0" ]
null
null
null
src/cdpy/cdpy.py
rch/cdpy
3cb9bad11ac08d5dc546a9bf91a2836067fa042c
[ "Apache-2.0" ]
null
null
null
src/cdpy/cdpy.py
rch/cdpy
3cb9bad11ac08d5dc546a9bf91a2836067fa042c
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ For Wrapping interactions with the Cloudera CDP CLI """ from cdpy.common import CdpSdkBase from cdpy.iam import CdpyIam from cdpy.environments import CdpyEnvironments from cdpy.datahub import CdpyDatahub from cdpy.datalake import CdpyDatalake from cdpy.ml import CdpyMl from cdpy.de import CdpyDe from cdpy.opdb import CdpyOpdb from cdpy.dw import CdpyDw from cdpy.df import CdpyDf class Cdpy(CdpSdkBase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.iam = CdpyIam(*args, **kwargs) self.environments = CdpyEnvironments(*args, **kwargs) self.datahub = CdpyDatahub(*args, **kwargs) self.datalake = CdpyDatalake(*args, **kwargs) self.ml = CdpyMl(*args, **kwargs) self.de = CdpyDe(*args, **kwargs) self.opdb = CdpyOpdb(*args, **kwargs) self.dw = CdpyDw(*args, **kwargs) self.df = CdpyDf(*args, **kwargs) self.de = CdpyDe(*args, **kwargs)
30
61
0.671717
123
990
5.341463
0.333333
0.182648
0.21309
0.048706
0.097412
0.097412
0.097412
0
0
0
0
0.001266
0.20202
990
32
62
30.9375
0.83038
0.074747
0
0.086957
0
0
0
0
0
0
0
0
0
1
0.043478
false
0
0.434783
0
0.521739
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
72b034a143a1f416c7e34fe11506d26efb4b3abc
169
py
Python
computesquare.py
kmuehlbauer/gitdemoerad2018
4dcb553d54d41c2c4d0399bbe155238621aa5d6e
[ "MIT" ]
null
null
null
computesquare.py
kmuehlbauer/gitdemoerad2018
4dcb553d54d41c2c4d0399bbe155238621aa5d6e
[ "MIT" ]
2
2018-07-01T09:33:05.000Z
2018-07-01T09:33:08.000Z
computesquare.py
kmuehlbauer/gitdemoerad2018
4dcb553d54d41c2c4d0399bbe155238621aa5d6e
[ "MIT" ]
2
2018-07-01T09:08:51.000Z
2018-07-01T09:09:56.000Z
def squareme(x): return(x**2) myvar = input("Give me a number to square: ") myvar = float(myvar) print("The square of %f is %f." % (myvar, squareme(myvar)) )
13
60
0.615385
27
169
3.851852
0.703704
0
0
0
0
0
0
0
0
0
0
0.007519
0.213018
169
12
61
14.083333
0.774436
0
0
0
0
0
0.307229
0
0
0
0
0
0
1
0.2
false
0
0
0.2
0.2
0.2
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
0
0
0
2
72cfab5b79e200bdf7ce464a3b5f34799427b607
1,409
py
Python
models/em/em_model.py
SPS-UCF/Python-Intro-Physics-Solver
abb83811473b700aaba540fd382f05c1a1bb8c50
[ "MIT" ]
3
2017-10-19T19:44:46.000Z
2021-12-08T02:13:26.000Z
models/em/em_model.py
A-Hopkins/Python-Intro-Physics-Solver
fb591af00705fb14106b07f20d8f41c4abe28d89
[ "MIT" ]
4
2017-10-19T21:08:13.000Z
2018-05-21T17:28:14.000Z
models/em/em_model.py
A-Hopkins/Python-Intro-Physics-Solver
fb591af00705fb14106b07f20d8f41c4abe28d89
[ "MIT" ]
4
2017-10-19T19:16:37.000Z
2021-08-19T21:50:04.000Z
""" Created by Alex Hopkins on 10/19/18 Model for Electricity and Magnetism. In this module there are functions that calculate the basic questions of physics 2. """ from models.em import em_plotting as emplt import numpy as np def coulomb_force(q1, q2, r): """ Calculates the force between two point charges. Applying coulombs law of F = k * q_1 * q_2 / r ** 2 to find the force of attraction/repulsion between two charges based on their distance from each other. :param q1: Scalar: Charge given in Coulombs :param q2: Scalar: Charge given in Coulombs :param r: Scalar: Distance between two charges given in meters :return: Scalar: Force between the two charges, given as Newtons """ k = 8.987e9 # N * m ** 2 / C ** 2 force = k * (q1 * q2) / r ** 2 return force def electric_field(q, r, x, y): """ Return the electric field vector E=(Ex,Ey) due to charge q at r. :param q: Scalar: Charge given in Coulombs :param r: Tuple: Vector x, y components, distance between two charges given in meters :param x: Mesh: X values of a grid :param y: Mesh: Y values of a grid :return: Vector: Force between the two charges, given as Newtons """ return q * (x - r[0]) / np.hypot(x - r[0], y - r[1]) ** 3, q * (y - r[1]) / np.hypot(x - r[0], y - r[1]) ** 3 def n_electric_field(nq): return emplt.e_field_plotter(nq)
27.627451
117
0.652236
237
1,409
3.839662
0.405063
0.054945
0.065934
0.062637
0.307692
0.307692
0.272527
0.116484
0.030769
0
0
0.030189
0.247693
1,409
50
118
28.18
0.828302
0.661462
0
0
0
0
0
0
0
0
0
0
0
1
0.3
false
0
0.2
0.1
0.8
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
72e20d4d7d714d9e910c8297488ec2b3d514bded
170
py
Python
nlp100/01.py
walkingmask/expr4-dm-2016
b62d4c9d57ea8e4efe044fc98e4bdc365e87666d
[ "MIT" ]
null
null
null
nlp100/01.py
walkingmask/expr4-dm-2016
b62d4c9d57ea8e4efe044fc98e4bdc365e87666d
[ "MIT" ]
null
null
null
nlp100/01.py
walkingmask/expr4-dm-2016
b62d4c9d57ea8e4efe044fc98e4bdc365e87666d
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 01.py # 2016/10/05(Wed) # walkingmask mojiretsu="パタトクカシーー" print(mojiretsu[1]+mojiretsu[3]+mojiretsu[5]+mojiretsu[7])
15.454545
58
0.670588
25
170
4.56
0.84
0
0
0
0
0
0
0
0
0
0
0.105263
0.105882
170
10
59
17
0.644737
0.452941
0
0
0
0
0.090909
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
72e8344cc451dd2f47dcde8c0b9fa42537364366
456
py
Python
lib/watchopticalutils/watchopticalutils/histoutils/__init__.py
davehadley/watchoptical
a3a999b1318b021a319497c6c23624051a1b1cb3
[ "MIT" ]
null
null
null
lib/watchopticalutils/watchopticalutils/histoutils/__init__.py
davehadley/watchoptical
a3a999b1318b021a319497c6c23624051a1b1cb3
[ "MIT" ]
null
null
null
lib/watchopticalutils/watchopticalutils/histoutils/__init__.py
davehadley/watchoptical
a3a999b1318b021a319497c6c23624051a1b1cb3
[ "MIT" ]
null
null
null
from .categoryhistogram import CategoryHistogram from .categoryhistplot import categoryhistplot from .categorymean import CategoryMean from .categorymeanplot import categorymeanplot from .exposureweightedhistogram import ExposureWeightedHistogram from .sumhistogrammap import sumhistogrammap __all__ = [ "CategoryHistogram", "categoryhistplot", "ExposureWeightedHistogram", "sumhistogrammap", "CategoryMean", "categorymeanplot", ]
28.5
64
0.811404
31
456
11.806452
0.290323
0
0
0
0
0
0
0
0
0
0
0
0.129386
456
15
65
30.4
0.921914
0
0
0
0
0
0.221491
0.054825
0
0
0
0
0
1
0
false
0
0.428571
0
0.428571
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
72f0068fe3399ea7ca9b2409e0ccdc364bdb232a
560
py
Python
contact/models.py
85599/my-first-contact-app
dda8c12cd9232ee6f962d11e18c397d9c5a2f251
[ "MIT" ]
null
null
null
contact/models.py
85599/my-first-contact-app
dda8c12cd9232ee6f962d11e18c397d9c5a2f251
[ "MIT" ]
null
null
null
contact/models.py
85599/my-first-contact-app
dda8c12cd9232ee6f962d11e18c397d9c5a2f251
[ "MIT" ]
null
null
null
from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.utils import timezone class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email = models.EmailField(max_length=250) phone = PhoneNumberField() def publish(self): self.published_date = timezone.now() self.save() def full_name(self): return '{} {}'.format(self.first_name, self.last_name) def __str__(self): return self.full_name()
26.666667
62
0.707143
71
560
5.366197
0.507042
0.070866
0.099738
0.115486
0.15748
0.15748
0
0
0
0
0
0.015453
0.191071
560
20
63
28
0.825607
0
0
0
0
0
0.008929
0
0
0
0
0
0
1
0.2
false
0
0.2
0.133333
0.866667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
72f98f80375bacb3e258481a5c8c4ae1053a3213
507
py
Python
starfish/agent/authentication/authentication_token.py
datacraft-dsc/starfish-py
95ff24410f056e8e2d313c3af97439fe003e294a
[ "Apache-2.0" ]
4
2019-02-08T03:47:36.000Z
2019-10-17T21:45:23.000Z
starfish/agent/authentication/authentication_token.py
datacraft-dsc/starfish-py
95ff24410f056e8e2d313c3af97439fe003e294a
[ "Apache-2.0" ]
81
2019-02-09T01:01:51.000Z
2020-07-01T08:35:07.000Z
starfish/agent/authentication/authentication_token.py
oceanprotocol/ocean-py
318ad0de2519e61d0a301c040a48d1839cd82425
[ "Apache-2.0" ]
1
2021-01-28T12:14:03.000Z
2021-01-28T12:14:03.000Z
""" AuthenticationToken """ from .authentication import Authentication class AuthenticationToken(Authentication): def __init__(self, token): super().__init__() self._token = token def is_access(self, access_data): if self.token and self._token == access_data: return True return False @property def token(self): return self._token @property def md5hash(self): return Authentication.calc_md5hash(self._token)
16.9
55
0.642998
52
507
5.961538
0.403846
0.174194
0.083871
0
0
0
0
0
0
0
0
0.00542
0.272189
507
29
56
17.482759
0.834688
0.037475
0
0.133333
0
0
0
0
0
0
0
0
0
1
0.266667
false
0
0.066667
0.133333
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
72ff9713350c3ee2cddc7201876faa31a96c6f1c
332
py
Python
graphene/tests/issues/test_956.py
tompao/graphene
3f6f4269462ba0f90c62de1140a9e49e0cda2fa5
[ "MIT" ]
7,451
2015-10-07T07:17:19.000Z
2022-03-30T21:56:42.000Z
graphene/tests/issues/test_956.py
tompao/graphene
3f6f4269462ba0f90c62de1140a9e49e0cda2fa5
[ "MIT" ]
1,218
2015-10-08T23:58:37.000Z
2022-03-27T20:47:58.000Z
graphene/tests/issues/test_956.py
tompao/graphene
3f6f4269462ba0f90c62de1140a9e49e0cda2fa5
[ "MIT" ]
985
2015-10-13T03:15:30.000Z
2022-03-29T08:30:54.000Z
import graphene def test_issue(): options = {"description": "This my enum", "deprecation_reason": "For the funs"} new_enum = graphene.Enum("MyEnum", [("some", "data")], **options) assert new_enum._meta.description == options["description"] assert new_enum._meta.deprecation_reason == options["deprecation_reason"]
36.888889
83
0.704819
39
332
5.769231
0.538462
0.226667
0.115556
0.151111
0
0
0
0
0
0
0
0
0.138554
332
8
84
41.5
0.786713
0
0
0
0
0
0.289157
0
0
0
0
0
0.333333
1
0.166667
false
0
0.166667
0
0.333333
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f404c2d6d62dd861e889d26d97fceba23303fa00
531
py
Python
P3-Data Wrangling/exercises/Lesson_4_Working_with_MongoDB/14-Inserting_Multiple_Documents/insert.py
lucasosouza/udacity-data-analysis
2603565cede0c5269ce643584475929f8f2053ce
[ "MIT" ]
null
null
null
P3-Data Wrangling/exercises/Lesson_4_Working_with_MongoDB/14-Inserting_Multiple_Documents/insert.py
lucasosouza/udacity-data-analysis
2603565cede0c5269ce643584475929f8f2053ce
[ "MIT" ]
null
null
null
P3-Data Wrangling/exercises/Lesson_4_Working_with_MongoDB/14-Inserting_Multiple_Documents/insert.py
lucasosouza/udacity-data-analysis
2603565cede0c5269ce643584475929f8f2053ce
[ "MIT" ]
null
null
null
from autos import process_file def insert_autos(infile, db): autos = process_file(infile) db.autos.insert(autos) # Your code here. Insert the data in one command # autos will be a list of dictionaries, as in the example in the previous video # You have to insert data in a collection 'autos' if __name__ == "__main__": from pymongo import MongoClient client = MongoClient("mongodb://localhost:27017") db = client.examples insert_autos('autos-small.csv', db) print db.autos.find_one()
31.235294
83
0.704331
77
531
4.688312
0.584416
0.091413
0.072022
0
0
0
0
0
0
0
0
0.011933
0.210923
531
17
84
31.235294
0.849642
0.323917
0
0
0
0
0.134831
0.070225
0
0
0
0.058824
0
0
null
null
0
0.2
null
null
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
1
0
0
0
0
0
0
0
0
2
f419f3b1aa467df07510252598599c5074819c6e
2,408
py
Python
qm3/constants.py
sergio-marti/qm3
00476b05a730de79511c003dd54894c5d2cfac7c
[ "MIT" ]
13
2020-12-19T02:37:39.000Z
2022-02-09T11:26:38.000Z
qm3/constants.py
sergio-marti/qm3
00476b05a730de79511c003dd54894c5d2cfac7c
[ "MIT" ]
2
2021-01-07T02:53:27.000Z
2021-07-02T17:58:42.000Z
qm3/constants.py
sergio-marti/qm3
00476b05a730de79511c003dd54894c5d2cfac7c
[ "MIT" ]
3
2020-12-20T11:30:52.000Z
2021-07-12T02:51:44.000Z
# -*- coding: iso-8859-1 -*- # # http://physics.nist.gov/cuu/Constants/index.html # from __future__ import print_function, division import sys if( sys.version_info[0] == 2 ): range = xrange import math C = 299792458.0 # m.s-1 NA = 6.02214129e23 # mol-1 H = 6.62606957e-34 # J.s KB = 1.3806488e-23 # J.K-1 R = 8.3144621 # J.mol-1.K-1 ME = 9.10938291e-31 # kg A0 = 0.52917721092 # 1e-10.m EV = 1.602176565e-19 # eV >> J HA = 4.35974434e-18 # Ha >> J K2J = 4.184 # cal >> J J2K = 0.239005736138 # J >> cal H2K = 627.509474277194 # Ha >> kcal.mol-1 H2J = 2625.49964037578 # Ha >> kJ.mol-1 R2D = 180.0 / math.pi # Radians to dregrees def water_density( temp = 300.0 ): tmp = min( max( -8.0, temp - 273.15 ), 108.0 ) tab = [ 0.998120,0.998398,0.998650,0.998877,0.999080,0.999259,0.999417,0.999553,0.999669,0.999765, 0.9998425,0.9999015,0.9999429,0.9999672,0.9999750,0.9999668,0.9999432,0.9999045,0.9998512,0.9997838, 0.9997026,0.9996018,0.9995004,0.9993801,0.9992474,0.9991026,0.9989460,0.9987779,0.9985986,0.9984082, 0.9982071,0.9979955,0.9977735,0.9975415,0.9972995,0.9970479,0.9967867,0.9965162,0.9962365,0.9959478, 0.9956502,0.9953440,0.9950292,0.9947060,0.9943745,0.9940349,0.9936872,0.9933316,0.9929683,0.9925973, 0.9922187,0.9918327,0.9914394,0.9910388,0.9906310,0.9902162,0.9897944,0.9893657,0.9889303,0.9884881, 0.9880393,0.9875839,0.9871220,0.9866537,0.9861791,0.9856982,0.9852111,0.9847178,0.9842185,0.9837132, 0.9832018,0.9826846,0.9821615,0.9816327,0.9810981,0.9805578,0.9800118,0.9794603,0.9789032,0.9783406, 0.9777726,0.9771991,0.9766203,0.9760361,0.9754466,0.9748519,0.9742520,0.9736468,0.9730366,0.9724212, 0.9718007,0.9711752,0.9705446,0.9699091,0.9692686,0.9686232,0.9679729,0.9673177,0.9666576,0.9659927, 0.9653230,0.9646486,0.9639693,0.9632854,0.9625967,0.9619033,0.9612052,0.9605025,0.9597951,0.9590831, 0.9583665,0.957662,0.956937,0.956207,0.955472,0.954733,0.953989,0.953240,0.952488,0.941730 ] i = math.floor( tmp ) p = tmp - i p2m1 = p * p - 1.0 p2m4 = p2m1 - 3.0 i = int( i ) + 10 d = p2m1 * p * ( p - 2.0 ) * tab[i-2] / 24.0 - ( p - 1.0 ) * p * p2m4 * tab[i-1] / 6.0 + p2m1 *p2m4 * tab[i] / 4.0 - ( p + 1.0 ) * p * p2m4 * tab[i+1] / 6.0 + p2m1 * p * ( p + 2.0 ) * tab[i+2] / 24.0 return( d )
44.592593
203
0.634136
443
2,408
3.431151
0.503386
0.013158
0.011842
0.009211
0.044079
0.044079
0.044079
0.044079
0.044079
0.044079
0
0.595033
0.180648
2,408
53
204
45.433962
0.175367
0.086794
0
0
0
0
0
0
0
0
0
0
0
1
0.025
false
0
0.075
0
0.1
0.025
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f41d9e485aaa3505d9a2adf14319d2d437d85643
450
py
Python
exercicios/ex037.py
ArthurLopesMagalhaes/Python-CursoEmVideo
de9006f620a7308c3001fa486b1a4bcd789f7a49
[ "MIT" ]
null
null
null
exercicios/ex037.py
ArthurLopesMagalhaes/Python-CursoEmVideo
de9006f620a7308c3001fa486b1a4bcd789f7a49
[ "MIT" ]
null
null
null
exercicios/ex037.py
ArthurLopesMagalhaes/Python-CursoEmVideo
de9006f620a7308c3001fa486b1a4bcd789f7a49
[ "MIT" ]
null
null
null
n = int(input('Digite um número: ')) print('''Escolha uma das bases para conversão: [ 1 ] BINÁRIO [ 2 ] OCTAL [ 3 ] HEXADECIMAL''') o = int(input('Qual a base de conversão: ')) while o < 1 or o > 3: o = int(input('Qual a base de conversão: ')) if n == 1: print(f'{n} convertido para BINÁRIO é {bin(n)[2:]}') elif n ==2: print(f'{n} convertido para OCTAL é {oct(n)[2:]}') else: print(f'{n} convertido para HEXADECIMAL é {hex(n)[2:]}')
30
60
0.604444
78
450
3.487179
0.448718
0.029412
0.077206
0.1875
0.444853
0.213235
0.213235
0.213235
0
0
0
0.027778
0.2
450
15
60
30
0.727778
0
0
0.142857
0
0
0.618625
0
0
0
0
0
0
1
0
false
0
0
0
0
0.285714
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f421420afd520c8ac64afca33001b74c39f7cc5e
701
py
Python
AIProject/Users/decorators.py
yuntw9112/jeachwi
fe97f4fcb5a76940343a7d3eb76896d4b59de9aa
[ "MIT" ]
null
null
null
AIProject/Users/decorators.py
yuntw9112/jeachwi
fe97f4fcb5a76940343a7d3eb76896d4b59de9aa
[ "MIT" ]
9
2021-03-30T14:26:13.000Z
2022-03-12T00:53:03.000Z
AIProject/Users/decorators.py
SweetWatermelon/jeachwi
fe97f4fcb5a76940343a7d3eb76896d4b59de9aa
[ "MIT" ]
1
2020-01-09T02:32:23.000Z
2020-01-09T02:32:23.000Z
from django.shortcuts import redirect from .models import Fcuser def login_required(function): def wrap(request, *args, **kwargs): user = request.session.get('user') if user is None or not user: return redirect('/login') return function(request, *args, **kwargs) return wrap def admin_required(function): def wrap(request, *args, **kwargs): user = request.session.get('user') if user is None or not user: return redirect('/login') user = Fcuser.objects.get(email=user) if user.level != 'admin': return redirect('/') return function(request, *args, **kwargs) return wrap
25.962963
49
0.60485
83
701
5.084337
0.337349
0.104265
0.161137
0.109005
0.691943
0.691943
0.691943
0.49763
0.49763
0.49763
0
0
0.279601
701
26
50
26.961538
0.835644
0
0
0.631579
0
0
0.03709
0
0
0
0
0
0
1
0.210526
false
0
0.105263
0
0.684211
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
f43838610d90b68c102c0eee5de78d2f3a1ebed7
856
py
Python
app/api/models.py
faregas2007/Recomendation_systems
cc7f5ddfd98e0eed5af9887bf472d76be832997c
[ "MIT" ]
null
null
null
app/api/models.py
faregas2007/Recomendation_systems
cc7f5ddfd98e0eed5af9887bf472d76be832997c
[ "MIT" ]
4
2021-08-22T22:36:41.000Z
2022-03-04T18:22:29.000Z
app/api/models.py
faregas2007/Recomendation_systems
cc7f5ddfd98e0eed5af9887bf472d76be832997c
[ "MIT" ]
null
null
null
from sqlalchemy import Table, Column, Integer, String from app.api.db import engine, Base, session from recsys import utils class Movies(Base): __tablename__ = 'Movies' id = Column(Integer, primary_key=True) item_id = Column(Integer) rating = Column(Integer) title = Column(String(500)) # intialize database ---> Great Expectation """ movie_db = utils.get_data().head().drop(['user_id', 'IMDb URL', 'timestamp'], axis=1) movie_data = utils.parse_csv(movie_db) try: # check if table has already stored inside db movies = session.query(models.Movies).all() if movie is None: session.bulk_insert_mappings(models.Movie, movie_data) # check if session in stored works for row in result: print('item_id', row.item_id, 'title', row.title) except: session.rollback() finally: session.close() """
27.612903
85
0.693925
118
856
4.889831
0.576271
0.090121
0.051993
0
0
0
0
0
0
0
0
0.005739
0.185748
856
30
86
28.533333
0.822095
0.047897
0
0
0
0
0.019231
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
f44b30a5c5a21c7abcc368dacb6894c28ef3e3a9
262
py
Python
cloud_init_gen/exceptions.py
sammck/cloud-init-gen
426a0212ed8e32566efe086f8fa5491df867120e
[ "MIT" ]
1
2022-03-31T23:59:36.000Z
2022-03-31T23:59:36.000Z
cloud_init_gen/exceptions.py
sammck/cloud-init-gen
426a0212ed8e32566efe086f8fa5491df867120e
[ "MIT" ]
null
null
null
cloud_init_gen/exceptions.py
sammck/cloud-init-gen
426a0212ed8e32566efe086f8fa5491df867120e
[ "MIT" ]
null
null
null
# # Copyright (c) 2022 Samuel J. McKelvie # # MIT License - See LICENSE file accompanying this package. # """Exception classes for cloud_init_gen package""" class CloudInitGenError(Exception): """Generic exception raised by package cloud_init_gen""" pass
20.153846
59
0.748092
33
262
5.818182
0.757576
0.09375
0.125
0
0
0
0
0
0
0
0
0.0181
0.156489
262
12
60
21.833333
0.850679
0.732824
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.5
0
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
1
0
0
0
0
0
2
f4602920d3dd062b2f171db37f79cd0c76634f33
3,619
py
Python
models/outside_envs/ISS.py
StanfordASL/UP
1677960690cc1a7576d62639333decb31b730707
[ "MIT" ]
6
2021-01-08T05:44:52.000Z
2021-12-12T06:39:14.000Z
models/outside_envs/ISS.py
StanfordASL/UP
1677960690cc1a7576d62639333decb31b730707
[ "MIT" ]
null
null
null
models/outside_envs/ISS.py
StanfordASL/UP
1677960690cc1a7576d62639333decb31b730707
[ "MIT" ]
1
2021-03-19T15:47:23.000Z
2021-03-19T15:47:23.000Z
#!/usr/bin/env python3 import numpy as np from ccscp.src.utils.polygonal_obstacles import PolygonalObstacle as PolyObs def get_ISS_zones(): #### INSIDE polytopes btms_lft, tops_rgt = [np.zeros(3)] * 6, [np.zeros(3)] * 6 btms_lft[0], tops_rgt[0] = np.array([ 5.9,-0.6, 4.2]), np.array([ 7.7, 0.6, 5.4]) # 3 btms_lft[1], tops_rgt[1] = np.array([10.2, 1.2, 4.2]), np.array([11.6, 2.7, 5.5]) # 4 btms_lft[2], tops_rgt[2] = np.array([ 9.6, 2.7, 3.8]), np.array([11.9, 7.3, 5.9]) # 5 btms_lft[3], tops_rgt[3] = np.array([10.3,-2.7, 4.3]), np.array([11.6,-1.2, 5.4]) # 6 btms_lft[4], tops_rgt[4] = np.array([ 7.7,-1.2, 3.7]), np.array([11.6, 1.2, 6.0]) # 8 btms_lft[5], tops_rgt[5] = np.array([11.6,-0.8, 4.1]), np.array([12.0, 0.8, 5.5]) # 16 keepin_zones = [] for (btm, top) in zip(btms_lft, tops_rgt): center, width = (top+btm)/2., (top-btm) keepin_zones.append( PolyObs(center,width) ) #### OUTSIDE btms_lft, tops_rgt = [np.zeros(3)] * 26, [np.zeros(3)] * 26 btms_lft[0], tops_rgt[0] = np.array([ 3.0,-0.6, 4.2]), np.array([ 5.9, 0.6, 5.4]) # 1 btms_lft[1], tops_rgt[1] = np.array([ 5.0, 0.6, 3.7]), np.array([ 7.7, 1.2, 6.0]) # 2 btms_lft[2], tops_rgt[2] = np.array([ 5.9, 1.2, 3.7]), np.array([10.2, 2.7, 6.0]) # 3 btms_lft[3], tops_rgt[3] = np.array([ 8.0, 2.7, 3.8]), np.array([ 9.6, 7.3, 5.9]) # 4 btms_lft[4], tops_rgt[4] = np.array([ 9.6, 7.3, 3.8]), np.array([11.9, 9.0, 5.9]) # 5 btms_lft[5], tops_rgt[5] = np.array([11.9, 2.7, 3.8]), np.array([13.0, 7.3, 5.9]) # 6 btms_lft[6], tops_rgt[6] = np.array([11.6, 1.2, 3.8]), np.array([12.0, 2.7, 5.9]) # 7 btms_lft[7], tops_rgt[7] = np.array([11.6, 0.8, 3.7]), np.array([12.0, 1.2, 6.0]) # 8 btms_lft[8], tops_rgt[8] = np.array([12.0,-0.8, 3.7]), np.array([13.0, 0.8, 6.0]) # 9 btms_lft[9], tops_rgt[9] = np.array([11.6,-1.2, 3.7]), np.array([12.0,-0.8, 6.0]) # 10 btms_lft[10], tops_rgt[10] = np.array([11.6,-2.7, 4.3]), np.array([12.0,-1.2, 5.4]) # 11 btms_lft[11], tops_rgt[11] = np.array([10.3,-4.0, 4.3]), np.array([11.6,-2.7, 5.4]) # 12 btms_lft[12], tops_rgt[12] = np.array([ 5.9,-4.0, 0.0]), np.array([10.3,-1.2, 0.0]) # 13 btms_lft[13], tops_rgt[13] = np.array([ 5.9,-1.2, 3.7]), np.array([ 7.7,-0.6, 6.0]) # 14 btms_lft[14], tops_rgt[14] = np.array([ 5.9,-1.2, 5.4]), np.array([ 7.7, 1.2, 6.0]) # 15 btms_lft[15], tops_rgt[15] = np.array([ 5.9,-1.2, 3.0]), np.array([ 7.7, 1.2, 4.2]) # 16 btms_lft[16], tops_rgt[16] = np.array([10.2, 1.2, 5.5]), np.array([11.6, 2.7, 7.0]) # 17 btms_lft[17], tops_rgt[17] = np.array([10.2, 1.2, 3.0]), np.array([11.6, 2.7, 4.2]) # 18 btms_lft[18], tops_rgt[18] = np.array([ 9.6, 2.7, 3.0]), np.array([11.9, 7.3, 3.8]) # 19 btms_lft[19], tops_rgt[19] = np.array([ 9.6, 2.7, 5.9]), np.array([11.9, 7.3, 7.0]) # 20 btms_lft[20], tops_rgt[20] = np.array([10.3,-2.7, 5.4]), np.array([11.6,-1.2, 7.0]) # 21 btms_lft[21], tops_rgt[21] = np.array([10.3,-2.7, 3.0]), np.array([11.6,-1.2, 4.3]) # 22 btms_lft[22], tops_rgt[22] = np.array([ 7.7,-1.2, 3.0]), np.array([11.6, 1.2, 3.7]) # 23 btms_lft[23], tops_rgt[23] = np.array([ 7.7,-1.2, 6.0]), np.array([11.6, 1.2, 7.0]) # 24 btms_lft[24], tops_rgt[24] = np.array([11.6,-0.8, 3.0]), np.array([12.0, 0.8, 4.1]) # 25 btms_lft[25], tops_rgt[25] = np.array([11.6,-0.8, 5.5]), np.array([12.0, 0.8, 7.0]) # 26 # btms_lft, tops_rgt = [np.array([ 0.0, 1.2, 3.7])], [np.array([10.2, 2.7, 7.0])] # 3 keepout_zones = [] for (btm, top) in zip(btms_lft, tops_rgt): center, width = (top+btm)/2., (top-btm) keepout_zones.append( PolyObs(center,width) ) return keepin_zones, keepout_zones
64.625
90
0.557889
859
3,619
2.253783
0.077998
0.238636
0.102273
0.08781
0.628616
0.576446
0.399277
0.297004
0.116219
0.090393
0
0.194472
0.150318
3,619
56
91
64.625
0.435122
0.058303
0
0.086957
0
0
0
0
0
0
0
0
0
1
0.021739
false
0
0.043478
0
0.086957
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f46c42d581f7f8b3b75c0f5538ac5faa472b03d6
2,698
py
Python
generalpackager/test/test_packager_files.py
ManderaGeneral/generalpackager
ec337c9b4decfa3d68f42d02fe49b1fb387f3b87
[ "MIT" ]
1
2021-02-10T11:21:55.000Z
2021-02-10T11:21:55.000Z
generalpackager/test/test_packager_files.py
ManderaGeneral/generalpackager
ec337c9b4decfa3d68f42d02fe49b1fb387f3b87
[ "MIT" ]
null
null
null
generalpackager/test/test_packager_files.py
ManderaGeneral/generalpackager
ec337c9b4decfa3d68f42d02fe49b1fb387f3b87
[ "MIT" ]
null
null
null
from generalpackager import Packager from generalfile.test.setup_workdir import setup_workdir import unittest class TestPackager(unittest.TestCase): """ Skip: GenerateFile generate generate_localfiles create_blank """ def test_relative_path_is_aesthetic(self): packager = Packager() self.assertEqual(False, packager.relative_path_is_aesthetic("setup.py")) self.assertEqual(True, packager.relative_path_is_aesthetic("README.md")) self.assertEqual(True, packager.relative_path_is_aesthetic(packager.localrepo.get_readme_path())) def test_filter_relative_filenames(self): packager = Packager() self.assertEqual(["setup.py"], packager.filter_relative_filenames("setup.py", aesthetic=None)) self.assertEqual(["setup.py"], packager.filter_relative_filenames("setup.py", aesthetic=False)) self.assertEqual([], packager.filter_relative_filenames("setup.py", aesthetic=True)) def test_compare_local_to_github(self): setup_workdir(use_working_dir=True) packager = Packager() packager.compare_local_to_github() def test_compare_local_to_pypi(self): setup_workdir(use_working_dir=True) packager = Packager() packager.compare_local_to_pypi() def test_generate_setup(self): packager = Packager() text = packager.generate_setup() self.assertIn(str(packager.localrepo.version), text) self.assertIn(str(packager.localrepo.name), text) def test_generate_manifest(self): packager = Packager() text = packager.generate_manifest() self.assertIn("include metadata.json", text) def test_generate_git_exclude(self): packager = Packager() text = packager.generate_git_exclude() self.assertIn(".idea", text) def test_generate_license(self): packager = Packager() text = packager.generate_license() self.assertIn("Mandera", text) def test_generate_workflow(self): packager = Packager() text = packager.generate_workflow() self.assertIn("runs-on", text) def test_generate_readme(self): packager = Packager() text = str(packager.generate_readme()) self.assertIn("pip install", text) def test_generate_personal_readme(self): packager = Packager() text = str(packager.generate_personal_readme()) self.assertIn("generallibrary", text) def test_get_new_packager(self): a = Packager() b = a.get_new_packager() self.assertEqual(a.name, b.name) self.assertIsNot(a, b) self.assertIs(b, Packager())
33.308642
105
0.679021
301
2,698
5.827243
0.229236
0.118586
0.102623
0.095781
0.522805
0.413341
0.299316
0.27252
0.159635
0.159635
0
0
0.216086
2,698
80
106
33.725
0.829314
0.022239
0
0.22807
1
0
0.047159
0
0
0
0
0
0.298246
1
0.210526
false
0
0.052632
0
0.280702
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
f473aa6c63a20bd99ab67be0c567c00586977dbb
17,694
py
Python
mwa_pb/mwa_impedance.py
NickSwainston/mwa_pb
6656ee2b83c23e6c31ae8dac6f67a46d9b881eae
[ "MIT" ]
2
2020-07-20T05:38:00.000Z
2020-08-10T01:31:52.000Z
mwa_pb/mwa_impedance.py
NickSwainston/mwa_pb
6656ee2b83c23e6c31ae8dac6f67a46d9b881eae
[ "MIT" ]
15
2019-05-01T01:58:06.000Z
2022-03-23T15:54:13.000Z
mwa_pb/mwa_impedance.py
NickSwainston/mwa_pb
6656ee2b83c23e6c31ae8dac6f67a46d9b881eae
[ "MIT" ]
7
2019-04-16T08:30:40.000Z
2022-03-28T13:34:13.000Z
#!/usr/bin/env python """Module containing measured and simulated impedances of MWA LNAs and dipoles """ import logging import numpy import matplotlib.pyplot as plt import astropy.io.fits as pyfits from . import config logging.basicConfig(format='# %(levelname)s:%(name)s: %(message)s') logger = logging.getLogger(__name__) # default logger level is WARNING vel_light = 2.99792e8 DQ = 435e-12 * vel_light # delay quantum in distance light travels for 1 quantum class LNAImpedance(object): """Measured MWA LNA impedance between 50 and 500 MHz. """ def __init__(self): self.freq = numpy.arange(50, 501, dtype=numpy.float32) * 1e6 self.Z = numpy.array([52.803 + 151.76j, 52.446 + 154.04j, 52.19 + 157.03j, 51.811 + 160.69j, 51.528 + 164.85j, 51.802 + 169.38j, 52.157 + 174.17j, 52.522 + 179.32j, 53.377 + 184.66j, 54.249 + 189.98j, 55.512 + 195.65j, 56.949 + 201.94j, 58.519 + 208.08j, 60.179 + 214.4j, 62.755 + 220.82j, 65.071 + 227.42j, 67.949 + 234.58j, 71.302 + 241.31j, 74.795 + 248.26j, 78.823 + 255.1j, 83.465 + 262.45j, 88.307 + 268.87j, 93.864 + 275.2j, 99.639 + 281.3j, 105.58 + 287.5j, 111.82 + 293.16j, 118.57 + 298.85j, 125.37 + 303.59j, 132.08 + 308.64j, 138.4 + 313.49j, 144.44 + 318.07j, 150.64 + 323.03j, 157.06 + 327.82j, 163.72 + 332.52j, 170.03 + 337.71j, 176.67 + 343.27j, 184.35 + 349.36j, 192.29 + 355.09j, 200.02 + 360.97j, 208.58 + 366.41j, 216.59 + 372.96j, 225.67 + 379.45j, 235.53 + 386.17j, 245.42 + 391.84j, 256.16 + 398.14j, 268.37 + 404.17j, 281.23 + 410.06j, 295.19 + 416.49j, 308.93 + 420.98j, 323.64 + 426.09j, 339.04 + 431.74j, 354.61 + 436.51j, 371.38 + 440.57j, 388.71 + 445.18j, 406.16 + 447.12j, 426.15 + 450.65j, 446.62 + 452.77j, 467.8 + 453.18j, 489.21 + 450.95j, 510.8 + 449.09j, 534.27 + 446.18j, 557.91 + 441.95j, 582.01 + 436.09j, 605.65 + 427.46j, 629.14 + 418.13j, 656.66 + 407.54j, 681.79 + 394.13j, 705.83 + 378.75j, 730.36 + 361.53j, 752.83 + 341.19j, 775.31 + 320.56j, 798.29 + 296.29j, 816.81 + 272.67j, 834.34 + 243.57j, 851.51 + 217.39j, 865.02 + 186.63j, 876.49 + 157.17j, 884.52 + 125.94j, 891.00 + 96.191j, 894.14 + 61.696j, 897.08 + 27.864j, 894.52 - 3.5946j, 892.67 - 35.799j, 887.2 - 67.153j, 881.6 - 99.435j, 872.62 - 129.87j, 864.69 - 155.42j, 853.69 - 179.82j, 840.15 - 205.61j, 825.47 - 227.86j, 811.32 - 249.27j, 794.84 - 268.09j, 778.56 - 283.31j, 760.98 - 301.41j, 745.14 - 317.45j, 728.93 - 332.33j, 712.62 - 344.89j, 695.47 - 357j, 678.85 - 367.29j, 662.72 - 377.19j, 645.2 - 384.83j, 628.67 - 392.63j, 611.52 - 398.84j, 594.87 - 405.96j, 577.85 - 411.64j, 561.2 - 416.75j, 545.01 - 421.23j, 531.35 - 426.39j, 516.58 - 428.47j, 501.43 - 431.9j, 486.88 - 433.12j, 473.71 - 434.81j, 461.38 - 435.33j, 448.13 - 435.89j, 434.9 - 434.92j, 421.63 - 434.71j, 409.75 - 433.7j, 397.58 - 432.03j, 386.65 - 430.36j, 376.25 - 428.97j, 366.39 - 427.51j, 356.49 - 426.02j, 347.71 - 424.14j, 339.13 - 421.65j, 330.76 - 420.74j, 322.54 - 417.59j, 314.44 - 415.14j, 305.26 - 411.58j, 297.84 - 408.67j, 290.45 - 405.71j, 282.98 - 402.77j, 276.15 - 399.56j, 268.95 - 397.06j, 262.05 - 393.77j, 256.48 - 391.53j, 250.55 - 388.55j, 244.67 - 385.83j, 239.24 - 383.2j, 234.1 - 379.97j, 229.17 - 377.32j, 224.07 - 374.82j, 219.45 - 372.16j, 214.22 - 369.4j, 209.86 - 366.82j, 205.51 - 363.94j, 201.02 - 361.7j, 196.64 - 358.88j, 192.06 - 356.2j, 187.99 - 353.37j, 184.01 - 350.71j, 180.82 - 347.86j, 177.31 - 345.16j, 173.86 - 342.35j, 170.04 - 339.97j, 167.37 - 337.48j, 163.77 - 334.91j, 160.71 - 332.13j, 157.16 - 329.43j, 153.89 - 326.64j, 150.9 - 324.17j, 148.42 - 321.22j, 145.32 - 318.78j, 142.8 - 316.5j, 140.51 - 313.88j, 138.07 - 311.21j, 135.65 - 308.95j, 133.56 - 306.19j, 131.42 - 303.79j, 129.42 - 301.32j, 127.57 - 298.73j, 125.73 - 296.62j, 123.7 - 294.57j, 121.82 - 292.36j, 119.93 - 290.17j, 118.27 - 288.21j, 116.39 - 286.06j, 114.48 - 283.88j, 112.76 - 281.88j, 111.13 - 280.13j, 109.49 - 278.22j, 107.74 - 276.41j, 105.99 - 274.7j, 104.74 - 272.75j, 103.35 - 270.97j, 101.76 - 269.11j, 100.21 - 267.31j, 98.957 - 265.44j, 97.601 - 263.75j, 96.383 - 261.71j, 94.926 - 260.1j, 93.655 - 258.33j, 92.223 - 256.45j, 91.028 - 254.56j, 89.743 - 252.72j, 88.719 - 251.07j, 87.393 - 249.27j, 86.092 - 247.57j, 84.946 - 245.82j, 83.73 - 244.29j, 82.535 - 242.85j, 81.653 - 241j, 80.563 - 239.12j, 79.475 - 237.62j, 78.791 - 235.9j, 77.636 - 234.28j, 76.866 - 232.99j, 76.39 - 231.17j, 75.255 - 230.01j, 74.317 - 228.71j, 73.493 - 227.35j, 72.697 - 225.99j, 72.096 - 224.74j, 71.661 - 223.36j, 70.576 - 222.31j, 69.961 - 221.11j, 69.4 - 220.12j, 68.796 - 218.83j, 67.94 - 217.5j, 67.31 - 216.31j, 66.216 - 215.06j, 65.584 - 213.54j, 64.877 - 212.28j, 63.893 - 210.78j, 63.306 - 209.5j, 62.675 - 208.11j, 61.585 - 207.05j, 61.274 - 205.98j, 60.893 - 204.93j, 60.162 - 203.75j, 59.491 - 202.39j, 58.785 - 201.23j, 58.037 - 200.33j, 57.763 - 199.1j, 57.082 - 197.79j, 56.345 - 196.7j, 55.75 - 195.54j, 55.49 - 194.62j, 54.995 - 193.59j, 54.358 - 192.45j, 53.946 - 191.27j, 53.429 - 190.25j, 52.941 - 189.14j, 52.774 - 188.19j, 52.502 - 187.32j, 52.019 - 186.36j, 51.827 - 185.47j, 51.392 - 184.55j, 50.93 - 183.64j, 50.507 - 182.67j, 50.048 - 181.69j, 49.391 - 180.64j, 48.997 - 179.7j, 48.551 - 178.69j, 48.098 - 177.85j, 47.737 - 176.85j, 47.302 - 175.93j, 46.857 - 174.99j, 46.454 - 174.01j, 46.187 - 173.1j, 45.907 - 172.37j, 45.59 - 171.47j, 45.215 - 170.71j, 44.848 - 170.01j, 44.296 - 169.24j, 43.968 - 168.56j, 43.492 - 167.7j, 43.203 - 166.91j, 42.812 - 166.24j, 42.453 - 165.32j, 42.256 - 164.43j, 42.245 - 163.79j, 41.847 - 163.03j, 41.537 - 162.33j, 41.211 - 161.44j, 40.928 - 160.64j, 40.545 - 159.95j, 40.022 - 159.18j, 39.594 - 158.33j, 39.436 - 157.57j, 39.083 - 156.85j, 38.585 - 155.97j, 38.308 - 155.22j, 38.104 - 154.41j, 37.944 - 153.69j, 37.686 - 152.85j, 37.312 - 152.05j, 37.102 - 151.4j, 37.074 - 150.78j, 36.776 - 149.94j, 36.544 - 149.26j, 36.359 - 148.6j, 36.08 - 147.97j, 35.99 - 147.3j, 35.746 - 146.63j, 35.507 - 145.93j, 35.38 - 145.39j, 35.17 - 144.62j, 34.934 - 143.98j, 34.799 - 143.29j, 34.627 - 142.76j, 34.442 - 142.15j, 34.097 - 141.54j, 33.835 - 140.87j, 33.512 - 140.46j, 33.297 - 139.72j, 32.991 - 139.29j, 32.688 - 138.53j, 32.479 - 137.92j, 32.298 - 137.37j, 32.054 - 136.76j, 31.97 - 136.07j, 31.669 - 135.6j, 31.519 - 134.87j, 31.281 - 134.45j, 31.115 - 133.84j, 30.888 - 133.34j, 30.746 - 132.8j, 30.581 - 132.2j, 30.414 - 131.7j, 30.129 - 131.1j, 30.007 - 130.48j, 29.826 - 129.88j, 29.702 - 129.29j, 29.507 - 128.72j, 29.274 - 128.22j, 29.115 - 127.6j, 28.968 - 127.13j, 28.758 - 126.62j, 28.543 - 126.12j, 28.386 - 125.6j, 28.211 - 125.14j, 28.065 - 124.65j, 27.857 - 124.23j, 27.758 - 123.82j, 27.619 - 123.41j, 27.564 - 122.98j, 27.532 - 122.53j, 27.377 - 122.06j, 27.215 - 121.69j, 27.072 - 121.15j, 26.882 - 120.59j, 26.655 - 120.07j, 26.442 - 119.52j, 26.172 - 119.02j, 25.979 - 118.44j, 25.805 - 117.82j, 25.732 - 117.32j, 25.542 - 116.85j, 25.435 - 116.32j, 25.251 - 115.89j, 24.992 - 115.5j, 24.86 - 115.1j, 24.668 - 114.68j, 24.544 - 114.24j, 24.343 - 113.81j, 24.136 - 113.33j, 23.995 - 112.84j, 23.9 - 112.27j, 23.732 - 111.82j, 23.654 - 111.39j, 23.413 - 110.92j, 23.39 - 110.41j, 23.214 - 109.92j, 23.097 - 109.4j, 22.958 - 108.96j, 22.836 - 108.51j, 22.7 - 108.03j, 22.618 - 107.6j, 22.428 - 107.26j, 22.419 - 106.93j, 22.344 - 106.53j, 22.267 - 106.2j, 22.137 - 105.8j, 22.05 - 105.3j, 21.98 - 104.92j, 21.851 - 104.54j, 21.762 - 104.11j, 21.648 - 103.81j, 21.493 - 103.38j, 21.433 - 102.92j, 21.34 - 102.64j, 21.154 - 102.32j, 20.983 - 101.8j, 20.861 - 101.37j, 20.606 - 101.01j, 20.523 - 100.61j, 20.314 - 100.25j, 20.112 - 99.741j, 19.995 - 99.266j, 19.955 - 98.997j, 19.758 - 98.615j, 19.688 - 98.133j, 19.582 - 97.774j, 19.581 - 97.42j, 19.475 - 97.13j, 19.387 - 96.75j, 19.285 - 96.317j, 19.257 - 95.976j, 19.19 - 95.605j, 19.042 - 95.164j, 18.918 - 94.76j, 18.813 - 94.341j, 18.675 - 93.897j, 18.573 - 93.465j, 18.45 - 93.078j, 18.416 - 92.723j, 18.373 - 92.336j, 18.222 - 91.964j, 18.151 - 91.644j, 18.142 - 91.32j, 18.12 - 90.964j, 18.066 - 90.571j, 17.921 - 90.204j, 17.831 - 89.837j, 17.799 - 89.529j, 17.705 - 89.176j, 17.555 - 88.883j, 17.417 - 88.52j, 17.354 - 88.098j, 17.344 - 87.786j, 17.25 - 87.435j, 17.144 - 87.005j, 17.013 - 86.724j, 16.952 - 86.38j, 16.872 - 86.119j, 16.786 - 85.864j, 16.636 - 85.441j, 16.569 - 85.112j, 16.519 - 84.808j, 16.461 - 84.443j, 16.327 - 84.082j, 16.251 - 83.738j, 16.066 - 83.371j, 15.943 - 83.089j, 15.814 - 82.782j, 15.669 - 82.459j, 15.522 - 82.064j, 15.458 - 81.733j, 15.293 - 81.351j, 15.243 - 81.042j, 15.146 - 80.671j, 15.05 - 80.296j, 14.973 - 79.911j, 14.955 - 79.614j, 14.876 - 79.266j, 14.839 - 78.892j, 14.723 - 78.569j, 14.683 - 78.282j, 14.643 - 78.058j, 14.614 - 77.894j, 14.594 - 77.713j], dtype=numpy.complex) def getZ(self, freq): """Return the interpolated LNA impedance (Ohms) for the freq (Hz) """ r = numpy.interp(freq, self.freq, numpy.real(self.Z)) i = numpy.interp(freq, self.freq, numpy.imag(self.Z)) return r + 1j * i class TileImpedanceMatrix(object): """Simulated or measured MWA dipole port coupling impedances vs frequency For a given freq, this is a 32x32 matrix where the first 16 are for the Y (N-S) dipoles and the second 16 are for the X (E-W) dipoles. """ def __init__(self): # load Z matrix from FITS file filename = config.Zmatrix logger.debug('Loading %s' % filename) try: hdus = pyfits.open(filename) except IOError: raise Exception('Cannot load impedance file %s' % filename) nfreqs = len(hdus) self.Zmatrix = numpy.empty((nfreqs,) + (32, 32), dtype=numpy.complex64) self.freqs = numpy.zeros(nfreqs) for i in range(nfreqs): mag = hdus[i].data[0, ...] ph = hdus[i].data[1, ...] self.Zmatrix[i, ...] = mag * (numpy.cos(ph) + 1.0j * numpy.sin(ph)) self.freqs[i] = hdus[i].header['FREQ'] # freqs_MHz=[88,119,155,186,216] # self.freqs = numpy.array(freqs_MHz,dtype=numpy.float32)*1e6 # self.Zmatrix = numpy.empty(self.freqs.shape + (32,32),dtype=numpy.complex) # freqind=0 # for f in freqs_MHz: # realfile = filesdir+"ZReal"+str(f)+"MHz.txt" # imagfile = filesdir+"ZImag"+str(f)+"MHz.txt" # r = numpy.loadtxt(realfile) # i = numpy.loadtxt(imagfile) # self.Zmatrix[freqind,...] = r+1j*i # freqind += 1 logger.debug("Loaded MWA tile impedance matrix with " + str(nfreqs) + " freqs") logger.debug("Freqs are: " + str(self.freqs)) def getImpedanceMatrix(self, freq): """Return an impedance matrix for the MWA tile for a given freq (Hz) Chooses the nearest known freq if if the exact freq isn't available. """ # find the nearest frequency pos = numpy.argmin(numpy.abs(self.freqs - freq)) if numpy.abs(self.freqs[pos] - freq) > 5e6: logger.warning( "Nearest tabulated impedance matrix freq is more than 5 MHz away from desired freq of " + str( freq / 1e6) + " MHz") logger.info("Selecting matrix for nearest freq " + str(self.freqs[pos])) return self.Zmatrix[pos, ...] # execute some test code if invoked as a standalone if __name__ == "__main__": logger.setLevel(logging.DEBUG) freqs = [80, 130, 150, 200, 230] z = LNAImpedance() fs = numpy.array(freqs) * 1e6 print(("LNA Impedance at " + str(freqs) + " MHz")) print((z.getZ(fs))) # delays = numpy.zeros(32) # set delays for 14 degs off zenith along meridian za = "14" delays = numpy.array([6, 6, 6, 6, 4, 4, 4, 4, 2, 2, 2, 2, 0, 0, 0, 0, 6, 6, 6, 6, 4, 4, 4, 4, 2, 2, 2, 2, 0, 0, 0, 0]) im = TileImpedanceMatrix() for i in range(len(freqs)): lam = vel_light / fs[i] phases = numpy.pi * -2.0 * delays * (DQ / lam) ph_rot = numpy.cos(phases) + 1j * numpy.sin(phases) z_total = im.getImpedanceMatrix(fs[i]) + numpy.eye(32) * z.getZ(fs[i]) inv_z = numpy.linalg.inv(z_total) current = numpy.dot(inv_z, ph_rot).reshape((2, 4, 4)) # to plot the Z_total mag and phase plt.imshow(numpy.abs(z_total), interpolation='nearest', cmap=plt.cm.get_cmap('gist_stern')) plt.title('MWA ' + str(freqs[i]) + 'MHz total Z matrix magnitude') plt.colorbar() plt.savefig('/tmp/MWA_Z_total_mag_' + str(freqs[i]) + 'MHz.png') plt.clf() plt.imshow(numpy.angle(z_total), interpolation='nearest') plt.title('MWA ' + str(freqs[i]) + 'MHz total Z matrix phase') plt.colorbar() plt.savefig('/tmp/MWA_Z_total_ph_' + str(freqs[i]) + 'MHz.png') plt.clf() # to display the z matrix inverse: plt.imshow(numpy.absolute(current[0, ...]) * 1e3, interpolation='nearest') plt.title('MWA ' + str(freqs[i]) + 'MHz Y dipole current amplitude (ZA=' + str(za) + 'deg)') plt.colorbar() plt.savefig('/tmp/MWA_' + str(freqs[i]) + 'MHz_Y_cur_amp_ZA' + str(za) + '.png') plt.clf() plt.imshow(numpy.angle(current[0, ...]) * 180.0 / numpy.pi, interpolation='nearest') plt.title('MWA ' + str(freqs[i]) + 'MHz Y dipole current phase (ZA=' + str(za) + 'deg)') plt.colorbar() plt.savefig('/tmp/MWA_' + str(freqs[i]) + 'MHz_Y_cur_ph_ZA' + str(za) + '.png') plt.clf() plt.imshow(numpy.angle(current[1, ...]) * 180.0 / numpy.pi, interpolation='nearest') plt.title('MWA ' + str(freqs[i]) + 'MHz X dipole current phase (ZA=' + str(za) + 'deg)') plt.colorbar() plt.savefig('/tmp/MWA_' + str(freqs[i]) + 'MHz_X_cur_ph_ZA' + str(za) + '.png') plt.clf() plt.imshow(numpy.absolute(current[1, ...]) * 1e3, interpolation='nearest') plt.title('MWA ' + str(freqs[i]) + 'MHz X dipole current amplitude (ZA=' + str(za) + 'deg)') plt.colorbar() plt.savefig('/tmp/MWA_' + str(freqs[i]) + 'MHz_X_cur_amp_ZA' + str(za) + '.png') plt.clf()
65.533333
119
0.477054
2,659
17,694
3.150056
0.365175
0.009312
0.012894
0.017192
0.123329
0.112345
0.105659
0.098376
0.08787
0.085482
0
0.409075
0.368486
17,694
269
120
65.776952
0.340523
0.078501
0
0.086124
0
0
0.045242
0.002712
0
0
0
0
0
1
0.019139
false
0
0.023923
0
0.062201
0.009569
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f477101972b590e9902d5a030543a66125310bc7
651
py
Python
bslparloursite/tgbot/models.py
natfarleydev/thebslparlour
ebb2588282cdb2a977ec6c5f8d82cec4e8fd1f99
[ "CC0-1.0" ]
1
2016-01-06T23:13:11.000Z
2016-01-06T23:13:11.000Z
bslparloursite/tgbot/models.py
natfarleydev/thebslparlour
ebb2588282cdb2a977ec6c5f8d82cec4e8fd1f99
[ "CC0-1.0" ]
4
2021-03-18T20:15:04.000Z
2021-06-10T17:52:31.000Z
bslparloursite/tgbot/models.py
natfarleydev/thebslparlour
ebb2588282cdb2a977ec6c5f8d82cec4e8fd1f99
[ "CC0-1.0" ]
null
null
null
from django.db import models from django.utils import timezone from videolibrary.models import SourceVideo # Create your models here. # TODO consider whether this is needed anymore class RequestedSign(models.Model): short_description = models.CharField(max_length=100) description = models.TextField() date_added = models.DateTimeField(default=timezone.now, editable=False) def __str__(self): return self.short_description+" ("+self.description+")" class TelegramGif(models.Model): file_id = models.CharField(max_length=200) # TODO change to telegram's max length source_video = models.ForeignKey(SourceVideo)
32.55
85
0.763441
81
651
6
0.62963
0.055556
0.074074
0.098765
0
0
0
0
0
0
0
0.01085
0.150538
651
19
86
34.263158
0.867993
0.162826
0
0
0
0
0.005545
0
0
0
0
0.052632
0
1
0.083333
false
0
0.25
0.083333
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
1
0
0
2
f47dfed1b81333fdca77a564b606b149c714883c
1,196
py
Python
kmod/test/test_util.py
wittawatj/kernel-mod
147a05888855a15d72b28a734752a91d93018604
[ "MIT" ]
20
2018-10-26T16:18:56.000Z
2020-11-10T01:08:56.000Z
kmod/test/test_util.py
wittawatj/kernel-mod
147a05888855a15d72b28a734752a91d93018604
[ "MIT" ]
null
null
null
kmod/test/test_util.py
wittawatj/kernel-mod
147a05888855a15d72b28a734752a91d93018604
[ "MIT" ]
2
2019-12-08T21:08:53.000Z
2020-11-10T01:08:57.000Z
""" Module for testing kmod.util . """ __author__ = 'wittawat' import autograd import autograd.numpy as np import numpy.testing as testing import matplotlib.pyplot as plt # Import all the submodules for testing purpose import kmod import kmod.config import kmod.mctest from kmod import data, density, util, kernel import scipy.stats as stats import unittest class Test(unittest.TestCase): def setUp(self): pass def test_multi_way_split(self): test_arr = np.random.randn(20, 3) restack = np.vstack(util.multi_way_split(test_arr, [12, 2, 6])) testing.assert_almost_equal(test_arr, restack) restack = np.vstack(util.multi_way_split(test_arr, [0, 11,1, 2, 0,6])) testing.assert_almost_equal(test_arr, restack) def test_top_lowzerohigh(self): arr = np.array([0, 1, 2, 3, 4]) A = np.array([0, 1, 2]) B = A C = np.array([4, 3, 2]) xa, xb, xc = util.top_lowzerohigh(arr, k=3) testing.assert_almost_equal(xa, A) testing.assert_almost_equal(xb, B) testing.assert_almost_equal(xc, C) def tearDown(self): pass if __name__ == '__main__': unittest.main()
22.148148
78
0.658027
178
1,196
4.213483
0.38764
0.046667
0.126667
0.16
0.234667
0.208
0.208
0.208
0.104
0
0
0.028261
0.230769
1,196
53
79
22.566038
0.786957
0.064381
0
0.121212
0
0
0.014427
0
0
0
0
0
0.151515
1
0.121212
false
0.060606
0.30303
0
0.454545
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
0
0
0
2
f4811309cbc5a31c05c96941a18e88aee4602495
236
py
Python
introduction_to_classic_ciphers/lesson6/task2/question_02.py
behzod/pycharm-courses
0ba74ff0ff87e7747173c60cd139c25b8d7f3b0e
[ "Apache-2.0" ]
213
2015-01-03T19:25:02.000Z
2020-02-06T03:08:43.000Z
introduction_to_classic_ciphers/lesson6/task2/question_02.py
behzod/pycharm-courses
0ba74ff0ff87e7747173c60cd139c25b8d7f3b0e
[ "Apache-2.0" ]
24
2015-01-01T17:03:09.000Z
2019-12-22T10:28:22.000Z
introduction_to_classic_ciphers/lesson6/task2/question_02.py
behzod/pycharm-courses
0ba74ff0ff87e7747173c60cd139c25b8d7f3b0e
[ "Apache-2.0" ]
139
2015-01-03T19:24:22.000Z
2020-01-24T18:05:51.000Z
ENCRYPTED_MESSAGE = 'IQ PQTVJ CV PQQP' DECRYPTED_MESSAGE = 'GO NORTH AT NOON' CIPHER_OPTIONS = ['null','caesar','atbash'] cipher_used_in_this_example = CIPHER_OPTIONS[1] # replace with the index of the cipher used in this encryption
33.714286
111
0.771186
36
236
4.833333
0.75
0.149425
0.137931
0.183908
0
0
0
0
0
0
0
0.004926
0.139831
236
6
112
39.333333
0.852217
0.254237
0
0
0
0
0.275862
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f486a5263eac03ac0b72828eafc0011f126d4cc9
4,532
py
Python
food/_nbdev.py
DmitriyG228/food
dc2375b06a47e742573e53b86d87f3ecd5b160bf
[ "Apache-2.0" ]
null
null
null
food/_nbdev.py
DmitriyG228/food
dc2375b06a47e742573e53b86d87f3ecd5b160bf
[ "Apache-2.0" ]
null
null
null
food/_nbdev.py
DmitriyG228/food
dc2375b06a47e742573e53b86d87f3ecd5b160bf
[ "Apache-2.0" ]
null
null
null
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"img_resize": "00_clipmodel.ipynb", "imgs_resize": "00_clipmodel.ipynb", "dict_to_device": "00_clipmodel.ipynb", "norm": "00_clipmodel.ipynb", "detach_norm": "00_clipmodel.ipynb", "text2clip_en": "00_clipmodel.ipynb", "images2clip_en": "00_clipmodel.ipynb", "image2clip": "00_clipmodel.ipynb", "en_model_name": "00_clipmodel.ipynb", "tokenizer": "00_clipmodel.ipynb", "en_processor": "00_clipmodel.ipynb", "en_size": "00_clipmodel.ipynb", "en_dim": "00_clipmodel.ipynb", "images2clip": "00_clipmodel.ipynb", "text2clip": "00_clipmodel.ipynb", "read_sql_query": "00_custom_pandas.ipynb", "Path.ls": "00_tools.ipynb", "mapbox_access_token": "00_paths.ipynb", "main_path": "00_paths.ipynb", "data_path": "00_paths.ipynb", "reference_images_path": "00_paths.ipynb", "testset_path": "00_paths.ipynb", "engine": "00_psql.ipynb", "Session": "00_psql.ipynb", "session": "00_psql.ipynb", "Base": "00_psql.ipynb", "du": "00_psql.ipynb", "query": "00_psql.ipynb", "current": "00_psql.ipynb", "kill": "00_tools.ipynb", "schema": "00_psql.ipynb", "LocalBase": "00_psql.ipynb", "insert_on_conflict": "00_psql.ipynb", "read_sql": "00_psql.ipynb", "Foods": "00_psql.ipynb", "Users": "00_psql.ipynb", "Dishes": "00_psql.ipynb", "User_properties": "00_psql.ipynb", "FoodsP": "00_psql.ipynb", "FoodsPI": "00_psql.ipynb", "FFoods": "00_psql.ipynb", "Food_reference_images": "00_psql.ipynb", "Portions": "00_psql.ipynb", "Indexed": "00_psql.ipynb", "collection_name": "01_search.ipynb", "dim": "00_qdrant.ipynb", "QdrantClient.get_collections": "00_qdrant.ipynb", "QdrantClient.collection_len": "00_qdrant.ipynb", "prod_client": "00_qdrant.ipynb", "dev_client": "00_qdrant.ipynb", "get_image_from_url": "00_tools.ipynb", "get_hash_folder": "00_tools.ipynb", "save_selected_cities": "00_tools.ipynb", "save_location_dicts": "00_tools.ipynb", "get_top_n_countries": "00_tools.ipynb", "path_info": "00_tools.ipynb", "rm_r": "00_tools.ipynb", "search_notebooks": "00_tools.ipynb", "df_chunk_generator": "00_tools.ipynb", "docker_container": "00_tools.ipynb", "LogDBHandler": "00_tools.ipynb", "get_logger": "00_tools.ipynb", "read_image_from_url": "01_search.ipynb", "compound_return": "00_tools.ipynb", "copy_func": "00_tools.ipynb", "patch_to": "00_tools.ipynb", "patch": "00_tools.ipynb", "to_pickle": "00_tools.ipynb", "from_pickle": "00_tools.ipynb", "telegram": "00_tools.ipynb", "pdrows": "00_tools.ipynb", "pd_highlight": "00_tools.ipynb", "inline": "00_tools.ipynb", "plot_map": "00_tools.ipynb", "htop": "00_tools.ipynb", "get_proxies": "00_tools.ipynb", "append_csv": "00_tools.ipynb", "repeat_df": "00_tools.ipynb", "to_sql": "00_tools.ipynb", "timestamp2int": "00_tools.ipynb", "pd_timestamp": "00_tools.ipynb", "startEndTimestamp": "00_tools.ipynb", "pd_set_float": "00_tools.ipynb", "plot_multiple_y": "00_tools.ipynb", "sql_head": "00_tools.ipynb", "make_clickable": "00_tools.ipynb", "selected_countries": "00_tools.ipynb", "foods": "01_search.ipynb", "search_image": "01_search.ipynb", "cos": "01_search.ipynb", "table": "01_search.ipynb", "search_image_": "01_search.ipynb", "series2tensor": "01_search.ipynb", "multiply_vector": "01_search.ipynb", "drop_vector": "01_search.ipynb", "multiple_foods": "01_search.ipynb"} modules = ["clipmodel.py", "custom_pandas.py", "paths.py", "psql.py", "qdrant.py", "tools.py", "classify_image.py", "search.py"] doc_url = "https://{user}.github.io/food/" git_url = "https://github.com/{user}/food/tree/{branch}/" def custom_doc_links(name): return None
39.068966
61
0.575463
523
4,532
4.625239
0.290631
0.109963
0.188508
0.029764
0.050021
0.050021
0.050021
0.030591
0
0
0
0.059103
0.257061
4,532
115
62
39.408696
0.659341
0.007944
0
0
1
0
0.587895
0.02648
0
0
0
0
0
1
0.009259
false
0
0
0.009259
0.009259
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
f487f9e30944e9b9fef9f2dedf8cd9eaaab8b61a
921
py
Python
loopchain/blockchain/blocks/v0_1a/block_prover.py
windies21/loopchain
6e96c8a7e006747af04187155678f2fae59e1389
[ "Apache-2.0" ]
105
2018-04-03T05:29:08.000Z
2022-01-28T17:33:20.000Z
loopchain/blockchain/blocks/v0_1a/block_prover.py
laurenceyoon/loopchain
e87032779be4715c135c2c91d2757d9c63bf4e31
[ "Apache-2.0" ]
135
2018-09-04T07:11:02.000Z
2021-12-15T06:25:47.000Z
loopchain/blockchain/blocks/v0_1a/block_prover.py
laurenceyoon/loopchain
e87032779be4715c135c2c91d2757d9c63bf4e31
[ "Apache-2.0" ]
46
2018-05-07T09:12:07.000Z
2022-02-23T09:58:37.000Z
from typing import Union from loopchain.blockchain.types import Hash32 from loopchain.blockchain.blocks import BlockProver as BaseBlockProver from loopchain.blockchain.blocks.v0_1a import BlockHeader class BlockProver(BaseBlockProver): version = BlockHeader.version def get_proof(self, hash_: Hash32): raise RuntimeError(f"get_proof: Not supported ver: {self.version}") def get_proof_root(self): raise RuntimeError(f"get_proof_root: Not supported ver: {self.version}") def prove(self, hash_: Hash32, root_hash: Hash32, proof: list): raise RuntimeError(f"prove: Not supported ver: {self.version}") def get_hash_generator(self): raise RuntimeError(f"get_hash_generator: Not supported ver: {self.version}") def to_hash32(self, value: Union[Hash32, bytes, bytearray, int, bool, dict]): raise RuntimeError(f"to_hash32: Not supported ver: {self.version}")
38.375
84
0.741585
121
921
5.512397
0.322314
0.074963
0.134933
0.142429
0.343328
0.182909
0.095952
0
0
0
0
0.020725
0.161781
921
23
85
40.043478
0.843264
0
0
0
0
0
0.249729
0
0
0
0
0
0
1
0.3125
false
0
0.25
0
0.6875
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
be31f50fb5db19848e619d9147c899f28c5033d7
5,154
py
Python
src/main/python/recognition/custom/recognizer.py
DonaldMcRonald/SketchRecognitionWithTensorFlow
f712a8d78bce8af88365045116b27d56ec71dbec
[ "MIT" ]
2
2016-05-12T18:30:39.000Z
2016-05-17T14:03:38.000Z
src/main/python/recognition/custom/recognizer.py
DonaldMcRonald/SketchRecognitionWithTensorFlow
f712a8d78bce8af88365045116b27d56ec71dbec
[ "MIT" ]
4
2016-05-14T22:53:49.000Z
2016-05-14T23:40:40.000Z
src/main/python/recognition/custom/recognizer.py
DonaldMcRonald/SketchRecognitionWithTensorFlow
f712a8d78bce8af88365045116b27d56ec71dbec
[ "MIT" ]
null
null
null
import math import tensorflow as tf from recognition import sketch_utils as utils import custom_recogntion_utilities as training_helpers from generated_proto import sketch_pb2 as Sketch from recognition.generation import feature_generation as features X = 0 Y = 1 ID = 2 class Recognizer: num_points = 32 classifier = None training_bundle_features = None training_bundle_targets = None training_bundle_amount = 1000 training_bundle_counter = 0 X_placeholder = None Y_placeholder = None num_classes = 2 session = None def __init__(self, label): self.label = label self.graph = tf.Graph() with self.graph.as_default() as g: with g.name_scope(label) as scope: self.points_placeholder = tf.placeholder(tf.float32, shape=[None, 2], name="points") feature_list = features.generate_features(self.points_placeholder) #feature_list = tf.Print(feature_list, [feature_list], "Features for recognition", summarize=500) column_list = features.generate_columns() mapping = features.match_features_columns(feature_list, column_list) first_layer = tf.contrib.layers.input_from_feature_columns(columns_to_tensors=mapping, feature_columns=column_list) with g.name_scope('layer2') as scope1: layer2 = tf.contrib.layers.fully_connected(first_layer, 50, scope=scope1) with g.name_scope('hidden1') as scope2: hidden = tf.contrib.layers.fully_connected(layer2, 20, scope=scope2) with g.name_scope('hidden2') as scope3: output = tf.contrib.layers.fully_connected(hidden, self.num_classes, scope=scope3) output = tf.sigmoid(output) print output self.class_index = tf.argmax(output, 0) output = tf.Print(output, [output, self.class_index], "Raw output of training data") self.output = output self.target = training_helpers.create_target_classes(self.num_classes) lossTarget = tf.Print(self.target, [self.target], "Raw target data") self.loss = training_helpers.create_loss_function(output, lossTarget) self.train_step = training_helpers.create_training(self.loss, .01) self.init = tf.initialize_all_variables() self.graph.finalize() def create_features(self, point_list): utils.strip_ids_from_points(point_list) return point_list def create_target(self, label): # big punishment to show difference between 0 and 1 true_class = 1.0 if label == self.label else 0.0 null_class = 1.0 if label != self.label else 0.0 return [[true_class, null_class]] def train(self, label, points): target = self.create_target(label) if self.training_bundle_features is None: self.training_bundle_features = [points] else: self.training_bundle_features.append(points) if self.training_bundle_targets is None: self.training_bundle_targets = [target] else: self.training_bundle_targets.append(target) if self.training_bundle_counter >= self.training_bundle_amount: self.execute_train_bundle() else: self.training_bundle_counter += 1 # TODO: change back to this when the code is fixed def single_train(self, label, features): target = self.create_target(label) self.classifier.fit(x=features, y=target, steps=1) def execute_train_bundle(self): print 'batch training: ' + self.label with tf.Session(graph=self.graph) as sess: sess.run(self.init) for i in range(self.training_bundle_counter): feed = {self.points_placeholder: self.training_bundle_features[i], self.target: self.training_bundle_targets[i]} result = sess.run(self.train_step, feed_dict=feed) print result self.training_bundle_features = None self.training_bundle_targets = None self.training_bundle_counter = 0 def finish_training(self): if self.training_bundle_counter > 0: self.execute_train_bundle() def recognize(self, features): interpretation = Sketch.SrlInterpretation() with tf.Session(graph=self.graph) as sess: sess.run(self.init) feed = {self.points_placeholder: features} raw_output, class_index = sess.run([self.output, self.class_index], feed) print class_index print 'result: ' + str(self.label if class_index == 0 else None) print raw_output interpretation.label = self.label interpretation.confidence = raw_output[class_index] return interpretation
42.245902
114
0.623399
601
5,154
5.123128
0.237937
0.090939
0.093537
0.042222
0.149399
0.050016
0.050016
0.050016
0.050016
0.050016
0
0.014127
0.299573
5,154
121
115
42.595041
0.838781
0.037835
0
0.111111
1
0
0.019032
0
0
0
0
0.008264
0
0
null
null
0
0.060606
null
null
0.060606
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
be39e9337b3cdfbb872af52ff302b6975a3db45e
12,547
py
Python
Lib/site-packages/tensorflow/core/protobuf/tpu/tpu_embedding_configuration_pb2.py
xorb813/Text-Mining
3dced9dd06fc9334d631ddf608b2ed96c2493276
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Lib/site-packages/tensorflow/core/protobuf/tpu/tpu_embedding_configuration_pb2.py
xorb813/Text-Mining
3dced9dd06fc9334d631ddf608b2ed96c2493276
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Lib/site-packages/tensorflow/core/protobuf/tpu/tpu_embedding_configuration_pb2.py
xorb813/Text-Mining
3dced9dd06fc9334d631ddf608b2ed96c2493276
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/tpu/tpu_embedding_configuration.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from tensorflow.core.protobuf.tpu import optimization_parameters_pb2 as tensorflow_dot_core_dot_protobuf_dot_tpu_dot_optimization__parameters__pb2 from tensorflow.core.protobuf.tpu import tpu_embedding_output_layout_pb2 as tensorflow_dot_core_dot_protobuf_dot_tpu_dot_tpu__embedding__output__layout__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='tensorflow/core/protobuf/tpu/tpu_embedding_configuration.proto', package='tensorflow.tpu', syntax='proto3', serialized_options=None, serialized_pb=_b('\n>tensorflow/core/protobuf/tpu/tpu_embedding_configuration.proto\x12\x0etensorflow.tpu\x1a:tensorflow/core/protobuf/tpu/optimization_parameters.proto\x1a>tensorflow/core/protobuf/tpu/tpu_embedding_output_layout.proto\"\xf1\x05\n\x19TPUEmbeddingConfiguration\x12S\n\x10table_descriptor\x18\x01 \x03(\x0b\x32\x39.tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor\x12<\n\x04mode\x18\x02 \x01(\x0e\x32..tensorflow.tpu.TPUEmbeddingConfiguration.Mode\x12\"\n\x1a\x62\x61tch_size_per_tensor_core\x18\x03 \x01(\x05\x12\x11\n\tnum_hosts\x18\x04 \x01(\x05\x12\x18\n\x10num_tensor_cores\x18\x05 \x01(\x05\x12U\n\x11sharding_strategy\x18\x06 \x01(\x0e\x32:.tensorflow.tpu.TPUEmbeddingConfiguration.ShardingStrategy\x12+\n#pipeline_execution_with_tensor_core\x18\x07 \x01(\x08\x12\x43\n\routput_layout\x18\x08 \x01(\x0b\x32(.tensorflow.tpu.TPUEmbeddingOutputLayoutB\x02\x18\x01\x1a\xaa\x01\n\x0fTableDescriptor\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0fvocabulary_size\x18\x02 \x01(\x05\x12\x11\n\tdimension\x18\x03 \x01(\x05\x12\x14\n\x0cnum_features\x18\x04 \x01(\x05\x12G\n\x17optimization_parameters\x18\x05 \x01(\x0b\x32&.tensorflow.tpu.OptimizationParameters\"L\n\x04Mode\x12\x0f\n\x0bUNSPECIFIED\x10\x00\x12\r\n\tINFERENCE\x10\x01\x12\x0c\n\x08TRAINING\x10\x02\x12\x16\n\x12\x42\x41\x43KWARD_PASS_ONLY\x10\x03\",\n\x10ShardingStrategy\x12\x0f\n\x0b\x44IV_DEFAULT\x10\x00\x12\x07\n\x03MOD\x10\x01\x62\x06proto3') , dependencies=[tensorflow_dot_core_dot_protobuf_dot_tpu_dot_optimization__parameters__pb2.DESCRIPTOR,tensorflow_dot_core_dot_protobuf_dot_tpu_dot_tpu__embedding__output__layout__pb2.DESCRIPTOR,]) _TPUEMBEDDINGCONFIGURATION_MODE = _descriptor.EnumDescriptor( name='Mode', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.Mode', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='UNSPECIFIED', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='INFERENCE', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='TRAINING', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='BACKWARD_PASS_ONLY', index=3, number=3, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=838, serialized_end=914, ) _sym_db.RegisterEnumDescriptor(_TPUEMBEDDINGCONFIGURATION_MODE) _TPUEMBEDDINGCONFIGURATION_SHARDINGSTRATEGY = _descriptor.EnumDescriptor( name='ShardingStrategy', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.ShardingStrategy', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='DIV_DEFAULT', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='MOD', index=1, number=1, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=916, serialized_end=960, ) _sym_db.RegisterEnumDescriptor(_TPUEMBEDDINGCONFIGURATION_SHARDINGSTRATEGY) _TPUEMBEDDINGCONFIGURATION_TABLEDESCRIPTOR = _descriptor.Descriptor( name='TableDescriptor', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor.name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='vocabulary_size', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor.vocabulary_size', index=1, number=2, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='dimension', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor.dimension', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='num_features', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor.num_features', index=3, number=4, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='optimization_parameters', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor.optimization_parameters', index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=666, serialized_end=836, ) _TPUEMBEDDINGCONFIGURATION = _descriptor.Descriptor( name='TPUEmbeddingConfiguration', full_name='tensorflow.tpu.TPUEmbeddingConfiguration', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='table_descriptor', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.table_descriptor', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='mode', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.mode', index=1, number=2, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='batch_size_per_tensor_core', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.batch_size_per_tensor_core', index=2, number=3, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='num_hosts', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.num_hosts', index=3, number=4, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='num_tensor_cores', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.num_tensor_cores', index=4, number=5, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='sharding_strategy', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.sharding_strategy', index=5, number=6, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='pipeline_execution_with_tensor_core', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.pipeline_execution_with_tensor_core', index=6, number=7, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='output_layout', full_name='tensorflow.tpu.TPUEmbeddingConfiguration.output_layout', index=7, number=8, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=_b('\030\001'), file=DESCRIPTOR), ], extensions=[ ], nested_types=[_TPUEMBEDDINGCONFIGURATION_TABLEDESCRIPTOR, ], enum_types=[ _TPUEMBEDDINGCONFIGURATION_MODE, _TPUEMBEDDINGCONFIGURATION_SHARDINGSTRATEGY, ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=207, serialized_end=960, ) _TPUEMBEDDINGCONFIGURATION_TABLEDESCRIPTOR.fields_by_name['optimization_parameters'].message_type = tensorflow_dot_core_dot_protobuf_dot_tpu_dot_optimization__parameters__pb2._OPTIMIZATIONPARAMETERS _TPUEMBEDDINGCONFIGURATION_TABLEDESCRIPTOR.containing_type = _TPUEMBEDDINGCONFIGURATION _TPUEMBEDDINGCONFIGURATION.fields_by_name['table_descriptor'].message_type = _TPUEMBEDDINGCONFIGURATION_TABLEDESCRIPTOR _TPUEMBEDDINGCONFIGURATION.fields_by_name['mode'].enum_type = _TPUEMBEDDINGCONFIGURATION_MODE _TPUEMBEDDINGCONFIGURATION.fields_by_name['sharding_strategy'].enum_type = _TPUEMBEDDINGCONFIGURATION_SHARDINGSTRATEGY _TPUEMBEDDINGCONFIGURATION.fields_by_name['output_layout'].message_type = tensorflow_dot_core_dot_protobuf_dot_tpu_dot_tpu__embedding__output__layout__pb2._TPUEMBEDDINGOUTPUTLAYOUT _TPUEMBEDDINGCONFIGURATION_MODE.containing_type = _TPUEMBEDDINGCONFIGURATION _TPUEMBEDDINGCONFIGURATION_SHARDINGSTRATEGY.containing_type = _TPUEMBEDDINGCONFIGURATION DESCRIPTOR.message_types_by_name['TPUEmbeddingConfiguration'] = _TPUEMBEDDINGCONFIGURATION _sym_db.RegisterFileDescriptor(DESCRIPTOR) TPUEmbeddingConfiguration = _reflection.GeneratedProtocolMessageType('TPUEmbeddingConfiguration', (_message.Message,), { 'TableDescriptor' : _reflection.GeneratedProtocolMessageType('TableDescriptor', (_message.Message,), { 'DESCRIPTOR' : _TPUEMBEDDINGCONFIGURATION_TABLEDESCRIPTOR, '__module__' : 'tensorflow.core.protobuf.tpu.tpu_embedding_configuration_pb2' # @@protoc_insertion_point(class_scope:tensorflow.tpu.TPUEmbeddingConfiguration.TableDescriptor) }) , 'DESCRIPTOR' : _TPUEMBEDDINGCONFIGURATION, '__module__' : 'tensorflow.core.protobuf.tpu.tpu_embedding_configuration_pb2' # @@protoc_insertion_point(class_scope:tensorflow.tpu.TPUEmbeddingConfiguration) }) _sym_db.RegisterMessage(TPUEmbeddingConfiguration) _sym_db.RegisterMessage(TPUEmbeddingConfiguration.TableDescriptor) _TPUEMBEDDINGCONFIGURATION.fields_by_name['output_layout']._options = None # @@protoc_insertion_point(module_scope)
49.789683
1,438
0.789033
1,483
12,547
6.346595
0.140931
0.041649
0.051317
0.03793
0.645878
0.571929
0.472907
0.461007
0.399596
0.393753
0
0.035316
0.10632
12,547
251
1,439
49.988048
0.804067
0.031561
0
0.588496
1
0.004425
0.262209
0.228691
0
0
0
0
0
1
0
false
0.00885
0.030973
0
0.030973
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
be3af530e7de92d11572b1683ad2225f6f207e01
304
py
Python
mtpylon/serialization/double.py
Zapix/mtpylon
b268a4e2d1bc641cace1962ea68de73c1156e44c
[ "MIT" ]
9
2021-11-10T08:53:51.000Z
2021-12-15T12:03:44.000Z
mtpylon/serialization/double.py
Zapix/mtpylon
b268a4e2d1bc641cace1962ea68de73c1156e44c
[ "MIT" ]
123
2020-10-22T07:08:20.000Z
2021-09-29T15:26:22.000Z
mtpylon/serialization/double.py
Zapix/mtpylon
b268a4e2d1bc641cace1962ea68de73c1156e44c
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import struct from .loaded import LoadedValue from .. import double def dump(value: double) -> bytes: return struct.pack('=d', value) def load(input: bytes) -> LoadedValue[double]: return LoadedValue( double(struct.unpack('d', input[:8])[0]), 8 )
17.882353
49
0.618421
38
304
4.947368
0.526316
0.180851
0
0
0
0
0
0
0
0
0
0.016878
0.220395
304
16
50
19
0.776371
0.069079
0
0
0
0
0.010676
0
0
0
0
0
0
1
0.2
false
0
0.3
0.2
0.7
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
be3df36488b94ed302e0ca1ad1714a26da12ffeb
328
py
Python
metadata.py
RusDavies/PyBlakemere
08c7a7170a98821a93957d9101f57e31b11c2085
[ "MIT" ]
null
null
null
metadata.py
RusDavies/PyBlakemere
08c7a7170a98821a93957d9101f57e31b11c2085
[ "MIT" ]
null
null
null
metadata.py
RusDavies/PyBlakemere
08c7a7170a98821a93957d9101f57e31b11c2085
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- __author__ = 'Russell Davies' __copyright__ = 'Copyright (c) 2019-present - Russell Davies' __description__ = 'The blakemere package provides a collection of python libraries created by Russell Davies.' __email__ = 'russell@blakemere.ca' __license__ = 'MIT' __title__ = 'blakemere' __version__ = '0.1.0'
36.444444
110
0.746951
39
328
5.564103
0.769231
0.179724
0
0
0
0
0
0
0
0
0
0.028169
0.134146
328
9
111
36.444444
0.735915
0.064024
0
0
0
0
0.601307
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
be5628b1a969b2a84c299d59fd10a942a5fca76e
7,115
py
Python
third_party/libSBML-5.9.0-Source/src/bindings/python/test/sbml/TestSBMLNamespaces.py
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
5
2015-04-16T14:27:38.000Z
2021-11-30T14:54:39.000Z
third_party/libSBML-5.9.0-Source/src/bindings/python/test/sbml/TestSBMLNamespaces.py
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
95
2015-03-06T12:14:06.000Z
2015-03-20T11:15:54.000Z
third_party/libSBML-5.9.0-Source/src/bindings/python/test/sbml/TestSBMLNamespaces.py
0u812/roadrunner
f464c2649e388fa1f5a015592b0b29b65cc84b4b
[ "Apache-2.0" ]
7
2016-05-29T08:12:59.000Z
2019-05-02T13:39:25.000Z
# # @file TestSBMLNamespaces.py # @brief SBMLNamespaces unit tests # # @author Akiya Jouraku (Python conversion) # @author Sarah Keating # # ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ====== # # DO NOT EDIT THIS FILE. # # This file was generated automatically by converting the file located at # src/sbml/test/TestSBMLNamespaces.cpp # using the conversion program dev/utilities/translateTests/translateTests.pl. # Any changes made here will be lost the next time the file is regenerated. # # ----------------------------------------------------------------------------- # This file is part of libSBML. Please visit http://sbml.org for more # information about SBML, and the latest version of libSBML. # # Copyright 2005-2010 California Institute of Technology. # Copyright 2002-2005 California Institute of Technology and # Japan Science and Technology Corporation. # # This library is free software; you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation. A copy of the license agreement is provided # in the file named "LICENSE.txt" included with this software distribution # and also available online as http://sbml.org/software/libsbml/license.html # ----------------------------------------------------------------------------- import sys import unittest import libsbml class TestSBMLNamespaces(unittest.TestCase): def test_SBMLNamespaces_L1V1(self): sbml = libsbml.SBMLNamespaces(1,1) self.assert_( sbml.getLevel() == 1 ) self.assert_( sbml.getVersion() == 1 ) ns = sbml.getNamespaces() self.assert_( ns.getLength() == 1 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level1" ) self.assert_( ns.getPrefix(0) == "" ) sbml = None pass def test_SBMLNamespaces_L1V2(self): sbml = libsbml.SBMLNamespaces(1,2) self.assert_( sbml.getLevel() == 1 ) self.assert_( sbml.getVersion() == 2 ) ns = sbml.getNamespaces() self.assert_( ns.getLength() == 1 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level1" ) self.assert_( ns.getPrefix(0) == "" ) sbml = None pass def test_SBMLNamespaces_L2V1(self): sbml = libsbml.SBMLNamespaces(2,1) self.assert_( sbml.getLevel() == 2 ) self.assert_( sbml.getVersion() == 1 ) ns = sbml.getNamespaces() self.assert_( ns.getLength() == 1 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level2" ) self.assert_( ns.getPrefix(0) == "" ) sbml = None pass def test_SBMLNamespaces_L2V2(self): sbml = libsbml.SBMLNamespaces(2,2) self.assert_( sbml.getLevel() == 2 ) self.assert_( sbml.getVersion() == 2 ) ns = sbml.getNamespaces() self.assert_( ns.getLength() == 1 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level2/version2" ) self.assert_( ns.getPrefix(0) == "" ) sbml = None pass def test_SBMLNamespaces_L2V3(self): sbml = libsbml.SBMLNamespaces(2,3) self.assert_( sbml.getLevel() == 2 ) self.assert_( sbml.getVersion() == 3 ) ns = sbml.getNamespaces() self.assert_( ns.getLength() == 1 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level2/version3" ) self.assert_( ns.getPrefix(0) == "" ) sbml = None pass def test_SBMLNamespaces_L2V4(self): sbml = libsbml.SBMLNamespaces(2,4) self.assert_( sbml.getLevel() == 2 ) self.assert_( sbml.getVersion() == 4 ) ns = sbml.getNamespaces() self.assert_( ns.getLength() == 1 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level2/version4" ) self.assert_( ns.getPrefix(0) == "" ) sbml = None pass def test_SBMLNamespaces_L3V1(self): sbml = libsbml.SBMLNamespaces(3,1) self.assert_( sbml.getLevel() == 3 ) self.assert_( sbml.getVersion() == 1 ) ns = sbml.getNamespaces() self.assert_( ns.getLength() == 1 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level3/version1/core" ) self.assert_( ns.getPrefix(0) == "" ) sbml = None pass def test_SBMLNamespaces_add_and_remove_namespaces(self): sbmlns = libsbml.SBMLNamespaces( 3,1 ) self.assert_( sbmlns.getLevel() == 3 ) self.assert_( sbmlns.getVersion() == 1 ) sbmlns.addNamespace("http://www.sbml.org/sbml/level3/version1/group/version1", "group") sbmlns.addNamespace("http://www.sbml.org/sbml/level3/version1/layout/version1", "layout") sbmlns.addNamespace("http://www.sbml.org/sbml/level3/version1/render/version1", "render") sbmlns.addNamespace("http://www.sbml.org/sbml/level3/version1/multi/version1", "multi") ns = sbmlns.getNamespaces() self.assert_( ns.getLength() == 5 ) self.assert_( ns.getURI(0) == "http://www.sbml.org/sbml/level3/version1/core" ) self.assert_( ns.getPrefix(0) == "" ) self.assert_( ns.getURI(1) == "http://www.sbml.org/sbml/level3/version1/group/version1" ) self.assert_( ns.getPrefix(1) == "group" ) self.assert_( ns.getURI(2) == "http://www.sbml.org/sbml/level3/version1/layout/version1" ) self.assert_( ns.getPrefix(2) == "layout" ) self.assert_( ns.getURI(3) == "http://www.sbml.org/sbml/level3/version1/render/version1" ) self.assert_( ns.getPrefix(3) == "render" ) self.assert_( ns.getURI(4) == "http://www.sbml.org/sbml/level3/version1/multi/version1" ) self.assert_( ns.getPrefix(4) == "multi" ) sbmlns.removeNamespace("http://www.sbml.org/sbml/level3/version1/layout/version1") sbmlns.removeNamespace("http://www.sbml.org/sbml/level3/version1/group/version1") sbmlns.removeNamespace("http://www.sbml.org/sbml/level3/version1/render/version1") sbmlns.removeNamespace("http://www.sbml.org/sbml/level3/version1/multi/version1") pass def test_SBMLNamespaces_getURI(self): self.assert_( libsbml.SBMLNamespaces.getSBMLNamespaceURI(1,1) == "http://www.sbml.org/sbml/level1" ) self.assert_( libsbml.SBMLNamespaces.getSBMLNamespaceURI(1,2) == "http://www.sbml.org/sbml/level1" ) self.assert_( libsbml.SBMLNamespaces.getSBMLNamespaceURI(2,1) == "http://www.sbml.org/sbml/level2" ) self.assert_( libsbml.SBMLNamespaces.getSBMLNamespaceURI(2,2) == "http://www.sbml.org/sbml/level2/version2" ) self.assert_( libsbml.SBMLNamespaces.getSBMLNamespaceURI(2,3) == "http://www.sbml.org/sbml/level2/version3" ) self.assert_( libsbml.SBMLNamespaces.getSBMLNamespaceURI(2,4) == "http://www.sbml.org/sbml/level2/version4" ) self.assert_( libsbml.SBMLNamespaces.getSBMLNamespaceURI(3,1) == "http://www.sbml.org/sbml/level3/version1/core" ) pass def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestSBMLNamespaces)) return suite if __name__ == "__main__": if unittest.TextTestRunner(verbosity=1).run(suite()).wasSuccessful() : sys.exit(0) else: sys.exit(1)
43.384146
147
0.6461
865
7,115
5.217341
0.195376
0.12187
0.085088
0.083758
0.675825
0.597385
0.541768
0.541768
0.525814
0.336362
0
0.029437
0.183556
7,115
163
148
43.650307
0.747461
0.186086
0
0.452991
0
0
0.222049
0
0
0
0
0
0.470085
1
0.08547
false
0.076923
0.025641
0
0.128205
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
1
0
0
0
0
0
2
be596f664d5a2ad46fcd8ec2a2eb9d6a185d75d2
29,182
py
Python
lizard_auth_server/tests/test_views_api_v2.py
lisannewapstra/lizard-auth-server
3824edfaedd01caff5eb84bbcb9557ccfec2371a
[ "MIT", "BSD-3-Clause" ]
null
null
null
lizard_auth_server/tests/test_views_api_v2.py
lisannewapstra/lizard-auth-server
3824edfaedd01caff5eb84bbcb9557ccfec2371a
[ "MIT", "BSD-3-Clause" ]
null
null
null
lizard_auth_server/tests/test_views_api_v2.py
lisannewapstra/lizard-auth-server
3824edfaedd01caff5eb84bbcb9557ccfec2371a
[ "MIT", "BSD-3-Clause" ]
null
null
null
from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.test import Client from django.test import TestCase from django.test.client import RequestFactory from django.urls import reverse from lizard_auth_server import views_api_v2 from lizard_auth_server.tests import factories import copy import datetime import json import jwt import mock class TestStartView(TestCase): def test_smoke(self): client = Client() result = client.get(reverse("lizard_auth_server.api_v2.start")) self.assertEqual(200, result.status_code) def test_url_includes_host(self): response = self.client.get("https://some.server/api2/") self.assertIn("http", str(response.content)) class TestCheckCredentialsView(TestCase): def setUp(self): self.sso_key = "sso key" factories.PortalF.create(sso_key=self.sso_key) self.view = views_api_v2.CheckCredentialsView() self.request_factory = RequestFactory() self.some_request = self.request_factory.get("/some/url/") self.organisation = factories.OrganisationF() self.username = "reinout" self.password = "annie" self.user = factories.UserF(username=self.username, password=self.password) def test_disallowed_get(self): client = Client() result = client.get(reverse("lizard_auth_server.api_v2.check_credentials")) self.assertEqual(405, result.status_code) def test_smoke_post(self): client = Client() result = client.post(reverse("lizard_auth_server.api_v2.check_credentials")) self.assertEqual(400, result.status_code) def test_valid_login(self): form = mock.Mock() form.cleaned_data = { "iss": self.sso_key, "username": self.username, "password": self.password, } result = self.view.form_valid(form) self.assertEqual(200, result.status_code) def test_invalid_login(self): form = mock.Mock() form.cleaned_data = { "iss": self.sso_key, "username": "pietje", "password": "ikkanniettypen", } self.assertRaises(PermissionDenied, self.view.form_valid, form) def test_inactive_user(self): self.user.is_active = False self.user.save() form = mock.Mock() form.cleaned_data = { "iss": self.sso_key, "username": self.username, "password": self.password, } self.assertRaises(PermissionDenied, self.view.form_valid, form) def test_missing_username(self): form = mock.Mock() form.cleaned_data = {"iss": self.sso_key, "password": "ikkanniettypen"} response = self.view.form_valid(form) self.assertEqual(400, response.status_code) class TestLoginView(TestCase): """Test the V2 API login view""" def setUp(self): self.username = "me" self.password = "bla" self.sso_key = "ssokey" self.secret_key = "a secret" self.client = Client() user = factories.UserF.create(username=self.username) user.set_password(self.password) user.save() self.user_profile = factories.UserProfileF(user=user) self.portal = factories.PortalF.create( sso_key=self.sso_key, sso_secret=self.secret_key, ) self.portal.save() self.payload = { "iss": self.sso_key, "login_success_url": "http://very.custom.net/sso/local_login/", } self.message = jwt.encode(self.payload, self.secret_key, algorithm="HS256") def test_login_redirect_back_to_site(self): params = { "username": self.username, "password": self.password, "next": "/api2/login/", } resp1 = self.client.post("/accounts/login/", params) self.assertEqual(resp1.status_code, 302) jwt_params = { "key": self.sso_key, "message": self.message, } self.assertEqual(resp1.url, "/api2/login/") resp2 = self.client.get("/api2/login/", jwt_params) self.assertEqual(resp2.status_code, 302) self.assertTrue("http://very.custom.net/sso/local_login/" in resp2.url) def test_no_login_redirect_back_to_site(self): payload = { "iss": self.sso_key, "login_success_url": "http://custom.net/sso/local_login/", "unauthenticated_is_ok_url": "http://cstm.net/not_logged_in/", } message = jwt.encode(payload, self.secret_key, algorithm="HS256") jwt_params = { "key": self.sso_key, "message": message, } response = self.client.get("/api2/login/", jwt_params) self.assertEqual(response.status_code, 302) self.assertTrue("http://cstm.net/not_logged_in/" in response.url) def test_redirect_to_login_page(self): jwt_params = { "key": self.sso_key, "message": self.message, } response = self.client.get("/api2/login/", jwt_params) self.assertEqual(response.status_code, 302) self.assertTrue("/accounts/login/" in response.url) def test_inactive_user_cant_login(self): # We're basically testing django functionality here. Ah well. self.user_profile.user.is_active = False self.user_profile.user.save() params = { "username": self.username, "password": self.password, "next": "/api2/login/", } response = self.client.post("/accounts/login/", params) # Basically this means that the redirect failed and the user couldn't # log in, which is in line with what we expect with an inactive user. self.assertTrue(response.status_code != 302) self.assertEqual(response.status_code, 200) def test_missing_success_url(self): faulty_payload = { "iss": self.sso_key, } faulty_message = jwt.encode(faulty_payload, self.secret_key, algorithm="HS256") jwt_params = { "key": self.sso_key, "message": faulty_message, } response = self.client.get("/api2/login/", jwt_params) self.assertEqual(response.status_code, 400) class TestLogoutViewV2(TestCase): """Test the V2 API logout""" def setUp(self): self.username = "me" self.password = "bla" self.sso_key = "ssokey" self.secret_key = "a secret" redirect = "http://default.portal.net" self.client = Client() user = factories.UserF.create(username=self.username) user.set_password(self.password) user.save() self.user_profile = factories.UserProfileF(user=user) self.portal = factories.PortalF.create( sso_key=self.sso_key, sso_secret=self.secret_key, redirect_url=redirect, ) self.portal.save() self.payload = { "iss": self.sso_key, "logout_url": "http://very.custom.net/sso/logout/", } self.message = jwt.encode(self.payload, self.secret_key, algorithm="HS256") def test_logout_with_missing_param(self): faulty_message = jwt.encode( {"iss": self.sso_key}, self.secret_key, algorithm="HS256" ) params = {"key": self.sso_key, "message": faulty_message} response = self.client.get("/api2/logout/", params) self.assertEqual(response.status_code, 400) def test_logout_phase_one(self): params = {"key": self.sso_key, "message": self.message} response = self.client.get("/api2/logout/", params) self.assertEqual(response.status_code, 302) self.assertTrue("/accounts/logout/" in response.url) self.assertTrue("key%3Dssokey" in response.url) def test_logout_phase_two(self): params = {"key": self.sso_key, "message": self.message} response = self.client.get("/api2/logout_redirect_back_to_portal/", params) self.assertEqual(response.status_code, 302) self.assertEqual("http://very.custom.net/sso/logout/", response.url) class TestNewUserView(TestCase): def setUp(self): self.view = views_api_v2.NewUserView() self.sso_key = "sso key" self.portal = factories.PortalF.create(sso_key=self.sso_key) self.request_factory = RequestFactory() self.some_request = self.request_factory.get("http://some.site/some/url/") self.user_data = { "iss": self.sso_key, "username": "pietje", "email": "pietje@klaasje.test.com", "first_name": "pietje", "last_name": "klaasje", } def test_disallowed_get(self): client = Client() result = client.get(reverse("lizard_auth_server.api_v2.new_user")) self.assertEqual(405, result.status_code) def test_new_user(self): form = mock.Mock() form.cleaned_data = self.user_data self.view.request = self.some_request result = self.view.form_valid(form) self.assertEqual(201, result.status_code) self.assertTrue(User.objects.get(username="pietje")) def test_new_user_starts_inactive(self): form = mock.Mock() form.cleaned_data = self.user_data self.view.request = self.some_request self.view.form_valid(form) self.assertFalse(User.objects.get(username="pietje").is_active) def test_new_user_sends_email(self): form = mock.Mock() form.cleaned_data = self.user_data self.view.request = self.some_request with mock.patch("lizard_auth_server.views_api_v2.send_mail") as mocked: self.view.form_valid(form) arguments = mocked.call_args[0] message = arguments[1] self.assertIn("sso%20key", message) def test_exiting_user(self): factories.UserF(email="pietje@klaasje.test.com") form = mock.Mock() form.cleaned_data = self.user_data result = self.view.form_valid(form) # Should return a 409 conflict statuscode. self.assertEqual(409, result.status_code) def test_exiting_user_different_case(self): factories.UserF(email="Pietje@Klaasje.Test.Com") form = mock.Mock() form.cleaned_data = self.user_data result = self.view.form_valid(form) # Should return a 409 conflict statucode self.assertEqual(409, result.status_code) def test_exiting_user_duplicate_email(self): factories.UserF(email="pietje@klaasje.test.com") factories.UserF(email="pietje@klaasje.test.com") form = mock.Mock() form.cleaned_data = self.user_data result = self.view.form_valid(form) # Should return a 409 conflict statuscode self.assertEqual(409, result.status_code) def test_duplicate_username(self): factories.UserF(username="pietje", email="nietpietje@example.com") form = mock.Mock() form.cleaned_data = self.user_data response = self.view.form_valid(form) self.assertEqual(409, response.status_code) def test_duplicate_username_http_response(self): # Duplicate username (with different e-mail) # should return HTTP 409 (conflict) factories.UserF(username="pietje", email="nietpietje@example.com") client = Client() params = { "username": "pietje", "email": "nietpietje1@example.com", "first_name": "pietje", "last_name": "pietje", "iss": self.sso_key, } # Encode data in JWT message = jwt.encode(params, self.portal.sso_secret, algorithm="HS256") # Send data both plain and in JWT. params.update({"key": self.sso_key, "message": message.decode("utf8")}) response = client.post(reverse("lizard_auth_server.api_v2.new_user"), params) self.assertEqual(409, response.status_code) def test_optional_visit_url(self): user_data = { "iss": self.sso_key, "username": "pietje", "email": "pietje@klaasje.test.com", "first_name": "pietje", "last_name": "klaasje", "visit_url": "http://reinout.vanrees.org/", } form = mock.Mock() form.cleaned_data = user_data self.view.request = self.some_request with mock.patch("jwt.encode") as mocked: mocked.return_value = "something" self.view.form_valid(form) args, kwargs = mocked.call_args payload = args[0] self.assertEqual("http://reinout.vanrees.org/", payload["visit_url"]) def test_optional_visit_url_in_email(self): user_data = { "iss": self.sso_key, "username": "pietje", "email": "pietje@klaasje.test.com", "first_name": "pietje", "last_name": "klaasje", "visit_url": "http://reinout.vanrees.org/", } form = mock.Mock() form.cleaned_data = user_data self.view.request = self.some_request with mock.patch("lizard_auth_server.views_api_v2.send_mail") as mocked: self.view.form_valid(form) arguments = mocked.call_args[0] message = arguments[1] self.assertIn("http://reinout.vanrees.org/", message) def test_missing_mandatory_field(self): form = mock.Mock() form.cleaned_data = copy.deepcopy(self.user_data) del form.cleaned_data["first_name"] response = self.view.form_valid(form) self.assertEqual(400, response.status_code) def test_failure_on_unavailable_language(self): form = mock.Mock() form.cleaned_data = copy.deepcopy(self.user_data) form.cleaned_data["language"] = "tlh" response = self.view.form_valid(form) self.assertEqual(400, response.status_code) class TestActivateAndSetPasswordView(TestCase): def setUp(self): self.user = factories.UserF.create() self.user.set_unusable_password() self.user.is_active = False self.user.save() self.portal = factories.PortalF.create() # Mimick url creation. See create_and_mail_user() key = self.portal.sso_key expiration = datetime.datetime.utcnow() + datetime.timedelta(days=1) payload = {"aud": key, "exp": expiration, "user_id": self.user.id} signed_message = jwt.encode(payload, self.portal.sso_secret, algorithm="HS256") self.activation_url = reverse( "lizard_auth_server.api_v2.activate-and-set-password", kwargs={ "user_id": self.user.id, "sso_key": key, "language": "en", "message": signed_message, }, ) def test_get_smoke(self): client = Client() response = client.get(self.activation_url) self.assertEqual(200, response.status_code) def test_post_smoke(self): client = Client() response = client.post( self.activation_url, {"new_password1": "Pietje123", "new_password2": "Pietje123"}, ) self.assertEqual(302, response.status_code) def test_user_is_activated(self): client = Client() client.post( self.activation_url, {"new_password1": "Pietje123", "new_password2": "Pietje123"}, ) self.user.refresh_from_db() self.assertTrue(self.user.is_active) self.assertTrue(self.user.has_usable_password()) def test_visit_url(self): key = self.portal.sso_key expiration = datetime.datetime.utcnow() + datetime.timedelta(days=1) payload = { "aud": key, "exp": expiration, "user_id": self.user.id, "visit_url": "http://reinout.vanrees.org/", } signed_message = jwt.encode(payload, self.portal.sso_secret, algorithm="HS256") activation_url = reverse( "lizard_auth_server.api_v2.activate-and-set-password", kwargs={ "user_id": self.user.id, "sso_key": key, "language": "en", "message": signed_message, }, ) client = Client() response = client.post( activation_url, {"new_password1": "Pietje123", "new_password2": "Pietje123"} ) self.assertEqual(302, response.status_code) self.assertIn("reinout.vanrees.org", response.url) def test_checks1(self): # Fail on expired JTW token key = self.portal.sso_key expiration = datetime.datetime.utcnow() - datetime.timedelta(days=1) payload = {"aud": key, "exp": expiration, "user_id": self.user.id} signed_message = jwt.encode(payload, self.portal.sso_secret, algorithm="HS256") activation_url = reverse( "lizard_auth_server.api_v2.activate-and-set-password", kwargs={ "user_id": self.user.id, "sso_key": key, "language": "en", "message": signed_message, }, ) client = Client() response = client.post( activation_url, {"new_password1": "Pietje123", "new_password2": "Pietje123"} ) self.assertEqual(400, response.status_code) def test_checks2(self): # Fail on missing 'aud' and 'exp' JWT fields. key = self.portal.sso_key payload = {"user_id": self.user.id} signed_message = jwt.encode(payload, self.portal.sso_secret, algorithm="HS256") activation_url = reverse( "lizard_auth_server.api_v2.activate-and-set-password", kwargs={ "user_id": self.user.id, "sso_key": key, "language": "en", "message": signed_message, }, ) client = Client() response = client.post( activation_url, {"new_password1": "Pietje123", "new_password2": "Pietje123"} ) self.assertEqual(400, response.status_code) def test_checks3(self): # Fail on non-matching user id key = self.portal.sso_key expiration = datetime.datetime.utcnow() + datetime.timedelta(days=1) payload = {"aud": key, "exp": expiration, "user_id": 12345} signed_message = jwt.encode(payload, self.portal.sso_secret, algorithm="HS256") activation_url = reverse( "lizard_auth_server.api_v2.activate-and-set-password", kwargs={ "user_id": self.user.id, "sso_key": key, "language": "en", "message": signed_message, }, ) client = Client() response = client.post( activation_url, {"new_password1": "Pietje123", "new_password2": "Pietje123"} ) self.assertEqual(400, response.status_code) def test_checks4(self): # Fail on unavailable language key = self.portal.sso_key expiration = datetime.datetime.utcnow() + datetime.timedelta(days=1) payload = {"aud": key, "exp": expiration, "user_id": self.user.id} signed_message = jwt.encode(payload, self.portal.sso_secret, algorithm="HS256") activation_url = reverse( "lizard_auth_server.api_v2.activate-and-set-password", kwargs={ "user_id": self.user.id, "sso_key": key, "language": "tlh", "message": signed_message, }, ) client = Client() response = client.post( activation_url, {"new_password1": "Pietje123", "new_password2": "Pietje123"} ) self.assertEqual(400, response.status_code) class TestActivatedGoToPortalView(TestCase): def setUp(self): self.portal = factories.PortalF.create() def test_smoke(self): client = Client() response = client.get("/api2/activated/%s/" % self.portal.id) self.assertEqual(200, response.status_code) def test_visit_url(self): client = Client() url = "/api2/activated/%s/?visit_url=%s" response = client.get( url % (self.portal.id, "http%3A%2F%2Freinout.vanrees.org%2F") ) self.assertIn("http://reinout.vanrees.org/", str(response.content)) class TestOrganisationsView(TestCase): def setUp(self): sso_key = "ssokey" secret_key = "a secret" factories.PortalF.create( sso_key=sso_key, sso_secret=secret_key, ) payload = {"iss": sso_key} message = jwt.encode(payload, secret_key, algorithm="HS256") self.jwt_params = { "key": sso_key, "message": message, } def test_unauthenticated_denied(self): # You need an sso key (=an empty jwt message) response = self.client.get("/api2/organisations/") self.assertEqual(400, response.status_code) def test_smoke(self): response = self.client.get("/api2/organisations/", self.jwt_params) self.assertEqual(200, response.status_code) def test_result(self): factories.OrganisationF(name="Signalmanufaktur Neuwitz") response = self.client.get("/api2/organisations/", self.jwt_params) self.assertIn("Neuwitz", str(response.content)) class TestFindUserView(TestCase): def setUp(self): self.view = views_api_v2.FindUserView() self.sso_key = "sso key" factories.PortalF.create(sso_key=self.sso_key) self.request_factory = RequestFactory() self.some_request = self.request_factory.get("http://some.site/some/url/") self.user_data = {"iss": self.sso_key, "email": "pietje@klaasje.test.com"} def test_exiting_user(self): factories.UserF(email="pietje@klaasje.test.com") form = mock.Mock() form.cleaned_data = self.user_data result = self.view.form_valid(form) self.assertEqual(200, result.status_code) def test_exiting_user_different_case(self): factories.UserF(email="Pietje@Klaasje.Test.Com") form = mock.Mock() form.cleaned_data = self.user_data result = self.view.form_valid(form) self.assertEqual(200, result.status_code) def test_nonexiting_user(self): form = mock.Mock() form.cleaned_data = self.user_data result = self.view.form_valid(form) self.assertEqual(404, result.status_code) def test_get_allowed(self): client = Client() result = client.get(reverse("lizard_auth_server.api_v2.find_user")) # Status code should be 400 because of an invalid form. It should not # be 405 because of a wrong method. self.assertEqual(400, result.status_code) def test_useful_api_error_response(self): client = Client() result = client.get(reverse("lizard_auth_server.api_v2.find_user")) # The returned content should be a textual message about the jwt # error, not a html page. self.assertNotIn("html", str(result.content)) class TestUserMigrationView(TestCase): def setUp(self): self.sso_key = "sso key" self.portal = factories.PortalF.create( sso_key=self.sso_key, allow_migrate_user=True ) self.view = views_api_v2.CognitoUserMigrationView() self.username = "foo" self.password = "bar" self.user = factories.UserF(username=self.username, password=self.password) self.url = reverse("lizard_auth_server.cognito.migrate_user") self.client = Client() self.expected_profile = { "username": self.user.username, "email": self.user.email, "first_name": self.user.first_name, "last_name": self.user.last_name, } def form_valid(self, **kwargs): form = mock.Mock() form.cleaned_data = { "iss": self.sso_key, "username": self.username, **kwargs, } return self.view.form_valid(form) def test_disallowed_get(self): result = self.client.get(self.url) self.assertEqual(405, result.status_code) def test_smoke_post(self): result = self.client.post(self.url) self.assertEqual(400, result.status_code) def test_migration_not_allowed(self): self.portal.allow_migrate_user = False self.portal.save() self.assertRaises(PermissionDenied, self.form_valid) def test_valid_password(self): result = self.form_valid(password=self.password) self.assertEqual(200, result.status_code) content = json.loads(result.content) self.assertDictEqual(content["user"], self.expected_profile) self.assertTrue(content["password_valid"]) # set migrated_at self.user.user_profile.refresh_from_db() self.assertIsNotNone(self.user.user_profile.migrated_at) def test_invalid_password(self): result = self.form_valid(password="ikkanniettypen") self.assertEqual(200, result.status_code) content = json.loads(result.content) self.assertDictEqual(content["user"], self.expected_profile) self.assertFalse(content["password_valid"]) # invalid password = no migration. do not set migrated_at self.user.user_profile.refresh_from_db() self.assertIsNone(self.user.user_profile.migrated_at) def test_no_password(self): result = self.form_valid() self.assertEqual(200, result.status_code) content = json.loads(result.content) self.assertDictEqual(content["user"], self.expected_profile) self.assertFalse(content["password_valid"]) # no password = forgot password flow. set migrated_at self.user.user_profile.refresh_from_db() self.assertIsNotNone(self.user.user_profile.migrated_at) def test_inactive_user(self): self.user.is_active = False self.user.save() result = self.form_valid() self.assertEqual(404, result.status_code) def test_case_insensitive_username(self): result = self.form_valid(username=self.username.upper()) self.assertEqual(200, result.status_code) # normal-case username is returned content = json.loads(result.content) self.assertEqual(self.username, content["user"]["username"]) def test_duplicate_user(self): factories.UserF(username=self.username.upper()) result = self.form_valid() self.assertEqual(409, result.status_code) def test_mark_migrated(self): self.form_valid() self.user.user_profile.refresh_from_db() self.assertIsNotNone(self.user.user_profile.migrated_at) def test_ignore_migrated(self): self.user.user_profile.migrated_at = datetime.datetime.utcnow() self.user.user_profile.save() result = self.form_valid() self.assertEqual(404, result.status_code) class TestUserExistsView(TestCase): def setUp(self): self.sso_key = "sso key" self.portal = factories.PortalF.create(sso_key=self.sso_key) self.view = views_api_v2.CognitoUserExistsView() self.username = "foo" self.password = "bar" self.email = "foo@bar.com" self.user = factories.UserF( username=self.username, password=self.password, email=self.email ) self.url = reverse("lizard_auth_server.cognito.user_exists") self.client = Client() def form_valid(self, **kwargs): form = mock.Mock() form.cleaned_data = {"iss": self.sso_key, **kwargs} return self.view.form_valid(form) def test_disallowed_get(self): result = self.client.get(self.url) self.assertEqual(405, result.status_code) def test_smoke_post(self): result = self.client.post(self.url) self.assertEqual(400, result.status_code) def test_does_not_exist(self): result = self.form_valid(username="nonexisting", email="a@b.com") self.assertFalse(json.loads(result.content)["exists"]) def test_username(self): result = self.form_valid(username=self.username) self.assertTrue(json.loads(result.content)["exists"]) def test_username_case_insensitive(self): result = self.form_valid(username=self.username.upper()) self.assertTrue(json.loads(result.content)["exists"]) def test_ignore_migrated(self): self.user.user_profile.migrated_at = datetime.datetime.utcnow() self.user.user_profile.save() result = self.form_valid(username=self.username) self.assertFalse(json.loads(result.content)["exists"]) def test_ignore_inactive(self): self.user.is_active = False self.user.save() result = self.form_valid(username=self.username) self.assertFalse(json.loads(result.content)["exists"])
36.706918
88
0.623329
3,402
29,182
5.159612
0.094356
0.023244
0.022218
0.028086
0.769099
0.732752
0.690537
0.667578
0.616761
0.591694
0
0.015421
0.257796
29,182
794
89
36.753149
0.795004
0.036358
0
0.637195
0
0
0.126108
0.040802
0
0
0
0
0.132622
1
0.117378
false
0.060976
0.019817
0
0.157012
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
be5e248cf78ed0d699232ad878a38b51865a877e
12,189
py
Python
internal/src/report.py
HPCToolkit/hpctest
5ff4455582bf39e75530a31badcf6142081b386b
[ "BSD-3-Clause" ]
1
2019-01-17T20:07:19.000Z
2019-01-17T20:07:19.000Z
internal/src/report.py
HPCToolkit/hpctest
5ff4455582bf39e75530a31badcf6142081b386b
[ "BSD-3-Clause" ]
null
null
null
internal/src/report.py
HPCToolkit/hpctest
5ff4455582bf39e75530a31badcf6142081b386b
[ "BSD-3-Clause" ]
2
2019-08-06T18:13:57.000Z
2021-11-05T18:19:49.000Z
################################################################################ # # # report.py # # print the results from running a test suite by extracting from a testdir # # # # # $HeadURL$ # # $Id$ # # # # --------------------------------------------------------------------------- # # Part of HPCToolkit (hpctoolkit.org) # # # # Information about sources of support for research and development of # # HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. # # --------------------------------------------------------------------------- # # # # Copyright ((c)) 2002-2017, Rice University # # All rights reserved. # # # # Redistribution and use in source and binary forms, with or without # # modification, are permitted provided that the following conditions are # # met: # # # # * Redistributions of source code must retain the above copyright # # notice, this list of conditions and the following disclaimer. # # # # * Redistributions in binary form must reproduce the above copyright # # notice, this list of conditions and the following disclaimer in the # # documentation and/or other materials provided with the distribution. # # # # * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. # # # ################################################################################ class Report(): def printReport(self, study, whichspec, sortKeys): from os import listdir from os.path import isfile, isdir, join, basename, relpath from common import homepath, options, percent, infomsg, debugmsg, errormsg, fatalmsg, sepmsg, truncate from util.yaml import readYamlFile, writeYamlFile def sortKeyFunc(result): def get_nested(my_dict, keys): key = keys.pop(0) return my_dict[key] if len(keys) == 0 else get_nested(my_dict[key], keys) keylist = [] for keypath in dimkeys: keylist.append(get_nested(result["input"], list(keypath))) # copy keypath b/c get_nested destroys its second argument return keylist studypath = study.path tableWidth = 110 # width of table row manually determined # TODO: better debugmsg("reporting on study at {} with options {}".format(studypath, options)) # collect the results from all runs meeting 'whichspec' reportAll = whichspec == "all" reportPassed = whichspec == "pass" # if 'reportAll', don't care runDirs = listdir(studypath) passes = list() fails = list() for runname in runDirs: runPath = join(studypath, runname) outPath = join(runPath, "OUT", "OUT.yaml") if isfile(outPath): resultdict, error = readYamlFile(outPath) if not error: try: ok = resultdict["summary"]["status"] == "OK" except: ok = False if reportAll or (reportPassed == ok): passes.append(resultdict) if not ok: fails.append(resultdict) else: errormsg("results file OUT.yaml can't be read for run {}, ignored".format(runPath)) else: errormsg("results file OUT.yaml not found for run {}, ignored".format(runPath)) # counts for final summary line numTests = len(runDirs) numFails = len(fails) numPasses = numTests - numFails # print a summary record for each result, sorted by the dim names in 'sortKeys' if passes: # sort passes and fails by input dimspec sequence dimkey_map = {"tests": ["test"], "build": ["build spec"], "hpctoolkit": ["hpctoolkit"], "profile": ["hpctoolkit params", "hpcrun"] } dimkeys = [] for key in sortKeys: if key in dimkey_map: dimkeys.append(dimkey_map[key]) else: errormsg("unknown sort key for report ignored: '{}'".format(key)) if len(dimkeys): # key func returns list of result fields corresponding to dimkey_list passes.sort(key=sortKeyFunc) fails.sort(key=sortKeyFunc) print for result in passes: # format for display -- line 1 testLabel = self.labelForTest(result) line1 = "| {}".format(testLabel) line1 += " " * (tableWidth - len(line1) - 1) + "|" # format for display -- line 2 info = self.extractRunInfo(result) try: status = info.status except: status = "FAILED" try: msg = info.msg except: msg = "no status produced" if status != "OK": line2 = ("| {}: {}").format(status, truncate(msg, 100)) line2 += " " * (tableWidth - len(line2) - 1) + "|" elif info.extractRunInfoMsg: line2 = ("| {}: {}").format("REPORTING FAILED", truncate(info.extractRunInfoMsg, 100)) line2 += " " * (tableWidth - len(line2) - 1) + "|" elif info.wantProfiling and info.status == "OK": line2 = ("| overhead: {:>5} | samples: {:>5} | recorded: {:>5} | blocked: {:>5} | errant: {:>5} | trolled: {:>5} |" ).format(info.overhead, info.samples, percent(info.recorded, info.samples), percent(info.blocked, info.samples), percent(info.errant, info.samples), percent(info.trolled, info.samples) ) else: line2 = ("| {}: {}").format(status, truncate(msg, 100)) line2 += " " * (tableWidth - len(line2) - 1) + "|" # print run's summary sepmsg(tableWidth) print line1 print line2 sepmsg(tableWidth) print; print # final summary print "TESTS: {}".format(numTests) print "PASSED: {}".format(numPasses) print "FAILED: {}".format(numFails) print if numFails: print "Failed tests:" for f in fails: print " {}".format(self.labelForTest(f)) print; print else: infomsg("no completed runs to report") debugmsg("reportspec = '--which {}'".format(whichspec)) def extractRunInfo(self, result): from argparse import Namespace from ast import literal_eval info = Namespace() info.extractRunInfoMsg = None try: info.test = result["input"]["test"].upper().replace("/", " / ") info.build = result["input"]["build spec"].upper() info.hpctoolkit = result["input"]["hpctoolkit"] info.params = result["input"]["hpctoolkit params"]["hpcrun"] info.wantProfiling = literal_eval(result["input"]["wantProfiling"]) info.status = result["summary"]["status"] info.msg = result["summary"]["status msg"] if info.status != "OK" else "cpu time {} seconds".format(result["run"]["normal"]["cpu time"]) run = result["run"] if info.wantProfiling and (run != "NA"): hpcrun = run["profiled"]["hpcrun"]["summary"] info.overhead = run["profiled"]["hpcrun"]["overhead %"] else: hpcrun = "NA" info.overhead = "NA" if hpcrun != "NA": info.blocked = hpcrun["blocked"] info.errant = hpcrun["errant"] info.frames = hpcrun["frames"] info.intervals = hpcrun["intervals"] info.recorded = hpcrun["recorded"] info.samples = hpcrun["samples"] info.trolled = hpcrun["trolled"] info.yielded = hpcrun["yielded"] else: info.blocked = None info.errant = None info.frames = None info.intervals = None info.recorded = None info.samples = None info.trolled = None info.yielded = None except Exception as e: info.extractRunInfoMsg = e.message # TODO: 'KeyError' => "status"; e.message and str(e) no better return info def labelForTest(self, testdict): info = self.extractRunInfo(testdict) label = "{} with {}".format(info.test, info.build) if info.wantProfiling: label += " and {}".format(info.params) # TODO: display hpctoolkit path but make sure line's not too long return label
47.8
159
0.433177
985
12,189
5.347208
0.326904
0.014619
0.01367
0.016708
0.085248
0.066262
0.05487
0.05487
0.046706
0.046706
0
0.007403
0.456969
12,189
254
160
47.988189
0.788337
0.333497
0
0.162338
0
0.006494
0.112097
0
0
0
0
0.003937
0
0
null
null
0.058442
0.038961
null
null
0.077922
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
be6601106ed9b7f62e01310b81d345d2b027cccc
237
py
Python
output/models/nist_data/list_pkg/int_pkg/schema_instance/nistschema_sv_iv_list_int_max_length_3_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
1
2021-08-14T17:59:21.000Z
2021-08-14T17:59:21.000Z
output/models/nist_data/list_pkg/int_pkg/schema_instance/nistschema_sv_iv_list_int_max_length_3_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
4
2020-02-12T21:30:44.000Z
2020-04-15T20:06:46.000Z
output/models/nist_data/list_pkg/int_pkg/schema_instance/nistschema_sv_iv_list_int_max_length_3_xsd/__init__.py
tefra/xsdata-w3c-tests
b6b6a4ac4e0ab610e4b50d868510a8b7105b1a5f
[ "MIT" ]
null
null
null
from output.models.nist_data.list_pkg.int_pkg.schema_instance.nistschema_sv_iv_list_int_max_length_3_xsd.nistschema_sv_iv_list_int_max_length_3 import NistschemaSvIvListIntMaxLength3 __all__ = [ "NistschemaSvIvListIntMaxLength3", ]
39.5
182
0.886076
32
237
5.84375
0.625
0.128342
0.149733
0.192513
0.331551
0.331551
0.331551
0.331551
0
0
0
0.017937
0.059072
237
5
183
47.4
0.820628
0
0
0
0
0
0.130802
0.130802
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
be6684e88f3535376a60cbf3fb06834de0b55e19
670
py
Python
library/__manifest__.py
odooerpdevelopers/odoo12-course
839e688043f24957eaf424ac5981dcfca649c9f4
[ "MIT" ]
null
null
null
library/__manifest__.py
odooerpdevelopers/odoo12-course
839e688043f24957eaf424ac5981dcfca649c9f4
[ "MIT" ]
null
null
null
library/__manifest__.py
odooerpdevelopers/odoo12-course
839e688043f24957eaf424ac5981dcfca649c9f4
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # by Juan Carlos Montoya <odooerpcloud@gmail.com> { 'name': "Library Management", 'summary': """ Library Management Module for Odoo 11 """, 'description': """ Library Management Module for Odoo 11 """, 'author': "Odoo ERP Cloud", 'website': "http://odooerpcloud.com", 'category': 'Tools', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base'], # always loaded 'data': [ "security/groups.xml", "security/ir.model.access.csv", "views/book_view.xml", "data/books.xml", ], 'application': True, }
20.30303
57
0.556716
71
670
5.239437
0.760563
0.137097
0.123656
0.139785
0.172043
0.172043
0
0
0
0
0
0.014403
0.274627
670
33
58
20.30303
0.751029
0.201493
0
0.190476
0
0
0.608286
0.052731
0
0
0
0
0
1
0
true
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
be74eb09c435e18acf5b9a89c5c3c5e32154d44d
233
py
Python
setup.py
aydjay/moatools
37cb2d6fc3fa03ef86e410c501a70dd67e09cef4
[ "Apache-2.0" ]
null
null
null
setup.py
aydjay/moatools
37cb2d6fc3fa03ef86e410c501a70dd67e09cef4
[ "Apache-2.0" ]
null
null
null
setup.py
aydjay/moatools
37cb2d6fc3fa03ef86e410c501a70dd67e09cef4
[ "Apache-2.0" ]
null
null
null
from setuptools import setup setup(name='moatools', version='0.1.0', packages=['moatools'], entry_points={ 'console_scripts': [ 'moatools = tools.__main__:main' ] }, )
19.416667
46
0.515021
21
233
5.428571
0.761905
0
0
0
0
0
0
0
0
0
0
0.019737
0.347639
233
11
47
21.181818
0.730263
0
0
0
0
0
0.283262
0
0
0
0
0
0
1
0
true
0
0.1
0
0.1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
be76f2cd0b6de9fde7198c56a0617e865c686be3
3,214
py
Python
origamibot/core/teletypes/__init__.py
cmd410/OrigamiBot
03667d069f0c0b088671936ce36bf8f85a029b93
[ "MIT" ]
4
2020-06-30T10:32:54.000Z
2020-11-01T23:07:58.000Z
origamibot/core/teletypes/__init__.py
cmd410/OrigamiBot
03667d069f0c0b088671936ce36bf8f85a029b93
[ "MIT" ]
6
2020-06-26T23:14:59.000Z
2020-07-26T11:48:07.000Z
origamibot/core/teletypes/__init__.py
cmd410/OrigamiBot
03667d069f0c0b088671936ce36bf8f85a029b93
[ "MIT" ]
1
2020-07-28T08:52:51.000Z
2020-07-28T08:52:51.000Z
from .base import TelegramStructure, InlineQueryResult, InputMessageContent from .animation import Animation from .audio import Audio from .bot_command import BotCommand from .callback_query import CallbackQuery from .chat import Chat from .chat_member import ChatMember from .chat_permissions import ChatPermissions from .chat_photo import ChatPhoto from .chosen_inline_result import ChosenInlineResult from .contact import Contact from .dice import Dice from .document import Document from .encrypted_credentials import EncryptedCredentials from .encrypted_passport_element import EncryptedPassportElement from .file import File from .force_reply import ForceReply from .game import Game from .invoice import Invoice from .labeled_price import LabeledPrice from .location import Location from .login_url import LoginUrl from .mask_position import MaskPosition from .message import Message from .message_entity import MessageEntity from .order_info import OrderInfo from .passport_data import PassportData from .passport_file import PassportFile from .photo_size import PhotoSize from .poll import Poll from .poll_answer import PollAnswer from .poll_option import PollOption from .pre_checkout_query import PreCheckoutQuery from .responce_parameters import ResponseParameters from .shipping_address import ShippingAddress from .shipping_option import ShippingOption from .shipping_query import ShippingQuery from .sticker import Sticker from .successful_payment import SuccessfulPayment from .update import Update from .user import User from .user_profile_photos import UserProfilePhotos from .venue import Venue from .video import Video from .video_note import VideoNote from .voice import Voice from .webhook_info import WebhookInfo from .inline_keyboard_button import InlineKeyboardButton from .inline_keyboard_markup import InlineKeyboardMarkup from .reply_keyboard_markup import ReplyKeyboardMarkup from .reply_keyboard_remove import ReplyKeyboardRemove from .keyboard_button import KeyboardButton from .keyboard_button_poll_type import KeyboardButtonPollType from .inline_query import InlineQuery from .input_file import InputFile from .input_location_message_content import InputLocationMessageContent from .input_text_message_content import InputTextMessageContent from .input_contact_message_content import InputContactMessageContent from .input_venue_message_content import InputVenueMessageContent from .input_media_animation import InputMediaAnimation from .input_media_audio import InputMediaAudio from .input_media_document import InputMediaDocument from .input_media_photo import InputMediaPhoto from .input_media_video import InputMediaVideo from .command_scope import ( BotCommandScope, BotCommandScopeAllChatAdministrators, BotCommandScopeAllGroupChats, BotCommandScopeAllPrivateChats, BotCommandScopeChat, BotCommandScopeChatAdministrators, BotCommandScopeChatMember, BotCommandScopeDefault ) from typing import Union ReplyMarkup = Union[ ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardMarkup ] InputMedia = Union[ InputMediaAnimation, InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo ]
33.134021
75
0.858121
354
3,214
7.596045
0.372881
0.03347
0.026032
0
0
0
0
0
0
0
0
0
0.114499
3,214
96
76
33.479167
0.944835
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0.034483
0.758621
0
0.758621
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
be7718c5b2dfcce8aad9101477fafe291fb94b1b
619
py
Python
contributivity.py
Thomas-Galtier/distributed-learning-contributivity
984060ea3b2437517380e77c6694194f7abaa58e
[ "Apache-2.0" ]
null
null
null
contributivity.py
Thomas-Galtier/distributed-learning-contributivity
984060ea3b2437517380e77c6694194f7abaa58e
[ "Apache-2.0" ]
null
null
null
contributivity.py
Thomas-Galtier/distributed-learning-contributivity
984060ea3b2437517380e77c6694194f7abaa58e
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Sun Sep 29 17:31:56 2019 @author: RGOUSSAULT """ import datetime class Contributivity: def __init__(self, name='', contributivity_scores=[], computation_time=0): self.name = name self.contributivity_scores = contributivity_scores self.computation_time = computation_time def __str__(self): output = self.name + '\n' output += 'computation time: ' + str(datetime.timedelta(seconds=self.computation_time)) + '\n' #TODO print only 3 digits output += 'contributivity scores: ' + str(self.contributivity_scores) return output
23.807692
98
0.680129
72
619
5.625
0.513889
0.246914
0.118519
0
0
0
0
0
0
0
0
0.030242
0.198708
619
25
99
24.76
0.78629
0.166397
0
0
0
0
0.088933
0
0
0
0
0.04
0
1
0.181818
false
0
0.090909
0
0.454545
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
2
be7f5c8f63beb7b9b52f3367d700124d64b49e1e
554
py
Python
server/annotation_tool/users/factories.py
bionikspoon/Annotation-Tool
0067d55259c02f0d1f1183c9814414f226c7f71f
[ "BSD-3-Clause" ]
null
null
null
server/annotation_tool/users/factories.py
bionikspoon/Annotation-Tool
0067d55259c02f0d1f1183c9814414f226c7f71f
[ "BSD-3-Clause" ]
1
2015-10-13T18:32:51.000Z
2015-10-13T19:11:36.000Z
server/annotation_tool/users/factories.py
bionikspoon/Annotation-Tool
0067d55259c02f0d1f1183c9814414f226c7f71f
[ "BSD-3-Clause" ]
null
null
null
from factory import DjangoModelFactory from faker import Faker from .models import User from ..core.utils.factory_utils import lazy_callback faker = Faker() class UserFactory(DjangoModelFactory): class Meta: model = User @classmethod def _create(cls, model_class, *args, **kwargs): manager = cls._get_manager(model_class) return manager.create_user(*args, **kwargs) username = lazy_callback(faker.user_name) email = lazy_callback(faker.email) name = lazy_callback(faker.name) password = 'secret'
24.086957
52
0.716606
67
554
5.746269
0.432836
0.124675
0.176623
0
0
0
0
0
0
0
0
0
0.194946
554
22
53
25.181818
0.863229
0
0
0
0
0
0.01083
0
0
0
0
0
0
1
0.0625
false
0.0625
0.25
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
be8acc5fcb75c5d793113dc7d2f89380896c00e2
1,502
py
Python
ModulesAndFunctions/typingphrases.py
BrandonP321/Python-masterclass
fac81fe4f8acfa37076820405d96132f9f23b311
[ "MIT" ]
null
null
null
ModulesAndFunctions/typingphrases.py
BrandonP321/Python-masterclass
fac81fe4f8acfa37076820405d96132f9f23b311
[ "MIT" ]
null
null
null
ModulesAndFunctions/typingphrases.py
BrandonP321/Python-masterclass
fac81fe4f8acfa37076820405d96132f9f23b311
[ "MIT" ]
null
null
null
import shelve with shelve.open('typing-phrases') as phrases: phrases['0'] = "There was no time. He ran out of the door without half the " \ "stuff he needed for work, but it didn't matter. He was late " \ "and if he didn't make this meeting on time, someone's life " \ "may be in danger." phrases['1'] = "Sometimes there isn't a good answer. No matter how you " \ "try to rationalize the outcome, it doesn't make sense. " \ "And instead of an answer, you are simply left with a " \ "question. Why?" phrases['2'] = "What was beyond the bend in the stream was unknown. " \ "Both were curious, but only one was brave enough to want " \ "to explore. That was the problem. There was always one " \ "that let fear rule her life." phrases['3'] = "She counted. One. She could hear the steps coming closer. " \ "Two. Puffs of breath could be seen coming from his mouth. " \ "Three. He stopped beside her. Four. She pulled the trigger " \ "of the gun." phrases['4'] = "There was no time. He ran out of the door without half the " \ "stuff he needed for work, but it didn't matter. He was late " \ "and if he didn't make this meeting on time, someone's life " \ "may be in danger."
60.08
84
0.543941
210
1,502
3.890476
0.519048
0.02448
0.02448
0.034272
0.362301
0.362301
0.362301
0.362301
0.362301
0.362301
0
0.005308
0.372836
1,502
24
85
62.583333
0.861996
0
0
0.272727
0
0
0.652674
0
0
0
0
0
0
1
0
true
0
0.045455
0
0.045455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
be8cbc8d4f1a87fc61e1fd34f921b3b3be667d6f
370
py
Python
codeChef/practice/easy/onp.py
gauravsingh58/algo
397859a53429e7a585e5f6964ad24146c6261326
[ "WTFPL" ]
1
2020-09-30T19:53:08.000Z
2020-09-30T19:53:08.000Z
codeChef/practice/easy/onp.py
gauravsingh58/algo
397859a53429e7a585e5f6964ad24146c6261326
[ "WTFPL" ]
null
null
null
codeChef/practice/easy/onp.py
gauravsingh58/algo
397859a53429e7a585e5f6964ad24146c6261326
[ "WTFPL" ]
1
2020-10-15T09:10:57.000Z
2020-10-15T09:10:57.000Z
from sys import stdin def parse(expr, i): i += 1 if expr[i] == '(': op1, i = parse(expr, i) else: op1 = expr[i] i += 1 opt = expr[i] i += 1 if expr[i] == '(': op2, i = parse(expr, i) else: op2 = expr[i] i += 1 i += 1 return op1 + op2 + opt, i stdin.readline() for expr in stdin: rpn, i = parse(expr, 0) print rpn
12.333333
28
0.486486
63
370
2.857143
0.333333
0.222222
0.133333
0.155556
0.322222
0.155556
0.155556
0
0
0
0
0.049383
0.343243
370
29
29
12.758621
0.691358
0
0
0.428571
0
0
0.00542
0
0
0
0
0
0
0
null
null
0
0.047619
null
null
0.047619
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
be9513a1c65befd91c731279cac2c9086a0e975f
54
py
Python
nugridpy/version.py
NuGrid/NuGridPy
35cab0e7fa5565fbb2f99917715a51e3658dd701
[ "BSD-3-Clause" ]
16
2016-08-05T18:37:11.000Z
2021-08-06T20:01:34.000Z
nugridpy/version.py
NuGrid/NuGridPy
35cab0e7fa5565fbb2f99917715a51e3658dd701
[ "BSD-3-Clause" ]
59
2016-05-19T19:17:41.000Z
2019-12-12T22:54:05.000Z
nugridpy/version.py
NuGrid/NuGridPy
35cab0e7fa5565fbb2f99917715a51e3658dd701
[ "BSD-3-Clause" ]
11
2016-05-16T22:37:36.000Z
2019-07-28T07:33:25.000Z
"""NuGridPy package version""" __version__ = '0.7.6'
13.5
30
0.666667
7
54
4.571429
0.857143
0
0
0
0
0
0
0
0
0
0
0.06383
0.12963
54
3
31
18
0.617021
0.444444
0
0
0
0
0.208333
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
be95517f0c0b66f08df59b444d3687c39f213965
1,010
py
Python
klasses/__init__.py
MrHamdulay/myjvm
03fbe54139a7fa77bd89b2305ba251ae85009ee8
[ "MIT" ]
2
2016-08-29T16:50:52.000Z
2017-02-22T09:34:00.000Z
klasses/__init__.py
MrHamdulay/myjvm
03fbe54139a7fa77bd89b2305ba251ae85009ee8
[ "MIT" ]
null
null
null
klasses/__init__.py
MrHamdulay/myjvm
03fbe54139a7fa77bd89b2305ba251ae85009ee8
[ "MIT" ]
null
null
null
import java_lang_System import java_lang_Object import java_lang_Class import java_lang_Float import java_lang_String import java_lang_Throwable import java_lang_Double import java_lang_Thread import java_lang_Runtime import java_security_AccessController import sun_misc_VM import sun_misc_Unsafe import sun_reflect_Reflection classes_with_natives = { 'java/lang/Object': java_lang_Object, 'java/lang/Class': java_lang_Class, 'java/lang/System': java_lang_System, 'java/lang/Float': java_lang_Float, 'java/lang/Throwable': java_lang_Throwable, 'java/lang/Double': java_lang_Double, 'java/lang/Thread': java_lang_Thread, 'java/lang/String': java_lang_String, 'java/lang/Runtime': java_lang_Runtime, 'java/security/AccessController': java_security_AccessController, 'sun/misc/VM': sun_misc_VM, 'sun/misc/Unsafe': sun_misc_Unsafe, 'sun/reflect/Reflection': sun_reflect_Reflection, } primitive_classes = {}
31.5625
73
0.753465
135
1,010
5.22963
0.177778
0.305949
0.17847
0.050992
0.366856
0
0
0
0
0
0
0
0.163366
1,010
31
74
32.580645
0.835503
0
0
0
0
0
0.221782
0.051485
0
0
0
0
0
1
0
false
0
0.448276
0
0.448276
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
be963d84ab334848b9cf174bd35a3f777f45e05b
522
py
Python
Chapter 10/customer.py
nescience8/starting-out-with-python-global-4th-edition
c16f93b7cbb4c7ae7b57653a7190bf192fe6b472
[ "MIT" ]
35
2019-05-03T00:30:31.000Z
2022-01-20T06:57:25.000Z
Chapter 10/customer.py
nescience8/starting-out-with-python-global-4th-edition
c16f93b7cbb4c7ae7b57653a7190bf192fe6b472
[ "MIT" ]
1
2020-09-04T02:04:33.000Z
2020-09-04T02:04:33.000Z
Chapter 10/customer.py
nescience8/starting-out-with-python-global-4th-edition
c16f93b7cbb4c7ae7b57653a7190bf192fe6b472
[ "MIT" ]
22
2020-05-13T21:20:02.000Z
2021-12-21T08:35:59.000Z
# Customer class class Customer: def __init__(self, name, address, phone): self.__name = name self.__address = address self.__phone = phone def set_name(self, name): self.__name = name def set_address(self, address): self.__address = address def set_phone(self, phone): self.__phone = phone def get_name(self): return self.__name def get_address(self): return self.__address def get_phone(self): return self.__phone
20.88
45
0.618774
64
522
4.609375
0.171875
0.135593
0.142373
0.115254
0
0
0
0
0
0
0
0
0.296935
522
24
46
21.75
0.803815
0.02682
0
0.352941
0
0
0
0
0
0
0
0
0
1
0.411765
false
0
0
0.176471
0.647059
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
be9fb0db46f4c4d3b24bdb01e5c2e795ffde7f6a
3,587
py
Python
validator/sawtooth_validator/consensus/dev_mode/dev_mode_consensus.py
gabykyei/GC_BlockChain_T_Rec
b72cb483064852d0a60286943ff55233462fea08
[ "Apache-2.0" ]
1
2019-03-18T13:31:11.000Z
2019-03-18T13:31:11.000Z
validator/sawtooth_validator/consensus/dev_mode/dev_mode_consensus.py
gabykyei/GC_BlockChain_T_Rec
b72cb483064852d0a60286943ff55233462fea08
[ "Apache-2.0" ]
null
null
null
validator/sawtooth_validator/consensus/dev_mode/dev_mode_consensus.py
gabykyei/GC_BlockChain_T_Rec
b72cb483064852d0a60286943ff55233462fea08
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 Intel Corporation # # 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 logging from time import time from sawtooth_validator.consensus.consensus_base import Consensus from sawtooth_validator.consensus.dev_mode import dev_mode_transaction_block LOGGER = logging.getLogger(__name__) class DevModeConsensus(Consensus): """Implements a journal based on the DevMode consensus. Attributes: block_publisher (EventHandler): The EventHandler tracking calls to make when the heartbeat timer fires. """ def __init__(self, block_publisher=None, block_wait_time=None): """Constructor for the DevModeJournal class. Args: node (Node): The local node. """ # the one who can publish blocks is always the genesis ledger self._block_publisher = True if block_publisher is not None: self._block_publisher = block_publisher self._block_wait_time = 1 if block_wait_time is not None: self._block_wait_time = int(block_wait_time) self._next_block_time = time() def initialization_complete(self, journal): # initialize the block handlers dev_mode_transaction_block.register_message_handlers(journal) def create_block(self, pub_key): """Build a new candidate transaction block. Args: pub_key: public key corresponding to the private key used to sign the block Returns: new transaction block. """ if not self._block_publisher: return None self._next_block_time = time() + self._block_wait_time minfo = {"PublicKey": pub_key} return dev_mode_transaction_block.DevModeTransactionBlock(minfo) def initialize_block(self, journal, block): """Builds a transaction block that is specific to this particular consensus mechanism, in this case there is nothing to do. Args: jounrnal: the journal block: the block to initialize. Returns: None """ pass def claim_block(self, journal, block): """ Nop there is no signing operations in devmode consensus. Args: block (DevModeTransactionBlock): The block to claim. """ pass def create_block_message(self, block): """Create a message wrapper for a block this validator is claiming. :param block: block: the block to wrap in the message. :return: the message object to be sent. """ msg = dev_mode_transaction_block.DevModeTransactionBlockMessage() msg.TransactionBlock = block return msg def verify_block(self, journal, block): return block.is_valid(self, journal) def check_claim_block(self, journal, block, now): return len(journal.pending_transactions) != 0 and \ now > self._next_block_time
33.212963
80
0.650125
430
3,587
5.251163
0.397674
0.031887
0.034544
0.040744
0.057573
0
0
0
0
0
0
0.003804
0.267076
3,587
107
81
33.523364
0.855078
0.460831
0
0.054054
0
0
0.00538
0
0
0
0
0
0
1
0.216216
false
0.054054
0.108108
0.054054
0.486486
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
bea3cbe39b9369d3ba5b1861b85d61e50f62ec0c
565
py
Python
Home/views.py
Piotr95/Yummy_Pies
a5101b41caa932a69a7c9eda59aef237cf6a69a8
[ "MIT" ]
null
null
null
Home/views.py
Piotr95/Yummy_Pies
a5101b41caa932a69a7c9eda59aef237cf6a69a8
[ "MIT" ]
null
null
null
Home/views.py
Piotr95/Yummy_Pies
a5101b41caa932a69a7c9eda59aef237cf6a69a8
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth import authenticate from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate, login from django.contrib.auth import logout from UserManagement.forms import Registration_Form def index(request): if request.user.is_authenticated(): return render(request, 'Home/authindex.html') return render(request,'Home/index.html') from django.contrib.staticfiles import finders # Create your views here.
24.565217
51
0.784071
73
565
5.972603
0.534247
0.137615
0.155963
0.144495
0.240826
0.178899
0
0
0
0
0
0.002049
0.136283
565
22
52
25.681818
0.891393
0.079646
0
0
0
0
0.065764
0
0
0
0
0
0
1
0.083333
false
0
0.666667
0
0.916667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
bebfce2ac4428370fa8bc947dac98290c05a570b
11,359
py
Python
src/spn/tests/test_inference.py
tkrons/SPFlow_topdownrules
6227fc973f4f36da7fbe25fa500d656eb7273033
[ "Apache-2.0" ]
199
2018-11-13T10:37:45.000Z
2022-02-06T17:07:28.000Z
src/spn/tests/test_inference.py
minimrbanana/SPFlow
32233bf29d107c62f0f727b0e64aaa74b37cfe1e
[ "Apache-2.0" ]
46
2018-11-30T13:40:38.000Z
2022-01-22T21:05:07.000Z
src/spn/tests/test_inference.py
minimrbanana/SPFlow
32233bf29d107c62f0f727b0e64aaa74b37cfe1e
[ "Apache-2.0" ]
78
2018-11-13T10:37:48.000Z
2022-03-14T21:34:13.000Z
import unittest import numpy as np from spn.algorithms.Inference import add_node_likelihood, likelihood, log_likelihood from spn.structure.Base import Leaf, get_nodes_by_type, assign_ids def identity_ll(node, data, dtype=np.float64, **kwargs): probs = np.zeros((data.shape[0], 1), dtype=dtype) probs[:] = np.prod(data[:, node.scope], keepdims=True, axis=1) return probs # The multiplier is just for testing purposes, to check that individual nodes add different contributions def multiply_ll(node, data, dtype=np.float64, **kwargs): probs = np.zeros((data.shape[0], 1), dtype=dtype) probs[:] = np.prod(data[:, node.scope], keepdims=True, axis=1) * node.multiplier return probs # The multiplier is just for testing purposes, to check that individual nodes add different contributions def sum_and_multiplier_ll(node, data, dtype=np.float64, **kwargs): probs = np.zeros((data.shape[0], 1), dtype=dtype) probs[:] = np.sum(data[:, node.scope], keepdims=True, axis=1) * node.multiplier return probs # The sum is just for testing purposes, to check that individual nodes add different contributions def sums_ll(node, data, dtype=np.float64, **kwargs): probs = np.zeros((data.shape[0], 1), dtype=dtype) probs[:] = np.sum(data[:, node.scope], keepdims=True, axis=1) return probs class TestInference(unittest.TestCase): def assert_correct(self, spn, data, result): l = likelihood(spn, data) self.assertEqual(l.shape[0], data.shape[0]) self.assertEqual(l.shape[1], 1) self.assertTrue(np.alltrue(np.isclose(result.reshape(-1, 1), l))) self.assertTrue(np.alltrue(np.isclose(np.log(l), log_likelihood(spn, data)))) self.assertTrue(np.alltrue(np.isclose(np.log(l), log_likelihood(spn, data, debug=True)))) self.assertTrue(np.alltrue(np.isclose(l, likelihood(spn, data, debug=True)))) def test_type(self): add_node_likelihood(Leaf, identity_ll) # test that we get basic computations right spn = 0.5 * Leaf(scope=[0, 1]) + 0.5 * (Leaf(scope=0) * Leaf(scope=1)) data = np.random.rand(10, 4) l = likelihood(spn, data, dtype=np.float32) self.assertEqual(l.dtype, np.float32) l = likelihood(spn, data, dtype=np.float128) self.assertEqual(l.dtype, np.float128) def test_sum_one_dimension(self): add_node_likelihood(Leaf, identity_ll) # test that we get basic computations right spn = 0.5 * Leaf(scope=0) + 0.5 * Leaf(scope=0) data = np.random.rand(10, 1) self.assert_correct(spn, data, data) spn = 0.1 * Leaf(scope=0) + 0.9 * Leaf(scope=0) data = np.random.rand(10, 1) self.assert_correct(spn, data, data) # test that we can pass whatever dataset, and the scopes are being respected # this is important for inner nodes spn = 0.1 * Leaf(scope=0) + 0.9 * Leaf(scope=0) data = np.random.rand(10, 3) r = 0.1 * data[:, 0] + 0.9 * data[:, 0] r = r.reshape(-1, 1) self.assert_correct(spn, data, r) # test that it fails if the weights are not normalized spn = 0.1 * Leaf(scope=0) + 0.9 * Leaf(scope=0) spn.weights[1] = 0.2 data = np.random.rand(10, 3) with self.assertRaises(AssertionError): l = likelihood(spn, data) with self.assertRaises(AssertionError): log_likelihood(spn, data) # test the log space spn = 0.1 * Leaf(scope=0) + 0.9 * Leaf(scope=0) data = np.random.rand(10, 3) r = 0.1 * data[:, 0] + 0.9 * data[:, 0] r = r.reshape(-1, 1) self.assert_correct(spn, data, r) def test_hierarchical_sum_one_dimension(self): add_node_likelihood(Leaf, identity_ll) # test basic computations in a hierarchy + respecting the scopes spn = 0.3 * (0.2 * Leaf(scope=0) + 0.8 * Leaf(scope=0)) + 0.7 * (0.4 * Leaf(scope=0) + 0.6 * Leaf(scope=0)) data = np.random.rand(10, 3) self.assert_correct(spn, data, data[:, 0]) add_node_likelihood(Leaf, multiply_ll) # test that the different nodes contribute differently spn = 0.3 * (0.2 * Leaf(scope=0) + 0.8 * Leaf(scope=0)) + 0.7 * (0.4 * Leaf(scope=0) + 0.6 * Leaf(scope=0)) spn.children[0].children[0].multiplier = 2 spn.children[0].children[1].multiplier = 3 spn.children[1].children[0].multiplier = 4 spn.children[1].children[1].multiplier = 5 data = np.random.rand(10, 3) r = 0.3 * (0.2 * 2 * data[:, 0] + 0.8 * 3 * data[:, 0]) + 0.7 * (0.4 * 4 * data[:, 0] + 0.6 * 5 * data[:, 0]) self.assert_correct(spn, data, r) def test_sum_multiple_dimension(self): add_node_likelihood(Leaf, identity_ll) # test basic computations in multiple dimensions spn = 0.5 * Leaf(scope=[0, 1]) + 0.5 * Leaf(scope=[0, 1]) data = np.random.rand(10, 2) l = likelihood(spn, data) self.assert_correct(spn, data, data[:, 0] * data[:, 1]) def test_hierarchical_sum_multiple_dimension(self): add_node_likelihood(Leaf, identity_ll) # test basic computations in a hierarchy spn = 0.3 * (0.2 * Leaf(scope=[0, 1]) + 0.8 * Leaf(scope=[0, 1])) + 0.7 * ( 0.4 * Leaf(scope=[0, 1]) + 0.6 * Leaf(scope=[0, 1]) ) data = np.random.rand(10, 3) self.assert_correct(spn, data, data[:, 0] * data[:, 1]) add_node_likelihood(Leaf, multiply_ll) # test different node contributions spn = 0.3 * (0.2 * Leaf(scope=[0, 1]) + 0.8 * Leaf(scope=[0, 1])) + 0.7 * ( 0.4 * Leaf(scope=[0, 1]) + 0.6 * Leaf(scope=[0, 1]) ) spn.children[0].children[0].multiplier = 2 spn.children[0].children[1].multiplier = 3 spn.children[1].children[0].multiplier = 4 spn.children[1].children[1].multiplier = 5 data = np.random.rand(10, 3) dprod = data[:, 0] * data[:, 1] r = 0.3 * (0.2 * 2 * dprod + 0.8 * 3 * dprod) + 0.7 * (0.4 * 4 * dprod + 0.6 * 5 * dprod) self.assert_correct(spn, data, r) def test_prod_one_dimension(self): add_node_likelihood(Leaf, identity_ll) # test basic product spn = Leaf(scope=0) * Leaf(scope=1) data = np.random.rand(10, 2) self.assert_correct(spn, data, data[:, 0] * data[:, 1]) # test respecting the scopes spn = Leaf(scope=0) * Leaf(scope=1) data = np.random.rand(10, 3) self.assert_correct(spn, data, data[:, 0] * data[:, 1]) def test_prod_multiple_dimension(self): add_node_likelihood(Leaf, sums_ll) # test basic computations in multiple dimensions spn = Leaf(scope=[0, 1]) * Leaf(scope=[2, 3]) data = np.random.rand(10, 4) r = (data[:, 0] + data[:, 1]) * (data[:, 2] + data[:, 3]) self.assert_correct(spn, data, r) def test_hierarchical_prod_multiple_dimension(self): add_node_likelihood(Leaf, identity_ll) # test basic computations in a hierarchy spn = (Leaf(scope=[0, 1]) * Leaf(scope=[2, 3])) * (Leaf(scope=[4, 5]) * Leaf(scope=[6, 7])) data = np.random.rand(10, 8) self.assert_correct(spn, data, np.prod(data, axis=1)) add_node_likelihood(Leaf, sums_ll) # test different node contributions spn = (Leaf(scope=[0, 1]) * Leaf(scope=[2, 3])) * (Leaf(scope=[4, 5]) * Leaf(scope=[6, 7])) data = np.random.rand(10, 10) dprod = ( (data[:, 0] + data[:, 1]) * (data[:, 2] + data[:, 3]) * (data[:, 4] + data[:, 5]) * (data[:, 6] + data[:, 7]) ) self.assert_correct(spn, data, dprod) def test_handmade_multidim(self): add_node_likelihood(Leaf, sum_and_multiplier_ll) spn = 0.3 * ((0.9 * (leaf(0, 1) * leaf(1, 2)) + 0.1 * (leaf(0, 3) * leaf(1, 4))) * leaf(2, 5)) + 0.7 * ( 0.6 * leaf([0, 1, 2], 6) + 0.4 * leaf([0, 1, 2], 7) ) data = np.random.rand(10, 10) r = 0.3 * ( (0.9 * (data[:, 0] * 2 * data[:, 1]) + 0.1 * (3 * data[:, 0] * 4 * data[:, 1])) * 5 * data[:, 2] ) + 0.7 * (0.6 * 6 * (data[:, 0] + data[:, 1] + data[:, 2]) + 0.4 * 7 * (data[:, 0] + data[:, 1] + data[:, 2])) self.assert_correct(spn, data, r) def test_ll_matrix(self): add_node_likelihood(Leaf, sum_and_multiplier_ll) node_1_1_1_1 = leaf(2, 1) node_1_1_1_2 = leaf(2, 2) node_1_1_1 = 0.7 * node_1_1_1_1 + 0.3 * node_1_1_1_2 node_1_1_2 = leaf([0, 1], 3) node_1_1 = node_1_1_1 * node_1_1_2 node_1_2_1_1_1 = leaf(0, 5) node_1_2_1_1_2 = leaf(1, 4) node_1_2_1_1 = node_1_2_1_1_1 * node_1_2_1_1_2 node_1_2_1_2 = leaf([0, 1], 6) node_1_2_1 = 0.1 * node_1_2_1_1 + 0.9 * node_1_2_1_2 node_1_2_2 = leaf(2, 3) node_1_2 = node_1_2_1 * node_1_2_2 spn = 0.4 * node_1_1 + 0.6 * node_1_2 assign_ids(spn) max_id = max([n.id for n in get_nodes_by_type(spn)]) data = np.random.rand(10, 10) node_1_1_1_1_r = data[:, 2] * 1 node_1_1_1_2_r = data[:, 2] * 2 node_1_1_1_r = 0.7 * node_1_1_1_1_r + 0.3 * node_1_1_1_2_r node_1_1_2_r = 3 * (data[:, 0] + data[:, 1]) node_1_1_r = node_1_1_1_r * node_1_1_2_r node_1_2_1_1_1_r = data[:, 0] * 5 node_1_2_1_1_2_r = data[:, 1] * 4 node_1_2_1_1_r = node_1_2_1_1_1_r * node_1_2_1_1_2_r node_1_2_1_2_r = 6 * (data[:, 0] + data[:, 1]) node_1_2_1_r = 0.1 * node_1_2_1_1_r + 0.9 * node_1_2_1_2_r node_1_2_2_r = data[:, 2] * 3 node_1_2_r = node_1_2_1_r * node_1_2_2_r spn_r = 0.4 * node_1_1_r + 0.6 * node_1_2_r self.assert_correct(spn, data, spn_r) lls = np.zeros((data.shape[0], max_id + 1)) likelihood(spn, data, lls_matrix=lls) llls = np.zeros((data.shape[0], max_id + 1)) log_likelihood(spn, data, lls_matrix=llls) self.assertTrue(np.alltrue(np.isclose(lls, np.exp(llls)))) self.assertTrue(np.alltrue(np.isclose(spn_r, lls[:, spn.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_2_r, lls[:, node_1_2.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_2_2_r, lls[:, node_1_2_2.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_2_1_r, lls[:, node_1_2_1.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_2_1_2_r, lls[:, node_1_2_1_2.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_2_1_1_r, lls[:, node_1_2_1_1.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_2_1_1_2_r, lls[:, node_1_2_1_1_2.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_2_1_1_1_r, lls[:, node_1_2_1_1_1.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_1_r, lls[:, node_1_1.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_1_2_r, lls[:, node_1_1_2.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_1_1_r, lls[:, node_1_1_1.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_1_1_2_r, lls[:, node_1_1_1_2.id]))) self.assertTrue(np.alltrue(np.isclose(node_1_1_1_1_r, lls[:, node_1_1_1_1.id]))) def leaf(scope, multiplier): l = Leaf(scope=scope) l.multiplier = multiplier return l if __name__ == "__main__": unittest.main()
41.305455
119
0.594859
1,901
11,359
3.336665
0.071541
0.025855
0.039729
0.033107
0.812865
0.748384
0.686899
0.625099
0.561722
0.517736
0
0.083021
0.248173
11,359
274
120
41.456204
0.659719
0.085483
0
0.413265
0
0
0.000772
0
0
0
0
0
0.209184
1
0.081633
false
0
0.020408
0
0.132653
0
0
0
0
null
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
fe24d0d9f108159c323a4ee3bba6a2ded3316020
465
py
Python
tests/unit/test_models.py
Sjors/patron
a496097ad0821b677c8e710e8aceb587928be31c
[ "MIT" ]
114
2018-12-30T20:43:37.000Z
2022-03-21T18:57:47.000Z
tests/unit/test_models.py
Sjors/patron
a496097ad0821b677c8e710e8aceb587928be31c
[ "MIT" ]
17
2019-04-25T20:20:57.000Z
2022-03-29T21:48:35.000Z
tests/unit/test_models.py
Sjors/patron
a496097ad0821b677c8e710e8aceb587928be31c
[ "MIT" ]
17
2019-01-02T06:37:11.000Z
2022-03-29T22:22:40.000Z
from datetime import datetime def test_new_user(new_user): ''' GIVEN a User model WHEN new User is created THEN check the email, hashed pass, authentication expiration, password reset ''' assert new_user.username == 'test' assert new_user.email == 'test@test.com' assert datetime.today() > new_user.expiration assert new_user.check_password('test') assert new_user.role == 'Patron' assert not new_user.mail_opt_out
27.352941
53
0.703226
65
465
4.846154
0.507692
0.2
0.165079
0.107937
0
0
0
0
0
0
0
0
0.210753
465
16
54
29.0625
0.858311
0.258065
0
0
0
0
0.085174
0
0
0
0
0
0.75
1
0.125
false
0.125
0.125
0
0.25
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
1
0
0
0
0
0
2
fe31864d1c9d60dbae006fde842faf57524a61d1
633
py
Python
onany/manager/base.py
vinyguedess/onany
e46986ffda69327582deca16fd8b3c2cb0403c58
[ "MIT" ]
1
2020-05-08T15:01:53.000Z
2020-05-08T15:01:53.000Z
onany/manager/base.py
vinyguedess/onany
e46986ffda69327582deca16fd8b3c2cb0403c58
[ "MIT" ]
null
null
null
onany/manager/base.py
vinyguedess/onany
e46986ffda69327582deca16fd8b3c2cb0403c58
[ "MIT" ]
null
null
null
from typing import Dict, List class EventManager: def __init__(self): self._events_pool: Dict[str, List[callable]] = {} def clear(self): self._events_pool = {} def listen(self, event: str, callback: callable): self._register_event(event) self._events_pool[event].append(callback) def emit(self, event: str, *args, **kwargs): self._register_event(event) for callback in self._events_pool[event]: callback(*args, **kwargs) def _register_event(self, event: str): if event not in self._events_pool: self._events_pool[event] = []
25.32
57
0.630332
78
633
4.833333
0.346154
0.159151
0.222812
0.151194
0
0
0
0
0
0
0
0
0.252765
633
24
58
26.375
0.79704
0
0
0.125
0
0
0
0
0
0
0
0
0
1
0.3125
false
0
0.0625
0
0.4375
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
fe34c28c2a33c89888bead78f8b4e3152575d78b
4,417
py
Python
jp.atcoder/abc140/abc140_f/31081582.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-09T03:06:25.000Z
2022-02-09T03:06:25.000Z
jp.atcoder/abc140/abc140_f/31081582.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-05T22:53:18.000Z
2022-02-09T01:29:30.000Z
jp.atcoder/abc140/abc140_f/31081582.py
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
null
null
null
import typing class FenwickTreeIntAdd: def __init__(self, arr: typing.List[int]) -> None: n = len(arr) data = [0] * (n + 1) data[1:] = arr.copy() for i in range(n): j = i + (i & -i) if j > n: continue data[j] += data[i] self.__data = data def __len__(self) -> int: return len(self.__data) - 1 def __setitem__(self, i: int, x: int) -> None: assert 0 <= i < len(self) i += 1 while i < len(self) + 1: self.__data[i] += x i += i & -i def __getitem__(self, i: int) -> int: assert 0 <= i <= len(self) v = 0 while i > 0: v += self.__data[i] i -= i & -i return v def get_range(self, left: int, right: int) -> int: return self[right] - self[left] def max_right(self, is_ok: typing.Callable[[int], bool]) -> int: n = len(self) + 1 length = 1 while length << 1 < n: length <<= 1 v, i = 0, 0 while length: if i + length < n and is_ok(v + self.__data[i + length]): i += length v += self.__data[i] length >>= 1 return i class FenwickTree: __max_value: int def __init__(self, max_value: int) -> None: """instance can contain values range of [0, max_value).""" self.__fw = FenwickTreeIntAdd([0] * max_value) self.__max_value = max_value @property def max_value(self) -> int: return self.__max_value def __len__(self) -> int: return self.__fw[self.max_value] def __contains__(self, x: int) -> bool: return self.count(x) >= 1 def count(self, x: int) -> int: if x < 0 or self.max_value <= x: return 0 return self.__fw.get_range(x, x + 1) def is_empty(self) -> bool: return len(self) == 0 def __bool__(self) -> bool: return not self.is_empty() def insert(self, x: int) -> None: assert 0 <= x < self.max_value self.__fw[x] = 1 def remove(self, x: int) -> None: if x not in self: raise KeyError(x) self.__fw[x] = -1 def remove_all(self, x: int) -> None: assert 0 <= x < self.max_value self.__fw[x] = -self.count(x) def __getitem__(self, i: int) -> typing.Optional[int]: """Return i-th element.""" if not 0 <= i < len(self): return None return self.__fw.max_right(lambda v: v < i + 1) def min(self) -> typing.Optional[int]: return None if len(self) == 0 else self[0] def max(self) -> typing.Optional[int]: return None if len(self) == 0 else self[len(self) - 1] def lower_bound(self, x: int) -> int: return self.__fw[x] def upper_bound(self, x: int) -> int: return self.__fw[x + 1] class ArrayCompression: """ Examples: >>> a = [3, 10, 2, 5] >>> compress = ArrayCompression(a) >>> compressed = [compress(x) for x in a] >>> compressed [1, 3, 0, 2] >>> equal_to_original = [compress.retrieve(x) for x in compressed] >>> equal_to_original [3, 10, 2, 5] """ __values: typing.List[int] def __init__(self, array: typing.List[int]) -> None: self.__values = sorted(set(array)) def __call__(self, value: int) -> int: import bisect i = bisect.bisect_left(self.__values, value) if i >= len(self.__values) or self.__values[i] != value: raise KeyError return i def retrieve(self, key: int) -> int: return self.__values[key] def main() -> None: n = int(input()) s = list(map(int, input().split())) compress = ArrayCompression(s) s = [compress(x) for x in s] ms = FenwickTree(len(s)) s.sort() for x in s[:-1]: ms.insert(x) a = [s[-1]] for _ in range(n): b = [] for x in a: i = ms.lower_bound(x) if i == 0: print("No") return v = ms[i - 1] b.append(v) ms.remove(v) a += b print("Yes") if __name__ == "__main__": main()
25.680233
71
0.485397
585
4,417
3.442735
0.17265
0.045184
0.041708
0.031778
0.215988
0.129593
0.116187
0.116187
0.116187
0.087388
0
0.019322
0.37899
4,417
171
72
25.830409
0.714911
0.070863
0
0.067227
0
0
0.003356
0
0
0
0
0
0.033613
1
0.210084
false
0
0.016807
0.10084
0.436975
0.016807
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
fe3b51ae8de6fd7591e893b513815a54d7f27756
2,628
py
Python
qiskit/pulse/channels/channels.py
biplab37/qiskit-aakash
e10b204887606f1f75bdfde182bb0c6d0a322c68
[ "Apache-2.0" ]
22
2019-08-15T04:39:15.000Z
2022-03-06T05:17:04.000Z
qiskit/pulse/channels/channels.py
biplab37/qiskit-aakash
e10b204887606f1f75bdfde182bb0c6d0a322c68
[ "Apache-2.0" ]
2
2020-10-26T07:12:12.000Z
2021-12-09T16:22:51.000Z
qiskit/pulse/channels/channels.py
biplab37/qiskit-aakash
e10b204887606f1f75bdfde182bb0c6d0a322c68
[ "Apache-2.0" ]
9
2019-09-05T05:33:00.000Z
2021-10-09T16:04:53.000Z
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ Channels. """ from abc import ABCMeta from qiskit.pulse.exceptions import PulseError class Channel(metaclass=ABCMeta): """Base class of channels.""" prefix = None def __init__(self, index: int = None, buffer: int = 0): """Channel class. Args: index: Index of channel buffer: Buffer that should be placed between instructions on channel Raises: PulseError: If integer index or buffer not supplied """ if not isinstance(index, int): raise PulseError('Channel index must be integer') self._index = index if not isinstance(buffer, int): raise PulseError('Channel buffer must be integer') self._buffer = buffer @property def index(self) -> int: """Return the index of this channel.""" return self._index @property def buffer(self) -> int: """Return the buffer for this channel.""" return self._buffer @property def name(self) -> str: """Return the name of this channel.""" return '%s%d' % (self.__class__.prefix, self._index) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self._index) def __eq__(self, other): """Two channels are the same if they are of the same type, and have the same index. Args: other (Channel): other Channel Returns: bool: are self and other equal. """ if type(self) is type(other) and \ self._index == other._index: return True return False def __hash__(self): return hash((type(self), self._index)) class AcquireChannel(Channel): """Acquire channel.""" prefix = 'a' class SnapshotChannel(Channel): """Snapshot channel.""" prefix = 's' def __init__(self): """Create new snapshot channel.""" super().__init__(0) class MemorySlot(Channel): """Memory slot channel.""" prefix = 'm' class RegisterSlot(Channel): """Classical resister slot channel.""" prefix = 'c'
23.890909
91
0.615677
328
2,628
4.795732
0.390244
0.040051
0.032422
0.031786
0
0
0
0
0
0
0
0.007911
0.278539
2,628
109
92
24.110092
0.82173
0.416667
0
0.076923
0
0
0.053324
0
0
0
0
0
0
1
0.205128
false
0
0.051282
0.051282
0.692308
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
fe50b9134db698d91172b5d19add452948f497e4
190
py
Python
portal/urls.py
yalattas/Django-REST-API-course
1cb6b4275f60cdfc8d7e0e7e40bb3b8729cfa335
[ "Apache-2.0" ]
null
null
null
portal/urls.py
yalattas/Django-REST-API-course
1cb6b4275f60cdfc8d7e0e7e40bb3b8729cfa335
[ "Apache-2.0" ]
null
null
null
portal/urls.py
yalattas/Django-REST-API-course
1cb6b4275f60cdfc8d7e0e7e40bb3b8729cfa335
[ "Apache-2.0" ]
null
null
null
from portal import views from django.urls import path # For the front end to call this app and access its URLs app_name = 'portal' urlpatterns = [ path('', views.home, name='home'), ]
19
56
0.705263
30
190
4.433333
0.7
0
0
0
0
0
0
0
0
0
0
0
0.194737
190
9
57
21.111111
0.869281
0.284211
0
0
0
0
0.074627
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
fe51123ba57a59c2f70a736d3a2b279da980fe6b
1,187
py
Python
setup.py
mlaponsky/pyyamllib
f8fce411976122c98197a06ffe0cdb84e3a1d96b
[ "MIT" ]
null
null
null
setup.py
mlaponsky/pyyamllib
f8fce411976122c98197a06ffe0cdb84e3a1d96b
[ "MIT" ]
null
null
null
setup.py
mlaponsky/pyyamllib
f8fce411976122c98197a06ffe0cdb84e3a1d96b
[ "MIT" ]
null
null
null
from setuptools import setup, find_packages import pathlib here = pathlib.Path(__file__).parent.resolve() long_description = (here / 'README.md').read_text(encoding='utf-8') setup( name='pyyamllib', version='0.1', description='A Yaml configuration file parser with support ' 'for environment variable interpolation and default arguments.', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/mlaponsky/pyyamllib', author='Max Laponsky', author_email='thebiglaponsky@gmail.com', license='MIT', keywords=['yml', 'yaml', 'config', 'configuration'], classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', "Programming Language :: Python :: 3.10", 'Programming Language :: Python :: 3 :: Only' ], packages=find_packages(), install_requires=['pyyaml'] )
35.969697
80
0.646167
126
1,187
5.968254
0.603175
0.176862
0.232713
0.242021
0
0
0
0
0
0
0
0.018182
0.2123
1,187
32
81
37.09375
0.786096
0
0
0
0
0
0.495366
0.020219
0
0
0
0
0
1
0
false
0
0.066667
0
0.066667
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
fe52e4e1364ee2dc449ddd26430f0d4bc2344132
2,440
py
Python
word_preprocessor.py
Jackline97/GAN_RoBERTa
9a338e4d1bebd0a749379e9f486eab5072fb8ac8
[ "Apache-2.0" ]
null
null
null
word_preprocessor.py
Jackline97/GAN_RoBERTa
9a338e4d1bebd0a749379e9f486eab5072fb8ac8
[ "Apache-2.0" ]
null
null
null
word_preprocessor.py
Jackline97/GAN_RoBERTa
9a338e4d1bebd0a749379e9f486eab5072fb8ac8
[ "Apache-2.0" ]
null
null
null
import re from tqdm import tqdm class Word_Preprocessing(): def __init__(self, df, target): self.df = df self.target = target def eliminate_url(self): print('Start eliminate url: : )') text = self.df[self.target] for i in tqdm(text): urls = re.findall( r'(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})', i) for i in urls: self.df[self.target] = self.df[self.target].apply(lambda x: x.replace(i, "")) return self.df def eliminate_username(self): print('Start eliminate username: : )') for i in tqdm(self.df[self.target]): user_name = re.findall(r'@\w*', i) for i in user_name: self.df[self.target] = self.df[self.target].apply(lambda x: x.replace(i, "")) return self.df def convert_abbreviation(self): am = "'m" are = "'re" have = "'ve" not_ = "n't" self.df[self.target] = self.df[self.target].apply(lambda x: x.replace(am, " am")) self.df[self.target] = self.df[self.target].apply(lambda x: x.replace(are, " are")) self.df[self.target] = self.df[self.target].apply(lambda x: x.replace(have, " have")) self.df[self.target] = self.df[self.target].apply(lambda x: x.replace(not_, " not")) return self.df def final_check(self): print('Start Final check: ') self.df[self.target] = self.df[self.target].apply( lambda x: re.sub(r'[^A-Za-z0-9 ]+', ' ', x).lower()) return self.df def eliminate_symbol(self): print('Start eliminate symbol: : )') symbol_list = [',', "'", '!', '@', '$', '%', '^', '&', '*', '(', ')', '-', '+', '?', '>', '<', '=', '.', ':', ';', ' ', ' ', ' ', ' ', ' ', ' ', ' '] for i in tqdm(symbol_list): self.df[self.target] = self.df[self.target].apply(lambda x: x.replace(i, ' ')) return self.df def process_all(self): self.convert_abbreviation() self.eliminate_url() self.eliminate_username() self.eliminate_symbol() df_final_check = self.final_check() print("finished!!") return df_final_check
40.666667
229
0.506967
325
2,440
3.726154
0.181538
0.123865
0.188274
0.23782
0.473163
0.445912
0.445912
0.428571
0.428571
0.428571
0
0.012458
0.27623
2,440
60
230
40.666667
0.673273
0
0
0.132075
0
0.018868
0.168374
0.085621
0
0
0
0
0
1
0.132075
false
0
0.037736
0
0.301887
0.09434
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
fe5bce2ce0d1554cfb7a46569db57fb03db00f18
624
py
Python
backup/some_tests.py
PepSalehi/boulder
08889f133458ef0b849397d45a17054eb8ec73cf
[ "MIT" ]
null
null
null
backup/some_tests.py
PepSalehi/boulder
08889f133458ef0b849397d45a17054eb8ec73cf
[ "MIT" ]
null
null
null
backup/some_tests.py
PepSalehi/boulder
08889f133458ef0b849397d45a17054eb8ec73cf
[ "MIT" ]
1
2019-09-29T01:38:57.000Z
2019-09-29T01:38:57.000Z
layer = qgis.utils.iface.activeLayer() for feature in layer.getFeatures(): numberOfLane = feature['NUMLANE'] lts = feature ['qLts12'] islLTS_1 = feature['qIsl_lts1'] islLTS_2 = feature['qIsl_lts2'] islLTS_3 = feature['qIsl_lts3'] islLTS_4 = feature['qIsl_lts4'] if lts ==1 : assert islLTS_1 > 0 elif lts ==2 : assert islLTS_1 == 0 assert islLTS_2 > 0 elif lts ==3 : assert islLTS_1 == islLTS_2 == 0 assert islLTS_3 > 0 elif lts ==4 : assert islLTS_1 == islLTS_2 == islLTS_3 == 0 assert islLTS_4 > 0 else: print "Yoohoo, no errors!"
29.714286
52
0.605769
87
624
4.137931
0.367816
0.233333
0.144444
0.077778
0.111111
0
0
0
0
0
0
0.068736
0.277244
624
21
53
29.714286
0.72949
0
0
0
0
0
0.1072
0
0
0
0
0
0.35
0
null
null
0
0
null
null
0.05
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
fe673a8fe787d6a0e841322e461b42e79e075cb0
3,634
py
Python
create.py
rafaelurben/mc-globaladvancements
d2d93abb828f9dd62a4a817c9ecde7b2c072d9b2
[ "MIT" ]
null
null
null
create.py
rafaelurben/mc-globaladvancements
d2d93abb828f9dd62a4a817c9ecde7b2c072d9b2
[ "MIT" ]
null
null
null
create.py
rafaelurben/mc-globaladvancements
d2d93abb828f9dd62a4a817c9ecde7b2c072d9b2
[ "MIT" ]
null
null
null
# This is a util to create the advancement files # Advancement list from https://github.com/jan00bl/mcfunction-novum/blob/master/lib/1.16/id/advancement.json advancements = [ "minecraft:adventure/adventuring_time", "minecraft:adventure/arbalistic", "minecraft:adventure/bullseye", "minecraft:adventure/hero_of_the_village", "minecraft:adventure/honey_block_slide", "minecraft:adventure/kill_all_mobs", "minecraft:adventure/kill_a_mob", "minecraft:adventure/ol_betsy", "minecraft:adventure/root", "minecraft:adventure/shoot_arrow", "minecraft:adventure/sleep_in_bed", "minecraft:adventure/sniper_duel", "minecraft:adventure/summon_iron_golem", "minecraft:adventure/throw_trident", "minecraft:adventure/totem_of_undying", "minecraft:adventure/trade", "minecraft:adventure/two_birds_one_arrow", "minecraft:adventure/very_very_frightening", "minecraft:adventure/voluntary_exile", "minecraft:adventure/whos_the_pillager_now", "minecraft:end/dragon_breath", "minecraft:end/dragon_egg", "minecraft:end/elytra", "minecraft:end/enter_end_gateway", "minecraft:end/find_end_city", "minecraft:end/kill_dragon", "minecraft:end/levitate", "minecraft:end/respawn_dragon", "minecraft:end/root", "minecraft:husbandry/balanced_diet", "minecraft:husbandry/bred_all_animals", "minecraft:husbandry/breed_an_animal", "minecraft:husbandry/complete_catalogue", "minecraft:husbandry/fishy_business", "minecraft:husbandry/obtain_netherite_hoe", "minecraft:husbandry/plant_seed", "minecraft:husbandry/root", "minecraft:husbandry/safely_harvest_honey", "minecraft:husbandry/silk_touch_nest", "minecraft:husbandry/tactical_fishing", "minecraft:husbandry/tame_an_animal", "minecraft:nether/all_effects", "minecraft:nether/all_potions", "minecraft:nether/brew_potion", "minecraft:nether/charge_respawn_anchor", "minecraft:nether/create_beacon", "minecraft:nether/create_full_beacon", "minecraft:nether/distract_piglin", "minecraft:nether/explore_nether", "minecraft:nether/fast_travel", "minecraft:nether/find_bastion", "minecraft:nether/find_fortress", "minecraft:nether/get_wither_skull", "minecraft:nether/loot_bastion", "minecraft:nether/netherite_armor", "minecraft:nether/obtain_ancient_debris", "minecraft:nether/obtain_blaze_rod", "minecraft:nether/obtain_crying_obsidian", "minecraft:nether/return_to_sender", "minecraft:nether/ride_strider", "minecraft:nether/root", "minecraft:nether/summon_wither", "minecraft:nether/uneasy_alliance", "minecraft:nether/use_lodestone", "minecraft:story/cure_zombie_villager", "minecraft:story/deflect_arrow", "minecraft:story/enchant_item", "minecraft:story/enter_the_end", "minecraft:story/enter_the_nether", "minecraft:story/follow_ender_eye", "minecraft:story/form_obsidian", "minecraft:story/iron_tools", "minecraft:story/lava_bucket", "minecraft:story/mine_diamond", "minecraft:story/mine_stone", "minecraft:story/obtain_armor", "minecraft:story/root", "minecraft:story/shiny_gear", "minecraft:story/smelt_iron", "minecraft:story/upgrade_tools" ] for i, a in enumerate(advancements): print("execute if entity @a[advancements={" + a + "=true}] run scoreboard players set #adv" + str( i) + " globaladvance 1") print("\n\n\n") for i, a in enumerate(advancements): print("execute if score #adv" + str(i) + " globaladvance matches 1 run advancement grant @a only " + a)
37.854167
108
0.733627
418
3,634
6.133971
0.433014
0.134555
0.024571
0.017161
0.032761
0.032761
0.032761
0.032761
0.032761
0
0
0.002233
0.137314
3,634
95
109
38.252632
0.81563
0.042102
0
0.022472
0
0
0.759632
0.693502
0
0
0
0
0
1
0
false
0
0
0
0
0.033708
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
fe6ab571c55c04a70ce6167213bab1c410485a0a
1,228
py
Python
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/membership/__manifest__.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
1
2019-12-19T01:53:13.000Z
2019-12-19T01:53:13.000Z
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/membership/__manifest__.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
null
null
null
apps/odoo/lib/odoo-10.0.post20170615-py2.7.egg/odoo/addons/membership/__manifest__.py
gtfarng/Odoo_migrade
9cc28fae4c379e407645248a29d22139925eafe7
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Membership Management', 'version': '1.0', 'category': 'Sales', 'description': """ This module allows you to manage all operations for managing memberships. ========================================================================= It supports different kind of members: -------------------------------------- * Free member * Associated member (e.g.: a group subscribes to a membership for all subsidiaries) * Paid members * Special member prices It is integrated with sales and accounting to allow you to automatically invoice and send propositions for membership renewal. """, 'depends': ['base', 'product', 'account'], 'data': [ 'security/ir.model.access.csv', 'wizard/membership_invoice_views.xml', 'data/membership_data.xml', 'views/product_views.xml', 'views/partner_views.xml', 'report/report_membership_views.xml', ], 'demo': [ 'data/membership_demo.xml', ], 'website': 'https://www.odoo.com/page/community-builder', 'test': [ '../account/test/account_minimal_test.xml', ], }
30.7
87
0.586319
132
1,228
5.378788
0.651515
0.04507
0
0
0
0
0
0
0
0
0
0.003067
0.203583
1,228
39
88
31.487179
0.722904
0.076547
0
0.090909
0
0
0.786914
0.302387
0
0
0
0
0
1
0
true
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
fe818a002fc0fda4bd44bada737cfa9e0fa8d7fc
315
py
Python
packages/api-server/api_server/models/tortoise_models/user.py
baviera08/romi-dashboard
ac3a15014ad3c3bdac523a6550934a06653cfba1
[ "Apache-2.0" ]
2
2021-02-22T06:08:25.000Z
2021-03-05T12:14:51.000Z
packages/api-server/api_server/models/tortoise_models/user.py
baviera08/romi-dashboard
ac3a15014ad3c3bdac523a6550934a06653cfba1
[ "Apache-2.0" ]
77
2020-12-08T22:10:22.000Z
2021-03-09T00:44:47.000Z
packages/api-server/api_server/models/tortoise_models/user.py
baviera08/romi-dashboard
ac3a15014ad3c3bdac523a6550934a06653cfba1
[ "Apache-2.0" ]
1
2021-01-11T05:35:28.000Z
2021-01-11T05:35:28.000Z
from tortoise.fields import BooleanField, CharField, ManyToManyField, ManyToManyRelation from tortoise.models import Model from .authorization import Role class User(Model): username = CharField(255, pk=True) is_admin = BooleanField() roles: ManyToManyRelation[Role] = ManyToManyField("models.Role")
28.636364
88
0.780952
34
315
7.205882
0.617647
0.097959
0
0
0
0
0
0
0
0
0
0.011029
0.136508
315
10
89
31.5
0.889706
0
0
0
0
0
0.034921
0
0
0
0
0
0
1
0
false
0
0.428571
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
fe839ada700e80059aebb8de1318e0cc126fc810
35,460
py
Python
pysnmp/HOTWIRE-MSDSL-INTERFACE-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/HOTWIRE-MSDSL-INTERFACE-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/HOTWIRE-MSDSL-INTERFACE-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module HOTWIRE-MSDSL-INTERFACE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HOTWIRE-MSDSL-INTERFACE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:20:19 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") pdnmsdsl, = mibBuilder.importSymbols("PDN-HEADER-MIB", "pdnmsdsl") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Gauge32, IpAddress, ObjectIdentity, NotificationType, NotificationType, Integer32, TimeTicks, iso, enterprises, Bits, Unsigned32, MibIdentifier, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "IpAddress", "ObjectIdentity", "NotificationType", "NotificationType", "Integer32", "TimeTicks", "iso", "enterprises", "Bits", "Unsigned32", "MibIdentifier", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "ModuleIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") msdslDevice = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1)) msdslCurrent = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1)) msdslInterval = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2)) msdslWorstInterval = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 3)) msdslTotal = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 4)) msdslFarEndCurrent = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 5)) msdslFarEndInterval = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6)) msdslFarEndWorstInterval = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 7)) msdslFarEndTotal = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 8)) msdslCurrentPerf = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9)) msdslIntervalPerf = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10)) msdslFarEndCurrentPerf = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 11)) msdslFarEndIntervalPerf = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12)) msdsldsx1WorstInterval = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13)) msdslG703WorstInterval = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14)) msdslConfiguration = MibIdentifier((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15)) msdslCurrentTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1), ) if mibBuilder.loadTexts: msdslCurrentTable.setStatus('mandatory') msdslCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslCurrentIfIndex")) if mibBuilder.loadTexts: msdslCurrentEntry.setStatus('mandatory') msdslCurrentIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentIfIndex.setStatus('mandatory') msdslCurrentESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentESs.setStatus('mandatory') msdslCurrentSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentSESs.setStatus('mandatory') msdslCurrentFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentFEBEs.setStatus('mandatory') msdslErrEventsCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslErrEventsCounter.setStatus('mandatory') msdslErrTimeElapsed = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 899))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslErrTimeElapsed.setStatus('mandatory') msdslErrValidIntervals = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslErrValidIntervals.setStatus('mandatory') msdslIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2, 2), ) if mibBuilder.loadTexts: msdslIntervalTable.setStatus('mandatory') msdslIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2, 2, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslIntervalIfIndex"), (0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslIntervalNumber")) if mibBuilder.loadTexts: msdslIntervalEntry.setStatus('mandatory') msdslIntervalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalIfIndex.setStatus('mandatory') msdslIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalNumber.setStatus('mandatory') msdslIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2, 2, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalESs.setStatus('mandatory') msdslIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2, 2, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalSESs.setStatus('mandatory') msdslIntervalFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 2, 2, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalFEBEs.setStatus('mandatory') msdslWorstIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 3, 3), ) if mibBuilder.loadTexts: msdslWorstIntervalTable.setStatus('mandatory') msdslWorstIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 3, 3, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslWorstIntervalIfIndex")) if mibBuilder.loadTexts: msdslWorstIntervalEntry.setStatus('mandatory') msdslWorstIntervalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslWorstIntervalIfIndex.setStatus('mandatory') msdslWorstIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 3, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslWorstIntervalESs.setStatus('mandatory') msdslWorstIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 3, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslWorstIntervalSESs.setStatus('mandatory') msdslWorstIntervalFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 3, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslWorstIntervalFEBEs.setStatus('mandatory') msdslTotalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 4, 4), ) if mibBuilder.loadTexts: msdslTotalTable.setStatus('mandatory') msdslTotalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 4, 4, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslTotalIfIndex")) if mibBuilder.loadTexts: msdslTotalEntry.setStatus('mandatory') msdslTotalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 4, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslTotalIfIndex.setStatus('mandatory') msdslTotalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 4, 4, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslTotalESs.setStatus('mandatory') msdslTotalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 4, 4, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslTotalSESs.setStatus('mandatory') msdslTotalFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 4, 4, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslTotalFEBEs.setStatus('mandatory') msdslFarEndCurrentTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 5, 5), ) if mibBuilder.loadTexts: msdslFarEndCurrentTable.setStatus('mandatory') msdslFarEndCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 5, 5, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFarEndCurrentIfIndex")) if mibBuilder.loadTexts: msdslFarEndCurrentEntry.setStatus('mandatory') msdslFarEndCurrentIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 5, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentIfIndex.setStatus('mandatory') msdslFarEndCurrentESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 5, 5, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentESs.setStatus('mandatory') msdslFarEndCurrentSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 5, 5, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentSESs.setStatus('mandatory') msdslFarEndCurrentFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 5, 5, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentFEBEs.setStatus('mandatory') msdslFarEndIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6, 6), ) if mibBuilder.loadTexts: msdslFarEndIntervalTable.setStatus('mandatory') msdslFarEndIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6, 6, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFarEndIntervalIfIndex"), (0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFarEndIntervalNumber")) if mibBuilder.loadTexts: msdslFarEndIntervalEntry.setStatus('mandatory') msdslFarEndIntervalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalIfIndex.setStatus('mandatory') msdslFarEndIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6, 6, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalNumber.setStatus('mandatory') msdslFarEndIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6, 6, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalESs.setStatus('mandatory') msdslFarEndIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6, 6, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalSESs.setStatus('mandatory') msdslFarEndIntervalFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 6, 6, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalFEBEs.setStatus('mandatory') msdslFarEndWorstIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 7, 7), ) if mibBuilder.loadTexts: msdslFarEndWorstIntervalTable.setStatus('mandatory') msdslFarEndWorstIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 7, 7, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFarEndWorstIntervalIfIndex")) if mibBuilder.loadTexts: msdslFarEndWorstIntervalEntry.setStatus('mandatory') msdslFarEndWorstIntervalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 7, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndWorstIntervalIfIndex.setStatus('mandatory') msdslFarEndWorstIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 7, 7, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndWorstIntervalESs.setStatus('mandatory') msdslFarEndWorstIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 7, 7, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndWorstIntervalSESs.setStatus('mandatory') msdslFarEndWorstIntervalFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 7, 7, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndWorstIntervalFEBEs.setStatus('mandatory') msdslFarEndTotalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 8, 8), ) if mibBuilder.loadTexts: msdslFarEndTotalTable.setStatus('mandatory') msdslFarEndTotalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 8, 8, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslTotalIfIndex")) if mibBuilder.loadTexts: msdslFarEndTotalEntry.setStatus('mandatory') msdslFarEndTotalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 8, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndTotalIfIndex.setStatus('mandatory') msdslFarEndTotalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 8, 8, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndTotalESs.setStatus('mandatory') msdslFarEndTotalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 8, 8, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndTotalSESs.setStatus('mandatory') msdslFarEndTotalFEBEs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 8, 8, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndTotalFEBEs.setStatus('mandatory') msdslCurrentPerfTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9), ) if mibBuilder.loadTexts: msdslCurrentPerfTable.setStatus('mandatory') msdslCurrentPerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslCurrentPerfIfIndex")) if mibBuilder.loadTexts: msdslCurrentPerfEntry.setStatus('mandatory') msdslCurrentPerfIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentPerfIfIndex.setStatus('mandatory') msdslCurrentPerfMargin = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentPerfMargin.setStatus('mandatory') msdslCurrentPerfTxPwr = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentPerfTxPwr.setStatus('mandatory') msdslCurrentPerfRxGain = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslCurrentPerfRxGain.setStatus('mandatory') msdslPerfPayloadRate = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslPerfPayloadRate.setStatus('mandatory') msdslTimeElapsed = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 899))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslTimeElapsed.setStatus('mandatory') msdslValidIntervals = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 9, 9, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslValidIntervals.setStatus('mandatory') msdslIntervalPerfTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10, 10), ) if mibBuilder.loadTexts: msdslIntervalPerfTable.setStatus('mandatory') msdslIntervalPerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10, 10, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslIntervalPerfIfIndex"), (0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslIntervalPerfNumber")) if mibBuilder.loadTexts: msdslIntervalPerfEntry.setStatus('mandatory') msdslIntervalPerfIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10, 10, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalPerfIfIndex.setStatus('mandatory') msdslIntervalPerfNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10, 10, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalPerfNumber.setStatus('mandatory') msdslIntervalPerfMargin = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10, 10, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalPerfMargin.setStatus('mandatory') msdslIntervalPerfTxPwr = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10, 10, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalPerfTxPwr.setStatus('mandatory') msdslIntervalPerfRxGain = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 10, 10, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslIntervalPerfRxGain.setStatus('mandatory') msdslFarEndCurrentPerfTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 11, 11), ) if mibBuilder.loadTexts: msdslFarEndCurrentPerfTable.setStatus('mandatory') msdslFarEndCurrentPerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 11, 11, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFarEndCurrentPerfIfIndex")) if mibBuilder.loadTexts: msdslFarEndCurrentPerfEntry.setStatus('mandatory') msdslFarEndCurrentPerfIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 11, 11, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentPerfIfIndex.setStatus('mandatory') msdslFarEndCurrentPerfMargin = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 11, 11, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentPerfMargin.setStatus('mandatory') msdslFarEndCurrentPerfTxPwr = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 11, 11, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentPerfTxPwr.setStatus('mandatory') msdslFarEndCurrentPerfRxGain = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 11, 11, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndCurrentPerfRxGain.setStatus('mandatory') msdslFarEndIntervalPerfTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12, 12), ) if mibBuilder.loadTexts: msdslFarEndIntervalPerfTable.setStatus('mandatory') msdslFarEndIntervalPerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12, 12, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFarEndIntervalPerfIfIndex"), (0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFarEndIntervalPerfNumber")) if mibBuilder.loadTexts: msdslFarEndIntervalPerfEntry.setStatus('mandatory') msdslFarEndIntervalPerfIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12, 12, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalPerfIfIndex.setStatus('mandatory') msdslFarEndIntervalPerfNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12, 12, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalPerfNumber.setStatus('mandatory') msdslFarEndIntervalPerfMargin = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12, 12, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalPerfMargin.setStatus('mandatory') msdslFarEndIntervalPerfTxPwr = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12, 12, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalPerfTxPwr.setStatus('mandatory') msdslFarEndIntervalPerfRxGain = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 12, 12, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFarEndIntervalPerfRxGain.setStatus('mandatory') msdsldsx1WorstIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13), ) if mibBuilder.loadTexts: msdsldsx1WorstIntervalTable.setStatus('mandatory') msdsldsx1WorstIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdsldsx1WorstIntervalIfIndex")) if mibBuilder.loadTexts: msdsldsx1WorstIntervalEntry.setStatus('mandatory') msdsldsx1WorstIntervalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdsldsx1WorstIntervalIfIndex.setStatus('mandatory') msdsldsx1WorstIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdsldsx1WorstIntervalESs.setStatus('mandatory') msdsldsx1WorstIntervalUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdsldsx1WorstIntervalUASs.setStatus('mandatory') msdsldsx1WorstIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdsldsx1WorstIntervalSESs.setStatus('mandatory') msdsldsx1WorstIntervalBESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdsldsx1WorstIntervalBESs.setStatus('mandatory') msdsldsx1WorstIntervalCSSs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdsldsx1WorstIntervalCSSs.setStatus('mandatory') msdsldsx1WorstIntervalLOFC = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 13, 13, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdsldsx1WorstIntervalLOFC.setStatus('mandatory') msdslG703WorstIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14), ) if mibBuilder.loadTexts: msdslG703WorstIntervalTable.setStatus('mandatory') msdslG703WorstIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslG703WorstIntervalIfIndex")) if mibBuilder.loadTexts: msdslG703WorstIntervalEntry.setStatus('mandatory') msdslG703WorstIntervalIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslG703WorstIntervalIfIndex.setStatus('mandatory') msdslG703WorstIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslG703WorstIntervalESs.setStatus('mandatory') msdslG703WorstIntervalUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslG703WorstIntervalUASs.setStatus('mandatory') msdslG703WorstIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslG703WorstIntervalSESs.setStatus('mandatory') msdslG703WorstIntervalBESs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslG703WorstIntervalBESs.setStatus('mandatory') msdslG703WorstIntervalCSSs = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslG703WorstIntervalCSSs.setStatus('mandatory') msdslG703WorstIntervalLOFC = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 14, 14, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslG703WorstIntervalLOFC.setStatus('mandatory') msdslFracTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 28), ) if mibBuilder.loadTexts: msdslFracTable.setStatus('mandatory') msdslFracEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 28, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFracPortIndex"), (0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslFracPortTS")) if mibBuilder.loadTexts: msdslFracEntry.setStatus('mandatory') msdslFracPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 28, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslFracPortIndex.setStatus('mandatory') msdslFracPortTS = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 28, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readwrite") if mibBuilder.loadTexts: msdslFracPortTS.setStatus('mandatory') msdslFracPortIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 28, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: msdslFracPortIfIndex.setStatus('mandatory') msdslFracPortIfTS = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 28, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: msdslFracPortIfTS.setStatus('mandatory') msdslFracPortVoiceData = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 28, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("voice", 1), ("data", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: msdslFracPortVoiceData.setStatus('mandatory') msdslPortConfigAllocMethodTable = MibTable((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 29), ) if mibBuilder.loadTexts: msdslPortConfigAllocMethodTable.setStatus('mandatory') msdslPortConfigAllocMethodEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 29, 1), ).setIndexNames((0, "HOTWIRE-MSDSL-INTERFACE-MIB", "msdslPortConfigAllocMethodIfIndex")) if mibBuilder.loadTexts: msdslPortConfigAllocMethodEntry.setStatus('mandatory') msdslPortConfigAllocMethodIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 29, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: msdslPortConfigAllocMethodIfIndex.setStatus('mandatory') msdslPortConfigAllocMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1, 15, 29, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("ds1ByPass", 1), ("ds1CrossConn", 2), ("ds0CrossConn", 3), ("notAssigned", 4), ("disabled", 5)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: msdslPortConfigAllocMethod.setStatus('mandatory') msdslMarginLow = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1) + (0,3)).setObjects(("IF-MIB", "ifIndex")) msdslMarginNormal = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1) + (0,103)).setObjects(("IF-MIB", "ifIndex")) msdslErrorRateHigh = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1) + (0,4)).setObjects(("IF-MIB", "ifIndex")) msdslErrorRateNormal = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1) + (0,104)).setObjects(("IF-MIB", "ifIndex")) msdslTestOver = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1) + (0,106)).setObjects(("IF-MIB", "ifIndex")) msdslNTUTypeMismatch = NotificationType((1, 3, 6, 1, 4, 1, 1795, 2, 24, 2, 6, 15, 1) + (0,7)).setObjects(("IF-MIB", "ifIndex")) mibBuilder.exportSymbols("HOTWIRE-MSDSL-INTERFACE-MIB", msdsldsx1WorstIntervalUASs=msdsldsx1WorstIntervalUASs, msdslFarEndTotalFEBEs=msdslFarEndTotalFEBEs, msdslFarEndCurrentPerfTxPwr=msdslFarEndCurrentPerfTxPwr, msdslFarEndWorstIntervalEntry=msdslFarEndWorstIntervalEntry, msdslPortConfigAllocMethodIfIndex=msdslPortConfigAllocMethodIfIndex, msdslNTUTypeMismatch=msdslNTUTypeMismatch, msdslPortConfigAllocMethod=msdslPortConfigAllocMethod, msdslWorstIntervalEntry=msdslWorstIntervalEntry, msdslFarEndIntervalPerfNumber=msdslFarEndIntervalPerfNumber, msdslFarEndCurrentPerfEntry=msdslFarEndCurrentPerfEntry, msdslFarEndWorstIntervalSESs=msdslFarEndWorstIntervalSESs, msdslPortConfigAllocMethodEntry=msdslPortConfigAllocMethodEntry, msdslG703WorstIntervalCSSs=msdslG703WorstIntervalCSSs, msdslFarEndIntervalEntry=msdslFarEndIntervalEntry, msdslIntervalPerfRxGain=msdslIntervalPerfRxGain, msdslFarEndCurrentSESs=msdslFarEndCurrentSESs, msdslMarginNormal=msdslMarginNormal, msdslFarEndIntervalPerf=msdslFarEndIntervalPerf, msdslIntervalPerfTxPwr=msdslIntervalPerfTxPwr, msdslFarEndCurrentEntry=msdslFarEndCurrentEntry, msdslG703WorstIntervalIfIndex=msdslG703WorstIntervalIfIndex, msdslFarEndCurrent=msdslFarEndCurrent, msdslTotal=msdslTotal, msdslFarEndIntervalPerfTxPwr=msdslFarEndIntervalPerfTxPwr, msdsldsx1WorstIntervalCSSs=msdsldsx1WorstIntervalCSSs, msdslG703WorstIntervalTable=msdslG703WorstIntervalTable, msdslFarEndTotalSESs=msdslFarEndTotalSESs, msdslTotalESs=msdslTotalESs, msdslWorstIntervalSESs=msdslWorstIntervalSESs, msdslIntervalSESs=msdslIntervalSESs, msdslFarEndWorstInterval=msdslFarEndWorstInterval, msdslFarEndTotalTable=msdslFarEndTotalTable, msdslG703WorstIntervalBESs=msdslG703WorstIntervalBESs, msdslFarEndCurrentPerfIfIndex=msdslFarEndCurrentPerfIfIndex, msdslCurrentPerf=msdslCurrentPerf, msdslCurrentPerfTxPwr=msdslCurrentPerfTxPwr, msdsldsx1WorstIntervalLOFC=msdsldsx1WorstIntervalLOFC, msdslConfiguration=msdslConfiguration, msdslFarEndTotal=msdslFarEndTotal, msdslFarEndCurrentFEBEs=msdslFarEndCurrentFEBEs, msdslTimeElapsed=msdslTimeElapsed, msdslFarEndInterval=msdslFarEndInterval, msdslIntervalPerfEntry=msdslIntervalPerfEntry, msdslCurrentPerfMargin=msdslCurrentPerfMargin, msdslG703WorstIntervalUASs=msdslG703WorstIntervalUASs, msdslCurrentPerfRxGain=msdslCurrentPerfRxGain, msdslFarEndIntervalPerfMargin=msdslFarEndIntervalPerfMargin, msdslFarEndIntervalNumber=msdslFarEndIntervalNumber, msdslIntervalEntry=msdslIntervalEntry, msdslFarEndTotalESs=msdslFarEndTotalESs, msdslFarEndWorstIntervalFEBEs=msdslFarEndWorstIntervalFEBEs, msdslFarEndIntervalTable=msdslFarEndIntervalTable, msdslIntervalPerf=msdslIntervalPerf, msdslFracPortIndex=msdslFracPortIndex, msdslTestOver=msdslTestOver, msdslFracPortVoiceData=msdslFracPortVoiceData, msdslFarEndCurrentPerfMargin=msdslFarEndCurrentPerfMargin, msdslFarEndIntervalPerfIfIndex=msdslFarEndIntervalPerfIfIndex, msdslFarEndIntervalPerfTable=msdslFarEndIntervalPerfTable, msdslFracTable=msdslFracTable, msdslIntervalFEBEs=msdslIntervalFEBEs, msdsldsx1WorstIntervalEntry=msdsldsx1WorstIntervalEntry, msdslCurrentTable=msdslCurrentTable, msdsldsx1WorstIntervalESs=msdsldsx1WorstIntervalESs, msdslFarEndCurrentPerf=msdslFarEndCurrentPerf, msdsldsx1WorstIntervalIfIndex=msdsldsx1WorstIntervalIfIndex, msdslWorstInterval=msdslWorstInterval, msdslFarEndIntervalPerfRxGain=msdslFarEndIntervalPerfRxGain, msdslTotalEntry=msdslTotalEntry, msdslFarEndWorstIntervalTable=msdslFarEndWorstIntervalTable, msdslFarEndWorstIntervalESs=msdslFarEndWorstIntervalESs, msdslG703WorstIntervalLOFC=msdslG703WorstIntervalLOFC, msdslCurrentESs=msdslCurrentESs, msdslFarEndTotalIfIndex=msdslFarEndTotalIfIndex, msdslFracPortTS=msdslFracPortTS, msdslFarEndIntervalPerfEntry=msdslFarEndIntervalPerfEntry, msdslFarEndCurrentIfIndex=msdslFarEndCurrentIfIndex, msdslErrEventsCounter=msdslErrEventsCounter, msdslFarEndTotalEntry=msdslFarEndTotalEntry, msdslTotalTable=msdslTotalTable, msdslErrValidIntervals=msdslErrValidIntervals, msdslFracPortIfTS=msdslFracPortIfTS, msdslCurrentPerfIfIndex=msdslCurrentPerfIfIndex, msdslTotalFEBEs=msdslTotalFEBEs, msdslDevice=msdslDevice, msdslFarEndIntervalESs=msdslFarEndIntervalESs, msdslIntervalPerfTable=msdslIntervalPerfTable, msdslG703WorstInterval=msdslG703WorstInterval, msdslFarEndCurrentPerfTable=msdslFarEndCurrentPerfTable, msdslMarginLow=msdslMarginLow, msdslIntervalPerfIfIndex=msdslIntervalPerfIfIndex, msdslIntervalIfIndex=msdslIntervalIfIndex, msdslIntervalESs=msdslIntervalESs, msdslFarEndCurrentPerfRxGain=msdslFarEndCurrentPerfRxGain, msdslErrorRateNormal=msdslErrorRateNormal, msdslIntervalNumber=msdslIntervalNumber, msdslIntervalPerfMargin=msdslIntervalPerfMargin, msdslIntervalTable=msdslIntervalTable, msdslFracEntry=msdslFracEntry, msdslPerfPayloadRate=msdslPerfPayloadRate, msdslFarEndIntervalIfIndex=msdslFarEndIntervalIfIndex, msdslFarEndWorstIntervalIfIndex=msdslFarEndWorstIntervalIfIndex, msdslFarEndCurrentTable=msdslFarEndCurrentTable, msdslWorstIntervalESs=msdslWorstIntervalESs, msdslCurrentSESs=msdslCurrentSESs, msdsldsx1WorstIntervalBESs=msdsldsx1WorstIntervalBESs, msdslErrorRateHigh=msdslErrorRateHigh, msdslWorstIntervalTable=msdslWorstIntervalTable, msdslTotalSESs=msdslTotalSESs, msdslCurrentPerfEntry=msdslCurrentPerfEntry, msdslG703WorstIntervalSESs=msdslG703WorstIntervalSESs, msdslFarEndIntervalSESs=msdslFarEndIntervalSESs, msdslInterval=msdslInterval, msdslCurrentFEBEs=msdslCurrentFEBEs, msdslG703WorstIntervalEntry=msdslG703WorstIntervalEntry, msdslCurrent=msdslCurrent, msdslTotalIfIndex=msdslTotalIfIndex, msdslIntervalPerfNumber=msdslIntervalPerfNumber, msdslG703WorstIntervalESs=msdslG703WorstIntervalESs, msdsldsx1WorstIntervalSESs=msdsldsx1WorstIntervalSESs, msdslCurrentIfIndex=msdslCurrentIfIndex, msdslErrTimeElapsed=msdslErrTimeElapsed, msdsldsx1WorstInterval=msdsldsx1WorstInterval, msdsldsx1WorstIntervalTable=msdsldsx1WorstIntervalTable, msdslPortConfigAllocMethodTable=msdslPortConfigAllocMethodTable, msdslFarEndIntervalFEBEs=msdslFarEndIntervalFEBEs, msdslCurrentEntry=msdslCurrentEntry, msdslWorstIntervalIfIndex=msdslWorstIntervalIfIndex, msdslValidIntervals=msdslValidIntervals, msdslCurrentPerfTable=msdslCurrentPerfTable, msdslFarEndCurrentESs=msdslFarEndCurrentESs, msdslWorstIntervalFEBEs=msdslWorstIntervalFEBEs, msdslFracPortIfIndex=msdslFracPortIfIndex)
135.862069
6,312
0.759955
4,116
35,460
6.547133
0.064869
0.011504
0.014918
0.019742
0.423111
0.399918
0.399918
0.371642
0.288778
0.288778
0
0.110501
0.090948
35,460
260
6,313
136.384615
0.725485
0.009814
0
0
0
0
0.096203
0.029029
0
0
0
0
0
1
0
false
0.003953
0.031621
0
0.031621
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
fe88d77e56ccc83cf76551b4f3d33cc0d3940ac8
3,671
py
Python
src/gui/gui_main.py
nathanawmk/TuringMachine
3a21df9123bf83eb1f852047c51f0f1eacca5ea1
[ "MIT" ]
2
2021-06-17T11:49:52.000Z
2021-11-11T03:52:37.000Z
src/gui/gui_main.py
nathanawmk/TuringMachine
3a21df9123bf83eb1f852047c51f0f1eacca5ea1
[ "MIT" ]
null
null
null
src/gui/gui_main.py
nathanawmk/TuringMachine
3a21df9123bf83eb1f852047c51f0f1eacca5ea1
[ "MIT" ]
1
2021-11-11T03:52:38.000Z
2021-11-11T03:52:38.000Z
#from PIL import Image, ImageTk # broken for some reason on windows box import Tkinter as tk import webbrowser import options_gui import run_gui textOptions = dict(font = ("Helvetica", 18), bg = "lightblue") class GUI: def __init__(self,window): self.window = window self.optionsGUI = None self.runGUI = None self.language = "English" self.speed = "Slow" w = 22 h = 7 self.programs = tk.Button(self.window, text = "Programs", height = h, width = w, command = self.showRun, **textOptions) self.programs.grid (row = 1, column = 2) self.about = tk.Button(self.window, text = "About", height = h, width = w, command = self.showAbout, **textOptions) self.about.grid (row = 2, column = 1) self.options = tk.Button(self.window, text = "Options", height = h, width = w, command = self.showOptions, **textOptions) self.options.grid (row = 2, column = 2) # doesn't work on windows, but seems to have better support on unix #image = Image.open("turing.jpg") #photo = ImageTk.PhotoImage(image) #self.ll = tk.Label(self.window, # height = h, # width = w, # image = photo # ) self.logo = tk.Label(self.window, text = "MIT Lincoln Lab", font = ("Helvetica", 22)) self.logo.grid(row = 1, column = 1) def showOptions(self): self.setState(tk.DISABLED) t = tk.Toplevel(self.window) t.minsize(width = 300, height = 150) self.optionsGUI = options_gui.Options(t,self) t.protocol("WM_DELETE_WINDOW", self.optionsGUI.close) t.mainloop() def showRun(self): self.setState(tk.DISABLED) t = tk.Toplevel(self.window) t.minsize(width = 600, height = 600) self.runGUI = run_gui.Run(t,self) t.protocol("WM_DELETE_WINDOW", self.runGUI.close) t.mainloop() def output(self): print self.language print self.speed def setState(self, newState): self.programs.config(state = newState) self.about.config(state = newState) self.options.config(state = newState) def showAbout(self): webbrowser.open("turing.html") window = tk.Tk() #window.minsize(width =10, height = 1) window.geometry = ("10x5") #window.resizable(width=tk.FALSE, height = tk.FALSE) window.wm_title("Turing Machine") app = GUI(window) window.mainloop()
37.459184
83
0.40997
314
3,671
4.751592
0.33121
0.060322
0.037534
0.034853
0.215818
0.171582
0.123324
0.123324
0.080429
0.080429
0
0.018132
0.504222
3,671
98
84
37.459184
0.801648
0.11441
0
0.223881
0
0
0.041358
0
0
0
0
0
0
0
null
null
0
0.059701
null
null
0.029851
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
fe8df127e3b5f38029afcf5b972e21e687ef0689
195,483
py
Python
unifhy/space.py
ThibHlln/unifhy
4105932ed7dfec34d428c1f2d2f85ec25ea522ed
[ "BSD-3-Clause" ]
2
2021-07-12T14:28:26.000Z
2021-08-12T08:16:55.000Z
unifhy/space.py
ThibHlln/unifhy
4105932ed7dfec34d428c1f2d2f85ec25ea522ed
[ "BSD-3-Clause" ]
33
2021-06-09T15:44:48.000Z
2021-12-02T09:09:36.000Z
unifhy/space.py
unifhy-org/unifhy
4105932ed7dfec34d428c1f2d2f85ec25ea522ed
[ "BSD-3-Clause" ]
2
2021-04-13T09:29:45.000Z
2021-05-02T11:42:04.000Z
import abc import numpy as np from copy import deepcopy import re import cf import cfunits import pyproj from .settings import atol, rtol, decr, dtype_float class SpaceDomain(metaclass=abc.ABCMeta): """SpaceDomain characterises a spatial dimension that is needed by a `Component`. Any supported spatial configuration for a `Component` is a subclass of SpaceDomain. TODO: deal with sub-grid heterogeneity schemes (e.g. tiling, HRUs) """ def __init__(self): # inner CF data model self._f = cf.Field() self._cell_area = None self._cell_area_field = None # optional flow direction attributes self._flow_direction = None self._flow_direction_field = None self._routing_out_mask = None self._routing_masks = {} # optional land sea mask attributes self._land_sea_mask = None self._land_sea_mask_field = None @property @abc.abstractmethod def shape(self): # The sizes of the SpaceDomain dimension axes as a `tuple`. # The corresponding names and order of the axes is accessible # through the `axes` property. return None @property @abc.abstractmethod def axes(self): # The names of the SpaceDomain dimension axes as a `tuple`. # These names are properties of SpaceDomain, which give access # to the coordinate values along each axis. return None @abc.abstractmethod def has_vertical_axis(self): return None @property @abc.abstractmethod def vertical_axis(self): # The name of the SpaceDomain vertical dimension axis as a `str`. return None @property @abc.abstractmethod def flow_direction(self): return self._flow_direction @flow_direction.setter @abc.abstractmethod def flow_direction(self, **kwargs): pass @property @abc.abstractmethod def land_sea_mask(self): return self._land_sea_mask @land_sea_mask.setter @abc.abstractmethod def land_sea_mask(self, **kwargs): pass @property @abc.abstractmethod def cell_area(self): return self._cell_area @cell_area.setter @abc.abstractmethod def cell_area(self, **kwargs): pass def __eq__(self, other): if isinstance(other, self.__class__): return self.is_space_equal_to(other._f) else: return False def __ne__(self, other): return not self.__eq__(other) @abc.abstractmethod def is_space_equal_to(self, *args): pass @abc.abstractmethod def spans_same_region_as(self, *args): pass @abc.abstractmethod def is_matched_in(self, *args): pass @abc.abstractmethod def subset_and_compare(self, field): pass @classmethod @abc.abstractmethod def from_field(cls, field): pass def to_field(self): """Return a deep copy of the inner cf.Field used to characterise the SpaceDomain. """ return deepcopy(self._f) @classmethod @abc.abstractmethod def from_config(cls, cfg): pass @abc.abstractmethod def to_config(self): pass class Grid(SpaceDomain): """Grid is a `SpaceDomain` subclass which represents space as a regular grid made of contiguous grid cells. Any supported regular grid for a `Component` is a subclass of Grid. """ # characteristics of the dimension coordinates _Z_name = None _Y_name = None _X_name = None _Z_units = [] _Y_units = [] _X_units = [] _Z_limits = None _Y_limits = None _X_limits = None # contiguity of lower and upper limits _Z_limits_contiguous = False _Y_limits_contiguous = False _X_limits_contiguous = False # allow domain to wrap around limits _Z_wrap_around = False _Y_wrap_around = False _X_wrap_around = False # characterise the routing directions as relative (Y, X) _routing_cardinal_map = { 'N': (1, 0), 'NE': (1, 1), 'E': (0, 1), 'SE': (-1, 1), 'S': (-1, 0), 'SW': (-1, -1), 'W': (0, -1), 'NW': (1, -1), 'O': (0, 0) } _routing_digits_map = { 1: (1, 0), 2: (1, 1), 3: (0, 1), 4: (-1, 1), 5: (-1, 0), 6: (-1, -1), 7: (0, -1), 8: (1, -1), 0: (0, 0) } # supported locations to generate grid _YX_loc_map = { 'centre': ('centre', 'center', '0', 0), 'lower_left': ('lower_left', 'lower left', '1', 1), 'upper_left': ('upper_left', 'upper left', '2', 2), 'lower_right': ('lower_right', 'lower right', '3', 3), 'upper_right': ('upper_right', 'upper right', '4', 4) } _Z_loc_map = { 'centre': ('centre', 'center', '0', 0), 'bottom': ('bottom', '1', 1), 'top': ('top', '2', 2) } # geometrical properties _earth_radius_m = 6371229.0 def __init__(self, **kwargs): super(Grid, self).__init__() @property def shape(self): """Return the size of the `Grid` dimension axes as a `tuple`. The corresponding names and order of the axes is accessible through the `axes` property. """ return ( (self._f.dim('Z').shape if self.has_vertical_axis() else ()) + self._f.dim('Y').shape + self._f.dim('X').shape ) @property def axes(self): """Return the name of the properties to use to get access to the axes defined for the `Grid` instance as a `tuple`. """ return ('Z', 'Y', 'X') if self.has_vertical_axis() else ('Y', 'X') def has_vertical_axis(self): """Determine whether the `Grid` features a vertical dimension. Return a `bool`. """ return ( True if self._f.dim(self._Z_name, key=True, default=False) else False ) @property def vertical_axis(self): """Return the name of the property to use to get access to the vertical axis defined for the `Grid` as a `str`. If not defined, return `None`. """ return 'Z' if self.has_vertical_axis() else None @property def Z(self): """Return the Z-axis of the `Grid` instance as a `cf.Data` instance if the Z-axis exists, otherwise return `None`. """ if self.has_vertical_axis(): return self._f.dim('Z').data else: return None @property def Y(self): """Return the Y-axis of the `Grid` instance as a `cf.Data` instance. """ return self._f.dim('Y').data @property def X(self): """Return the X-axis of the `Grid` instance as a `cf.Data` instance. """ return self._f.dim('X').data @property def Z_bounds(self): """Return the bounds of the Z-axis of the `Grid` instance as a `cf.Data` instance if the Z-axis exists, otherwise return `None`. """ if self.has_vertical_axis(): return self._f.dim('Z').bounds.data else: return None @property def Y_bounds(self): """Return the bounds of the Y-axis of the `Grid` instance as a `cf.Data` instance. """ return self._f.dim('Y').bounds.data @property def X_bounds(self): """Return the bounds of the X-axis of the `Grid` instance as a `cf.Data` instance. """ return self._f.dim('X').bounds.data @property def Z_name(self): """Return the name of the Z-axis of the `Grid` instance as a `str` if the Z-axis exists, otherwise return `None`. """ if self.has_vertical_axis(): return self._f.dim('Z').standard_name else: return None @property def Y_name(self): """Return the name of the Y-axis of the `Grid` instance as a `str`. """ return self._f.dim('Y').standard_name @property def X_name(self): """Return the name of the X-axis of the `Grid` instance as a `str`. """ return self._f.dim('X').standard_name @property def land_sea_mask(self): """The land-sea mask for the `Grid` of boolean/binary values (i.e. True/1 for land, False/0 for sea) given as a `cf.Field` and returned as a processed `numpy.ndarray`. :Parameters: mask: `cf.Field` The field containing the land-sea information. The shape of the data array must be the same as the `Grid`. The field data must contain boolean/binary values (True/1 for land, False/0 for sea). :Returns: `numpy.ndarray` The array containing the land-sea information as boolean values (True for land, False for sea). The shape of the array is the same as of the `Grid`. If not set, return `None`. **Examples** Assigning land sea mask to grid using binary values: >>> import numpy >>> grid = LatLonGrid.from_extent_and_resolution( ... latitude_extent=(51, 55), ... latitude_resolution=1, ... longitude_extent=(-2, 1), ... longitude_resolution=1 ... ) >>> print(grid.land_sea_mask) None >>> mask = grid.to_field() >>> mask.set_data(numpy.array([[0, 1, 1], ... [1, 1, 0], ... [0, 1, 0], ... [0, 0, 0]])) >>> grid.land_sea_mask = mask >>> print(grid.land_sea_mask) [[False True True] [ True True False] [False True False] [False False False]] >>> print(grid) LatLonGrid( shape {Y, X}: (4, 3) Y, latitude (4,): [51.5, ..., 54.5] degrees_north X, longitude (3,): [-1.5, -0.5, 0.5] degrees_east Y_bounds (4, 2): [[51.0, ..., 55.0]] degrees_north X_bounds (3, 2): [[-2.0, ..., 1.0]] degrees_east land_sea_mask (4, 3): [[False, ..., False]] ) Assigning land sea mask to grid using boolean values: >>> mask.set_data(numpy.array([[False, True, True], ... [True, True, False], ... [False, True, False], ... [False, False, False]])) >>> grid.land_sea_mask = mask >>> print(grid.land_sea_mask) [[False True True] [ True True False] [False True False] [False False False]] """ return self._land_sea_mask @land_sea_mask.setter def land_sea_mask(self, mask): error = RuntimeError( f"mask shape incompatible with {self.__class__.__name__}" ) # check type if not isinstance(mask, cf.Field): raise TypeError("mask not a cf.Field") # store given field for config file self._land_sea_mask_field = mask # drop potential size-1 Z axis since land sea mask is # only relevant horizontally if mask.domain_axis(self.vertical_axis, key=True, default=False): mask.squeeze(self.vertical_axis, inplace=True) # check that mask and spacedomain are compatible grid = self.to_horizontal_grid() try: mask = grid.subset_and_compare(mask) except RuntimeError: raise error # determine horizontal-only shape of spacedomain shp = grid.shape # get field's data array mask = mask.array # convert binary to boolean if necessary if not mask.dtype == np.dtype(bool): if (np.sum(mask == 1) + np.sum(mask == 0)) == mask.size: mask = np.asarray(mask, dtype=bool) else: raise TypeError("mask must contain boolean/binary values") if not mask.shape == shp: raise error # apply mask to underlying data to be taken into account in remapping self._f.data[:] = np.ma.array(self._f.array, mask=~mask) self._land_sea_mask = mask @property def flow_direction(self): """The information necessary to move any variable laterally (i.e. along Y and/or X) to its nearest receiving neighbour in the `Grid` given as a `cf.Field` and returned as a processed `numpy.ndarray`. :Parameters: directions: `cf.Field` The field containing flow direction. The supported kinds of directional information are listed in the table below. The shape of the array must be the same as the Grid, except for the relative kind, where an additional trailing axis of size two holding the pairs must be present. ================= ===================================== kind information ================= ===================================== cardinal The field data contains the direction using `str` for the eight following cardinal points: 'N' for North, 'NE' for North-East, 'E' for East, 'SE' for South East, 'S' for South, 'SW' for South West, 'W' for West, 'NW' for North West. digits The field data contains the direction using `int` for the eight following cardinal points: 1 for North, 2 for North-East, 3 for East, 4 for South East, 5 for South, 6 for South West, 7 for West, 8 for North West. relative The field data contains the direction using pairs of `int` (Y, X) for the eight following cardinal points: (1, 0) for North, (1, 1) for North-East, (0, 1) for East, (-1, 1) for South East, (-1, 0) for South, (-1, -1) for South West, (0, -1) for West, (1, -1) for North West. ================= ===================================== :Returns: `numpy.ndarray` The information to route any variable to its destination in the `Grid` in the relative format (see table above). If not set, return `None`. **Examples** Assigning flow direction to grid using cardinal values: >>> import numpy >>> grid = LatLonGrid.from_extent_and_resolution( ... latitude_extent=(51, 55), ... latitude_resolution=1, ... longitude_extent=(-2, 1), ... longitude_resolution=1 ... ) >>> print(grid.flow_direction) None >>> directions = grid.to_field() >>> directions.set_data(numpy.array([['SE', 'S', 'E'], ... ['NE', 'E', 'N'], ... ['S', 'S', 'W'], ... ['NW', 'E', 'SW']])) >>> grid.flow_direction = directions >>> print(grid.flow_direction) [[[-1 1] [-1 0] [ 0 1]] <BLANKLINE> [[ 1 1] [ 0 1] [ 1 0]] <BLANKLINE> [[-1 0] [-1 0] [ 0 -1]] <BLANKLINE> [[ 1 -1] [ 0 1] [-1 -1]]] >>> print(grid) LatLonGrid( shape {Y, X}: (4, 3) Y, latitude (4,): [51.5, ..., 54.5] degrees_north X, longitude (3,): [-1.5, -0.5, 0.5] degrees_east Y_bounds (4, 2): [[51.0, ..., 55.0]] degrees_north X_bounds (3, 2): [[-2.0, ..., 1.0]] degrees_east flow_direction (4, 3, 2): [[[-1, ..., -1]]] ) Assigning flow direction to grid using digits: >>> flow_direction = grid.flow_direction >>> directions.set_data(numpy.array([[4, 5, 3], ... [2, 3, 1], ... [5, 5, 7], ... [8, 3, 6]])) >>> grid.flow_direction = directions >>> numpy.array_equal(flow_direction, grid.flow_direction) True Assigning flow direction to grid using relative values: >>> import cf >>> ax = directions.set_construct(cf.DomainAxis(2)) >>> dim = cf.DimensionCoordinate( ... properties={'name': 'relative flow direction along y and x components', ... 'units': '1'}, ... data=cf.Data(['y_rel', 'x_rel']) ... ) >>> dim = directions.set_construct(dim, axes=ax) >>> directions.set_data( ... numpy.array([[[-1, 1], [-1, 0], [0, 1]], ... [[1, 1], [0, 1], [1, 0]], ... [[-1, 0], [-1, 0], [0, -1]], ... [[1, -1], [0, 1], [-1, -1]]] ... ), ... axes=('Y', 'X', dim) ... ) >>> grid.flow_direction = directions >>> numpy.array_equal(flow_direction, grid.flow_direction) True Assigning masked flow direction to grid: >>> directions = grid.to_field() >>> directions.set_data( ... numpy.ma.array( ... [['SE', 'S', 'E'], ... ['NE', 'E', 'N'], ... ['S', 'S', 'W'], ... ['NW', 'E', 'SW']], ... mask=[[1, 0, 0], ... [1, 0, 0], ... [1, 1, 0], ... [0, 0, 0]] ... ) ... ) >>> grid.flow_direction = directions >>> print(grid.flow_direction) [[[-- --] [-1 0] [0 1]] <BLANKLINE> [[-- --] [0 1] [1 0]] <BLANKLINE> [[-- --] [-- --] [0 -1]] <BLANKLINE> [[1 -1] [0 1] [-1 -1]]] """ return self._flow_direction @flow_direction.setter def flow_direction(self, directions): error_valid = RuntimeError("flow direction contains invalid data") error_dim = RuntimeError( f"flow direction dimensions not compatible " f"with {self.__class__.__name__}" ) # check type if not isinstance(directions, cf.Field): raise TypeError("flow direction not a cf.Field") # store given field for config file self._flow_direction_field = directions # drop potential size-1 Z axis since flow direction is # only relevant horizontally if directions.domain_axis(self.vertical_axis, key=True, default=False): directions.squeeze(self.vertical_axis, inplace=True) # check that directions and spacedomain are compatible grid = self.to_horizontal_grid() try: directions = grid.subset_and_compare(directions) except RuntimeError: raise error_dim # get field's data array directions = directions.array # determine horizontal-only shape of spacedomain shp = grid.shape # initialise info array by extending by one trailing axis of # size 2 (for relative Y movement, and relative X movement) # if masked array, use same mask on info if np.ma.is_masked(directions): if (shp + (2,)) == directions.shape: info = np.ma.masked_array( np.zeros(shp + (2,), int), mask=directions.mask ) elif shp == directions.shape: info = np.ma.masked_array( np.zeros(shp + (2,), int), mask=np.tile(directions.mask[..., np.newaxis], 2) ) else: raise error_dim info[~info.mask] = -9 else: info = np.zeros(shp + (2,), int) info[:] = -9 # convert directions to relative Y X movement if directions.dtype == np.dtype('<U2'): # cardinal if not directions.shape == shp: raise error_dim # strip and capitalise strings if np.ma.is_masked(directions): directions[~directions.mask] = np.char.strip( np.char.upper(directions[~directions.mask]) ) else: directions = np.char.strip(np.char.upper(directions)) for card, yx_rel in self._routing_cardinal_map.items(): info[directions == card] = yx_rel elif issubclass(directions.dtype.type, np.integer): if info.shape == directions.shape: # relative if np.amin(directions) < -1 or np.amax(directions) > 1: raise error_valid info[:] = directions elif shp == directions.shape: # digits for digit, yx_rel in self._routing_digits_map.items(): info[directions == digit] = yx_rel else: raise error_dim else: raise error_valid # check that match found for everywhere in grid if not np.sum(info == -9) == 0: raise error_valid # assign main routing mask self._flow_direction = info # find outflow towards outside domain # to set relative direction special value 9 info_ = np.zeros(shp + (2,), int) info_[:] = info if not (self._Y_limits_contiguous and (self.Y_bounds.array[0, 0] in self._Y_limits) and (self.Y_bounds.array[-1, -1] in self._Y_limits)): # northwards on north edge info_[..., 0, :, 0][info_[..., 0, :, 0] == -1] = 9 # southwards on south edge info_[..., -1, :, 0][info_[..., -1, :, 0] == 1] = 9 if not (self._X_limits_contiguous and (self.X_bounds.array[0, 0] in self._X_limits) and (self.X_bounds.array[-1, -1] in self._X_limits)): # eastwards on east edge info_[..., :, -1, 1][info_[..., :, -1, 1] == 1] = 9 # westwards on west edge info_[..., :, 0, 1][info_[..., :, 0, 1] == -1] = 9 # create mask for location with outflow towards outside domain to_out = (info_[..., 0] == 9) | (info_[..., 1] == 9) # find outflow towards masked location if np.ma.is_masked(directions): # get absolute destination from relative directions y, x = to_out.shape[-2:] abs_dst = np.zeros(info_.shape, dtype=int) abs_dst[..., 0][~to_out] = (np.arange(y, dtype=int)[:, np.newaxis] + info_[..., 0])[~to_out] abs_dst[..., 1][~to_out] = (np.arange(x, dtype=int)[np.newaxis, :] + info_[..., 1])[~to_out] # avoid IndexError by arbitrarily setting (0, 0) where domain outflow abs_dst[..., 0][to_out] = 0 abs_dst[..., 1][to_out] = 0 # use destination on mask to determine if towards masked location to_msk = directions.mask[tuple(abs_dst.T)].T # eliminate previous arbitrary action that avoided IndexError to_msk[to_out] = False # set relative direction to special value 9 # where outflow towards masked location info_[..., 0][to_msk] = 9 info_[..., 1][to_msk] = 9 else: to_msk = np.zeros(shp, dtype=bool) # pre-process some convenience masks out of main routing mask # to avoid generating them every time *route* method is called # Y-wards movement for j in [-1, 0, 1]: # X-wards movement for i in [-1, 0, 1]: # note: special value 9 set previously allows here to # ignore them in the routing masks self._routing_masks[(j, i)] = ( (info_[..., 0] == j) & (info_[..., 1] == i) ) # OUT-wards movement # (i.e. towards outside domain or towards masked location) self._routing_out_mask = to_out | to_msk def route(self, values_to_route): """Move the given values from their current location in the `Grid` to their downstream/downslope location according to the *flow_direction* property of `Grid`. :Parameters: values_to_route: `numpy.ndarray` The values to route following the flow direction, e.g. how river discharge to route. The shape of this array must be the same as of the grid. :Returns: values_routed: `numpy.ndarray` The values routed following the flow direction, e.g. how much river discharge is coming into each grid element from their upstream grid elements. The shape of this array is the same as of the grid. values_out: `numpy.ndarray` The values that routed following the flow direction would have left the domain (a value is considered to leave the domain if it is directed towards beyond the bounds of of the domain, or towards a masked location within the domain, if the *flow_direction* is masked), e.g. how much river discharge has not been routed towards the downstream grid element because this one is not defined (i.e. outside the grid) or masked (i.e. outside the drainage area or into the sea). The shape of this array is the same as of the grid. **Examples** .. warning :: Given that Y and X `Grid` coordinates are ordered increasingly northwards and eastwards, respectively, and given that a 2D `numpy.ndarray` origin (i.e. [0, 0]) is in the upper-left corner when visualising the content of an array (i.e. using `print`), routing a value northwards will result in visualising it "moving down" the array (and not up), and routing a value eastwards will result in visualising it "moving right". Using grid routing functionality with basic domain and flow direction: >>> import numpy >>> grid = LatLonGrid.from_extent_and_resolution( ... latitude_extent=(51, 55), ... latitude_resolution=1, ... longitude_extent=(-2, 1), ... longitude_resolution=1 ... ) >>> values = numpy.arange(12).reshape(4, 3) + 1 >>> print(values) [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] >>> directions = grid.to_field() >>> directions.set_data(numpy.array([['NE', 'N', 'E'], ... ['SE', 'E', 'S'], ... ['N', 'N', 'W'], ... ['SW', 'E', 'NW']])) >>> grid.flow_direction = directions >>> moved, out = grid.route(values) >>> print(moved) [[ 0 4 6] [ 0 3 5] [ 0 9 0] [ 7 8 11]] >>> print(out) [[ 0 0 3] [ 0 0 0] [ 0 0 0] [10 0 12]] Using grid routing functionality with masked flow direction: >>> directions.set_data( ... numpy.ma.array( ... [['NE', 'N', 'E'], ... ['SE', 'E', 'S'], ... ['N', 'N', 'W'], ... ['SW', 'E', 'NW']], ... mask=[[1, 0, 0], ... [1, 0, 0], ... [1, 1, 0], ... [0, 0, 0]] ... ) ... ) >>> grid.flow_direction = directions >>> moved, out = grid.route(values) >>> print(moved) [[-- 0 6] [-- 2 5] [-- -- 0] [0 0 11]] >>> print(out) [[-- 0 3] [-- 0 0] [-- -- 9] [10 0 12]] Using grid routing functionality with a wrap-around domain: >>> grid = LatLonGrid.from_extent_and_resolution( ... latitude_extent=(-90, 90), ... latitude_resolution=45, ... longitude_extent=(-180, 180), ... longitude_resolution=120 ... ) >>> values = numpy.arange(12).reshape(4, 3) + 1 >>> print(values) [[ 1 2 3] [ 4 5 6] [ 7 8 9] [10 11 12]] >>> directions = grid.to_field() >>> directions.set_data(numpy.array([['NE', 'N', 'E'], ... ['SE', 'E', 'S'], ... ['N', 'N', 'W'], ... ['SW', 'E', 'NW']])) >>> grid.flow_direction = directions >>> moved, out = grid.route(values) >>> print(moved) [[ 3 16 6] [ 0 3 5] [ 0 9 10] [ 7 8 11]] >>> print(out) [[0 0 0] [0 0 0] [0 0 0] [0 0 0]] Using grid routing functionality on a whole cartesian domain: >>> grid = BritishNationalGrid.from_extent_and_resolution( ... projection_y_coordinate_extent=(0, 1300000), ... projection_y_coordinate_resolution=325000, ... projection_x_coordinate_extent=(0, 700000), ... projection_x_coordinate_resolution=700000/3 ... ) >>> values = numpy.arange(12).reshape(4, 3) + 1 >>> directions = grid.to_field() >>> directions.set_data(numpy.array([['NE', 'N', 'E'], ... ['SE', 'E', 'S'], ... ['N', 'N', 'W'], ... ['SW', 'E', 'NW']])) >>> grid.flow_direction = directions >>> moved, out = grid.route(values) >>> print(moved) [[ 0 4 6] [ 0 3 5] [ 0 9 0] [ 7 8 11]] >>> print(out) [[ 0 0 3] [ 0 0 0] [ 0 0 0] [10 0 12]] """ # check whether method can be used if self.flow_direction is None: raise RuntimeError("method 'route' requires setting " "property 'flow_direction'") # check that values_to_route has the same shape as flow_direction if not self.flow_direction.shape[:-1] == values_to_route.shape: raise RuntimeError("shape mismatch between 'values_to_route' " "and 'flow_direction' in 'route' method") # initialise routed and out arrays depending on mask/no-mask if np.ma.is_masked(self.flow_direction): mask = self.flow_direction.mask[..., 0] values_routed = np.ma.array( np.zeros(values_to_route.shape, values_to_route.dtype), mask=mask ) values_out = np.ma.array( np.zeros(values_to_route.shape, values_to_route.dtype), mask=mask ) else: mask = None values_routed = np.zeros(values_to_route.shape, values_to_route.dtype) values_out = np.zeros(values_to_route.shape, values_to_route.dtype) # if no mask, keep as is, if not, take logical negation of it mask = None if mask is None else ~mask # collect the values routed towards outside the domain out_mask = self._routing_out_mask if np.ma.is_masked(self.flow_direction): values_out[out_mask & mask] = values_to_route[out_mask & mask] else: values_out[out_mask] = values_to_route[out_mask] # perform the routing using the routing mask # Y-wards movement for j in [-1, 0, 1]: # X-wards movement for i in [-1, 0, 1]: routing_mask = self._routing_masks[(j, i)] values_routed[mask] += np.roll( values_to_route * routing_mask, shift=(j, i), axis=(-2, -1) )[mask] return values_routed, values_out @property def cell_area(self): """The horizontal area for the grid cells of the `Grid` in square metres given as a `cf.Field` and returned as a `numpy.ndarray`. :Parameters: areas: `cf.Field` The field containing the horizontal grid cell area. The shape of the data array must be the same as the `Grid`. The field data must contain surface area values in square metres. :Returns: `numpy.ndarray` The array containing the horizontal grid cell area values in square metres. If not set previously, computed automatically. **Examples** >>> grid = LatLonGrid.from_extent_and_resolution( ... latitude_extent=(51, 55), ... latitude_resolution=1, ... longitude_extent=(-2, 1), ... longitude_resolution=1 ... ) >>> print(grid.cell_area) [[7.69725703e+09 7.69725703e+09 7.69725703e+09] [7.52719193e+09 7.52719193e+09 7.52719193e+09] [7.35483450e+09 7.35483450e+09 7.35483450e+09] [7.18023725e+09 7.18023725e+09 7.18023725e+09]] >>> print(grid) # doctest: +ELLIPSIS LatLonGrid( shape {Y, X}: (4, 3) Y, latitude (4,): [51.5, ..., 54.5] degrees_north X, longitude (3,): [-1.5, -0.5, 0.5] degrees_east Y_bounds (4, 2): [[51.0, ..., 55.0]] degrees_north X_bounds (3, 2): [[-2.0, ..., 1.0]] degrees_east cell_area (4, 3): [[7697257030.0..., ..., 7180237253.9...]] m2 ) >>> import numpy >>> areas = grid.to_field() >>> areas.set_data(numpy.array([[7.70e+09, 7.70e+09, 7.70e+09], ... [7.53e+09, 7.53e+09, 7.53e+09], ... [7.35e+09, 7.35e+09, 7.35e+09], ... [7.18e+09, 7.18e+09, 7.18e+09]])) >>> areas.units = 'm2' >>> grid.cell_area = areas >>> print(grid.cell_area) [[7.70e+09 7.70e+09 7.70e+09] [7.53e+09 7.53e+09 7.53e+09] [7.35e+09 7.35e+09 7.35e+09] [7.18e+09 7.18e+09 7.18e+09]] """ if self._cell_area is None: self._cell_area = self._compute_cell_area() return self._cell_area @cell_area.setter def cell_area(self, areas): error_dim = RuntimeError( f"cell_area shape incompatible with {self.__class__.__name__}" ) error_units = ValueError( "cell_area units are missing or not in square metres" ) # check type if not isinstance(areas, cf.Field): raise TypeError("cell_area not a cf.Field") # store given field for config file self._cell_area_field = areas # drop potential size-1 Z axis since areas is # only relevant horizontally if areas.domain_axis(self.vertical_axis, key=True, default=False): areas.squeeze(self.vertical_axis, inplace=True) # check that mask and spacedomain are compatible grid = self.to_horizontal_grid() try: areas = grid.subset_and_compare(areas) except RuntimeError: raise error_dim # check area units if not (areas.data.has_units() and cfunits.Units('m2').equals(areas.Units)): raise error_units # get field's data array areas = areas.array self._cell_area = areas def _compute_cell_area(self): # make use of cf-python to retrieve ESMF objects operator = self._f.regrids( self._f, 'conservative', return_operator=True ) # retrieve ESMF source (arbitrarily chosen) field esmf_field = operator.regrid.srcfield # let ESMF compute the cell area esmf_field.get_area() # retrieve the values and scale them from unit sphere to Earth area_unit_sphere = esmf_field.data.T area = area_unit_sphere * self._earth_radius_m ** 2 return area @staticmethod def _check_dimension_limits(dimension, name, limits): """**Examples:** >>> import numpy >>> Grid._check_dimension_limits( # scalar ... numpy.array(-1.), 'test', (-2, 2)) >>> Grid._check_dimension_limits( # no wrap around ... numpy.array([-1., 0., 1., 2.]), 'test', (-2, 2)) >>> Grid._check_dimension_limits( # wrap around ... numpy.array([0.5, 1.5, -1.5]), 'test', (-2, 2)) >>> Grid._check_dimension_limits( # exceed lower limit ... numpy.array([-3., -2., -1.]), 'test', (-2, 2)) Traceback (most recent call last): ... RuntimeError: test dimension beyond limits [-2, 2] >>> Grid._check_dimension_limits( # exceed upper limit ... numpy.array([1., 2., 3.]), 'test', (-2, 2)) Traceback (most recent call last): ... RuntimeError: test dimension beyond limits [-2, 2] >>> Grid._check_dimension_limits( # wrapping around repetition ... numpy.array([0., 1., 2., -1., 0.]), 'test', (-2, 2)) Traceback (most recent call last): ... RuntimeError: duplicates in test dimension: [0.] """ # check for values outside of limits if limits is not None: if np.amin(dimension) < limits[0] or np.amax(dimension) > limits[1]: raise RuntimeError(f"{name} dimension beyond limits " f"[{limits[0]}, {limits[1]}]") # check for duplicated coordinates, meaning domain overlap # for cyclic dimensions, but should not happen anyway so check # for non-cyclic dimensions too if dimension.ndim > 0: sort_dim = np.sort(dimension) dup_dim = sort_dim[1:][sort_dim[1:] == sort_dim[:-1]] if dup_dim.size > 0: raise RuntimeError(f"duplicates in {name} dimension: {dup_dim}") @staticmethod def _check_dimension_direction(dimension, name, limits, wrap_around): """**Examples:** >>> import numpy >>> Grid._check_dimension_direction( # scalar ... numpy.array(1.), 'test', (-2, 2), False) >>> Grid._check_dimension_direction( # not cyclic, no wrap around ... numpy.array([0., 1., 2.]), 'test', (-2, 2), False) >>> Grid._check_dimension_direction( # cyclic, no wrap around ... numpy.array([0., 1., 2.]), 'test', (-2, 2), True) >>> Grid._check_dimension_direction( # cyclic, wrap around, sign case 1 ... numpy.array([-1., 0., 2.]), 'test', (-2, 2), True) >>> Grid._check_dimension_direction( # cyclic, wrap around, sign case 2 ... numpy.array([-1., 0., -2.]), 'test', (-2, 2), True) >>> Grid._check_dimension_direction( # cyclic, wrap around, end ... numpy.array([0., 2., -2.]), 'test', (-3, 3), True) >>> Grid._check_dimension_direction( # cyclic, wrap around, start ... numpy.array([2., -2., 0.]), 'test', (-3, 3), True) >>> Grid._check_dimension_direction( # negative direction ... numpy.array([2., 1., 0.]), 'test', (-2, 2), True) Traceback (most recent call last): ... RuntimeError: test dimension not directed positively """ error = RuntimeError(f"{name} dimension not directed positively") if dimension.ndim > 0: space_diff = np.diff(dimension) if wrap_around: if np.any(space_diff < 0): # add one full rotation to first negative difference # to assume it is wrapping around (since positive # direction is required, and cross-over can happen # at most once without domain wrapping on itself) neg = space_diff[space_diff < 0] neg[0] += limits[1] - limits[0] space_diff[space_diff < 0] = neg else: # it is a scalar, set difference to one to pass next check space_diff = 1 if not np.all(space_diff > 0): # if not all positive, at least one space gap is in # negative direction raise error @staticmethod def _check_dimension_regularity(dimension, name, limits, wrap_around): """**Examples:** >>> import numpy >>> Grid._check_dimension_regularity( # scalar ... numpy.array(1.), 'test', (-2, 2), False) >>> Grid._check_dimension_regularity( # not cyclic, no wrap around ... numpy.array([0., 1., 2.]), 'test', (-2, 2), False) >>> Grid._check_dimension_regularity( # cyclic, no wrap around ... numpy.array([0., 1., 2.]), 'test', (-2, 2), True) >>> Grid._check_dimension_regularity( # cyclic, wrap around, sign case 1 ... numpy.array([-2., 0., 2.]), 'test', (-2, 2), True) >>> Grid._check_dimension_regularity( # cyclic, wrap around, sign case 2 ... numpy.array([-2., 0., -2.]), 'test', (-2, 2), True) >>> Grid._check_dimension_regularity( # cyclic, wrap around, end ... numpy.array([.9, 1.9, -1.1]), 'test', (-2, 2), True) >>> Grid._check_dimension_regularity( # cyclic, wrap around, start ... numpy.array([1.9, -1.1, -0.1]), 'test', (-2, 2), True) >>> Grid._check_dimension_regularity( # irregular, not cyclic ... numpy.array([0., .9, 1.]), 'test', (-2, 2), False) Traceback (most recent call last): ... RuntimeError: test space gap not constant across region >>> Grid._check_dimension_regularity( # irregular, cyclic ... numpy.array([1., 1.9, -1]), 'test', (-2, 2), True) Traceback (most recent call last): ... RuntimeError: test space gap not constant across region """ if dimension.ndim > 0: space_diff = np.diff(dimension) if wrap_around: if np.any(space_diff < 0): # add one full rotation to first negative difference # to assume it is wrapping around (since positive # direction is required, and cross-over can happen # at most once without domain wrapping on itself) neg = space_diff[space_diff < 0] neg[0] += limits[1] - limits[0] space_diff[space_diff < 0] = neg else: # it is a scalar, set difference to one to pass next check space_diff = 1 if not np.isclose(np.amin(space_diff), np.amax(space_diff), rtol(), atol()): raise RuntimeError( f"{name} space gap not constant across region" ) @staticmethod def _check_dimension_bounds_limits(bounds, name, limits): """**Examples:** >>> import numpy >>> Grid._check_dimension_bounds_limits( # 1D ... numpy.array([0., -1.]), 'test', (-2, 2)) >>> Grid._check_dimension_bounds_limits( # 2D, edging upper limit ... numpy.array([[0., 1.], [1., 2.], [2., 3.]]), 'test', (-3, 3)) >>> Grid._check_dimension_bounds_limits( # 2D, edging lower limit ... numpy.array([[-3., -2.], [-2., -1.], [-1., 0.]]), 'test', (-3, 3)) >>> Grid._check_dimension_bounds_limits( # 1D, beyond upper limit ... numpy.array([0., 3.]), 'test', (-2, 2)) Traceback (most recent call last): ... RuntimeError: test dimension bounds beyond limits [-2, 2] >>> Grid._check_dimension_bounds_limits( # 2D, beyond upper limit ... numpy.array([[0., 1.], [1., 2.], [2., 3.]]), 'test', (-2, 2)) Traceback (most recent call last): ... RuntimeError: test dimension bounds beyond limits [-2, 2] >>> Grid._check_dimension_bounds_limits( # 2D, beyond lower limit ... numpy.array([[-3., -2.], [-2., -1.], [-1., 0.]]), 'test', (-2, 2)) Traceback (most recent call last): ... RuntimeError: test dimension bounds beyond limits [-2, 2] """ if limits is not None: if np.amin(bounds) < limits[0] or np.amax(bounds) > limits[1]: raise RuntimeError(f"{name} dimension bounds beyond limits " f"[{limits[0]}, {limits[1]}]") @staticmethod def _check_dimension_bounds_direction(bounds, name, limits, wrap_around): """ TODO: Last example should raise error because last pair of bounds is either in the negative direction or a second wrap around, but because the algorithm allows for up to two negative differences to cover for a pair of bounds across the limits, the negative value for this last pair is caught in the assumption it is a wrap around, while the first wrap around only generated one negative difference, so the second negative difference was tolerated erroneously. This is likely to be really an edge case, so it is kept as is for now. Plus, it is caught as an error in `_check_dimension_bounds_regularity`. **Examples:** >>> import numpy >>> Grid._check_dimension_bounds_direction( # 1D, not cyclic ... numpy.array([0., 1.]), 'test', (-2, 2), False) >>> Grid._check_dimension_bounds_direction( # 1D, cyclic, no wrap around ... numpy.array([0., 1.]), 'test', (-2, 2), True) >>> Grid._check_dimension_bounds_direction( # 1D, cyclic, wrap around ... numpy.array([0., -1.]), 'test', (-2, 2), True) >>> Grid._check_dimension_bounds_direction( # 2D, not cyclic ... numpy.array([[-1., 0.], [0., 1.], [1., 2.]]), 'test', (-3, 3), False) >>> Grid._check_dimension_bounds_direction( # 2D, cyclic ... numpy.array([[-1., 0.], [0., 1.], [1., 2.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_direction( # 2D, cyclic, wrap around, bound across ... numpy.array([[1.5, 2.5], [2.5, -2.5], [-2.5, -1.5]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_direction( # 2D, cyclic, wrap around, bound edging, sign case 1 ... numpy.array([[1., 2.], [2., 3.], [3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_direction( # 2D, cyclic, wrap around, bound edging, sign case 2 ... numpy.array([[1., 2.], [2., 3.], [-3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_direction( # 2D, cyclic, wrap around, bound edging, sign case 3 ... numpy.array([[1., 2.], [2., -3.], [3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_direction( # 2D, cyclic, wrap around, bound edging, sign case 4 ... numpy.array([[1., 2.], [2., -3.], [-3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_direction( # negative direction ... numpy.array([2., 1.]), 'test', (-2, 2), False) Traceback (most recent call last): ... RuntimeError: test dimension bounds not directed positively >>> Grid._check_dimension_bounds_direction( # not cyclic but wrap around ... numpy.array([0., -1.]), 'test', (-2, 2), False) Traceback (most recent call last): ... RuntimeError: test dimension bounds not directed positively >>> Grid._check_dimension_bounds_direction( # negative direction, not cyclic ... numpy.array([[3., 2.], [2., 1.], [1., 0.]]), 'test', (-3, 3), False) Traceback (most recent call last): ... RuntimeError: test dimension bounds not directed positively >>> Grid._check_dimension_bounds_direction( # negative direction, cyclic ... numpy.array([[3., 2.], [2., 1.], [1., 0.]]), 'test', (-3, 3), True) Traceback (most recent call last): ... RuntimeError: test dimension bounds not directed positively >>> Grid._check_dimension_bounds_direction( # wrap around, negative after ... numpy.array([[2., 3.], [-3., -2.], [-1., -2.]]), 'test', (-3, 3), True) Traceback (most recent call last): ... RuntimeError: test dimension bounds not directed positively >>> Grid._check_dimension_bounds_direction( # [!] current bug ... numpy.array([[1., 2.], [-2., -1.], [-1., -2]]), 'test', (-2, 2), True) """ # replace lower limit by upper limit to acknowledge it is same # location (e.g. -180degE same as +180degE, so replace -180degE # by +180degE) bnds = deepcopy(bounds) if wrap_around: bnds[np.isclose(bnds, limits[0], rtol(), atol())] = limits[1] error = RuntimeError(f"{name} dimension bounds not directed positively") if bnds.ndim > 0: space_diff = np.diff(bnds, axis=0) if wrap_around: if np.any(space_diff <= 0): # add one full rotation to first and second negative # differences to assume it is wrapping around (since # positive direction is required, and cross-over # can happen at most once without domain wrapping on # itself) neg = space_diff[space_diff <= 0] neg[0:2] += limits[1] - limits[0] space_diff[space_diff <= 0] = neg else: # it is a scalar, set difference to one to pass next check space_diff = 1 if not np.all(space_diff > 0): raise error if bnds.ndim > 1: space_diff = np.diff(bnds, axis=1) if wrap_around: if np.any(space_diff <= 0): # add one full rotation to first negative difference # to assume it is wrapping around (since positive # direction is required, and cross-over can happen # at most once without domain wrapping on itself) neg = space_diff[space_diff <= 0] neg[0] += limits[1] - limits[0] space_diff[space_diff <= 0] = neg else: # it is a scalar, set difference to one to pass next check space_diff = 1 if not np.all(space_diff > 0): raise error @staticmethod def _check_dimension_bounds_regularity(bounds, name, limits, wrap_around): """**Examples:** >>> import numpy >>> Grid._check_dimension_bounds_regularity( # 1D, not cyclic ... numpy.array([0., 1.]), 'test', (-2, 2), False) >>> Grid._check_dimension_bounds_regularity( # 1D, cyclic, no wrap around ... numpy.array([0., 1.]), 'test', (-2, 2), True) >>> Grid._check_dimension_bounds_regularity( # 2D, cyclic, wrap around ... numpy.array([0., -1.]), 'test', (-2, 2), True) >>> Grid._check_dimension_bounds_regularity( # 2D, not cyclic ... numpy.array([[-1., 0.], [0., 1.], [1., 2.]]), 'test', (-3, 3), False) >>> Grid._check_dimension_bounds_regularity( # 2D, cyclic ... numpy.array([[-1., 0.], [0., 1.], [1., 2.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_regularity( # 2D, cyclic, wrap around, bound across ... numpy.array([[1.5, 2.5], [2.5, -2.5], [-2.5, -1.5]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_regularity( # 2D, cyclic, wrap around, bound edging, sign case 1 ... numpy.array([[1., 2.], [2., 3.], [3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_regularity( # 2D, cyclic, wrap around, bound edging, sign case 2 ... numpy.array([[1., 2.], [2., 3.], [-3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_regularity( # 2D, cyclic, wrap around, bound edging, sign case 3 ... numpy.array([[1., 2.], [2., -3.], [3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_regularity( # 2D, cyclic, wrap around, bound edging, sign case 4 ... numpy.array([[1., 2.], [2., -3.], [-3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_regularity( # irregular (not cyclic) ... numpy.array([[0., .9], [.9, 2.], [2., 3.]]), 'test', (0, 3), False) Traceback (most recent call last): ... RuntimeError: test bounds space gap not constant across region >>> Grid._check_dimension_bounds_regularity( # irregular (cyclic) ... numpy.array([[0., .9], [.9, 2.], [2., 3.]]), 'test', (-2, 2), True) Traceback (most recent call last): ... RuntimeError: test bounds space gap not constant across region >>> Grid._check_dimension_bounds_regularity( # not cyclic, no wrap around ... numpy.array([[1., 2.], [2., -1.], [-1., 0.]]), 'test', (-2, 2), False) Traceback (most recent call last): ... RuntimeError: test bounds space gap not constant across region >>> Grid._check_dimension_bounds_regularity( # gap ... numpy.array([[-1., 0.], [0., 1.], [2., 3.]]), 'test', (-3, 3), False) Traceback (most recent call last): ... RuntimeError: test bounds space gap not constant across region >>> Grid._check_dimension_bounds_regularity( # inverted direction ... numpy.array([[1., 2.], [-2., -1.], [-1., -2]]), 'test', (-2, 2), True) Traceback (most recent call last): ... RuntimeError: test bounds space gap not constant across region """ rtol_ = rtol() atol_ = atol() # replace lower limit by upper limit to acknowledge it is same # location (e.g. -180degE same as +180degE, so replace -180degE # by +180degE) bnds = deepcopy(bounds) if wrap_around: bnds[np.isclose(bnds, limits[0], rtol_, atol_)] = limits[1] error = RuntimeError(f"{name} bounds space gap not constant across region") if bnds.ndim > 0: space_diff = np.diff(bnds, axis=0) if wrap_around: if np.any(space_diff < 0): # add one full rotation to first and second negative # differences to assume it is wrapping around (since # positive direction is required, and cross-over # can happen at most once without domain wrapping on # itself) neg = space_diff[space_diff < 0] neg[0:2] += limits[1] - limits[0] space_diff[space_diff < 0] = neg else: space_diff = 0 if not np.isclose(np.amin(space_diff), np.amax(space_diff), rtol_, atol_): raise error if bnds.ndim > 1: space_diff = np.diff(bnds, axis=1) if wrap_around: if np.any(space_diff < 0): # add one full rotation to first negative difference # to assume it is wrapping around (since positive # direction is required, and cross-over can happen # at most once without domain wrapping on itself) neg = space_diff[space_diff < 0] neg[0] += limits[1] - limits[0] space_diff[space_diff < 0] = neg else: space_diff = 0 if not np.isclose(np.amin(space_diff), np.amax(space_diff), rtol_, atol_): raise error @staticmethod def _check_dimension_bounds_contiguity(bounds, name, limits, wrap_around): """**Examples:** >>> import numpy >>> Grid._check_dimension_bounds_contiguity( # 1D, not cyclic ... numpy.array([0., 1.]), 'test', (-2, 2), False) >>> Grid._check_dimension_bounds_contiguity( # 1D, cyclic, no wrap around ... numpy.array([0., 1.]), 'test', (-2, 2), True) >>> Grid._check_dimension_bounds_contiguity( # 2D, cyclic, wrap around ... numpy.array([0., -1.]), 'test', (-2, 2), True) >>> Grid._check_dimension_bounds_contiguity( # 2D, not cyclic ... numpy.array([[-1., 0.], [0., 1.], [1., 2.]]), 'test', (-3, 3), False) >>> Grid._check_dimension_bounds_contiguity( # 2D, cyclic ... numpy.array([[-1., 0.], [0., 1.], [1., 2.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_contiguity( # 2D, cyclic, wrap around, bound across ... numpy.array([[1.5, 2.5], [2.5, -2.5], [-2.5, -1.5]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_contiguity( # 2D, cyclic, wrap around, bound edging, sign case 1 ... numpy.array([[1., 2.], [2., 3.], [3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_contiguity( # 2D, cyclic, wrap around, bound edging, sign case 2 ... numpy.array([[1., 2.], [2., 3.], [-3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_contiguity( # 2D, cyclic, wrap around, bound edging, sign case 3 ... numpy.array([[1., 2.], [2., -3.], [3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_contiguity( # 2D, cyclic, wrap around, bound edging, sign case 4 ... numpy.array([[1., 2.], [2., -3.], [-3., -2.], [-2., -1.]]), 'test', (-3, 3), True) >>> Grid._check_dimension_bounds_contiguity( # gaps (not cyclic) ... numpy.array([[0.0, 0.9], [1.0, 1.9], [2.0, 2.9]]), 'test', (-3, 3), False) Traceback (most recent call last): ... RuntimeError: test bounds not contiguous across region >>> Grid._check_dimension_bounds_contiguity( # gaps (cyclic) ... numpy.array([[0.0, 0.9], [1.0, 1.9], [-2.0, -1.1]]), 'test', (-2, 2), False) Traceback (most recent call last): ... RuntimeError: test bounds not contiguous across region """ rtol_ = rtol() atol_ = atol() # replace lower limit by upper limit to acknowledge it is same # location (e.g. -180degE same as +180degE, so replace -180degE # by +180degE) bnds = deepcopy(bounds) if wrap_around: bnds[np.isclose(bnds, limits[0], rtol_, atol_)] = limits[1] # compare previous upper bound to next lower bound prev_to_next = (bnds[1:, 0] - bnds[:-1, 1] if bnds.ndim > 1 else 0) if not np.allclose(prev_to_next, 0, rtol_, atol_): raise RuntimeError(f"{name} bounds not contiguous across region") @staticmethod def _check_dimension_in_bounds(dimension, bounds, name, limits, wrap_around): """**Examples:** >>> import numpy >>> Grid._check_dimension_in_bounds( # 1 coord, not cyclic ... numpy.array(.5), numpy.array([0., 1.]), 'test', (0, 2), False) >>> Grid._check_dimension_in_bounds( # 1 coord, cyclic, no wrap around ... numpy.array(.5), numpy.array([0., 1.]), 'test', (0, 2), True) >>> Grid._check_dimension_in_bounds( # x coords, not cyclic ... numpy.array([0.5, 1.5, 2.5]), ... numpy.array([[0., 1.], [1., 2.], [2., 3.]]), ... 'test', (0, 3), False) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, no wrap around ... numpy.array([0.5, 1.5, 2.5]), ... numpy.array([[0., 1.], [1., 2.], [2., 3.]]), ... 'test', (0, 3), True) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, wrap around ... numpy.array([0.5, 1.5, -1.5]), ... numpy.array([[0., 1.], [1., 2.], [2., -1.]]), ... 'test', (-2, 2), True) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, wrap around, bound across, sign case 1 ... numpy.array([2., 3., -2.]), ... numpy.array([[1.5, 2.5], [2.5, -2.5], [-2.5, -1.5]]), ... 'test', (-3, 3), True) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, wrap around, bound across, sign case 2 ... numpy.array([2., -3., -2.]), ... numpy.array([[1.5, 2.5], [2.5, -2.5], [-2.5, -1.5]]), ... 'test', (-3, 3), True) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, wrap around, bound edging, sign case 1 ... numpy.array([1.5, 2.5, -2.5, -1.5]), ... numpy.array([[1., 2.], [2., 3.], [3., -2.], [-2., -1.]]), ... 'test', (-3, 3), True) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, wrap around, bound edging, sign case 2 ... numpy.array([1.5, 2.5, -2.5, -1.5]), ... numpy.array([[1., 2.], [2., 3.], [-3., -2.], [-2., -1.]]), ... 'test', (-3, 3), True) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, wrap around, bound edging, sign case 3 ... numpy.array([1.5, 2.5, -2.5, -1.5]), ... numpy.array([[1., 2.], [2., -3.], [3., -2.], [-2., -1.]]), ... 'test', (-3, 3), True) >>> Grid._check_dimension_in_bounds( # x coords, cyclic, wrap around, bound edging, sign case 4 ... numpy.array([1.5, 2.5, -2.5, -1.5]), ... numpy.array([[1., 2.], [2., -3.], [-3., -2.], [-2., -1.]]), ... 'test', (-3, 3), True) >>> Grid._check_dimension_in_bounds( # last coord not in its bounds, not cyclic ... numpy.array([0.5, 1.5, 1.9]), ... numpy.array([[0., 1.], [1., 2.], [2., 3.]]), ... 'test', (0, 3), False) Traceback (most recent call last): ... RuntimeError: test coordinates not all in their bounds >>> Grid._check_dimension_in_bounds( # last coord not in its bounds, cyclic, wrap around ... numpy.array([2., -2., -2.]), ... numpy.array([[1.5, 2.5], [2.5, -2.5], [-2.5, -1.5]]), ... 'test', (-3, 3), True) Traceback (most recent call last): ... RuntimeError: test coordinates not all in their bounds """ # replace lower limit by upper limit to acknowledge it is same # location (e.g. -180degE same as +180degE, so replace -180degE # by +180degE) bnds = deepcopy(bounds) if wrap_around: bnds[np.isclose(bnds, limits[0], rtol(), atol())] = limits[1] # check if coordinates inside their bounds if dimension.ndim > 0: inside = (bnds[:, 0] <= dimension) & (dimension <= bnds[:, 1]) if wrap_around: if np.sum(~inside) >= 1: not_in_dim = dimension[~inside] not_in_bnds = bnds[~inside] not_in = inside[~inside] # add one full rotation to upper bound in first # inequality to assume it is wrapping around if ((not_in_bnds[0, 0] <= not_in_dim[0]) & (not_in_dim[0] > not_in_bnds[0, 1])): not_in[0] = ((not_in_bnds[0, 0] <= not_in_dim[0]) & (not_in_dim[0] <= (not_in_bnds[0, 1] + limits[1] - limits[0]))) # remove one full rotation to lower bound in first # inequality to assume it is wrapping around elif ((not_in_bnds[0, 0] > not_in_dim[0]) & (not_in_dim[0] <= not_in_bnds[0, 1])): not_in[0] = ( ((not_in_bnds[0, 0] - limits[1] + limits[0]) <= not_in_dim[0]) & (not_in_dim[0] <= not_in_bnds[0, 1]) ) inside[~inside] = not_in else: inside = (bnds[0] <= dimension) & (dimension <= bnds[1]) if wrap_around: if not inside: # add one full rotation to upper bound in first # inequality to assume it is wrapping around if (bnds[0] <= dimension) & (dimension > bnds[1]): inside = ( (bnds[0] <= dimension) & (dimension <= (bnds[1] + limits[1] - limits[0])) ) # remove one full rotation to lower bound in first # inequality to assume it is wrapping around elif (bnds[0] > dimension) & (dimension <= bnds[1]): inside = ( ((bnds[0] - limits[1] + limits[0]) <= dimension) & (dimension <= bnds[1]) ) if not np.all(inside): raise RuntimeError(f"{name} coordinates not all in their bounds") def _set_space(self, dimension, dimension_bounds, name, units, axis, limits, wrap_around): """**Examples:** >>> import numpy >>> Grid()._set_space([[0.5]], [0., 1.], 'test', '1', 'I', (0, 2), False) >>> Grid()._set_space([[0, 1], [1, 2]], [[0., 1.], [1., 2.], [2., 3.]], ... 'test', '1', 'I', (-3, 3), True) Traceback (most recent call last): ... RuntimeError: Grid test not convertible to 1D-array >>> Grid()._set_space([0.5, 1.5, 2.5], [[0., 1.], [1., 2.], [2., 3.]], ... 'test', '1', 'I', (-3, 3), True) >>> Grid()._set_space([0.5, 1.5], [[0., 1.], [1., 2.], [2., 3.]], ... 'test', '1', 'I', (-3, 3), True) Traceback (most recent call last): ... RuntimeError: Grid test bounds not compatible in size with test coordinates """ # checks on dimension coordinates if not isinstance(dimension, np.ndarray): dimension = np.asarray(dimension) dimension = np.squeeze(dimension) if dimension.ndim > 1: raise RuntimeError( f"{self.__class__.__name__} {name} not convertible to 1D-array" ) self._check_dimension_limits(dimension, name, limits) self._check_dimension_direction(dimension, name, limits, wrap_around) self._check_dimension_regularity(dimension, name, limits, wrap_around) # checks on dimension coordinate bounds if not isinstance(dimension_bounds, np.ndarray): dimension_bounds = np.asarray(dimension_bounds) dimension_bounds = np.squeeze(dimension_bounds) if dimension_bounds.shape != (*dimension.shape, 2): raise RuntimeError( f"{self.__class__.__name__} {name} bounds not compatible " f"in size with {name} coordinates" ) self._check_dimension_bounds_limits(dimension_bounds, name, limits) self._check_dimension_bounds_direction( dimension_bounds, name, limits, wrap_around ) self._check_dimension_bounds_regularity( dimension_bounds, name, limits, wrap_around ) self._check_dimension_bounds_contiguity( dimension_bounds, name, limits, wrap_around ) # check coordinates in their bounds self._check_dimension_in_bounds( dimension, dimension_bounds, name, limits, wrap_around ) # deal with special case of dimension with only one-element # due to squeeze, dimension is scalar array, dimension_bounds is 1D # cf-python will want 1D dimension coordinates, and 2D # dimension coordinate bounds, respectively if dimension.ndim == 0: dimension = np.array([dimension]) dimension_bounds = np.array([dimension_bounds]) # set construct axis_ = self._f.set_construct(cf.DomainAxis(dimension.size)) self._f.set_construct( cf.DimensionCoordinate( properties={ 'standard_name': name, 'units': units, 'axis': axis }, data=cf.Data(dimension), bounds=cf.Bounds(data=cf.Data(dimension_bounds))), axes=axis_ ) def _set_dummy_data(self): self._f.set_data(cf.Data(np.zeros(self.shape, dtype_float())), axes=self.axes) @classmethod def _get_grid_from_extent_and_resolution( cls, y_extent, x_extent, y_resolution, x_resolution, yx_location, # z_extent=None, z_resolution=None, z_location=None ): # infer grid span in relation to coordinate from location if yx_location in cls._YX_loc_map['centre']: x_span, y_span = [[-0.5, 0.5]], [[-0.5, 0.5]] elif yx_location in cls._YX_loc_map['lower_left']: x_span, y_span = [[0, 1]], [[0, 1]] elif yx_location in cls._YX_loc_map['upper_left']: x_span, y_span = [[0, 1]], [[-1, 0]] elif yx_location in cls._YX_loc_map['lower_right']: x_span, y_span = [[-1, 0]], [[0, 1]] elif yx_location in cls._YX_loc_map['upper_right']: x_span, y_span = [[-1, 0]], [[-1, 0]] else: raise ValueError( f"{cls.__name__} {cls._Y_name}-{cls._X_name} location " f"'{yx_location}' not supported" ) # determine Y and X coordinates and their bounds y, y_bounds = cls._get_dimension_from_extent_and_resolution( y_extent, y_resolution, y_span, cls._Y_name, cls._Y_limits, cls._Y_wrap_around ) x, x_bounds = cls._get_dimension_from_extent_and_resolution( x_extent, x_resolution, x_span, cls._X_name, cls._X_limits, cls._X_wrap_around ) # # infer Z span in relation to coordinate from location # if z_extent is not None and z_resolution is not None: # if z_location in cls._Z_loc_map['centre'] or z_location is None: # z_span = [[-0.5, 0.5]] # elif z_location in cls._Z_loc_map['bottom']: # z_span = [[0, 1]] # elif z_location in cls._Z_loc_map['top']: # z_span = [[-1, 0]] # else: # raise ValueError( # f"{cls.__name__} {cls._Z_name} location '{z_location}' " # f"not supported" # ) # # # determine latitude and longitude coordinates and their bounds # z, z_bounds = cls._get_dimension_from_extent_and_resolution( # z_extent, z_resolution, z_span, cls._Z_name, # cls._Z_limits, cls._Z_wrap_around # ) # else: # z = None # z_bounds = None return { cls._Y_name: y, cls._X_name: x, # cls._Z_name: z, cls._Y_name + '_bounds': y_bounds, cls._X_name + '_bounds': x_bounds, # cls._Z_name + '_bounds': z_bounds } @staticmethod def _get_dimension_from_extent_and_resolution(extent, resolution, span, name, limits, wrap_around): # check sign of resolution if resolution <= 0: raise ValueError(f"{name} resolution must be positive") # check extent dim_start, dim_end = extent if limits is not None: if (dim_start < limits[0]) or (dim_start > limits[1]): raise ValueError( f"{name} extent start beyond limits " f"[{limits[0]}, {limits[1]}]" ) if (dim_end < limits[0]) or (dim_end > limits[1]): raise ValueError( f"{name} extent end beyond limits " f"[{limits[0]}, {limits[1]}]" ) if wrap_around: if dim_end == dim_start: dim_end += limits[1] - limits[0] if dim_end < dim_start: dim_end += limits[1] - limits[0] else: if dim_start == dim_end: raise ValueError(f"{name} extent empty") if dim_end < dim_start: raise ValueError(f"{name} extent oriented negatively") # check compatibility between extent and resolution # (i.e. need to produce a whole number of grid cells) rtol_ = rtol() atol_ = atol() if np.isclose((dim_end - dim_start) % resolution, 0, rtol_, atol_): dim_size = (dim_end - dim_start) // resolution elif np.isclose((dim_end - dim_start) % resolution, resolution, rtol_, atol_): dim_size = ((dim_end - dim_start) // resolution) + 1 else: raise RuntimeError( f"{name} extent and resolution do not define a whole number " f"of grid cells" ) # determine dimension coordinates dim = ( (np.arange(dim_size) + 0.5 - np.mean(span)) * resolution + dim_start ) # determine dimension coordinate bounds dim_bounds = ( dim.reshape((dim.size, -1)) + np.array(span) * resolution ) # deal with wrap around values if wrap_around: dim[dim > limits[1]] -= limits[1] - limits[0] dim_bounds[dim_bounds > limits[1]] -= limits[1] - limits[0] # round the arrays and return them decr_ = decr() return ( np.around(dim, decimals=decr_).tolist(), np.around(dim_bounds, decimals=decr_).tolist() ) def _get_dimension_resolution(self, axis): # return dimension extent (i.e. (start, end) for dimension) if getattr(self, axis) is None: return None else: # try to use _resolution attribute # (available if instantiated via method from_extent_and_resolution) if hasattr(self, '_resolution'): return self._resolution[axis] # infer from first and second coordinates along dimension else: dim = getattr(self, axis).array dim_bnds = getattr(self, f'{axis}_bounds').array return np.around(dim[1] - dim[0] if dim.size > 1 else dim_bnds[0, 1] - dim_bnds[0, 0], decr()).tolist() def _get_dimension_extent(self, axis): # return dimension extent (i.e. (start, end) for dimension) if getattr(self, axis) is None: return None else: # try to use _extent attribute # (available if instantiated via method from_extent_and_resolution) if hasattr(self, '_extent'): return self._extent[axis] # infer from first coordinate lower/upper bounds along dimension else: decr_ = decr() dim_bnds = getattr(self, f'{axis}_bounds').array return (np.around(dim_bnds[0, 0], decr_).tolist(), np.around(dim_bnds[-1, -1], decr_).tolist()) def _get_dimension_span(self, axis): if getattr(self, axis) is None: return None else: # infer dimension span from first coordinate and its bounds # (i.e. relative location of bounds around coordinate) dim = getattr(self, axis).array dim_bnds = getattr(self, f'{axis}_bounds').array dim_res = self._get_dimension_resolution(axis) left_wing = (dim_bnds[0, 0] - dim[0]) / dim_res right_wing = (dim_bnds[0, 1] - dim[0]) / dim_res decr_ = decr() return (np.around(left_wing, decr_).tolist(), np.around(right_wing, decr_).tolist()) def _get_yx_location(self): # return location of Y/X coordinates relative to their grid cell # try to use _location attribute # (available if instantiated via method from_extent_and_resolution) if hasattr(self, '_location'): return self._location['YX'] # infer YX location from spans else: x_span = self._get_dimension_span('X') y_span = self._get_dimension_span('Y') rtol_ = rtol() atol_ = atol() if (np.allclose(x_span, [-0.5, 0.5], rtol_, atol_) and np.allclose(y_span, [-0.5, 0.5], rtol_, atol_)): yx_loc = 'centre' elif (np.allclose(x_span, [0, 1], rtol_, atol_) and np.allclose(y_span, [0, 1], rtol_, atol_)): yx_loc = 'lower_left' elif (np.allclose(x_span, [0, 1], rtol_, atol_) and np.allclose(y_span, [-1, 0], rtol_, atol_)): yx_loc = 'upper_left' elif (np.allclose(x_span, [-1, 0], rtol_, atol_) and np.allclose(y_span, [0, 1], rtol_, atol_)): yx_loc = 'lower_right' elif (np.allclose(x_span, [-1, 0], rtol_, atol_) and np.allclose(y_span, [-1, 0], rtol_, atol_)): yx_loc = 'upper_right' else: yx_loc = None return yx_loc def _get_z_location(self): # return location of Z coordinate relative to its grid cell if self.Z is None: return None else: # try to use _location attribute # (available if instantiated via method from_extent_and_resolution) if hasattr(self, '_location'): return self._location['Z'] # infer Z location from span else: z_span = self._get_dimension_span('Z') rtol_ = rtol() atol_ = atol() if np.allclose(z_span, [-0.5, 0.5], rtol_, atol_): z_loc = 'centre' elif np.allclose(z_span, [0, 1], rtol_, atol_): z_loc = 'bottom' elif np.allclose(z_span, [-1, 0], rtol_, atol_): z_loc = 'top' else: z_loc = None return z_loc @classmethod def _extract_xyz_from_field(cls, field): # check dimension coordinates if not field.dim(cls._Y_name, default=False): raise RuntimeError( f"{cls.__name__} field missing '{cls._Y_name}' " f"dimension coordinate" ) y = field.dim(cls._Y_name) if not field.dim(cls._X_name, default=False): raise RuntimeError( f"{cls.__name__} field missing '{cls._X_name}' " f"dimension coordinate" ) x = field.dim(cls._X_name) z_array = None z_bounds_array = None if field.dim(cls._Z_name, default=False): if field.dim(cls._Z_name).has_bounds(): z_array = field.dim(cls._Z_name).array z_units = field.dim(cls._Z_name).units z_bounds_array = field.dim(cls._Z_name).bounds.array if z_units not in cls._Z_units: raise RuntimeError( f"{cls.__name__} field dimension coordinate " f"'{cls._Z_name}' units are not in {cls._Z_units[0]}" ) # check units if y.units not in cls._Y_units: raise RuntimeError( f"{cls.__name__} field dimension coordinate " f"'{cls._Y_name}' units are not in {cls._Y_units[0]}" ) if x.units not in cls._X_units: raise RuntimeError( f"{cls.__name__} field dimension coordinate " f"'{cls._X_name}' units are not in {cls._X_units[0]}" ) # check bounds if not y.has_bounds(): raise RuntimeError( f"{cls.__name__} field dimension coordinate " f"'{cls._Y_name}' has no bounds" ) if not x.has_bounds(): raise RuntimeError( f"{cls.__name__} field dimension coordinate " f"'{cls._X_name}' has no bounds" ) return { 'X': x.array, 'X_bounds': x.bounds.array, 'Y': y.array, 'Y_bounds': y.bounds.array, 'Z': z_array, 'Z_bounds': z_bounds_array } def __str__(self): has_z = self.has_vertical_axis() return "\n".join( [f"{self.__class__.__name__}("] + [f" shape {{{', '.join(self.axes)}}}: {self.shape}"] + ([" Z, {} {}: {}".format( self._f.dim('Z').standard_name, self._f.dim('Z').data.shape, self._f.dim('Z').data)] if has_z else []) + [" Y, {} {}: {}".format( self._f.dim('Y').standard_name, self._f.dim('Y').data.shape, self._f.dim('Y').data)] + [" X, {} {}: {}".format( self._f.dim('X').standard_name, self._f.dim('X').data.shape, self._f.dim('X').data)] + ([" Z_bounds {}: {}".format( self._f.dim('Z').bounds.data.shape, self._f.dim('Z').bounds.data)] if has_z else []) + [" Y_bounds {}: {}".format( self._f.dim('Y').bounds.data.shape, self._f.dim('Y').bounds.data)] + [" X_bounds {}: {}".format( self._f.dim('X').bounds.data.shape, self._f.dim('X').bounds.data)] + ([" cell_area {}: {}".format( self._cell_area.shape, cf.Data(self._cell_area, 'm2'))] if self._cell_area is not None else []) + ([" land_sea_mask {}: {}".format( self._land_sea_mask.shape, cf.Data(self._land_sea_mask))] if self._land_sea_mask is not None else []) + ([" flow_direction {}: {}".format( self._flow_direction.shape, cf.Data(self._flow_direction))] if self._flow_direction is not None else []) + [")"] ) def is_space_equal_to(self, field, ignore_z=False): """Compare equality between the `Grid` and the spatial (X, Y, and Z) dimension coordinates in a `cf.Field`. The coordinate values, the bounds (if field has some), and the units of the field are compared against those of the `Grid`. :Parameters: field: `cf.Field` The field that needs to be compared against this grid. ignore_z: `bool`, optional Option to ignore the dimension coordinate along the Z axis. If not provided, set to default `False` (i.e. Z is not ignored). :Returns: `bool` """ rtol_ = rtol() atol_ = atol() # check whether X/Y dimension coordinates are identical x_y = [] for axis_name in [self._X_name, self._Y_name]: # try to retrieve dimension coordinate using name dim_coord = field.dim( re.compile(r'name={}$'.format(axis_name)), default=None ) if dim_coord is not None: # collect properties of given dimension coordinate properties = list(dim_coord.properties()) try: # these will be ignored except for 'units' properties.remove('units') except ValueError: pass # if field has no bounds, remove them from spacedomain bounds = None if not dim_coord.has_bounds(): bounds = self._f.dim(axis_name).del_bounds() # compare dimension coordinates try: x_y.append( self._f.dim(axis_name).equals( dim_coord, rtol=rtol_, atol=atol_, ignore_data_type=True, ignore_fill_value=True, ignore_properties=properties ) ) finally: # if bounds were removed, append them back to spacedomain if bounds is not None: self._f.dim(axis_name).set_bounds(bounds) else: x_y.append(False) # check whether Z dimension coordinates are identical (if not ignored) if ignore_z: z = True else: if self._f.dim('Z', default=False): # try to retrieve dimension coordinate using name dim_coord = field.dim( re.compile(r'name={}$'.format(self._Z_name)), default=None ) if dim_coord is not None: # collect properties of given dimension coordinate properties = list(dim_coord.properties()) try: # these will be ignored except for 'units' properties.remove('units') except ValueError: pass # compare dimension coordinates z = self._f.dim(self._Z_name).equals( dim_coord, rtol=rtol_, atol=atol_, ignore_data_type=True, ignore_fill_value=True, ignore_properties=properties ) else: z = False elif field.dim('Z', default=False): z = False else: z = True return all(x_y) and z def spans_same_region_as(self, grid, ignore_z=False): """Compare equality in region spanned between the grid and another instance of `Grid`. For each axis, the lower bound of their first cell and the upper bound of their last cell are compared. :Parameters: grid: `Grid` The other grid to be compared against this grid. Note, the two grids must be of the same type (e.g. `LatLonGrid`). ignore_z: `bool`, optional If True, the dimension coordinates along the Z axes of the `Grid` instances will not be compared. If not provided, set to default value `False` (i.e. Z is not ignored). :Returns: `bool` """ if isinstance(grid, self.__class__): start_x = self.X_bounds[[0], [0]] == grid.X_bounds[[0], [0]] end_x = self.X_bounds[[-1], [-1]] == grid.X_bounds[[-1], [-1]] start_y = self.Y_bounds[[0], [0]] == grid.Y_bounds[[0], [0]] end_y = self.Y_bounds[[-1], [-1]] == grid.Y_bounds[[-1], [-1]] if ignore_z: start_z, end_z = True, True else: if self.Z_bounds is not None and grid.Z_bounds is not None: start_z = ( self.Z_bounds[[0], [0]] == grid.Z_bounds[[0], [0]] ).array.item() end_z = ( self.Z_bounds[[-1], [-1]] == grid.Z_bounds[[-1], [-1]] ).array.item() elif self.Z_bounds is not None or grid.Z_bounds is not None: start_z, end_z = False, False else: start_z, end_z = True, True return all((start_x.array.item(), end_x.array.item(), start_y.array.item(), end_y.array.item(), start_z, end_z)) else: raise TypeError( f"{self.__class__.__name__} instance cannot be " f"compared to {grid.__class__.__name__} instance" ) def is_matched_in(self, grid): """Determine whether the horizontal cell bounds of the grid are overlapping with the cell bounds of another instance of `Grid`. In other words, determine whether the cells of the grid are fully containing the cells (i.e. not area fractions) of another instance of `Grid`. :Parameters: grid: `Grid` The grid whose cells are checked as being fully contained this grid. Note, the two grids must be of the same type (e.g. `LatLonGrid`). :Returns: `bool` """ if isinstance(grid, self.__class__): x_match = ( np.all(np.in1d(self.X_bounds[:, 0], grid.X_bounds[:, 0])) and self.X_bounds.array[-1, -1] == grid.X_bounds.array[-1, -1] ) y_match = ( np.all(np.in1d(self.Y_bounds[:, 0], grid.Y_bounds[:, 0])) and self.Y_bounds.array[-1, -1] == grid.Y_bounds.array[-1, -1] ) return x_match and y_match else: raise TypeError( f"{self.__class__.__name__} instance cannot be " f"compared to {grid.__class__.__name__} instance" ) def subset_and_compare(self, field): error = RuntimeError( f"field not compatible with {self.__class__.__name__}" ) # TODO: include Z axis in subset when 3D components are # effectively supported # avoid floating-point error problems by rounding up for axis in [self.X_name, self.Y_name]: field.dim(axis, error).round(decr(), inplace=True) # try to subset in space kwargs = { self.X_name: cf.wi(*self.X.array[[0, -1]]), self.Y_name: cf.wi(*self.Y.array[[0, -1]]) } if field.subspace('test', **kwargs): field_subset = field.subspace(**kwargs) else: raise error # check that data and component spacedomains are compatible if not self.is_space_equal_to(field_subset): raise error return field_subset @classmethod def from_extent_and_resolution(cls, **kwargs): inst = cls( **cls._get_grid_from_extent_and_resolution( kwargs[f'{cls._Y_name}_extent'], kwargs[f'{cls._X_name}_extent'], kwargs[f'{cls._Y_name}_resolution'], kwargs[f'{cls._X_name}_resolution'], kwargs[f'{cls._Y_name}_{cls._X_name}_location'], # kwargs[f'{cls._Z_name}_extent'], # kwargs[f'{cls._Z_name}_resolution'], # kwargs[f'{cls._Z_name}_location'] ) ) inst._extent = { # 'Z': kwargs[f'{cls._Z_name}_extent'], 'Y': kwargs[f'{cls._Y_name}_extent'], 'X': kwargs[f'{cls._X_name}_extent'] } inst._resolution = { # 'Z': kwargs[f'{cls._Z_name}_resolution'], 'Y': kwargs[f'{cls._Y_name}_resolution'], 'X': kwargs[f'{cls._X_name}_resolution'] } inst._location = { # 'Z': kwargs[f'{cls._Z_name}_location'], 'YX': kwargs[f'{cls._Y_name}_{cls._X_name}_location'] } return inst @classmethod def from_config(cls, cfg): cfg = cfg.copy() cfg.pop('class') extras = {} for extra in ['land_sea_mask', 'flow_direction', 'cell_area']: extras[extra] = cfg.pop(extra, None) inst = cls.from_extent_and_resolution(**cfg) for extra in ['land_sea_mask', 'flow_direction', 'cell_area']: value = extras[extra] if value is not None: setattr( inst, extra, cf.read(value['files']).select_field(value['select']) ) return inst def to_config(self): extras = {} for extra in ['land_sea_mask', 'flow_direction', 'cell_area']: attrib = getattr(self, f'_{extra}_field') if attrib and attrib.get_filenames(): extras[extra] = {'files': attrib.get_filenames(), 'select': attrib.identity()} else: extras[extra] = None return { 'class': self.__class__.__name__, f'{self._Y_name}_extent': self._get_dimension_extent('Y'), f'{self._Y_name}_resolution': self._get_dimension_resolution('Y'), f'{self._X_name}_extent': self._get_dimension_extent('X'), f'{self._X_name}_resolution': self._get_dimension_resolution('X'), f'{self._Y_name}_{self._X_name}_location': self._get_yx_location(), # f'{self._Z_name}_extent': self._get_dimension_extent('Z'), # f'{self._Z_name}_resolution': self._get_dimension_resolution('Z'), # f'{self._Z_name}_location': self._get_z_location(), **extras } @classmethod def from_field(cls, field): extraction = cls._extract_xyz_from_field(field) return cls( **{ getattr(cls, f'_{axis}_name') + prop: extraction[axis + prop] # for axis in ['X', 'Y', 'Z'] for axis in ['X', 'Y'] for prop in ['', '_bounds'] } ) def to_horizontal_grid(self, drop_extras=True): cfg = self.to_config() for prop in ['extent', 'resolution']: cfg.pop(f'{self._Z_name}_{prop}', None) if drop_extras: for extra in ['land_sea_mask', 'flow_direction', 'cell_area']: cfg.pop(extra) return self.__class__.from_config(cfg) class LatLonGrid(Grid): """This class characterises the spatial dimension for a `Component` as a regular grid on a spherical domain whose coordinates are latitudes and longitudes, and whose rotation axis is aligned with the North pole (`EPSG:4326 <https://epsg.io/4326>`_). """ # characteristics of the dimension coordinates _Z_name = 'altitude' _Y_name = 'latitude' _X_name = 'longitude' _Z_units = ['m', 'metre', 'meter', 'metres', 'meters'] _Y_units = ['degrees_north', 'degree_north', 'degrees_N', 'degree_N', 'degreesN', 'degreeN'] _X_units = ['degrees_east', 'degree_east', 'degrees_E', 'degree_E', 'degreesE', 'degreeE'] _Z_limits = None _Y_limits = (-90, 90) _X_limits = (-180, 180) # contiguity of lower and upper limits _Z_limits_contiguous = False _Y_limits_contiguous = True _X_limits_contiguous = True # allow domain to wrap around limits _Z_wrap_around = False _Y_wrap_around = False _X_wrap_around = True def __init__( self, latitude, longitude, latitude_bounds, longitude_bounds, # altitude=None, altitude_bounds=None ): """**Instantiation** :Parameters: latitude: one-dimensional array-like object The array of latitude coordinates in degrees North defining a spatial dimension of the domain. May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. Coordinates must be ordered from South to North. Coordinates must be regularly spaced. *Parameter example:* :: latitude=[15, 45, 75] *Parameter example:* :: latitude=numpy.arange(-89.5, 90.5, 1) longitude: one-dimensional array-like object The array of longitude coordinates in degrees East defining a spatial dimension of the domain. May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. Coordinates must be ordered from West to East. Coordinates must be regularly spaced. *Parameter example:* :: longitude=(-150, -90, -30, 30, 90, 150) *Parameter example:* :: longitude=numpy.arange(-179.5, 180.5, 1) latitude_bounds: two-dimensional array-like object The array of latitude coordinate bounds in degrees North defining the extent of the grid cell around the coordinate. May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *latitude* and the second dimension equal to 2. Must contain numerical values. *Parameter example:* :: latitude_bounds=[[0, 30], [30, 60], [60, 90]] *Parameter example:* :: latitude_bounds=numpy.column_stack( (numpy.arange(-90, 90, 1), numpy.arange(-89, 91, 1)) ) longitude_bounds: two-dimensional array-like object The array of longitude coordinate bounds in degrees East defining the extent of the grid cell around the coordinate. May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *longitude* and the second dimension equal to 2. Must contain numerical values. *Parameter example:* :: longitude_bounds=((-180, -120), (-120, -60), (-60, 0) (0, 60), (60, 120), (120, 180)) *Parameter example:* :: longitude_bounds=numpy.column_stack( (numpy.arange(-180, 180, 1), numpy.arange(-179, 181, 1)) ) .. altitude: one-dimensional array-like object, optional The array of altitude coordinates in metres defining a spatial dimension (with upwards as the positive direction). May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. Ignored if *altitude_bounds* not also provided. *Parameter example:* :: altitude=[10] .. altitude_bounds: two-dimensional array-like object, optional The array of altitude coordinate bounds in metres defining the extent of the grid cell around the coordinate (with upwards as the positive direction). May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *altitude* and the second dimension equal to 2. Must contain numerical values. Ignored if *altitude* not also provided. *Parameter example:* :: altitude_bounds=[[0, 20]] **Examples** Instantiating grid using lists: >>> import numpy >>> sd = LatLonGrid( ... latitude=[15, 45, 75], ... longitude=[30, 90, 150], ... latitude_bounds=[[0, 30], [30, 60], [60, 90]], ... longitude_bounds=[[0, 60], [60, 120], [120, 180]] ... ) >>> print(sd) LatLonGrid( shape {Y, X}: (3, 3) Y, latitude (3,): [15, 45, 75] degrees_north X, longitude (3,): [30, 90, 150] degrees_east Y_bounds (3, 2): [[0, ..., 90]] degrees_north X_bounds (3, 2): [[0, ..., 180]] degrees_east ) .. Instantiating grid using numpy arrays and Z axis: .. .. >>> sd = LatLonGrid( .. ... latitude=numpy.arange(-89.5, 90.5, 1), .. ... longitude=numpy.arange(-179.5, 180.5, 1), .. ... latitude_bounds=numpy.column_stack( .. ... (numpy.arange(-90, 90, 1), .. ... numpy.arange(-89, 91, 1)) .. ... ), .. ... longitude_bounds=numpy.column_stack( .. ... (numpy.arange(-180, 180, 1), .. ... numpy.arange(-179, 181, 1)) .. ... ), .. ... altitude=[10], .. ... altitude_bounds=[[0, 10]] .. ... ) .. >>> print(sd) .. LatLonGrid( .. shape {Z, Y, X}: (1, 180, 360) .. Z, altitude (1,): [10] m .. Y, latitude (180,): [-89.5, ..., 89.5] degrees_north .. X, longitude (360,): [-179.5, ..., 179.5] degrees_east .. Z_bounds (1, 2): [[0, 10]] m .. Y_bounds (180, 2): [[-90, ..., 90]] degrees_north .. X_bounds (360, 2): [[-180, ..., 180]] degrees_east .. ) Trying to instantiate grid with latitudes from East to West: >>> sd = LatLonGrid( ... latitude=[75, 45, 15], ... longitude=[30, 90, 150], ... latitude_bounds=[[90, 60], [60, 30], [30, 0]], ... longitude_bounds=[[0, 60], [60, 120], [120, 180]] ... ) Traceback (most recent call last): ... RuntimeError: latitude dimension not directed positively Trying to instantiate grid with latitude cells of varying width: >>> sd = LatLonGrid( ... latitude=[15, 45, 75], ... longitude=[30, 90, 150], ... latitude_bounds=[[10, 20], [20, 70], [70, 80]], ... longitude_bounds=[[0, 60], [60, 120], [120, 180]] ... ) Traceback (most recent call last): ... RuntimeError: latitude bounds space gap not constant across region """ super(LatLonGrid, self).__init__() # TODO: reintroduce Z dimension when 3D components # are effectively supported # if altitude is not None and altitude_bounds is not None: # self._set_space(altitude, altitude_bounds, name=self._Z_name, # units=self._Z_units[0], axis='Z', # limits=self._Z_limits, wrap_around=self._Z_wrap_around) # self._f.dim('Z').set_property('positive', 'up') self._set_space(latitude, latitude_bounds, name=self._Y_name, units=self._Y_units[0], axis='Y', limits=self._Y_limits, wrap_around=self._Y_wrap_around) self._set_space(longitude, longitude_bounds, name=self._X_name, units=self._X_units[0], axis='X', limits=self._X_limits, wrap_around=self._X_wrap_around) # set dummy data needed for using inner field for remapping self._set_dummy_data() @classmethod def from_extent_and_resolution( cls, latitude_extent, longitude_extent, latitude_resolution, longitude_resolution, latitude_longitude_location='centre', # altitude_extent=None, # altitude_resolution=None, # altitude_location='centre' ): """Instantiate a `LatLonGrid` from the extent and the resolution of latitude, longitude (and optionally altitude) coordinates. :Parameters: latitude_extent: pair of `float` or `int` The extent of latitude coordinates in degrees North for the desired grid. The first element of the pair is the location of the start of the extent along the latitude coordinate, the second element of the pair is the location of the end of the extent along the latitude coordinate. Extent must be from South to North. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: latitude_extent=(30, 70) longitude_extent: pair of `float` or `int` The extent of longitude coordinates in degrees East for the desired grid. The first element of the pair is the location of the start of the extent along the longitude coordinate, the second element of the pair is the location of the end of the extent along the longitude coordinate. Extent must be from West to East. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: longitude_extent=(0, 90) latitude_resolution: `float` or `int` The spacing between two consecutive latitude coordinates in degrees North for the desired grid. Must be positive. *Parameter example:* :: latitude_resolution=10 longitude_resolution: `float` or `int` The spacing between two consecutive longitude coordinates in degrees East for the desired grid. Must be positive. *Parameter example:* :: longitude_resolution=10 latitude_longitude_location: `str` or `int`, optional The location of the latitude and longitude coordinates in relation to their grid cells (i.e. their bounds). This information is required to generate the latitude and longitude bounds for each grid coordinate. If not provided, set to default 'centre'. The locations left and right are related to the longitude coordinates (X-axis), while the locations lower and upper are related to the latitude coordinates (Y-axis). The orientation of the coordinate system considered is detailed below (i.e. positive directions are northwards and eastwards). :: Y, latitude (degrees North) ↑ · * · → X, longitude (degrees East) This parameter can be set using the labels (as a `str`) or the indices (as an `int`) detailed in the table below. ================= ===== ============================== label idx description ================= ===== ============================== ``'centre'`` ``0`` The latitude and longitude bounds extend equally on both sides of the coordinate along the two axes of a length equal to half the resolution along the given coordinate axis. ``'lower left'`` ``1`` The latitude bounds extend northwards of a length equal to the latitude resolution. The longitude bounds extend eastwards of a length equal to the longitude resolution. ``'upper left'`` ``2`` The latitude bounds extend southwards of a length equal to the latitude resolution. The longitude bounds extend eastwards of a length equal to the longitude resolution. ``'lower right'`` ``3`` The latitude bounds extend northwards of a length equal to the latitude resolution. The longitude bounds extend westwards of a length equal to the longitude resolution. ``'upper right'`` ``4`` The latitude bounds extend southwards of a length equal to the latitude resolution. The longitude bounds extend westwards of a length equal to the longitude resolution. ================= ===== ============================== The indices defining the location of the coordinate in relation to its grid cell are made explicit below, where the '+' characters depict the coordinates, and the '·' characters delineate the relative location of the grid cell whose height and width are determined using the latitude and longitude resolutions, respectively. :: 2 4 northwards + · · · + ↑ · · · · 0 + · westwards ← · * · → eastwards · · · + · · · + ↓ 1 3 southwards *Parameter example:* :: latitude_longitude_location='centre' *Parameter example:* :: latitude_longitude_location=0 .. altitude_extent: pair of `float` or `int`, optional The extent of altitude coordinate in metres for the desired grid. The first element of the pair is the location of the start of the extent along the altitude coordinate, the second element of the pair is the location of the end of the extent along the altitude coordinate. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: altitude_extent=(0, 20) .. altitude_resolution: `float` or `int`, optional The spacing between two consecutive altitude coordinates in metres for the desired grid. *Parameter example:* :: altitude_resolution=20 .. altitude_location: `str` or `int`, optional The location of the altitude coordinates in relation to their grid cells (i.e. their bounds). This information is required to generate the altitude bounds for each grid coordinate. If not provided, set to default 'centre'. The locations top and bottom are related to the altitude coordinate (Z-axis). The orientation of the coordinate system considered is such that the positive direction is upwards. This parameter can be set using the labels (as a `str`) or the indices (as an `int`) detailed in the table below. ================ ===== =============================== label idx description ================ ===== =============================== ``'centre'`` ``0`` The altitude bounds extend equally upwards and downwards of a length equal to half the resolution along the altitude axis. ``'bottom'`` ``1`` The altitude bounds extend upwards of a length equal to the resolution along the altitude axis. ``'top'`` ``2`` The altitude bounds extend downwards of a length equal to the resolution along the altitude axis. ================ ===== =============================== *Parameter example:* :: altitude_location='centre' :Returns: `LatLonGrid` **Examples** .. Instantiating grid with optional altitude coordinates: .. .. >>> sd = LatLonGrid.from_extent_and_resolution( .. ... latitude_extent=(30, 70), .. ... longitude_extent=(0, 90), .. ... latitude_resolution=5, .. ... longitude_resolution=10, .. ... altitude_extent=(0, 20), .. ... altitude_resolution=20 .. ... ) .. >>> print(sd) .. LatLonGrid( .. shape {Z, Y, X}: (1, 8, 9) .. Z, altitude (1,): [10.0] m .. Y, latitude (8,): [32.5, ..., 67.5] degrees_north .. X, longitude (9,): [5.0, ..., 85.0] degrees_east .. Z_bounds (1, 2): [[0.0, 20.0]] m .. Y_bounds (8, 2): [[30.0, ..., 70.0]] degrees_north .. X_bounds (9, 2): [[0.0, ..., 90.0]] degrees_east .. ) Instantiating grid using non-standard coordinates location in their cells: >>> sd = LatLonGrid.from_extent_and_resolution( ... latitude_extent=(30, 70), ... longitude_extent=(0, 90), ... latitude_resolution=5, ... longitude_resolution=10, ... latitude_longitude_location='upper right' ... ) >>> print(sd) LatLonGrid( shape {Y, X}: (8, 9) Y, latitude (8,): [35.0, ..., 70.0] degrees_north X, longitude (9,): [10.0, ..., 90.0] degrees_east Y_bounds (8, 2): [[30.0, ..., 70.0]] degrees_north X_bounds (9, 2): [[0.0, ..., 90.0]] degrees_east ) """ return super(LatLonGrid, cls).from_extent_and_resolution( latitude_extent=latitude_extent, longitude_extent=longitude_extent, latitude_resolution=latitude_resolution, longitude_resolution=longitude_resolution, latitude_longitude_location=latitude_longitude_location, # altitude_extent=altitude_extent, # altitude_resolution=altitude_resolution, # altitude_location=altitude_location ) @classmethod def from_field(cls, field): """Instantiate a `LatLonGrid` from spatial dimension coordinates of a `cf.Field`. :Parameters: field: `cf.Field` The field object that will be used to instantiate a `LatLonGrid` instance. This field must feature a 'latitude' and a 'longitude' dimension coordinates, and these coordinates must feature bounds. .. This field may optionally feature an 'altitude' dimension coordinate alongside its bounds (both required otherwise ignored). :Returns: `LatLonGrid` **Examples** Instantiating from a 2D field: >>> import cf >>> f = cf.Field() >>> lat = f.set_construct( ... cf.DimensionCoordinate( ... properties={'standard_name': 'latitude', ... 'units': 'degrees_north', ... 'axis': 'Y'}, ... data=cf.Data([15, 45, 75]), ... bounds=cf.Bounds(data=cf.Data([[0, 30], [30, 60], [60, 90]])) ... ), ... axes=f.set_construct(cf.DomainAxis(size=3)) ... ) >>> lon = f.set_construct( ... cf.DimensionCoordinate( ... properties={'standard_name': 'longitude', ... 'units': 'degrees_east', ... 'axis': 'X'}, ... data=cf.Data([30, 90, 150]), ... bounds=cf.Bounds(data=cf.Data([[0, 60], [60, 120], [120, 180]])) ... ), ... axes=f.set_construct(cf.DomainAxis(size=3)) ... ) >>> sd = LatLonGrid.from_field(f) >>> print(sd) LatLonGrid( shape {Y, X}: (3, 3) Y, latitude (3,): [15, 45, 75] degrees_north X, longitude (3,): [30, 90, 150] degrees_east Y_bounds (3, 2): [[0, ..., 90]] degrees_north X_bounds (3, 2): [[0, ..., 180]] degrees_east ) Using the field interface back and forth: >>> sd1 = LatLonGrid.from_extent_and_resolution( ... latitude_extent=(30, 70), ... longitude_extent=(0, 90), ... latitude_resolution=5, ... longitude_resolution=10, ... latitude_longitude_location='upper right' ... ) >>> sd2 = LatLonGrid.from_field(sd1.to_field()) >>> sd2 == sd1 True .. Instantiating from a 3D field: .. .. >>> import cf .. >>> f = cf.Field() .. >>> lat = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'latitude', .. ... 'units': 'degrees_north', .. ... 'axis': 'Y'}, .. ... data=cf.Data([15, 45, 75]), .. ... bounds=cf.Bounds(data=cf.Data([[0, 30], [30, 60], [60, 90]])) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=3)) .. ... ) .. >>> lon = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'longitude', .. ... 'units': 'degrees_east', .. ... 'axis': 'X'}, .. ... data=cf.Data([30, 90, 150]), .. ... bounds=cf.Bounds(data=cf.Data([[0, 60], [60, 120], [120, 180]])) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=3)) .. ... ) .. >>> alt = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'altitude', .. ... 'units': 'm', .. ... 'axis': 'Z'}, .. ... data=cf.Data([10]), .. ... bounds=cf.Bounds(data=cf.Data([[0, 20]])) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=1)) .. ... ) .. >>> sd = LatLonGrid.from_field(f) .. >>> print(sd) .. LatLonGrid( .. shape {Z, Y, X}: (1, 3, 3) .. Z, altitude (1,): [10] m .. Y, latitude (3,): [15, 45, 75] degrees_north .. X, longitude (3,): [30, 90, 150] degrees_east .. Z_bounds (1, 2): [[0, 20]] m .. Y_bounds (3, 2): [[0, ..., 90]] degrees_north .. X_bounds (3, 2): [[0, ..., 180]] degrees_east .. ) """ return super(LatLonGrid, cls).from_field(field) class RotatedLatLonGrid(Grid): """This class characterises the spatial dimension for a `Component` as a regular grid on a spherical domain whose coordinates are latitudes and longitudes, and whose rotation axis is not aligned with the North pole. Its ellipsoid and datum are those of WGS 84 (see `EPSG:4326 <https://epsg.io/4326>`_). """ # characteristics of the dimension coordinates _Z_name = 'altitude' _Y_name = 'grid_latitude' _X_name = 'grid_longitude' _Z_units = ['m', 'metre', 'meter', 'metres', 'meters'] _Y_units = ['degrees', 'degree'] _X_units = ['degrees', 'degree'] _Z_limits = None _Y_limits = (-90, 90) _X_limits = (-180, 180) # contiguity of lower and upper limits _Z_limits_contiguous = False _Y_limits_contiguous = True _X_limits_contiguous = True # allow domain to wrap around limits _Z_wrap_around = False _Y_wrap_around = False _X_wrap_around = True def __init__( self, grid_latitude, grid_longitude, grid_latitude_bounds, grid_longitude_bounds, grid_north_pole_latitude, grid_north_pole_longitude, north_pole_grid_longitude=0., # altitude=None, altitude_bounds=None ): """**Instantiation** :Parameters: grid_latitude: one-dimensional array-like object The array of latitude coordinates in degrees defining a spatial dimension of the domain. May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. *Parameter example:* :: grid_latitude=[0.88, 0.44, 0., -0.44, -0.88] grid_longitude: one-dimensional array-like object The array of longitude coordinates in degrees defining a spatial dimension of the domain. May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. *Parameter example:* :: grid_longitude=[-2.5, -2.06, -1.62, -1.18] grid_latitude_bounds: two-dimensional array-like object The array of latitude coordinate bounds in degrees defining the extent of the grid cell around the coordinate. May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *grid_latitude* and the second dimension equal to 2. Must contain numerical values. *Parameter example:* :: grid_latitude_bounds=[[1.1, 0.66], [0.66, 0.22], [0.22, -0.22], [-0.22, -0.66], [-0.66, -1.1]] grid_longitude_bounds: two-dimensional array-like object The array of longitude coordinate bounds in degrees defining the extent of the grid cell around the coordinate. May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *grid_longitude* and the second dimension equal to 2. Must contain numerical values. *Parameter example:* :: grid_longitude_bounds=[[-2.72, -2.28], [-2.28, -1.84], [-1.84, -1.4], [-1.4, -0.96]] grid_north_pole_latitude: `int` or `float` The true latitude (i.e. in `EPSG:4326`_) of the north pole of the rotated grid in degrees North. This parameter is required to project the rotated grid into a true latitude-longitude coordinate system. grid_north_pole_longitude: `int` or `float` The true longitude (i.e. in `EPSG:4326`_) of the north pole of the rotated grid in degrees East. This parameter is required to project the rotated grid into a true latitude-longitude coordinate system. north_pole_grid_longitude: `int` or `float`, optional The longitude of the true north pole (i.e. in `EPSG:4326`_) in the rotated grid in degrees. This parameter is optional to project the rotated grid into a true latitude-longitude coordinate system. If not provided, set to default value 0. .. altitude: one-dimensional array-like object, optional The array of altitude coordinates in metres defining a spatial dimension of the domain (with upwards as the positive direction). May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. Ignored if *altitude_bounds* not also provided. *Parameter example:* :: altitude=[10] .. altitude_bounds: two-dimensional array-like object, optional The array of altitude coordinate bounds in metres defining the extent of the grid cell around the coordinate (with upwards as the positive direction). May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *altitude* and the second dimension equal to 2. Must contain numerical values. Ignored if *altitude* not also provided. *Parameter example:* :: altitude_bounds=[[0, 20]] .. _`EPSG:4326`: https://epsg.io/4326 **Examples** Instantiate 2D grid using lists: >>> sd = RotatedLatLonGrid( ... grid_latitude=[-0.88, -0.44, 0., 0.44, 0.88], ... grid_longitude=[-2.5, -2.06, -1.62, -1.18], ... grid_latitude_bounds=[[-1.1, -0.66], [-0.66, -0.22], [-0.22, 0.22], ... [0.22, 0.66], [0.66, 1.1]], ... grid_longitude_bounds=[[-2.72, -2.28], [-2.28, -1.84], ... [-1.84, -1.4], [-1.4, -0.96]], ... grid_north_pole_latitude=38.0, ... grid_north_pole_longitude=190.0, ... ) >>> print(sd) RotatedLatLonGrid( shape {Y, X}: (5, 4) Y, grid_latitude (5,): [-0.88, ..., 0.88] degrees X, grid_longitude (4,): [-2.5, ..., -1.18] degrees Y_bounds (5, 2): [[-1.1, ..., 1.1]] degrees X_bounds (4, 2): [[-2.72, ..., -0.96]] degrees ) .. Instantiate 3D grid using lists: .. .. >>> sd = RotatedLatLonGrid( .. ... grid_latitude=[-0.88, -0.44, 0., 0.44, 0.88], .. ... grid_longitude=[-2.5, -2.06, -1.62, -1.18], .. ... grid_latitude_bounds=[[-1.1, -0.66], [-0.66, -0.22], [-0.22, 0.22], .. ... [0.22, 0.66], [0.66, 1.1]], .. ... grid_longitude_bounds=[[-2.72, -2.28], [-2.28, -1.84], .. ... [-1.84, -1.4], [-1.4, -0.96]], .. ... grid_north_pole_latitude=38.0, .. ... grid_north_pole_longitude=190.0, .. ... altitude=[10], .. ... altitude_bounds=[[0, 20]] .. ... ) .. >>> print(sd) .. RotatedLatLonGrid( .. shape {Y, X}: (1, 5, 4) .. Y, grid_latitude (5,): [-0.88, ..., 0.88] degrees .. X, grid_longitude (4,): [-2.5, ..., -1.18] degrees .. Z_bounds (1, 2): [[0, 20]] m .. Y_bounds (5, 2): [[-1.1, ..., 1.1]] degrees .. X_bounds (4, 2): [[-2.72, ..., -0.96]] degrees .. ) """ super(RotatedLatLonGrid, self).__init__() # TODO: reintroduce Z dimension when 3D components # are effectively supported # if altitude is not None and altitude_bounds is not None: # self._set_space(altitude, altitude_bounds, name=self._Z_name, # units=self._Z_units[0], axis='Z', # limits=self._Z_limits, wrap_around=self._Z_wrap_around) # self._f.dim('Z').set_property('positive', 'up') self._set_space(grid_latitude, grid_latitude_bounds, name=self._Y_name, units=self._Y_units[0], axis='Y', limits=self._Y_limits, wrap_around=self._Y_wrap_around) self._set_space(grid_longitude, grid_longitude_bounds, name=self._X_name, units=self._X_units[0], axis='X', limits=self._X_limits, wrap_around=self._X_wrap_around) self._rotate_and_set_lat_lon(grid_north_pole_latitude, grid_north_pole_longitude, north_pole_grid_longitude) self._set_crs_parameters(grid_north_pole_latitude, grid_north_pole_longitude, north_pole_grid_longitude) # set dummy data needed for using inner field for remapping self._set_dummy_data() @classmethod def from_extent_and_resolution( cls, grid_latitude_extent, grid_longitude_extent, grid_latitude_resolution, grid_longitude_resolution, grid_north_pole_latitude, grid_north_pole_longitude, north_pole_grid_longitude=0., grid_latitude_grid_longitude_location='centre', # altitude_extent=None, # altitude_resolution=None, # altitude_location='centre' ): """Instantiate a `RotatedLatLonGrid` from the extent and the resolution of grid_latitude and grid_longitude coordinates (and optional altitude coordinates). :Parameters: grid_latitude_extent: pair of `float` or `int` The extent of grid_latitude coordinates in degrees for the desired grid. The first element of the pair is the location of the start of the extent along the grid_latitude coordinate, the second element of the pair is the location of the end of the extent along the grid_latitude coordinate. Extent must be oriented positively. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: grid_latitude_extent=(30, 70) grid_longitude_extent: pair of `float` or `int` The extent of grid_longitude coordinates in degrees for the desired grid. The first element of the pair is the location of the start of the extent along the grid_longitude coordinate, the second element of the pair is the location of the end of the extent along the grid_latitude coordinate. Extent must be oriented positively. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: grid_longitude_extent=(0, 90) grid_latitude_resolution: `float` or `int` The spacing between two consecutive grid_latitude coordinates in degrees for the desired grid. Must be positive. *Parameter example:* :: grid_latitude_resolution=10 grid_longitude_resolution: `float` or `int` The spacing between two consecutive grid_longitude coordinates in degrees for the desired grid. Must be positive. *Parameter example:* :: grid_longitude_resolution=10 grid_latitude_grid_longitude_location: `str` or `int`, optional The location of the grid_latitude and grid_longitude coordinates in relation to their grid cells (i.e. their bounds). This information is required to generate the grid_latitude and grid_longitude bounds for each grid coordinate. If not provided, set to default 'centre'. The locations left and right are related to the grid_longitude coordinates (X-axis), while the locations lower and upper are related to the grid_latitude coordinates (Y-axis). The orientation of the coordinate system considered is detailed below. .. seealso:: *latitude_longitude_location* in `LatLonGrid.from_extent_and_resolution` grid_north_pole_latitude: `int` or `float` The true latitude (i.e. in `EPSG:4326`_) of the north pole of the rotated grid in degrees North. This parameter is required to project the rotated grid into a true latitude-longitude coordinate system. grid_north_pole_longitude: `int` or `float` The true longitude (i.e. in `EPSG:4326`_) of the north pole of the rotated grid in degrees East. This parameter is required to project the rotated grid into a true latitude-longitude coordinate system. north_pole_grid_longitude: `int` or `float`, optional The longitude of the true north pole in the rotated grid in degrees. This parameter is optional to project the rotated grid into a true latitude-longitude coordinate system (i.e. `EPSG:4326`_). If not provided, set to default value 0. .. altitude_extent: pair of `float` or `int`, optional The extent of altitude coordinate in metres for the desired grid. The first element of the pair is the location of the start of the extent along the altitude coordinate, the second element of the pair is the location of the end of the extent along the altitude coordinate. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: altitude_extent=(0, 20) .. altitude_resolution: `float` or `int`, optional The spacing between two consecutive altitude coordinates in metres for the desired grid. *Parameter example:* :: altitude_resolution=20 .. altitude_location: `str` or `int`, optional The location of the altitude coordinates in relation to their grid cells (i.e. their bounds). This information is required to generate the altitude bounds for each grid coordinate. If not provided, set to default 'centre'. The locations top and bottom are related to the altitude coordinate (Z-axis). The orientation of the coordinate system considered is such that the positive direction is upwards. .. seealso:: *altitude_location* in `LatLonGrid.from_extent_and_resolution` *Parameter example:* :: altitude_location='centre' .. _`EPSG:4326`: https://epsg.io/4326 :Returns: `RotatedLatLonGrid` **Examples** >>> sd = RotatedLatLonGrid.from_extent_and_resolution( ... grid_latitude_extent=(-1.1, 1.1), ... grid_longitude_extent=(-2.72, -0.96), ... grid_latitude_resolution=0.44, ... grid_longitude_resolution=0.44, ... grid_north_pole_latitude=38.0, ... grid_north_pole_longitude=190.0 ... ) >>> print(sd) RotatedLatLonGrid( shape {Y, X}: (5, 4) Y, grid_latitude (5,): [-0.88, ..., 0.88] degrees X, grid_longitude (4,): [-2.5, ..., -1.18] degrees Y_bounds (5, 2): [[-1.1, ..., 1.1]] degrees X_bounds (4, 2): [[-2.72, ..., -0.96]] degrees ) """ inst = cls( **cls._get_grid_from_extent_and_resolution( grid_latitude_extent, grid_longitude_extent, grid_latitude_resolution, grid_longitude_resolution, grid_latitude_grid_longitude_location, # altitude_extent, altitude_resolution, altitude_location ), grid_north_pole_latitude=grid_north_pole_latitude, grid_north_pole_longitude=grid_north_pole_longitude, north_pole_grid_longitude=north_pole_grid_longitude ) inst._extent = { # 'Z': altitude_extent, 'Y': grid_latitude_extent, 'X': grid_longitude_extent } inst._resolution = { # 'Z': altitude_resolution, 'Y': grid_latitude_resolution, 'X': grid_longitude_resolution } inst._location = { # 'Z': altitude_location, 'YX': grid_latitude_grid_longitude_location } return inst @classmethod def from_field(cls, field): """Instantiate a `RotatedLatLonGrid` from spatial dimension coordinates of a `cf.Field`. :Parameters: field: `cf.Field` The field object that will be used to instantiate a `RotatedLatLonGrid` instance. This field must feature a 'grid_latitude' and a 'grid_longitude' dimension coordinates, and these must feature bounds. In addition, the parameters required for the conversion of the grid to a true latitude-longitude reference system must be set (i.e. grid_north_pole_latitude, grid_north_pole_longitude, and optional north_pole_grid_longitude). .. This field may optionally feature an 'altitude' dimension coordinate alongside its bounds (both required otherwise ignored). :Returns: `RotatedLatLonGrid` **Examples** Instantiating from a 2D field: >>> import cf >>> f = cf.Field() >>> lat = f.set_construct( ... cf.DimensionCoordinate( ... properties={'standard_name': 'grid_latitude', ... 'units': 'degrees', ... 'axis': 'Y'}, ... data=cf.Data([-0.88, -0.44, 0., 0.44, 0.88]), ... bounds=cf.Bounds(data=cf.Data([[-1.1, -0.66], [-0.66, -0.22], ... [-0.22, 0.22], [0.22, 0.66], ... [0.66, 1.1]])) ... ), ... axes=f.set_construct(cf.DomainAxis(size=5)) ... ) >>> lon = f.set_construct( ... cf.DimensionCoordinate( ... properties={'standard_name': 'grid_longitude', ... 'units': 'degrees', ... 'axis': 'X'}, ... data=cf.Data([-2.5, -2.06, -1.62, -1.18]), ... bounds=cf.Bounds(data=cf.Data([[-2.72, -2.28], [-2.28, -1.84], ... [-1.84, -1.4], [-1.4, -0.96]])) ... ), ... axes=f.set_construct(cf.DomainAxis(size=4)) ... ) >>> crs = f.set_construct( ... cf.CoordinateReference( ... coordinate_conversion=cf.CoordinateConversion( ... parameters={'grid_mapping_name': 'rotated_latitude_longitude', ... 'grid_north_pole_latitude': 38.0, ... 'grid_north_pole_longitude': 190.0}), ... coordinates=(lat, lon) ... ) ... ) >>> sd = RotatedLatLonGrid.from_field(f) >>> print(sd) RotatedLatLonGrid( shape {Y, X}: (5, 4) Y, grid_latitude (5,): [-0.88, ..., 0.88] degrees X, grid_longitude (4,): [-2.5, ..., -1.18] degrees Y_bounds (5, 2): [[-1.1, ..., 1.1]] degrees X_bounds (4, 2): [[-2.72, ..., -0.96]] degrees ) Using the field interface back and forth: >>> sd1 = RotatedLatLonGrid.from_extent_and_resolution( ... grid_latitude_extent=(-1.1, 1.1), ... grid_longitude_extent=(-2.72, -0.96), ... grid_latitude_resolution=0.44, ... grid_longitude_resolution=0.44, ... grid_north_pole_latitude=38.0, ... grid_north_pole_longitude=190.0 ... ) >>> sd2 = RotatedLatLonGrid.from_field(sd1.to_field()) >>> sd2 == sd1 True .. Instantiating from a 3D field: .. .. >>> import cf .. >>> f = cf.Field() .. >>> lat = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'grid_latitude', .. ... 'units': 'degrees', .. ... 'axis': 'Y'}, .. ... data=cf.Data([-0.88, -0.44, 0., 0.44, 0.88]), .. ... bounds=cf.Bounds(data=cf.Data([[-1.1, -0.66], [-0.66, -0.22], .. ... [-0.22, 0.22], [0.22, 0.66], .. ... [0.66, 1.1]])) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=5)) .. ... ) .. >>> lon = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'grid_longitude', .. ... 'units': 'degrees', .. ... 'axis': 'X'}, .. ... data=cf.Data([-2.5, -2.06, -1.62, -1.18]), .. ... bounds=cf.Bounds(data=cf.Data([[-2.72, -2.28], [-2.28, -1.84], .. ... [-1.84, -1.4], [-1.4, -0.96]])) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=4)) .. ... ) .. >>> alt = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'altitude', .. ... 'units': 'm', .. ... 'axis': 'Z'}, .. ... data=cf.Data([10]), .. ... bounds=cf.Bounds(data=cf.Data([[0, 20]])) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=1)) .. ... ) .. >>> crs = f.set_construct( .. ... cf.CoordinateReference( .. ... coordinate_conversion=cf.CoordinateConversion( .. ... parameters={'grid_mapping_name': 'rotated_latitude_longitude', .. ... 'grid_north_pole_latitude': 38.0, .. ... 'grid_north_pole_longitude': 190.0}), .. ... coordinates=(lat, lon) .. ... ) .. ... ) .. >>> sd = RotatedLatLonGrid.from_field(f) .. >>> print(sd) .. RotatedLatLonGrid( .. shape {Y, X}: (1, 5, 4) .. Y, grid_latitude (5,): [-0.88, ..., 0.88] degrees .. X, grid_longitude (4,): [-2.5, ..., -1.18] degrees .. Z_bounds (1, 2): [[0, 20]] m .. Y_bounds (5, 2): [[-1.1, ..., 1.1]] degrees .. X_bounds (4, 2): [[-2.72, ..., -0.96]] degrees .. ) """ extraction_xyz = cls._extract_xyz_from_field(field) extraction_param = cls._extract_crs_rotation_parameters_from_field(field) return cls(grid_latitude=extraction_xyz['Y'], grid_longitude=extraction_xyz['X'], grid_latitude_bounds=extraction_xyz['Y_bounds'], grid_longitude_bounds=extraction_xyz['X_bounds'], # altitude=extraction_xyz['Z'], # altitude_bounds=extraction_xyz['Z_bounds'], **extraction_param) def to_config(self): cfg = super(RotatedLatLonGrid, self).to_config() cfg.update( self._extract_crs_rotation_parameters_from_field(self._f) ) return cfg @property def coordinate_reference(self): """Return the coordinate reference of the RotatedLatLonGrid instance as a `cf.CoordinateReference` instance. """ return self._f.coordinate_reference( 'grid_mapping_name:rotated_latitude_longitude' ) @classmethod def _extract_crs_rotation_parameters_from_field(cls, field): # check conversion parameters if field.coordinate_reference( 'grid_mapping_name:rotated_latitude_longitude', default=False ): crs = field.coordinate_reference( 'grid_mapping_name:rotated_latitude_longitude' ) else: raise RuntimeError( f"{cls.__name__} field missing coordinate conversion " f"'grid_mapping_name:rotated_latitude_longitude" ) if crs.coordinate_conversion.has_parameter('grid_north_pole_latitude'): grid_north_pole_lat = crs.coordinate_conversion.get_parameter( 'grid_north_pole_latitude') else: raise RuntimeError( f"{cls.__name__} field coordinate conversion missing " f"property 'grid_north_pole_latitude'" ) if crs.coordinate_conversion.has_parameter('grid_north_pole_longitude'): grid_north_pole_lon = crs.coordinate_conversion.get_parameter( 'grid_north_pole_longitude') else: raise RuntimeError( f"{cls.__name__} field coordinate conversion missing " f"property 'grid_north_pole_longitude'" ) if crs.coordinate_conversion.has_parameter('north_pole_grid_longitude'): north_pole_grid_lon = crs.coordinate_conversion.get_parameter( 'north_pole_grid_longitude') else: north_pole_grid_lon = 0. return { 'grid_north_pole_latitude': grid_north_pole_lat, 'grid_north_pole_longitude': grid_north_pole_lon, 'north_pole_grid_longitude': north_pole_grid_lon } def _set_crs_parameters(self, grid_north_pole_latitude, grid_north_pole_longitude, north_pole_grid_longitude): # WGS84 coord_conversion = cf.CoordinateConversion( parameters={'grid_mapping_name': 'latitude_longitude', 'unit_conversion_factor': 0.0174532925199433}) datum = cf.Datum( parameters={'geographic_crs_name': 'WGS 84', 'horizontal_datum_name': 'WGS_1984', 'semi_major_axis': 6378137.0, 'inverse_flattening': 298.257223563, 'longitude_of_prime_meridian': 0.0} ) self._f.set_construct( cf.CoordinateReference( datum=datum, coordinate_conversion=coord_conversion, coordinates=[self._f.dim(self._Y_name, key=True), self._f.dim(self._X_name, key=True), self._f.aux('latitude', key=True), self._f.aux('longitude', key=True)] ) ) # Rotated Grid coord_conversion = cf.CoordinateConversion( parameters={'grid_mapping_name': 'rotated_latitude_longitude', 'unit_conversion_factor': 0.0174532925199433, 'grid_north_pole_latitude': grid_north_pole_latitude, 'grid_north_pole_longitude': grid_north_pole_longitude, 'north_pole_grid_longitude': north_pole_grid_longitude} ) datum = cf.Datum( parameters={'horizontal_datum_name': 'WGS_1984', 'semi_major_axis': 6378137.0, 'inverse_flattening': 298.257223563, 'longitude_of_prime_meridian': 0.0} ) self._f.set_construct( cf.CoordinateReference( datum=datum, coordinate_conversion=coord_conversion, coordinates=[self._f.dim(self._Y_name, key=True), self._f.dim(self._X_name, key=True), self._f.aux('latitude', key=True), self._f.aux('longitude', key=True)] ) ) def _check_crs_rotation_parameters(self, coord_ref): if hasattr(coord_ref, 'coordinate_conversion'): # eliminate 'unit'/'units' parameter as it is not standardised in # the CF convention, and the split of the coordinate reference into # coordinate conversion/datum is a CF data model artifact so they # are bundled in as one and can share parameters in CF-netCDF # (which can result in one unit parameter overwriting another) for p in ['unit', 'units']: coord_ref.coordinate_conversion.del_parameter(p, None) conversion = self._f.coordinate_reference( 'grid_mapping_name:rotated_latitude_longitude' ).coordinate_conversion.equals(coord_ref.coordinate_conversion) else: conversion = False return conversion def _rotate_and_set_lat_lon(self, grid_north_pole_latitude, grid_north_pole_longitude, north_pole_grid_longitude): # define transformation from rotated lat/lon to 'true' lat/lon trans = pyproj.Transformer.from_crs( # Rotated Grid f"+proj=ob_tran +o_proj=lonlat +ellps=WGS84 +datum=WGS84 " f"+o_lat_p={grid_north_pole_latitude} " f"+o_lon_p={north_pole_grid_longitude} " f"+lon_0={grid_north_pole_longitude + 180.}", # WGS84 'epsg:4326', always_xy=True ) # project coordinates lon, lat = trans.transform(*np.meshgrid(self.X.array, self.Y.array)) # project coordinate bounds lon_bnds = np.zeros(lon.shape + (4,), lon.dtype) lat_bnds = np.zeros(lat.shape + (4,), lat.dtype) lon_bnds[..., 0], lat_bnds[..., 0] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 0], self.Y_bounds.array[..., 0]) ) lon_bnds[..., 1], lat_bnds[..., 1] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 1], self.Y_bounds.array[..., 0]) ) lon_bnds[..., 2], lat_bnds[..., 2] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 1], self.Y_bounds.array[..., 1]) ) lon_bnds[..., 3], lat_bnds[..., 3] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 0], self.Y_bounds.array[..., 1]) ) # set constructs self._f.set_construct( cf.AuxiliaryCoordinate( properties={'standard_name': 'latitude', 'units': 'degrees_north'}, data=cf.Data(lat), bounds=cf.Bounds(data=cf.Data(lat_bnds)) ), axes=['Y', 'X'] ) self._f.set_construct( cf.AuxiliaryCoordinate( properties={'standard_name': 'longitude', 'units': 'degrees_east'}, data=cf.Data(lon), bounds=cf.Bounds(data=cf.Data(lon_bnds)) ), axes=['Y', 'X'] ) def is_space_equal_to(self, field, ignore_z=False): """Compare equality between the RotatedLatLonGrid and the spatial (X, Y, and Z) dimension coordinate in a `cf.Field`. The coordinate values, the bounds, the units, and the coordinate conversion and its datum of the field are compared against those of the Grid. :Parameters: field: `cf.Field` The field that needs to be compared against RotatedLatLonGrid. ignore_z: `bool`, optional Option to ignore the dimension coordinate along the Z axis. If not provided, set to default False (i.e. Z is not ignored). :Returns: `bool` """ # check whether X/Y(/Z if not ignored) constructs are identical # and if coordinate_reference match (by checking its # coordinate_conversion and its datum separately, because # coordinate_reference.equals() would also check the size of # the collections of coordinates, which may be rightfully # different if Z is ignored) y_x_z = super(RotatedLatLonGrid, self).is_space_equal_to(field, ignore_z) conversion = False if hasattr(field, 'coordinate_reference'): if field.coordinate_reference('grid_mapping_name:' 'rotated_latitude_longitude', default=False): conversion = self._check_crs_rotation_parameters( field.coordinate_reference( 'grid_mapping_name:rotated_latitude_longitude' ) ) return y_x_z and conversion def spans_same_region_as(self, rotated_grid, ignore_z=False): """Compare equality in region spanned between the RotatedLatLonGrid and another instance of RotatedLatLonGrid. For each axis, the lower bound of their first cell and the upper bound of their last cell are compared. :Parameters: rotated_grid: `RotatedLatLonGrid` The other RotatedLatLonGrid to be compared against RotatedLatLonGrid. ignore_z: `bool`, optional If True, the dimension coordinates along the Z axes of the RotatedLatLonGrid instances will not be compared. If not provided, set to default value False (i.e. Z is not ignored). :Returns: `bool` """ if not isinstance(rotated_grid, RotatedLatLonGrid): return False else: y_x_z = super(RotatedLatLonGrid, self).spans_same_region_as( rotated_grid, ignore_z ) if hasattr(rotated_grid, 'coordinate_reference'): conversion = self._check_crs_rotation_parameters( rotated_grid.coordinate_reference ) else: conversion = False return y_x_z and conversion class BritishNationalGrid(Grid): """This class characterises the spatial dimension for a `Component` as a regular grid on a cartesian domain whose coordinates are northings and eastings covering Great Britain and Northern Ireland (`EPSG:27700 <https://epsg.io/27700>`_). """ # characteristics of the dimension coordinates _Z_name = 'altitude' _Y_name = 'projection_y_coordinate' _X_name = 'projection_x_coordinate' _Z_units = ['m', 'metre', 'meter', 'metres', 'meters'] _Y_units = ['m', 'metre', 'meter', 'metres', 'meters'] _X_units = ['m', 'metre', 'meter', 'metres', 'meters'] _Z_limits = None _Y_limits = (0, 1300000) _X_limits = (0, 700000) # contiguity of lower and upper limits _Z_limits_contiguous = False _Y_limits_contiguous = False _X_limits_contiguous = False # allow domain to wrap around limits _Z_wrap_around = False _Y_wrap_around = False _X_wrap_around = False def __init__( self, projection_y_coordinate, projection_x_coordinate, projection_y_coordinate_bounds, projection_x_coordinate_bounds, # altitude=None, altitude_bounds=None ): """**Instantiation** :Parameters: projection_y_coordinate: one-dimensional array-like object The array of northing coordinates in metres defining a spatial dimension of the domain. May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. Coordinates must be ordered positively. *Parameter example:* :: projection_y_coordinate=[12500, 13500, 14500] *Parameter example:* :: projection_y_coordinate=numpy.arange(12500, 15500, 1000) projection_x_coordinate: one-dimensional array-like object The array of easting coordinates in metres defining a spatial dimension of the domain. May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. Coordinates must be ordered positively. *Parameter example:* :: projection_x_coordinate=(80500, 81500, 82500, 83500) *Parameter example:* :: projection_x_coordinate=numpy.arange(80500, 84500, 1000) projection_y_coordinate_bounds: two-dimensional array-like object The array of northing coordinate bounds in metres defining the extent of the grid cell around the coordinate. May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *projection_y_coordinate* and the second dimension equal to 2. Must contain numerical values. *Parameter example:* :: projection_y_coordinate_bounds=[ [12e3, 13e3], [13e3, 14e3], [14e3, 15e3] ] *Parameter example:* :: projection_y_coordinate_bounds=numpy.column_stack( (numpy.arange(12000, 15000, 1000), numpy.arange(13000, 16000, 1000)) ) projection_x_coordinate_bounds: two-dimensional array-like object The array of easting coordinate bounds in metres defining the extent of the grid cell around the coordinate. May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *projection_x_coordinate* and the second dimension equal to 2. Must contain numerical values. *Parameter example:* :: projection_x_coordinate_bounds=((80e3, 81e3), (81e3, 82e3), (82e3, 83e3), (83e3, 84e3)) *Parameter example:* :: projection_x_coordinate_bounds=numpy.column_stack( (numpy.arange(80000, 84000, 1000), numpy.arange(81000, 85000, 1000)) ) .. altitude: one-dimensional array-like object, optional The array of altitude coordinates in metres defining a spatial dimension of the domain (with upwards as the positive direction). May be any type that can be cast to a `numpy.ndarray`. Must contain numerical values. Ignored if *altitude_bounds* not also provided. *Parameter example:* :: altitude=[10] .. altitude_bounds: two-dimensional array-like object, optional The array of altitude coordinate bounds in metres defining the extent of the grid cell around the coordinate (with upwards as the positive direction). May be any type that can be cast to a `numpy.ndarray`. Must be two dimensional with the first dimension equal to the size of *altitude* and the second dimension equal to 2. Must contain numerical values. Ignored if *altitude* not also provided. *Parameter example:* :: altitude_bounds=[[0, 20]] **Examples** Instantiating a 2D grid: >>> import numpy >>> sd = BritishNationalGrid( ... projection_y_coordinate=[12500, 13500, 14500], ... projection_x_coordinate=(80500, 81500, 82500, 83500), ... projection_y_coordinate_bounds=numpy.column_stack( ... (numpy.arange(12000, 15000, 1000), ... numpy.arange(13000, 16000, 1000)) ... ), ... projection_x_coordinate_bounds=numpy.column_stack( ... (numpy.arange(80000, 84000, 1000), ... numpy.arange(81000, 85000, 1000)) ... ) ... ) >>> print(sd) BritishNationalGrid( shape {Y, X}: (3, 4) Y, projection_y_coordinate (3,): [12500, 13500, 14500] m X, projection_x_coordinate (4,): [80500, ..., 83500] m Y_bounds (3, 2): [[12000, ..., 15000]] m X_bounds (4, 2): [[80000, ..., 84000]] m ) .. Instantiating a 3D grid: .. .. >>> import numpy .. >>> sd = BritishNationalGrid( .. ... projection_y_coordinate=[12500, 13500, 14500], .. ... projection_x_coordinate=(80500, 81500, 82500, 83500), .. ... projection_y_coordinate_bounds=numpy.column_stack( .. ... (numpy.arange(12000, 15000, 1000), .. ... numpy.arange(13000, 16000, 1000)) .. ... ), .. ... projection_x_coordinate_bounds=numpy.column_stack( .. ... (numpy.arange(80000, 84000, 1000), .. ... numpy.arange(81000, 85000, 1000)) .. ... ), .. ... altitude=[10], .. ... altitude_bounds=[[0, 20]] .. ... ) .. >>> print(sd) .. BritishNationalGrid( .. shape {Z, Y, X}: (1, 3, 4) .. Z, altitude (1,): [10] m .. Y, projection_y_coordinate (3,): [12500, 13500, 14500] m .. X, projection_x_coordinate (4,): [80500, ..., 83500] m .. Z_bounds (1, 2): [[0, 20]] m .. Y_bounds (3, 2): [[12000, ..., 15000]] m .. X_bounds (4, 2): [[80000, ..., 84000]] m .. ) """ super(BritishNationalGrid, self).__init__() # TODO: reintroduce Z dimension when 3D components # are effectively supported # if altitude is not None and altitude_bounds is not None: # self._set_space(altitude, altitude_bounds, name=self._Z_name, # units=self._Z_units[0], axis='Z', # limits=self._Z_limits, wrap_around=self._Z_wrap_around) # self._f.dim('Z').set_property('positive', 'up') self._set_space(projection_y_coordinate, projection_y_coordinate_bounds, name=self._Y_name, units=self._Y_units[0], axis='Y', limits=self._Y_limits, wrap_around=self._Y_wrap_around) self._set_space(projection_x_coordinate, projection_x_coordinate_bounds, name=self._X_name, units=self._X_units[0], axis='X', limits=self._X_limits, wrap_around=self._X_wrap_around) self._project_and_set_lat_lon() self._set_crs_parameters() # set dummy data needed for using inner field for remapping self._set_dummy_data() @classmethod def from_extent_and_resolution( cls, projection_y_coordinate_extent, projection_x_coordinate_extent, projection_y_coordinate_resolution, projection_x_coordinate_resolution, projection_y_coordinate_projection_x_coordinate_location='centre', # altitude_extent=None, # altitude_resolution=None, # altitude_location='centre' ): """Instantiate a `BritishNationalGrid` from the extent and the resolution of northing, easting coordinates. :Parameters: projection_y_coordinate_extent: pair of `float` or `int` The extent of northing coordinates in metres for the desired grid. The first element of the pair is the location of the start of the extent along the northing coordinate, the second element of the pair is the location of the end of the extent along the northing coordinate. Extent must be oriented positively. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: projection_y_coordinate_extent=(12000, 15000) projection_x_coordinate_extent: pair of `float` or `int` The extent of easting coordinates in metres for the desired grid. The first element of the pair is the location of the start of the extent along the easting coordinate, the second element of the pair is the location of the end of the extent along the easting coordinate. Extent must be oriented positively. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: projection_x_coordinate_extent=(80000, 84000) projection_y_coordinate_resolution: `float` or `int` The spacing between two consecutive northing coordinates in metres for the desired grid. Must be positive. *Parameter example:* :: projection_y_coordinate_resolution=1000 projection_x_coordinate_resolution: `float` or `int` The spacing between two consecutive easting coordinates in metres for the desired grid. Must be positive. *Parameter example:* :: projection_x_coordinate_resolution=1000 projection_y_coordinate_projection_x_coordinate_location: `str` or `int`, optional The location of the northing and easting coordinates in relation to their grid cells (i.e. their bounds). This information is required to generate the latitude and longitude bounds for each grid coordinate. If not provided, set to default 'centre'. The locations left and right are related to the easting coordinates (X-axis), while the locations lower and upper are related to the northing coordinates (Y-axis). The orientation of the coordinate system considered is detailed below (i.e. positive directions are northwards and eastwards). .. seealso:: *latitude_longitude_location* in `LatLonGrid.from_extent_and_resolution` .. altitude_extent: pair of `float` or `int`, optional The extent of altitude coordinate in metres for the desired grid. The first element of the pair is the location of the start of the extent along the altitude coordinate, the second element of the pair is the location of the end of the extent along the altitude coordinate. May be any type that can be unpacked (e.g. `tuple`, `list`, `numpy.ndarray`). *Parameter example:* :: altitude_extent=(0, 20) .. altitude_resolution: `float` or `int`, optional The spacing between two consecutive altitude coordinates in metres for the desired grid. *Parameter example:* :: altitude_resolution=20 .. altitude_location: `str` or `int`, optional The location of the altitude coordinates in relation to their grid cells (i.e. their bounds). This information is required to generate the altitude bounds for each grid coordinate. If not provided, set to default 'centre'. The locations top and bottom are related to the altitude coordinate (Z-axis). The orientation of the coordinate system considered is such that the positive direction is upwards. .. seealso:: *altitude_location* in `LatLonGrid.from_extent_and_resolution` :Returns: `BritishNationalGrid` **Examples** .. Instantiating grid with optional altitude coordinates: .. .. >>> sd = BritishNationalGrid.from_extent_and_resolution( .. ... projection_y_coordinate_extent=(12000, 15000), .. ... projection_x_coordinate_extent=(80000, 84000), .. ... projection_y_coordinate_resolution=1000, .. ... projection_x_coordinate_resolution=1000, .. ... altitude_extent=(0, 20), .. ... altitude_resolution=20 .. ... ) .. >>> print(sd) .. BritishNationalGrid( .. shape {Z, Y, X}: (1, 3, 4) .. Z, altitude (1,): [10.0] m .. Y, projection_y_coordinate (3,): [12500.0, 13500.0, 14500.0] m .. X, projection_x_coordinate (4,): [80500.0, ..., 83500.0] m .. Z_bounds (1, 2): [[0.0, 20.0]] m .. Y_bounds (3, 2): [[12000.0, ..., 15000.0]] m .. X_bounds (4, 2): [[80000.0, ..., 84000.0]] m .. ) Instantiating grid using non-standard coordinates location in their cells: >>> sd = BritishNationalGrid.from_extent_and_resolution( ... projection_y_coordinate_extent=(12000, 15000), ... projection_x_coordinate_extent=(80000, 84000), ... projection_y_coordinate_resolution=1000, ... projection_x_coordinate_resolution=1000, ... projection_y_coordinate_projection_x_coordinate_location='upper right' ... ) >>> print(sd) BritishNationalGrid( shape {Y, X}: (3, 4) Y, projection_y_coordinate (3,): [13000.0, 14000.0, 15000.0] m X, projection_x_coordinate (4,): [81000.0, ..., 84000.0] m Y_bounds (3, 2): [[12000.0, ..., 15000.0]] m X_bounds (4, 2): [[80000.0, ..., 84000.0]] m ) """ return super(BritishNationalGrid, cls).from_extent_and_resolution( projection_y_coordinate_extent=projection_y_coordinate_extent, projection_x_coordinate_extent=projection_x_coordinate_extent, projection_y_coordinate_resolution=projection_y_coordinate_resolution, projection_x_coordinate_resolution=projection_x_coordinate_resolution, projection_y_coordinate_projection_x_coordinate_location=( projection_y_coordinate_projection_x_coordinate_location ), # altitude_extent=altitude_extent, # altitude_resolution=altitude_resolution, # altitude_location=altitude_location ) @classmethod def from_field(cls, field): """Instantiate a `BritishNationalGrid` from spatial dimension coordinates of a `cf.Field`. :Parameters: field: `cf.Field` The field object that will be used to instantiate a `BritishNationalGrid` instance. This field must feature a 'projection_y_coordinate' and a 'projection_x_coordinate' dimension coordinates, and these must feature bounds. In addition, the coordination conversion 'transverse_mercator' must correspond to the parameters of the British National Grid (`EPSG:27700`_). .. This field may optionally feature an 'altitude' dimension coordinate alongside its bounds (both required otherwise ignored). .. _`EPSG:27700`: https://epsg.io/27700 :Returns: `BritishNationalGrid` **Examples** Instantiating from a 2D field: >>> import cf >>> import numpy >>> f = cf.Field() >>> yc = f.set_construct( ... cf.DimensionCoordinate( ... properties={'standard_name': 'projection_y_coordinate', ... 'units': 'metres', ... 'axis': 'Y'}, ... data=cf.Data([12500, 13500, 14500]), ... bounds=cf.Bounds( ... data=cf.Data( ... numpy.column_stack( ... (numpy.arange(12000, 15000, 1000), ... numpy.arange(13000, 16000, 1000)) ... ) ... ) ... ) ... ), ... axes=f.set_construct(cf.DomainAxis(size=3)) ... ) >>> xc = f.set_construct( ... cf.DimensionCoordinate( ... properties={'standard_name': 'projection_x_coordinate', ... 'units': 'metres', ... 'axis': 'X'}, ... data=cf.Data([80500, 81500, 82500, 83500]), ... bounds=cf.Bounds( ... data=cf.Data( ... numpy.column_stack( ... (numpy.arange(80000, 84000, 1000), ... numpy.arange(81000, 85000, 1000)) ... ) ... ) ... ) ... ), ... axes=f.set_construct(cf.DomainAxis(size=4)) ... ) >>> crs = f.set_construct( ... cf.CoordinateReference( ... coordinate_conversion=cf.CoordinateConversion( ... parameters={'grid_mapping_name': 'transverse_mercator', ... 'projected_crs_name': 'OSGB 1936 / British National Grid', ... 'latitude_of_projection_origin': 49.0, ... 'longitude_of_central_meridian': -2.0, ... 'scale_factor_at_central_meridian': 0.9996012717, ... 'false_easting': 400000.0, ... 'false_northing': -100000.0, ... 'unit_conversion_factor': 0.0174532925199433} ... ), ... datum=cf.Datum( ... parameters={'geographic_crs_name': 'OSGB 1936', ... 'horizontal_datum_name': 'OSGB_1936', ... 'semi_major_axis': 6377563.396, ... 'inverse_flattening': 299.3249646, ... 'towgs84': [375., -111., 431., 0., 0., 0., 0.], ... 'longitude_of_prime_meridian': 0.0} ... ), ... coordinates=(yc, xc) ... ) ... ) >>> sd = BritishNationalGrid.from_field(f) >>> print(sd) BritishNationalGrid( shape {Y, X}: (3, 4) Y, projection_y_coordinate (3,): [12500, 13500, 14500] m X, projection_x_coordinate (4,): [80500, ..., 83500] m Y_bounds (3, 2): [[12000, ..., 15000]] m X_bounds (4, 2): [[80000, ..., 84000]] m ) Using the field interface back and forth: >>> sd1 = BritishNationalGrid.from_extent_and_resolution( ... projection_y_coordinate_extent=(12000, 15000), ... projection_x_coordinate_extent=(80000, 84000), ... projection_y_coordinate_resolution=1000, ... projection_x_coordinate_resolution=1000, ... ) >>> sd2 = BritishNationalGrid.from_field(sd1.to_field()) >>> sd2 == sd1 True .. Instantiating from a 3D field: .. .. >>> import cf .. >>> import numpy .. >>> f = cf.Field() .. >>> yc = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'projection_y_coordinate', .. ... 'units': 'metres', .. ... 'axis': 'Y'}, .. ... data=cf.Data([12500, 13500, 14500]), .. ... bounds=cf.Bounds( .. ... data=cf.Data( .. ... numpy.column_stack( .. ... (numpy.arange(12000, 15000, 1000), .. ... numpy.arange(13000, 16000, 1000)) .. ... ) .. ... ) .. ... ) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=3)) .. ... ) .. >>> xc = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'projection_x_coordinate', .. ... 'units': 'metres', .. ... 'axis': 'X'}, .. ... data=cf.Data([80500, 81500, 82500, 83500]), .. ... bounds=cf.Bounds( .. ... data=cf.Data( .. ... numpy.column_stack( .. ... (numpy.arange(80000, 84000, 1000), .. ... numpy.arange(81000, 85000, 1000)) .. ... ) .. ... ) .. ... ) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=4)) .. ... ) .. >>> alt = f.set_construct( .. ... cf.DimensionCoordinate( .. ... properties={'standard_name': 'altitude', .. ... 'units': 'm', .. ... 'axis': 'Z'}, .. ... data=cf.Data([10]), .. ... bounds=cf.Bounds(data=cf.Data([[0, 20]])) .. ... ), .. ... axes=f.set_construct(cf.DomainAxis(size=1)) .. ... ) .. >>> crs = f.set_construct( .. ... cf.CoordinateReference( .. ... coordinate_conversion=cf.CoordinateConversion( .. ... parameters={'grid_mapping_name': 'transverse_mercator', .. ... 'projected_crs_name': 'OSGB 1936 / British National Grid', .. ... 'latitude_of_projection_origin': 49.0, .. ... 'longitude_of_central_meridian': -2.0, .. ... 'scale_factor_at_central_meridian': 0.9996012717, .. ... 'false_easting': 400000.0, .. ... 'false_northing': -100000.0, .. ... 'unit_conversion_factor': 0.0174532925199433} .. ... ), .. ... datum=cf.Datum( .. ... parameters={'geographic_crs_name': 'OSGB 1936', .. ... 'horizontal_datum_name': 'OSGB_1936', .. ... 'semi_major_axis': 6377563.396, .. ... 'inverse_flattening': 299.3249646, .. ... 'towgs84': [375., -111., 431., 0., 0., 0., 0.], .. ... 'longitude_of_prime_meridian': 0.0} .. ... ), .. ... coordinates=(yc, xc) .. ... ) .. ... ) .. >>> sd = BritishNationalGrid.from_field(f) .. >>> print(sd) .. BritishNationalGrid( .. shape {Y, X}: (1, 3, 4) .. Y, projection_y_coordinate (3,): [12500, 13500, 14500] m .. X, projection_x_coordinate (4,): [80500, ..., 83500] m .. Z_bounds (1, 2): [[0, 20]] m .. Y_bounds (3, 2): [[12000, ..., 15000]] m .. X_bounds (4, 2): [[80000, ..., 84000]] m .. ) """ extraction_xyz = cls._extract_xyz_from_field(field) inst = cls( projection_y_coordinate=extraction_xyz['Y'], projection_x_coordinate=extraction_xyz['X'], projection_y_coordinate_bounds=extraction_xyz['Y_bounds'], projection_x_coordinate_bounds=extraction_xyz['X_bounds'], # altitude=extraction_xyz['Z'], # altitude_bounds=extraction_xyz['Z_bounds'] ) conversion = False if hasattr(field, 'coordinate_reference'): if field.coordinate_reference('grid_mapping_name:' 'transverse_mercator', default=False): conversion = inst._check_crs_projection_parameters( field.coordinate_reference( 'grid_mapping_name:transverse_mercator' ) ) if conversion: return inst else: raise RuntimeError( 'field coordinate reference not compatible ' 'with British National Grid (EPSG:27700)' ) @property def coordinate_reference(self): """Return the coordinate reference of the `BritishNationalGrid` instance as a `cf.CoordinateReference` instance. """ return self._f.coordinate_reference( 'grid_mapping_name:transverse_mercator' ) def _set_crs_parameters(self): # WGS84 coord_conversion = cf.CoordinateConversion( parameters={'grid_mapping_name': 'latitude_longitude', 'unit_conversion_factor': 0.0174532925199433} ) datum = cf.Datum( parameters={'geographic_crs_name': 'WGS 84', 'horizontal_datum_name': 'WGS_1984', 'semi_major_axis': 6378137.0, 'inverse_flattening': 298.257223563, 'longitude_of_prime_meridian': 0.0} ) self._f.set_construct( cf.CoordinateReference( datum=datum, coordinate_conversion=coord_conversion, coordinates=[self._f.dim(self._Y_name, key=True), self._f.dim(self._X_name, key=True), self._f.aux('latitude', key=True), self._f.aux('longitude', key=True)] ) ) # OSGB_1936/BNG coord_conversion = cf.CoordinateConversion( parameters={'grid_mapping_name': 'transverse_mercator', 'projected_crs_name': 'OSGB 1936 / British National Grid', 'latitude_of_projection_origin': 49.0, 'longitude_of_central_meridian': -2.0, 'scale_factor_at_central_meridian': 0.9996012717, 'false_easting': 400000.0, 'false_northing': -100000.0, 'unit_conversion_factor': 0.0174532925199433} ) datum = cf.Datum( parameters={'geographic_crs_name': 'OSGB 1936', 'horizontal_datum_name': 'OSGB_1936', 'semi_major_axis': 6377563.396, 'inverse_flattening': 299.3249646, 'towgs84': [375., -111., 431., 0., 0., 0., 0.], 'longitude_of_prime_meridian': 0.0} ) self._f.set_construct( cf.CoordinateReference( datum=datum, coordinate_conversion=coord_conversion, coordinates=[self._f.dim(self._Y_name, key=True), self._f.dim(self._X_name, key=True), self._f.aux('latitude', key=True), self._f.aux('longitude', key=True)] ) ) def _check_crs_projection_parameters(self, coord_ref): if (hasattr(coord_ref, 'coordinate_conversion') and hasattr(coord_ref, 'datum')): # eliminate 'unit'/'units' parameter as it is not standardised in # the CF convention, and the split of the coordinate reference into # coordinate conversion/datum is a CF data model artifact so they # are bundled in as one and can share parameters in CF-netCDF # (which can result in one unit parameter overwriting another) for p in ['unit', 'units']: coord_ref.coordinate_conversion.del_parameter(p, None) coord_ref.datum.del_parameter(p, None) coord_conversion = self._f.coordinate_reference( 'grid_mapping_name:transverse_mercator' ).coordinate_conversion.equals(coord_ref.coordinate_conversion) datum = self._f.coordinate_reference( 'grid_mapping_name:transverse_mercator' ).datum.equals(coord_ref.datum) conversion = coord_conversion and datum else: conversion = False return conversion def _project_and_set_lat_lon(self): # define transformation from BNG to 'true' lat/lon trans = pyproj.Transformer.from_crs( # British National Grid 'epsg:27700', # WGS84 'epsg:4326', always_xy=True ) # project coordinates lon, lat = trans.transform(*np.meshgrid(self.X.array, self.Y.array)) # project coordinate bounds lon_bnds = np.zeros(lon.shape + (4,), lon.dtype) lat_bnds = np.zeros(lat.shape + (4,), lat.dtype) lon_bnds[..., 0], lat_bnds[..., 0] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 0], self.Y_bounds.array[..., 0]) ) lon_bnds[..., 1], lat_bnds[..., 1] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 1], self.Y_bounds.array[..., 0]) ) lon_bnds[..., 2], lat_bnds[..., 2] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 1], self.Y_bounds.array[..., 1]) ) lon_bnds[..., 3], lat_bnds[..., 3] = trans.transform( *np.meshgrid(self.X_bounds.array[..., 0], self.Y_bounds.array[..., 1]) ) # set constructs self._f.set_construct( cf.AuxiliaryCoordinate( properties={'standard_name': 'latitude', 'units': 'degrees_north'}, data=cf.Data(lat), bounds=cf.Bounds(data=cf.Data(lat_bnds)) ), axes=['Y', 'X'] ) self._f.set_construct( cf.AuxiliaryCoordinate( properties={'standard_name': 'longitude', 'units': 'degrees_east'}, data=cf.Data(lon), bounds=cf.Bounds(data=cf.Data(lon_bnds)) ), axes=['Y', 'X'] ) @Grid.cell_area.getter def cell_area(self): """The horizontal area for the grid cells of the SpaceDomain in square metres given as a `cf.Field` and returned as a `numpy.ndarray`. :Parameters: areas: `cf.Field` The field containing the horizontal grid cell area. The shape of the data array must be the same as the SpaceDomain. The field data must contain surface area values in square metres. :Returns: `numpy.ndarray` The array containing the horizontal grid cell area values in square metres. If not set previously, computed automatically. **Examples** Retrieving automatically computed grid cell area: >>> grid = BritishNationalGrid.from_extent_and_resolution( ... projection_y_coordinate_extent=(12000, 15000), ... projection_y_coordinate_resolution=1000, ... projection_x_coordinate_extent=(80000, 84000), ... projection_x_coordinate_resolution=2000 ... ) >>> print(grid.cell_area) [[2000000. 2000000.] [2000000. 2000000.] [2000000. 2000000.]] >>> print(grid) BritishNationalGrid( shape {Y, X}: (3, 2) Y, projection_y_coordinate (3,): [12500.0, 13500.0, 14500.0] m X, projection_x_coordinate (2,): [81000.0, 83000.0] m Y_bounds (3, 2): [[12000.0, ..., 15000.0]] m X_bounds (2, 2): [[80000.0, ..., 84000.0]] m cell_area (3, 2): [[2000000.0, ..., 2000000.0]] m2 ) Manually assigning grid cell area values: >>> import numpy >>> areas = grid.to_field() >>> areas.set_data(numpy.array([[1999999, 1999999], ... [1999999, 1999999], ... [1999999, 1999999]])) >>> areas.units = 'm2' >>> grid.cell_area = areas >>> print(grid.cell_area) [[1999999. 1999999.] [1999999. 1999999.] [1999999. 1999999.]] """ if self._cell_area is None: self._cell_area = self._compute_cell_area() return self._cell_area def _compute_cell_area(self): x_side = self.X_bounds.array[:, 1] - self.X_bounds.array[:, 0] y_side = self.Y_bounds.array[:, 1] - self.Y_bounds.array[:, 0] return np.dot(y_side[:, np.newaxis], x_side[np.newaxis, :]) def is_space_equal_to(self, field, ignore_z=False): """Compare equality between the BritishNationalGrid and the spatial (X, Y, and Z) dimension coordinate in a `cf.Field`. The coordinate values, the bounds, the units, and the coordinate conversion and its datum of the field are compared against those of the BritishNationalGrid. :Parameters: field: `cf.Field` The field that needs to be compared against BritishNationalGrid. ignore_z: `bool`, optional Option to ignore the dimension coordinate along the Z axis. If not provided, set to default False (i.e. Z is not ignored). :Returns: `bool` """ # check whether X/Y(/Z if not ignored) constructs are identical # and if coordinate_reference match (by checking its # coordinate_conversion and its datum separately, because # coordinate_reference.equals() would also check the size of # the collections of coordinates, which may be rightfully # different if Z is ignored) y_x_z = super(BritishNationalGrid, self).is_space_equal_to( field, ignore_z ) conversion = False if hasattr(field, 'coordinate_reference'): if field.coordinate_reference('grid_mapping_name:' 'transverse_mercator', default=False): conversion = self._check_crs_projection_parameters( field.coordinate_reference( 'grid_mapping_name:transverse_mercator' ) ) return y_x_z and conversion def spans_same_region_as(self, grid, ignore_z=False): """Compare equality in region spanned between the RotatedLatLonGrid and another instance of RotatedLatLonGrid. For each axis, the lower bound of their first cell and the upper bound of their last cell are compared. :Parameters: grid: `BritishNationalGrid` The other BritishNationalGrid to be compared against BritishNationalGrid. ignore_z: `bool`, optional If True, the dimension coordinates along the Z axes of the BritishNationalGrid instances will not be compared. If not provided, set to default value False (i.e. Z is not ignored). :Returns: `bool` """ if not isinstance(grid, BritishNationalGrid): return False else: y_x_z = super(BritishNationalGrid, self).spans_same_region_as( grid, ignore_z ) if hasattr(grid, 'coordinate_reference'): conversion = self._check_crs_projection_parameters( grid.coordinate_reference ) else: conversion = False return y_x_z and conversion
41.55676
106
0.51428
21,624
195,483
4.471698
0.042962
0.008118
0.015823
0.012162
0.789381
0.745305
0.696461
0.659014
0.628785
0.601804
0
0.042595
0.366973
195,483
4,703
107
41.565596
0.73861
0.54792
0
0.463263
0
0
0.094355
0.028959
0
0
0
0.001276
0
1
0.059776
false
0.007472
0.004981
0.004981
0.156912
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
fe8fea4597c0df59594cbe1d20b21b18432cb95d
1,222
py
Python
tasksapi/models/utils.py
mwiens91/saltant
9e72175a896f5859ada304ad3ae4d84dfc3834db
[ "MIT" ]
3
2018-12-08T01:18:29.000Z
2018-12-14T23:18:42.000Z
tasksapi/models/utils.py
saltant-org/saltant
db498a1186fc74221f8214ad1819dd03bf4b08ac
[ "MIT" ]
3
2019-05-23T07:43:13.000Z
2021-06-10T20:46:53.000Z
tasksapi/models/utils.py
saltant-org/saltant
db498a1186fc74221f8214ad1819dd03bf4b08ac
[ "MIT" ]
2
2019-03-13T22:31:09.000Z
2019-05-03T00:18:30.000Z
"""Common bits of code used by model files.""" from django.core.validators import RegexValidator from tasksapi.constants import CONTAINER_TASK, EXECUTABLE_TASK # RegexValidator for validating a names. sane_name_validator = RegexValidator( regex=r"^[\w@+-]+$", message=" @/+/-/_ only" ) def determine_task_class(obj): """Determine the task class of an object. The object obj being passed in must be a task instance or task type, else an exception is raised. To avoid circular imports we test against the string representation of the object, which is very much unideal, but I have no better ideas right now. TODO: come up with better ideas """ obj_class_string = str(obj.__class__) if obj_class_string in ( "<class 'tasksapi.models.container_tasks.ContainerTaskInstance'>", "<class 'tasksapi.models.container_tasks.ContainerTaskType'>", ): return CONTAINER_TASK elif obj_class_string in ( "<class 'tasksapi.models.executable_tasks.ExecutableTaskInstance'>", "<class 'tasksapi.models.executable_tasks.ExecutableTaskType'>", ): return EXECUTABLE_TASK raise TypeError("Must pass in task types or instances!")
31.333333
76
0.711948
154
1,222
5.5
0.584416
0.03778
0.089728
0.03778
0.195986
0.082645
0.082645
0
0
0
0
0
0.198854
1,222
38
77
32.157895
0.865169
0.328151
0
0.111111
0
0
0.394366
0.28169
0
0
0
0.026316
0
1
0.055556
false
0.055556
0.111111
0
0.277778
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
fe96b11b1ca675ec7a8b83b8ee6947c6944d8ba1
645
py
Python
virtual/lib/python3.6/site-packages/registration/backends/default/__init__.py
Ruterana/clone_instagram
a068587ef1d1a93ec8d1c08086bf11c0fb274b83
[ "MIT" ]
33
2018-10-07T21:50:44.000Z
2022-02-16T18:16:56.000Z
virtual/lib/python3.6/site-packages/registration/backends/default/__init__.py
Ruterana/clone_instagram
a068587ef1d1a93ec8d1c08086bf11c0fb274b83
[ "MIT" ]
13
2020-01-12T13:03:07.000Z
2022-02-10T13:44:28.000Z
virtual/lib/python3.6/site-packages/registration/backends/default/__init__.py
amiinegal/Awwards
dd667a1ffbd3fa9b90c8282d44d497b3a9d0c1ed
[ "MIT", "Unlicense" ]
12
2018-11-24T16:39:12.000Z
2022-03-02T21:05:59.000Z
""" Backwards-compatible import location for the model-based activation workflow. Formerly this was the default registration workflow of django-registration, and so was found at registration.backends.default. As of the current release, however, it is no longer the default workflow (there is now no default), and has accordingly been moved to registration.backends.model_activation. Attempting to import the views or include() the URLconf found here will raise deprecation warnings to make users aware of this fact, and remind them to modify imports and include()s, as support for this location will be removed in django-registration 3.0 """
37.941176
69
0.807752
100
645
5.2
0.62
0.038462
0
0
0
0
0
0
0
0
0
0.00363
0.145736
645
16
70
40.3125
0.940109
0.984496
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
feaa2da210da61f7b4e607930a1cff0008c8d2bb
486
py
Python
kmeans.py
J040/look-up-to-the-sky-and-see
c6beb7cab172f975a3f1cb7041affbd97293548d
[ "MIT" ]
null
null
null
kmeans.py
J040/look-up-to-the-sky-and-see
c6beb7cab172f975a3f1cb7041affbd97293548d
[ "MIT" ]
null
null
null
kmeans.py
J040/look-up-to-the-sky-and-see
c6beb7cab172f975a3f1cb7041affbd97293548d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue Jun 18 10:18:52 2019 @author: João Victor Ribeiro de Jesus """ from __future__ import print_function from sklearn.cluster import KMeans import numpy as np import matplotlib.pyplot as plt def aplicarIA(dados): X = np.array(dados) kmeans = KMeans(n_clusters=2, init='k-means++', max_iter=300, n_init=10, random_state=5) classificacoes = kmeans.fit_predict(X) print('\nClassificações:',classificacoes) return classificacoes
27
92
0.728395
71
486
4.84507
0.746479
0
0
0
0
0
0
0
0
0
0
0.04878
0.156379
486
18
93
27
0.790244
0.197531
0
0
0
0
0.067885
0
0
0
0
0
0
1
0.1
false
0
0.4
0
0.6
0.2
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
feb3c5930de9be2adade63eda2efeed1623c122f
868
py
Python
com/alipay/ams/api/model/payment_method_detail_type.py
simkemc/global-open-sdk-python
408d19f6b9673cade967e167a686e25406a6c7d4
[ "MIT" ]
3
2021-07-09T07:40:13.000Z
2022-03-16T09:13:27.000Z
com/alipay/ams/api/model/payment_method_detail_type.py
simkemc/global-open-sdk-python
408d19f6b9673cade967e167a686e25406a6c7d4
[ "MIT" ]
null
null
null
com/alipay/ams/api/model/payment_method_detail_type.py
simkemc/global-open-sdk-python
408d19f6b9673cade967e167a686e25406a6c7d4
[ "MIT" ]
3
2020-06-18T03:12:35.000Z
2022-01-25T08:55:23.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- from enum import Enum, unique @unique class PaymentMethodDetailType(Enum): CARD = "CARD" EXTERNALACCOUNT = "EXTERNALACCOUNT" COUPON = "COUPON" DISCOUNT = "DISCOUNT" def to_ams_dict(self): return self.name @staticmethod def value_of(value): if not value: return None if PaymentMethodDetailType.CARD.value == value: return PaymentMethodDetailType.CARD elif PaymentMethodDetailType.EXTERNALACCOUNT.value == value: return PaymentMethodDetailType.EXTERNALACCOUNT elif PaymentMethodDetailType.COUPON.value == value: return PaymentMethodDetailType.COUPON elif PaymentMethodDetailType.DISCOUNT.value == value: return PaymentMethodDetailType.DISCOUNT else: return None
27.125
68
0.662442
77
868
7.428571
0.415584
0.096154
0.111888
0.272727
0
0
0
0
0
0
0
0.001563
0.262673
868
31
69
28
0.892188
0.048387
0
0.086957
0
0
0.040097
0
0
0
0
0
0
1
0.086957
false
0
0.043478
0.043478
0.652174
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
227fc2154c802dc9ea2afa860b3f24671c3c2b55
514
py
Python
tests/r/test_markets.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
199
2017-07-24T01:34:27.000Z
2022-01-29T00:50:55.000Z
tests/r/test_markets.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
46
2017-09-05T19:27:20.000Z
2019-01-07T09:47:26.000Z
tests/r/test_markets.py
hajime9652/observations
2c8b1ac31025938cb17762e540f2f592e302d5de
[ "Apache-2.0" ]
45
2017-07-26T00:10:44.000Z
2022-03-16T20:44:59.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.markets import markets def test_markets(): """Test module markets.py by downloading markets.csv and testing shape of extracted data has 56 rows and 5 columns """ test_path = tempfile.mkdtemp() x_train, metadata = markets(test_path) try: assert x_train.shape == (56, 5) except: shutil.rmtree(test_path) raise()
21.416667
43
0.752918
72
514
5.097222
0.569444
0.081744
0.13079
0
0
0
0
0
0
0
0
0.014252
0.180934
514
23
44
22.347826
0.857482
0.215953
0
0
0
0
0
0
0
0
0
0
0.066667
1
0.066667
false
0
0.466667
0
0.533333
0.066667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
229bb94f51b6e378252e72a15492aae1881df2a9
627
py
Python
26_htmltestrunner/try_test01.py
ITXIAOKE/XKSelenium
c023dd1933d617a5b499502567209ee5d2818eb4
[ "Apache-2.0" ]
1
2021-03-11T06:06:13.000Z
2021-03-11T06:06:13.000Z
26_htmltestrunner/try_test01.py
ITXIAOKE/XKSelenium
c023dd1933d617a5b499502567209ee5d2818eb4
[ "Apache-2.0" ]
null
null
null
26_htmltestrunner/try_test01.py
ITXIAOKE/XKSelenium
c023dd1933d617a5b499502567209ee5d2818eb4
[ "Apache-2.0" ]
null
null
null
import HtmlTestRunner import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_error(self): """ This test should be marked as error one. """ raise ValueError def test_fail(self): """ This test should fail. """ self.assertEqual(1, 2) @unittest.skip("This is a skipped test.") def test_skip(self): """ This test should be skipped. """ pass if __name__ == '__main__': unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='result222'))
24.115385
80
0.61563
70
627
5.342857
0.5
0.074866
0.096257
0.144385
0.106952
0
0
0
0
0
0
0.01087
0.266348
627
25
81
25.08
0.802174
0.14992
0
0
0
0
0.094262
0
0
0
0
0
0.142857
1
0.285714
false
0.071429
0.142857
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
229c216ec5e111d65a78478d3395c8c00f45bfbc
5,292
py
Python
test/asm_test.py
sk-/python-exceptions-improved
089f7389bb54757d768e046f2ddf095343d83f65
[ "Apache-2.0" ]
null
null
null
test/asm_test.py
sk-/python-exceptions-improved
089f7389bb54757d768e046f2ddf095343d83f65
[ "Apache-2.0" ]
null
null
null
test/asm_test.py
sk-/python-exceptions-improved
089f7389bb54757d768e046f2ddf095343d83f65
[ "Apache-2.0" ]
1
2019-11-24T22:17:56.000Z
2019-11-24T22:17:56.000Z
# Copyright 2013-2014 Sebastian Kreft # # 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 new import unittest import python_exceptions_improved.asm as asm def patch(f): return new.function(asm.patch_code(f.func_code), f.func_globals, f.func_name, f.func_defaults, f.func_closure) class Foo(object): def __init__(self): self.name = 'Foo' class AsmTest(unittest.TestCase): def testSubscrBinary(self): def f(): return [1, 2][1] self.assertEqual(f(), patch(f)()) self.assertNotIn('_s_attr', globals()) self.assertNotIn('_s_index', globals()) def testSubscBinaryWithException(self): def f(): {'1': 1}[0] with self.assertRaises(KeyError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual({'1': 1}, globals()['_s_attr']) self.assertIn('_s_index', globals()) self.assertEqual(0, globals()['_s_index']) def testSubscrDelete(self): def f(): a = {'1': 2} del a['1'] return a self.assertEqual(f(), patch(f)()) self.assertNotIn('_s_attr', globals()) self.assertNotIn('_s_index', globals()) def testSubscrDeleteWithException(self): def f(): a = {'a': 'b'} del a['1'] with self.assertRaises(KeyError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual({'a': 'b'}, globals()['_s_attr']) self.assertIn('_s_index', globals()) self.assertEqual('1', globals()['_s_index']) def testSubscrStore(self): def f(): a = [1, 2] a[0] = 2 return a self.assertEqual(f(), patch(f)()) self.assertNotIn('_s_attr', globals()) self.assertNotIn('_s_index', globals()) def testSubscrStoreWithException(self): def f(): a = [1, 2] a[2] = 2 with self.assertRaises(IndexError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual([1, 2], globals()['_s_attr']) self.assertIn('_s_index', globals()) self.assertEqual(2, globals()['_s_index']) def testNested_SubscrStoreWithException(self): def f(): a = [1, 2] b = [2, 3, 4] c = 0 return a[b[c]] with self.assertRaises(IndexError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual([1, 2], globals()['_s_attr']) self.assertIn('_s_index', globals()) self.assertEqual(2, globals()['_s_index']) def testInnerCode_SubscrStoreWithException(self): def f(): def g(): a = [1, 2] a[2] = 2 return g() with self.assertRaises(IndexError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual([1, 2], globals()['_s_attr']) self.assertIn('_s_index', globals()) self.assertEqual(2, globals()['_s_index']) def testAttrLoad(self): def f(): o = Foo() return o.name self.assertEqual(f(), patch(f)()) self.assertNotIn('_s_attr', globals()) self.assertNotIn('_s_index', globals()) def testAttrLoadWithException(self): o = Foo() def f(): return o.names with self.assertRaises(AttributeError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual(o, globals()['_s_attr']) self.assertNotIn('_s_index', globals()) def testAttrDelete(self): def f(): o = Foo() del o.name self.assertEqual(f(), patch(f)()) self.assertNotIn('_s_attr', globals()) self.assertNotIn('_s_index', globals()) def testAttrDeleteWithException(self): o = Foo() def f(): del o.names with self.assertRaises(AttributeError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual(o, globals()['_s_attr']) self.assertNotIn('_s_index', globals()) def testAttrStore(self): def f(): o = Foo() o.var = 1 self.assertEqual(f(), patch(f)()) self.assertNotIn('_s_attr', globals()) self.assertNotIn('_s_index', globals()) def testAttrStoreWithException(self): o = object() def f(): o.var = 1 with self.assertRaises(AttributeError): patch(f)() self.assertIn('_s_attr', globals()) self.assertEqual(o, globals()['_s_attr']) self.assertNotIn('_s_index', globals()) if __name__ == '__main__': unittest.main()
28.605405
81
0.560091
605
5,292
4.727273
0.208264
0.038462
0.083916
0.078322
0.58986
0.568881
0.558392
0.55
0.55
0.55
0
0.014753
0.29554
5,292
184
82
28.76087
0.752414
0.105253
0
0.666667
0
0
0.069265
0
0
0
0
0
0.407407
1
0.22963
false
0
0.022222
0.022222
0.325926
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
1
0
0
0
0
0
0
0
2
22a469dfeffc8f4aae119cac28dad12f6311965b
344
py
Python
Aulas/aula011.py
mpaullos/cursoemvideo-python
80732626b6b5471ec7fea6dc01d83931e5cfd8fb
[ "MIT" ]
null
null
null
Aulas/aula011.py
mpaullos/cursoemvideo-python
80732626b6b5471ec7fea6dc01d83931e5cfd8fb
[ "MIT" ]
null
null
null
Aulas/aula011.py
mpaullos/cursoemvideo-python
80732626b6b5471ec7fea6dc01d83931e5cfd8fb
[ "MIT" ]
null
null
null
# print('\033[0;35;40mOla Mundo\033[m') # a = 3 # b = 5 # print('Os valores são \033[1;32m{}\033[m e \033[4;035m{}'.format(a,b)) n1 = 1 n2 = 8 cores = {'limpa': '\033[m', 'azul': '\033[7;30;44m', 'amarelo': '\033[0;033m'} print('Os valores são {}{}{} e {}{}{}'.format(cores['azul'], n1, cores['limpa'], cores['amarelo'], n2, cores['limpa']))
31.272727
119
0.55814
61
344
3.147541
0.508197
0.0625
0.145833
0.177083
0
0
0
0
0
0
0
0.177258
0.130814
344
10
120
34.4
0.464883
0.348837
0
0
0
0
0.444954
0
0
0
0
0
0
1
0
false
0
0
0
0
0.25
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
22b2740f76eca6fbaaa3677eee7cd5aac4be0cd9
7,434
py
Python
test/service/test_event_service.py
stat-kwon/plugin-aws-sns-mon-webhook
2b2e966eb9231339b00dee952bd56f8fba483170
[ "Apache-2.0" ]
1
2022-02-11T02:01:44.000Z
2022-02-11T02:01:44.000Z
test/service/test_event_service.py
stat-kwon/plugin-aws-sns-mon-webhook
2b2e966eb9231339b00dee952bd56f8fba483170
[ "Apache-2.0" ]
null
null
null
test/service/test_event_service.py
stat-kwon/plugin-aws-sns-mon-webhook
2b2e966eb9231339b00dee952bd56f8fba483170
[ "Apache-2.0" ]
null
null
null
import logging import unittest from spaceone.core.unittest.runner import RichTestRunner from spaceone.tester import TestCase, print_json _LOGGER = logging.getLogger(__name__) class TestEventService(TestCase): def test_parse_all_type_of_param(self): confirm_param = {"options": {}, "data": { "SigningCertURL": "https://sns.ap-southeast-2.amazonaws.com/SimpleNotificationService-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.pem", "TopicArn": "arn:aws:sns:ap-southeast-2:1234567890:sns-phd-info-test-ver4", "SubscribeURL": "https://sns.ap-southeast-2.amazonaws.com/?Action=ConfirmSubscription&TopicArn=arn:aws:sns:ap-southeast-2:1234567890:sns-phd-info-test-ver4&Token=2336412f37fb687f5d51e6e2425dacbbac3c5c0debf3c71e76a8544d1db6416ba1c4cee67ce62f401d8f0031de0ce30bac08b8364ec3adb94c6c2a7a3f9131073616112180b039dba6d4214c07ac74ce7d8621735fe937997a0152a077328f23c1250891e93494640bde540e5621faf173a6613a2ca261eb561bc93666ec4a84", "Signature": "c0JAv7pvDZf6ikx5swCPOam9JOdgIRE4uzzpMIFLIyKu1jLd8+ax8a/HVjgXBYCWddx7YHWBS62YScFsnefI/vmrUNqrOhLiB11ntWocamyYQcvDJunN2vDf3n+Sp4WnNFlwrQnGrakPjTJ+b1Yyhw92NtkG3qtvujJrely0vJ4bkgW4o+7J1R8EDh81K/WF5oU3CP+Yk75UAiLU0mAy8zkUcCIynXbmk4o5yw/KN9rRTrGxeEJZQvrvHf1aARM2QEcvZulFJJEeVL5XBhcAAJufwamcgP0tNhH7clAKxA13NYgNZucfjwZIKcr0ScQWfuOcjxCofcC0NkYFqozkqw==", "MessageId": "aeaae1f1-cfe3-452d-be2d-8fc315894c7d", "Timestamp": "2022-03-16T11:06:53.295Z", "Type": "SubscriptionConfirmation", "Token": "2336412f37fb687f5d51e6e2425dacbbac3c5c0debf3c71e76a8544d1db6416ba1c4cee67ce62f401d8f0031de0ce30bac08b8364ec3adb94c6c2a7a3f9131073616112180b039dba6d4214c07ac74ce7d8621735fe937997a0152a077328f23c1250891e93494640bde540e5621faf173a6613a2ca261eb561bc93666ec4a84", "Message": "You have chosen to subscribe to the topic arn:aws:sns:ap-southeast-2:1234567890:sns-phd-info-test-ver4.\nTo confirm the subscription, visit the SubscribeURL included in this message.", "SignatureVersion": "1"}} cloudwatch_param = { "options": {}, "data": { "SigningCertURL": "https://sns.ap-northeast-2.amazonaws.com/SimpleNotificationService-010a507c1833636cd94bdb98bd93083a.pem", "Subject": "OK: \"ContainerInsight-pod_cpu_utilization\" in Asia Pacific (Seoul)", "SignatureVersion": "1", "TopicArn": "arn:aws:sns:ap-northeast-2:1234567890:spaceone-notification", "Message": "{\"AlarmName\":\"ContainerInsight-pod_cpu_utilization\",\"AlarmDescription\":null,\"AWSAccountId\":\"1234567890\",\"NewStateValue\":\"OK\",\"NewStateReason\":\"Thresholds Crossed: 1 out of the last 1 datapoints [0.46522264287069004 (27/06/21 13:52:00)] was not less than the lower thresholds [0.4129373661576242] or not greater than the upper thresholds [0.4700330400585261] (minimum 1 datapoint for ALARM -> OK transition).\",\"StateChangeTime\":\"2021-06-27T13:53:39.351+0000\",\"Region\":\"Asia Pacific (Seoul)\",\"AlarmArn\":\"arn:aws:cloudwatch:ap-northeast-2:257706363616:alarm:ContainerInsight-pod_cpu_utilization\",\"OldStateValue\":\"ALARM\",\"Trigger\":{\"Period\":60,\"EvaluationPeriods\":1,\"ComparisonOperator\":\"LessThanLowerOrGreaterThanUpperThreshold\",\"ThresholdMetricId\":\"ad1\",\"TreatMissingData\":\"- TreatMissingData: missing\",\"EvaluateLowSampleCountPercentile\":\"\",\"Metrics\":[{\"Id\":\"m1\",\"MetricStat\":{\"Metric\":{\"Dimensions\":[{\"value\":\"cloudone-dev-v1-eks-cluster\",\"name\":\"ClusterName\"}],\"MetricName\":\"pod_cpu_utilization\",\"Namespace\":\"ContainerInsights\"},\"Period\":60,\"Stat\":\"Average\"},\"ReturnData\":true},{\"Expression\":\"ANOMALY_DETECTION_BAND(m1, 0.592)\",\"Id\":\"ad1\",\"Label\":\"pod_cpu_utilization (expected)\",\"ReturnData\":true}]}}", "Signature": "LGJ46/jQIeVuIm8HngPVVholvGYSD2ul1C6erjiWH4PwcuDjYQOTLIdxbCzesH6KcqkUnHPKecF8yzdx4gxE70sT7rfyAEI+jcYNEkPLFJiRiwo3x3LquUu78Pud/pyjUMS7FiXajrxMw2D/t5KOf+o1//gejCZj+opuFNTe+lZ5Vr80mUKxwUtEz/KgXZ4tg9BMarTBJ3/1apg3Bs6gVRACiAz9Vy16vyrB1Nq9wsueV/Zin4zHJrlVHwAAVQhBhunfBW4+CySMZzeq1X8yyVqnlE4i29dW5fYxFzXdxrWbM8BjwCnK4au2UxwfvB6OJdgIpdiRbUn9Z0h9wnLcxw==", "MessageId": "448b4055-f4e5-5887-a547-190771c6686b", "UnsubscribeURL": "https://sns.ap-northeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-northeast-2:1234567890:spaceone-notification:4f9519e8-e213-4b33-b4a9-6cc24322f047", "Type": "Notification", "Timestamp": "2021-06-27T13:53:39.389Z" } } health_param = { "options": {}, "data": { "SigningCertURL": "https://sns.ap-southeast-2.amazonaws.com/SimpleNotificationService-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.pem", "TopicArn": "arn:aws:sns:ap-southeast-2:1234567890:phd-info-dev", "Timestamp": "2022-02-18T08:35:33.452Z", "Type": "Notification", "SignatureVersion": "1", "Signature": "ExampleSample+QUAZahFKkv0Ka8MKK7T3hPs9GExampleSample+cPGINMcfBB6EzL76aK4HnhL8vUTz/8bV46Xhh0EIExampleSample3dl69c3G63WtJM8WmLuWiQqvAILctKy9WLUl5twPQJJ+4n0wBFafWIvKGvwoA29E+QrwTsSOBk/7ZyfHRdeBBK/jNjwOBT1iJL9SIsT6+iOANr7SzhJ0Sk/SqjoQSZsb1TJvLXKu6I6D9Vv1yI/yfXdvtr4Ff6guBL6I+DE+6luQfxigzsUdsCjUlAbiLNmvsG44k6uMKfU22CwocBbLsuQkuYt73Kks4CaVE/vl+GsHc2g==", "MessageId": "3737b6d6-1c86-59a2-9111-ec5f4013dd65", "Message": "{\n \"version\": \"0\",\n \"id\": \"7bf73129-1428-4cd3-a780-95db273d1602\",\n \"detail-type\": \"AWS Health Abuse Event\",\n \"source\": \"aws.health\",\n \"account\": \"123456789012\",\n \"time\": \"2018-08-02T05:30:00Z\",\n \"region\": \"global\",\n \"resources\": [\"arn:aws:cloudfront::123456789012:distribution/DSF867DUMMY87SDF\", \"arn:aws:ec2:us-east-1:123456789012:instance/i-abcd2222\"],\n \"detail\": {\n \"eventArn\": \"arn:aws:health:global::event/AWS_ABUSE_COPYRIGHT_DMCA_REPORT_2345235545_5323_2018_08_02_02_12_98\",\n \"service\": \"ABUSE\",\n \"eventTypeCode\": \"AWS_ABUSE_COPYRIGHT_DMCA_REPORT\",\n \"eventTypeCategory\": \"issue\",\n \"startTime\": \"Thu, 02 Aug 2018 05:30:00 GMT\",\n \"eventDescription\": [{\n \"language\": \"en_US\",\n \"latestDescription\": \"A description of the event will be provided here\"\n }],\n \"affectedEntities\": [{\n \"entityValue\": \"arn:aws:cloudfront::123456789012:distribution/DSF867DUMMY87SDF\"\n }, {\n \"entityValue\": \"arn:aws:ec2:us-east-1:123456789012:instance/i-abcd2222\"\n }]\n }\n}", "UnsubscribeURL": "https://sns.ap-southeast-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:ap-southeast-2:1234567890:phd-info-dev:46b11fb0-xxxx-xxxx-xxx-xxxxxxxxxxxx"} } confirm_parsed_data = self.monitoring.Event.parse({'options': {}, 'data': confirm_param.get('data')}) print_json(confirm_parsed_data) print() cloudwatch_parsed_data = self.monitoring.Event.parse({'options': {}, 'data': cloudwatch_param.get('data')}) print_json(cloudwatch_parsed_data) print() health_parsed_data = self.monitoring.Event.parse({'options': {}, 'data': health_param.get('data')}) print_json(health_parsed_data) print() if __name__ == "__main__": unittest.main(testRunner=RichTestRunner)
109.323529
1,356
0.715631
667
7,434
7.872564
0.461769
0.012379
0.023995
0.025709
0.251571
0.222053
0.200724
0.185298
0.148734
0.131404
0
0.156978
0.127657
7,434
67
1,357
110.955224
0.652737
0
0
0.22807
0
0.122807
0.498655
0.23258
0
0
0
0
0
1
0.017544
false
0
0.070175
0
0.105263
0.122807
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
22ba26865743bd3266f2ffacb5a3c4cd61144d85
1,169
py
Python
test.py
dmreiland/Ripsnort
b3595a6a0eaa6eb4a725c1c302ccea3ac1b65b87
[ "BSD-3-Clause" ]
5
2018-07-30T23:25:39.000Z
2020-07-06T19:53:46.000Z
test.py
dmreiland/Ripsnort
b3595a6a0eaa6eb4a725c1c302ccea3ac1b65b87
[ "BSD-3-Clause" ]
null
null
null
test.py
dmreiland/Ripsnort
b3595a6a0eaa6eb4a725c1c302ccea3ac1b65b87
[ "BSD-3-Clause" ]
2
2020-01-08T02:54:56.000Z
2021-12-30T01:34:29.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import logging dirname = os.path.dirname(os.path.realpath( __file__ )) import disc_track import disc_name sys.path.append( os.path.join(dirname,"notification","audionotify") ) import audionotify sys.path.append( os.path.join(dirname,"notification","emailsmtp") ) import emailsmtp sys.path.append( os.path.join(dirname,"notification","localnotify") ) import localnotify sys.path.append( os.path.join(dirname,"notification","macnotificationcenter") ) import macnotificationcenter sys.path.append( os.path.join(dirname,"scraper") ) import scraper sys.path.append( os.path.join(dirname,"scraper","imdb") ) import imdb sys.path.append( os.path.join(dirname,"scraper","opensubtitles") ) import opensubtitles if __name__ == "__main__": email_source='email@gmail.com' email_password='password' email_server='smtp.gmail.com' logging.basicConfig(level=logging.DEBUG) disc_track.test() disc_name.test() audionotify.test() emailsmtp.test(email_source,email_password,email_server) localnotify.test() scraper.test() imdb.test() opensubtitles.test()
21.254545
79
0.737382
148
1,169
5.675676
0.277027
0.064286
0.108333
0.125
0.332143
0.332143
0.332143
0.332143
0
0
0
0.000972
0.11976
1,169
54
80
21.648148
0.815355
0.035928
0
0
0
0
0.162811
0.018683
0
0
0
0
0
1
0
false
0.060606
0.363636
0
0.363636
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
0
0
0
2
22bfb77f616ed677df517377d2e72162e1bbe853
818
py
Python
mostFrequent.py
SkyJiashu/CS440-Local-Search
8d2f1749e08105b0cb4cd7013ac25d3e7a5241eb
[ "MIT" ]
1
2019-05-24T04:19:26.000Z
2019-05-24T04:19:26.000Z
mostFrequent.py
SkyJiashu/CS440-Local-Search
8d2f1749e08105b0cb4cd7013ac25d3e7a5241eb
[ "MIT" ]
null
null
null
mostFrequent.py
SkyJiashu/CS440-Local-Search
8d2f1749e08105b0cb4cd7013ac25d3e7a5241eb
[ "MIT" ]
null
null
null
# mostFrequent.py # --------------- import util import classificationMethod class MostFrequentClassifier(classificationMethod.ClassificationMethod): """ The MostFrequentClassifier is a very simple classifier: for every test instance presented to it, the classifier returns the label that was seen most often in the training data. """ def __init__(self, legalLabels): self.guess = None self.type = "mostfrequent" def train(self, data, labels, validationData, validationLabels): """ Find the most common label in the training data. """ counter = util.Counter() counter.incrementAll(labels, 1) self.guess = counter.argMax() def classify(self, testData): """ Classify all test data as the most common label. """ return [self.guess for i in testData]
27.266667
72
0.696822
95
818
5.957895
0.557895
0.047703
0.045936
0.060071
0
0
0
0
0
0
0
0.001534
0.202934
818
29
73
28.206897
0.866564
0.375306
0
0
0
0
0.025862
0
0
0
0
0
0
1
0.25
false
0
0.166667
0
0.583333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
22cc8338eb348f882a58238faaa99d217e2d7be1
783
py
Python
data_facility_admin/api/urls.py
NYU-CI/dfadmin
071f38c62aea8ef8bf4ae82dbd672694e719b9bf
[ "CC0-1.0" ]
1
2021-04-08T05:22:35.000Z
2021-04-08T05:22:35.000Z
data_facility_admin/api/urls.py
NYU-CI/dfadmin
071f38c62aea8ef8bf4ae82dbd672694e719b9bf
[ "CC0-1.0" ]
8
2019-08-05T18:16:07.000Z
2019-10-29T18:42:53.000Z
data_facility_admin/api/urls.py
NYU-CI/dfadmin
071f38c62aea8ef8bf4ae82dbd672694e719b9bf
[ "CC0-1.0" ]
2
2019-09-11T15:24:32.000Z
2020-01-08T20:34:05.000Z
from django.conf.urls import url from data_facility_admin.api import views from rest_framework import routers api_router = routers.SimpleRouter() api_router.register(r'dfroles', views.DfRoleViewSet) api_router.register(r'users', views.UserViewSet) api_router.register(r'datasets', views.DatasetViewSet, basename='dataset') api_router.register(r'categories', views.CategoryViewSet) api_router.register(r'projects', views.ProjectViewSet, basename='project') api_router.register(r'DataStewards'.lower(), views.DataStewardViewSet) api_router.register(r'DataProviders'.lower(), views.DataProviderViewSet) api_router.register(r'DatabaseSchema'.lower(), views.DatabaseSchemaViewSet) urls = [ url(r'^db-sync', views.DatabaseSyncListView, name='db-sync') ] urls += api_router.urls
39.15
75
0.804598
99
783
6.232323
0.424242
0.145867
0.220421
0.233387
0
0
0
0
0
0
0
0
0.068966
783
19
76
41.210526
0.846365
0
0
0
0
0
0.135377
0
0
0
0
0
0
1
0
false
0
0.1875
0
0.1875
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
22ce265bca3ea69c01058c9893f51dbc7b780ed3
2,455
py
Python
models/state_request.py
JMcWhorter150/ArtemisAPI
4173010221cc9d905b591bec97c2f3ba72dce66f
[ "MIT" ]
null
null
null
models/state_request.py
JMcWhorter150/ArtemisAPI
4173010221cc9d905b591bec97c2f3ba72dce66f
[ "MIT" ]
null
null
null
models/state_request.py
JMcWhorter150/ArtemisAPI
4173010221cc9d905b591bec97c2f3ba72dce66f
[ "MIT" ]
null
null
null
from typing import Union from enum import Enum from pydantic import BaseModel, Field from datetime import date class DateQueryModel(BaseModel): gt: date = Field(default=None, alias='$gt') lt: date = Field(default=None, alias='$lt') gte: date = Field(default=None, alias='$gte') lte: date = Field(default=None, alias='$lte') class Config: schema_extra = { "example": { "$gt": "2000-01-01", "$lte": "2011-01-01" } } class NumberQueryModel(BaseModel): gt: Union[int, float] = Field(default=None, alias='$gt') lt: Union[int, float] = Field(default=None, alias='$lt') gte: Union[int, float] = Field(default=None, alias='$gte') lte: Union[int, float] = Field(default=None, alias='$lte') class Config: schema_extra = { "example": { "$gt": "15", "$lte": "24" } } class FilterModel(BaseModel): state: str = Field(...) date_filter: Union[date, DateQueryModel] = Field(default=None, alias="date") ad_count: Union[int, NumberQueryModel, None] = Field() avg_age: Union[float, int, NumberQueryModel, None] = Field() email_count: Union[int, NumberQueryModel, None] = Field() phone_count: Union[int, NumberQueryModel, None] = Field() class Config: schema_extra = { "example": { "state": "NEW YORK", "date": { "$gt": "2000-01-01", "$lt": "2005-09-31" }, "ad_count": { "$gte": 17 }, "avg_age": 21, "email_count": { "$lte": 90 }, "phone_count": 400 } } class OptionModel(BaseModel): # TODO: need validation in form key:asc or key:desc as str sortBy: str = Field() limit: int = Field() page: int = Field() skip: int = Field() class StateCountBody(BaseModel): filter: FilterModel = Field(...) options: OptionModel = Field(...) class StateRequest(BaseModel): state: str = Field(...) date_from: date = Field(...) date_to: date = Field(...) class Config: schema_extra = { "example": { "state": "GEORGIA", "date_from": "2022-02-19", "date_to": "2022-02-28" } }
28.546512
80
0.507536
252
2,455
4.876984
0.293651
0.087876
0.117168
0.153784
0.466233
0.410903
0.246542
0.089504
0.089504
0.089504
0
0.037959
0.345418
2,455
86
81
28.546512
0.72682
0.022811
0
0.219178
0
0
0.097581
0
0
0
0
0.011628
0
1
0
false
0
0.054795
0
0.506849
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
1
0
0
2
22d1f1b62c6b2bbf86ecd54ace5045b484251806
602
py
Python
python/app.py
Alex-Ueki/elm-binary-tree
1ce285533778747ed0fa1f463640fd7e6d87fd26
[ "MIT" ]
null
null
null
python/app.py
Alex-Ueki/elm-binary-tree
1ce285533778747ed0fa1f463640fd7e6d87fd26
[ "MIT" ]
null
null
null
python/app.py
Alex-Ueki/elm-binary-tree
1ce285533778747ed0fa1f463640fd7e6d87fd26
[ "MIT" ]
null
null
null
from flask import Flask, redirect, url_for, request, render_template import json app = Flask(__name__) @app.route('/') def index(): return redirect(url_for('login')) @app.route('/login', methods=['GET', 'POST']) def login(): """Gets the url path for a given username""" if request.method == 'POST': return json.dumps(url_for('tree', username=request.json)) else: return render_template('login.html') @app.route('/tree/<username>') def tree(username): # Username is currently not used, but added in as an example return render_template('binaryTree.html')
23.153846
68
0.674419
82
602
4.829268
0.52439
0.045455
0.070707
0
0
0
0
0
0
0
0
0
0.17608
602
25
69
24.08
0.798387
0.162791
0
0
0
0
0.136546
0
0
0
0
0
0
1
0.2
false
0
0.133333
0.133333
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
22d2323685dfe4f5ce30156064a87fa16fa1cff3
2,077
py
Python
tests/test_bad_os_use.py
timgates42/dlint
501acbc53f710fed00d16b443076581d03f33163
[ "BSD-3-Clause" ]
null
null
null
tests/test_bad_os_use.py
timgates42/dlint
501acbc53f710fed00d16b443076581d03f33163
[ "BSD-3-Clause" ]
null
null
null
tests/test_bad_os_use.py
timgates42/dlint
501acbc53f710fed00d16b443076581d03f33163
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import unittest import dlint class TestBadOSUse(dlint.test.base.BaseTest): def test_bad_os_usage(self): python_string = self.get_ast_node( """ import os var = 'echo "TEST"' os.popen('ls') os.popen2('ls') os.popen3('ls') os.popen4('ls') os.system(var) os.tempnam() os.tmpnam() """ ) linter = dlint.linters.BadOSUseLinter() linter.visit(python_string) result = linter.get_results() expected = [ dlint.linters.base.Flake8Result( lineno=6, col_offset=0, message=dlint.linters.BadOSUseLinter._error_tmpl ), dlint.linters.base.Flake8Result( lineno=7, col_offset=0, message=dlint.linters.BadOSUseLinter._error_tmpl ), dlint.linters.base.Flake8Result( lineno=8, col_offset=0, message=dlint.linters.BadOSUseLinter._error_tmpl ), dlint.linters.base.Flake8Result( lineno=9, col_offset=0, message=dlint.linters.BadOSUseLinter._error_tmpl ), dlint.linters.base.Flake8Result( lineno=10, col_offset=0, message=dlint.linters.BadOSUseLinter._error_tmpl ), dlint.linters.base.Flake8Result( lineno=11, col_offset=0, message=dlint.linters.BadOSUseLinter._error_tmpl ), dlint.linters.base.Flake8Result( lineno=12, col_offset=0, message=dlint.linters.BadOSUseLinter._error_tmpl ), ] assert result == expected if __name__ == "__main__": unittest.main()
25.641975
64
0.510351
186
2,077
5.462366
0.349462
0.177165
0.204724
0.192913
0.59252
0.559055
0.559055
0.559055
0.559055
0.507874
0
0.021652
0.399615
2,077
80
65
25.9625
0.793103
0.009629
0
0.509091
0
0
0.004459
0
0
0
0
0
0.018182
1
0.018182
false
0
0.072727
0
0.109091
0.018182
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
22d67cd5126b7c77eb2ba6b46e74fb18b04731e8
201
py
Python
src/1.pandas/PRACTICE_1_pandas_11.py
LTurret/NFU-Biotech-MachineLearning
3b73467846ec04e46a94a38e0c1e76bba3d1b369
[ "MIT" ]
null
null
null
src/1.pandas/PRACTICE_1_pandas_11.py
LTurret/NFU-Biotech-MachineLearning
3b73467846ec04e46a94a38e0c1e76bba3d1b369
[ "MIT" ]
null
null
null
src/1.pandas/PRACTICE_1_pandas_11.py
LTurret/NFU-Biotech-MachineLearning
3b73467846ec04e46a94a38e0c1e76bba3d1b369
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np # np.reshape() and describe() df = pd.DataFrame(np.random.randint(0, 100, 5).reshape(3, 4)) print(df) print(df.describe()) print(df.T) print((df.T).describe())
18.272727
61
0.691542
36
201
3.861111
0.555556
0.201439
0.115108
0
0
0
0
0
0
0
0
0.039548
0.119403
201
11
62
18.272727
0.745763
0.134328
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0.571429
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
22d84cf045bf0e3155fc185566efd4db375a6c79
701
py
Python
final_project/machinetranslation/tests/tests.py
sugan84/xzceb-flask_eng_fr
18adfcefd838580490eb9a74da1356d76f0ecd9d
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/tests.py
sugan84/xzceb-flask_eng_fr
18adfcefd838580490eb9a74da1356d76f0ecd9d
[ "Apache-2.0" ]
null
null
null
final_project/machinetranslation/tests/tests.py
sugan84/xzceb-flask_eng_fr
18adfcefd838580490eb9a74da1356d76f0ecd9d
[ "Apache-2.0" ]
null
null
null
import unittest from translator import englishToFrench, frenchToEnglish class TestE2F(unittest.TestCase): def test1(self): self.assertEqual(englishToFrench('Hello'), 'Bonjour') def test2(self): self.assertEqual(englishToFrench(''), None) def test3(self): self.assertNotEqual(englishToFrench('Hello'), 'Hello') class TestF2E(unittest.TestCase): def test1(self): self.assertEqual(frenchToEnglish('Bonjour'), 'Hello') def test2(self): self.assertEqual(frenchToEnglish(''), None) def test3(self): self.assertNotEqual(frenchToEnglish('Bonjour'), 'Bonjour') if __name__ == "__main__": unittest.main()
25.962963
66
0.661912
66
701
6.909091
0.348485
0.105263
0.166667
0.105263
0.45614
0.337719
0.188596
0
0
0
0
0.014414
0.208274
701
27
67
25.962963
0.807207
0
0
0.333333
0
0
0.079772
0
0
0
0
0
0.333333
1
0.333333
false
0
0.111111
0
0.555556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
fe012dc3071f98dda46e7debe43fffb92b5bafa4
105
py
Python
__aulas/Parte3/main_student.py
igormotta92/gta-exercices-python-flask
b094b987857a9be5d0677a61e44312cca891e448
[ "MIT" ]
null
null
null
__aulas/Parte3/main_student.py
igormotta92/gta-exercices-python-flask
b094b987857a9be5d0677a61e44312cca891e448
[ "MIT" ]
null
null
null
__aulas/Parte3/main_student.py
igormotta92/gta-exercices-python-flask
b094b987857a9be5d0677a61e44312cca891e448
[ "MIT" ]
null
null
null
from student_get_set import Student student1 = Student("Tiago", 37) student1 = 12.5 print(student1.age)
17.5
35
0.771429
16
105
4.9375
0.75
0
0
0
0
0
0
0
0
0
0
0.086957
0.12381
105
6
36
17.5
0.771739
0
0
0
0
0
0.04717
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.25
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
fe096c98a03e0d2ae5b2b6616cc832335563291b
556
py
Python
Mundo 1/29_exercicio.py
Kelf1729/Curso-em-video-Python
29eefcc7fd9621e7d1986e5e9d44043071f62da3
[ "MIT" ]
null
null
null
Mundo 1/29_exercicio.py
Kelf1729/Curso-em-video-Python
29eefcc7fd9621e7d1986e5e9d44043071f62da3
[ "MIT" ]
null
null
null
Mundo 1/29_exercicio.py
Kelf1729/Curso-em-video-Python
29eefcc7fd9621e7d1986e5e9d44043071f62da3
[ "MIT" ]
null
null
null
"""Criar um programa que leia a velocidade de um carro com as sequintes condições *Se ele ultrapassar 80km/h será multado com R$ 7,00 por km a mais acima do limite *Caso esteja no limite não será multado""" speed = float(input("Digite a velocidade do veículo: ")) if speed >= 80: print('A multa por ultrapassar a velocidade será de \n' 'R$ {:.2f} sendo R$ 7,00 por km a mais acima do limite'.format((speed - 80)*7)) else: print('O limite de velocidade não foi ultrapassado\n' 'Sua velocidade foi de {:.2f} km/h'.format(speed))
50.545455
89
0.68705
96
556
3.979167
0.53125
0.086387
0.020942
0.036649
0.141361
0.141361
0.141361
0.141361
0.141361
0.141361
0
0.034014
0.206835
556
11
90
50.545455
0.8322
0.359712
0
0
0
0
0.60114
0
0
0
0
0
0
1
0
false
0.285714
0
0
0
0.285714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
fe09d2845723edb62285b9f2e7f30d7e52ba5c66
303
py
Python
Server/core/views.py
mohanj098/Item-Price-Forecasting
14fc787ad4d9dcc6af03b43fa5e866cd254a99f5
[ "MIT" ]
null
null
null
Server/core/views.py
mohanj098/Item-Price-Forecasting
14fc787ad4d9dcc6af03b43fa5e866cd254a99f5
[ "MIT" ]
2
2021-03-15T15:53:22.000Z
2021-05-03T09:32:34.000Z
Server/core/views.py
mohanj098/Item-Price-Forecasting
14fc787ad4d9dcc6af03b43fa5e866cd254a99f5
[ "MIT" ]
1
2021-05-04T15:35:06.000Z
2021-05-04T15:35:06.000Z
from django.shortcuts import render #from prediction.prediction import predictionFunc from prediction.models import price, product # Create your views here. def updatePrice(): obj = product.objects.raw("SELECT pid, domain, url FROM prediction_product").distinct return obj print(updatePrice())
30.3
89
0.788779
38
303
6.263158
0.684211
0.176471
0
0
0
0
0
0
0
0
0
0
0.132013
303
10
90
30.3
0.904943
0.237624
0
0
0
0
0.204348
0
0
0
0
0
0
1
0.166667
false
0
0.333333
0
0.666667
0.166667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
fe14af5c5c385a27ff5eb02ce7e333e8f781ce22
266
py
Python
backend/arXivo/admin.py
DebadityaPal/arXivo
811b0b642887ce469827c9a530ff41036b8163a5
[ "MIT" ]
1
2021-12-07T10:32:59.000Z
2021-12-07T10:32:59.000Z
backend/arXivo/admin.py
DebadityaPal/arXivo
811b0b642887ce469827c9a530ff41036b8163a5
[ "MIT" ]
null
null
null
backend/arXivo/admin.py
DebadityaPal/arXivo
811b0b642887ce469827c9a530ff41036b8163a5
[ "MIT" ]
null
null
null
from arXivo.models import ArXivoUser from django.contrib import admin from django.contrib.auth.admin import UserAdmin class ArXivoUserAdmin(UserAdmin): model = ArXivoUser list_display = ["email", "username", "public_key"] admin.site.register(ArXivoUser)
22.166667
54
0.778195
32
266
6.40625
0.65625
0.097561
0.165854
0
0
0
0
0
0
0
0
0
0.131579
266
11
55
24.181818
0.887446
0
0
0
0
0
0.086466
0
0
0
0
0
0
1
0
false
0
0.428571
0
0.857143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
fe197052d3f22bf17757bae3d9a57de111efcc9f
1,294
py
Python
Crawl/Code/Cipin/Lrc.py
ivitan/LearnPython
f7c1c8f450f5cbcbd8cabe03711c5e0d81dfdee3
[ "MIT" ]
1
2020-02-05T12:13:31.000Z
2020-02-05T12:13:31.000Z
Crawl/Code/Cipin/Lrc.py
ivitan/LearnPython
f7c1c8f450f5cbcbd8cabe03711c5e0d81dfdee3
[ "MIT" ]
null
null
null
Crawl/Code/Cipin/Lrc.py
ivitan/LearnPython
f7c1c8f450f5cbcbd8cabe03711c5e0d81dfdee3
[ "MIT" ]
null
null
null
# -*- coding: UTF-8 -*- # Author:Vitan lrc = '''I walk these streets,searching to find The steps that we left behind Your lonely eyes stare back at mine In pictures from that time I hold my heart,closing my eyes I see your smile,lies behind In this place,you entered my life How I wish,you were still mine I know that if I see you again Beside that cafe we met I'd forget about the past Lose track of time,with you Talking about our lives To show you a whole new side of me And see the changes we've made,can we Be more than we have been Start our story again All I can say,is tell you just one thing I hold my heart,closing my eyes I see your smile,lies behind In this place,you entered my life How I wish,you were still mine I know that if I see you again Beside that cafe we met I'd forget about the past Lose track of time,with you Talking about our lives To show you a whole new side of me And see the changes we've made,can we Be more than we have been Start our story again All I can say,is tell you just one thing ''' lrc = lrc.lower() #转换为小写 # 替换所有符号 import string for i in string.punctuation: lrc = lrc.replace(i,' ') lrc = lrc.split() lrcSet = set(lrc) lrclist = list(lrcSet) result = {} for item in lrclist : result[item] = lrclist.count(item) print(result)
80.875
988
0.738022
256
1,294
3.730469
0.410156
0.016754
0.01466
0.025131
0.684817
0.684817
0.684817
0.684817
0.684817
0.684817
0
0.000972
0.204791
1,294
16
989
80.875
0.927114
0.035549
0
0
0
0.083333
0.794142
0
0
0
0
0
0
1
0
false
0
0.083333
0
0.083333
0.083333
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
a3a94903fdd44e41f11ea7e7e93311f6a6eb2e3d
155
py
Python
Basic/Calculate Factorial of A Number/SolutionbyMahima.py
MAHIMA01/Programmers-Community
49a8d09d1b8d2f7c47e67e63a4c854071cccac43
[ "MIT" ]
null
null
null
Basic/Calculate Factorial of A Number/SolutionbyMahima.py
MAHIMA01/Programmers-Community
49a8d09d1b8d2f7c47e67e63a4c854071cccac43
[ "MIT" ]
null
null
null
Basic/Calculate Factorial of A Number/SolutionbyMahima.py
MAHIMA01/Programmers-Community
49a8d09d1b8d2f7c47e67e63a4c854071cccac43
[ "MIT" ]
null
null
null
# Program to calculate Factorial of a Number. N = int(input("N = ")) def factorial(N): f = 1 for i in range(1,N+1): f *= i print(f) factorial(N)
11.923077
45
0.6
29
155
3.206897
0.62069
0.215054
0
0
0
0
0
0
0
0
0
0.025424
0.23871
155
12
46
12.916667
0.762712
0.277419
0
0
0
0
0.036364
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.142857
0.142857
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
a3b2dd0990b2d05ae82ef27ad278d149aa8ecfae
5,187
py
Python
tests/unit/test_feeder_work_types.py
DakaraProject/dakara-feeder
0e4c158dcdb0c1d72cd7340e4566ca409ca3e98d
[ "MIT" ]
null
null
null
tests/unit/test_feeder_work_types.py
DakaraProject/dakara-feeder
0e4c158dcdb0c1d72cd7340e4566ca409ca3e98d
[ "MIT" ]
17
2019-09-30T15:15:43.000Z
2022-03-31T01:41:00.000Z
tests/unit/test_feeder_work_types.py
DakaraProject/dakara-feeder
0e4c158dcdb0c1d72cd7340e4566ca409ca3e98d
[ "MIT" ]
null
null
null
from unittest import TestCase from unittest.mock import patch from dakara_feeder.feeder.work_types import ( WorkTypeAlreadyExistsError, WorkTypeInvalidError, WorkTypesFeeder, ) @patch("dakara_feeder.feeder.work_types.HTTPClientDakara", autoset=True) class WorkTypesFeederTestCase(TestCase): """Test the WorkTypesFeeder class.""" def setUp(self): # create base config self.config = {"server": {}, "kara_folder": "basepath"} @patch("dakara_feeder.feeder.work_types.check_version", autoset=True) def test_load(self, mocked_check_version, mocked_http_client_class): """Test to run side-effect tasks.""" # create the object feeder = WorkTypesFeeder(self.config, "path/to/file", progress=False) # call the method feeder.load() # assert the call mocked_check_version.assert_called_with() mocked_http_client_class.return_value.authenticate.assert_called_with() @patch("dakara_feeder.feeder.work_types.get_yaml_file_content", autoset=True) def test_feed(self, mocked_get_yaml_file_content, mocked_http_client_class): """Test to feed work types.""" # create the mock work_type = { "query_name": "wt1", "name": "Work Type 1", "name_plural": "Work types 1", } mocked_get_yaml_file_content.return_value = [work_type] # create the object feeder = WorkTypesFeeder(self.config, "path/to/file", progress=False) # call the method feeder.feed() # assert the call mocked_http_client_class.return_value.post_work_type.assert_called_with( work_type ) @patch("dakara_feeder.feeder.work_types.get_yaml_file_content", autoset=True) def test_feed_error_no_query_name( self, mocked_get_yaml_file_content, mocked_http_client_class ): """Test to feed a work type without query name.""" # create the mock work_type = { "name": "Work Type 1", "name_plural": "Work types 1", "icon_name": "icon_1", } mocked_get_yaml_file_content.return_value = [work_type] # create the object feeder = WorkTypesFeeder(self.config, "path/to/file", progress=False) # call the method with self.assertRaisesRegex( WorkTypeInvalidError, "Work type #0 must have a query name" ): feeder.feed() @patch("dakara_feeder.feeder.work_types.get_yaml_file_content", autoset=True) def test_feed_error_no_name( self, mocked_get_yaml_file_content, mocked_http_client_class ): """Test to feed a work type without name.""" # create the mock work_type = { "query_name": "wt1", "name_plural": "Work types 1", "icon_name": "icon_1", } mocked_get_yaml_file_content.return_value = [work_type] # create the object feeder = WorkTypesFeeder(self.config, "path/to/file", progress=False) # call the method with self.assertRaisesRegex( WorkTypeInvalidError, "Work type #0 must have a name" ): feeder.feed() @patch("dakara_feeder.feeder.work_types.get_yaml_file_content", autoset=True) def test_feed_error_no_name_plural( self, mocked_get_yaml_file_content, mocked_http_client_class ): """Test to feed a work type without plural name.""" # create the mock work_type = {"query_name": "wt1", "name": "Work Type 1", "icon_name": "icon_1"} mocked_get_yaml_file_content.return_value = [work_type] # create the object feeder = WorkTypesFeeder(self.config, "path/to/file", progress=False) # call the method with self.assertRaisesRegex( WorkTypeInvalidError, "Work type #0 must have a plural name" ): feeder.feed() @patch("dakara_feeder.feeder.work_types.get_yaml_file_content", autoset=True) def test_feed_error_work_type_exists( self, mocked_get_yaml_file_content, mocked_http_client_class ): """Test to feed a work type that already exists.""" # create the mocks work_type = { "query_name": "wt1", "name": "Work Type 1", "name_plural": "Work types 1", "icon_name": "icon_1", } mocked_get_yaml_file_content.return_value = [work_type] mocked_http_client_class.return_value.post_work_type.side_effect = ( WorkTypeAlreadyExistsError ) # create the object feeder = WorkTypesFeeder(self.config, "path/to/file", progress=False) # call the method with self.assertLogs("dakara_feeder.feeder.work_types", "INFO") as logger: feeder.feed() # assert the logs self.assertListEqual( logger.output, [ "INFO:dakara_feeder.feeder.work_types:Found 1 work types to create", "INFO:dakara_feeder.feeder.work_types:Work type wt1 already exists on " "server and will not be updated", ], )
34.812081
87
0.634471
621
5,187
5.014493
0.148148
0.066795
0.052987
0.086705
0.7614
0.744059
0.676622
0.676622
0.676622
0.648362
0
0.005551
0.270677
5,187
148
88
35.047297
0.817605
0.118758
0
0.541667
0
0
0.225471
0.10454
0
0
0
0
0.083333
1
0.072917
false
0
0.03125
0
0.114583
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
a3b8a98a8b4f7d0ffbb4c331d81b982e7ae94e9f
1,203
py
Python
SNDG/Sequence/Primers.py
ezequieljsosa/sndg-bio
5f709b5b572564ec1dfa40d090eca9a34295743e
[ "MIT" ]
null
null
null
SNDG/Sequence/Primers.py
ezequieljsosa/sndg-bio
5f709b5b572564ec1dfa40d090eca9a34295743e
[ "MIT" ]
null
null
null
SNDG/Sequence/Primers.py
ezequieljsosa/sndg-bio
5f709b5b572564ec1dfa40d090eca9a34295743e
[ "MIT" ]
1
2020-09-01T15:57:54.000Z
2020-09-01T15:57:54.000Z
import os import sys class Primers: pass if __name__ == "__main__": import argparse import Bio.SeqIO as bpio import os import fileinput import subprocess as sp import traceback parser = argparse.ArgumentParser(description='Download NCBI assemblies') # parser.add_argument('positional', action="store") # parser.add_argument('-p', '--primers', required=True) # parser.add_argument('-i', '--input_fasta', required=True) # parser.add_argument('-o', '--output', help="output_directory", default="./") # parser.add_argument('-o', '--output', help="output_directory", default="./") subparsers = parser.add_subparsers(help='commands', description='valid subcommands', required=True, dest='command') amplicon = subparsers.add_parser('amplicon', help='List contents') amplicon.add_argument('-o', '--output', help="output_directory", default="./") subseq = subparsers.add_parser('hits', help='List contents') subseq.add_argument('-o', '--output', help="output_directory", default="./") args = parser.parse_args() print(args) # if args.primers == "-": # for primer in fileinput.input("-"): # pass
32.513514
119
0.660017
135
1,203
5.703704
0.422222
0.1
0.11039
0.093506
0.297403
0.244156
0.244156
0.244156
0.12987
0
0
0
0.175395
1,203
36
120
33.416667
0.77621
0.329177
0
0.105263
0
0
0.197995
0
0
0
0
0
0
1
0
false
0.052632
0.421053
0
0.473684
0.052632
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
0
0
0
2
a3bc6bea55542862b888d2c6e4992758374c2d64
451
py
Python
test/get_stock_quote.py
ankit-ps/pynse
c208dacafda27fa62b662a3b9316ddbb212081e6
[ "MIT" ]
null
null
null
test/get_stock_quote.py
ankit-ps/pynse
c208dacafda27fa62b662a3b9316ddbb212081e6
[ "MIT" ]
null
null
null
test/get_stock_quote.py
ankit-ps/pynse
c208dacafda27fa62b662a3b9316ddbb212081e6
[ "MIT" ]
null
null
null
import sys import requests import traceback sys.path.append("../pynse") from pynse import Pynse p = Pynse() try: #p.get_scrip_quote("HDFCBANK") #p.get_scrip_pe("HDFCBANK") #p.get_scrip_and_sector_pe("HDFCBANK") #p.get_unique_index_list() #p.get_top_10_gainers() p.get_top_10_losers() #except requests.ConnectionError as err_c: #print "could not connect to internet" except Exception as e: print traceback.print_exc()
22.55
42
0.727273
69
451
4.478261
0.550725
0.07767
0.087379
0.110032
0
0
0
0
0
0
0
0.010526
0.157428
451
19
43
23.736842
0.802632
0.481153
0
0
0
0
0.035242
0
0
0
0
0
0
0
null
null
0
0.4
null
null
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
2
a3cbda5678544258bfb0ee1a99b7f59c887ed28e
526
py
Python
src/backup/feature_engineering/new_featureEngeneer/utils.py
wu-uw/OpenCompetition
9aa9d7a50ada1deb653d295dd8a7fe46321b9094
[ "Apache-2.0" ]
15
2019-12-22T14:26:47.000Z
2020-11-02T10:57:37.000Z
src/backup/feature_engineering/new_featureEngeneer/utils.py
GT-JLU/OpenCompetition
5262fc5fa7efd7b483c1dc09cb7747dd75e37175
[ "Apache-2.0" ]
2
2020-02-03T07:10:11.000Z
2020-02-11T16:38:56.000Z
src/backup/feature_engineering/new_featureEngeneer/utils.py
GT-JLU/OpenCompetition
5262fc5fa7efd7b483c1dc09cb7747dd75e37175
[ "Apache-2.0" ]
12
2020-01-06T14:16:52.000Z
2020-05-23T14:12:30.000Z
# encoding:utf-8 import pandas as pd def get_continue_feature(data): continus_features, discrete_features = [], [] for col in data.columns: if data[col].dtype != object: try: pd.qcut(data[col], 4) continus_features.append(col) except ValueError: discrete_features.append(col) print('Continus features are: ', continus_features) print('Discrete features are: ', discrete_features) return continus_features, discrete_features
30.941176
55
0.636882
59
526
5.508475
0.525424
0.246154
0.147692
0.196923
0
0
0
0
0
0
0
0.005222
0.271863
526
16
56
32.875
0.843342
0.026616
0
0
0
0
0.090196
0
0
0
0
0
0
1
0.076923
false
0
0.076923
0
0.230769
0.153846
0
0
0
null
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
a3cd546673a96187d696144b1a4aec2a2988c7f7
804
py
Python
week_2/ex4.py
scodes1/pyneta
73012860b49488b882898ddf0060e3f662212ed7
[ "Apache-2.0" ]
null
null
null
week_2/ex4.py
scodes1/pyneta
73012860b49488b882898ddf0060e3f662212ed7
[ "Apache-2.0" ]
null
null
null
week_2/ex4.py
scodes1/pyneta
73012860b49488b882898ddf0060e3f662212ed7
[ "Apache-2.0" ]
null
null
null
from netmiko import ConnectHandler from getpass import getpass from datetime import datetime device1 = { 'host':'cisco3.lasthop.io', 'username':'pyclass', 'password':getpass(), 'device_type':'cisco_ios' } net_connect = ConnectHandler(**device1) cfg = [ 'ip name-server 1.1.1.1', 'ip name-server 1.0.0.1', 'ip domain-lookup' ] config_change = net_connect.send_config_set(cfg) print("-"*25) print("Sending configuration to device: ") print("-"*25) print('\n') print(config_change) print('\n') print("-"*25) print('\n') verify = net_connect.send_command("ping google.com") print('-'*25) print('Testing DNS') print('-'*25) print('\n') if '!!' in verify: print("DNS confirmed working") print(verify) else: print("DNS response failed") net_connect.disconnect()
17.866667
52
0.670398
109
804
4.844037
0.486239
0.066288
0.113636
0.073864
0
0
0
0
0
0
0
0.030747
0.150498
804
44
53
18.272727
0.742313
0
0
0.257143
0
0
0.29602
0
0
0
0
0
0
1
0
false
0.057143
0.085714
0
0.085714
0.428571
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
1
0
2
a3df58277d5936a6a2796134955c62e50ea1300d
2,358
py
Python
images/replication-job/start.py
MapColonies/microcOSM
702c72c2ce27490162fe9b40ec1215cd4f37c8c3
[ "MIT" ]
null
null
null
images/replication-job/start.py
MapColonies/microcOSM
702c72c2ce27490162fe9b40ec1215cd4f37c8c3
[ "MIT" ]
55
2020-10-27T13:28:32.000Z
2021-10-17T15:43:51.000Z
images/replication-job/start.py
MapColonies/microcOSM
702c72c2ce27490162fe9b40ec1215cd4f37c8c3
[ "MIT" ]
1
2020-11-30T07:22:58.000Z
2020-11-30T07:22:58.000Z
#!/usr/bin/env python3 import os from time import sleep from osmeterium.run_command import run_command from MapColoniesJSONLogger.logger import generate_logger app_name = 'replication-job' pg_host = os.environ['POSTGRES_HOST'] pg_db = os.environ['POSTGRES_DB'] pg_user = os.environ['POSTGRES_USER'] pg_password = os.environ['POSTGRES_PASSWORD'] replication_directory = os.environ['REPLICATION_DIRECTORY'] osmosis_min_interval = 60000 osmosis_iterations = 0 osmosis_validate_schema_version = False log = None process_log = None def handle_osmosis_failure(exit_code): log.error('osmosis has failed with exit code = {0}'.format(exit_code)) exit(exit_code) def handle_osmosis_success(): log.info('osmosis successfully created a replication') # osmosis tuning: https://wiki.openstreetmap.org/wiki/Osmosis/Tuning,https://lists.openstreetmap.org/pipermail/talk/2012-October/064771.html def build_osmosis_command(min_interval, iterations, validate_schema_version): validate_schema_version = 'yes' if validate_schema_version else 'no' return 'osmosis --replicate-apidb iterations={0} minInterval={1} host={2} database={3} user={4} password={5} validateSchemaVersion={6} --write-replication workingDirectory={7}'\ .format(iterations, min_interval, pg_host, pg_db, pg_user, pg_password, validate_schema_version, replication_directory) def run_minute_replication(): osmosis_command = build_osmosis_command(osmosis_min_interval, osmosis_iterations, osmosis_validate_schema_version) run_command(osmosis_command, process_log.info, process_log.info, handle_osmosis_failure, handle_osmosis_success) def main(): log.info('{0} is up'.format(app_name)) run_minute_replication() if __name__ == "__main__": osmosis_name = 'osmosis' base_log_path = os.path.join('/var/log', app_name) service_logs_path = os.path.join(base_log_path, app_name + '.log') osmosis_logs_path = os.path.join(base_log_path, osmosis_name + '.log') os.makedirs(base_log_path, exist_ok=True) log = generate_logger(app_name, log_level='INFO', handlers=[{'type': 'rotating_file', 'path': service_logs_path},{ 'type': 'stream', 'output': 'stderr' }]) process_log = generate_logger(osmosis_name, log_level='INFO', handlers=[{'type': 'rotating_file', 'path': osmosis_logs_path}, { 'type': 'stream', 'output': 'stderr' }]) main()
46.235294
181
0.766327
321
2,358
5.302181
0.339564
0.049354
0.074031
0.024677
0.121034
0.121034
0.085781
0.085781
0.051704
0
0
0.012857
0.109415
2,358
50
182
47.16
0.797619
0.067854
0
0
1
0.025641
0.217213
0.020947
0
0
0
0
0
1
0.128205
false
0.076923
0.102564
0
0.25641
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
a3e491a7d2af660d2fce194e2f0de45040d2896d
792
py
Python
detection/views.py
omid-taj/Deepfake-Detection-Website
8ba5cb5dda05df884a25120e7b2faffe900ca251
[ "MIT" ]
1
2021-08-01T00:17:56.000Z
2021-08-01T00:17:56.000Z
detection/views.py
omid-taj/Deepfake-Detection-Website
8ba5cb5dda05df884a25120e7b2faffe900ca251
[ "MIT" ]
8
2021-03-30T13:17:39.000Z
2022-03-12T00:28:19.000Z
detection/views.py
omid-taj/Deepfake-Detection-Website
8ba5cb5dda05df884a25120e7b2faffe900ca251
[ "MIT" ]
null
null
null
from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.core.files.storage import FileSystemStorage from django.shortcuts import render, redirect # Create your views here. from django.views.generic import View from utilities import save_file class EvaluationView(LoginRequiredMixin, View): def get(self, request): files = request.user.files.all() return render(request, 'eval.html', {'files': files}) def post(self, request): try: myfile = request.FILES['myFile'] save_file(myfile, request.user) return redirect('home') except: files = request.user.files.all() return render(request, 'eval.html', {'files': files})
31.68
65
0.686869
93
792
5.817204
0.451613
0.092421
0.062847
0.077634
0.225508
0.225508
0.225508
0.225508
0.225508
0.225508
0
0
0.213384
792
25
65
31.68
0.868379
0.02904
0
0.222222
0
0
0.049479
0
0
0
0
0
0
1
0.111111
false
0
0.333333
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
a3e8158d3c247b08268673a46a78cfcf35467bdf
157
py
Python
07 Model Deployment/client.py
shekarroy15/AIML-Projects
48945108c728de1095e5b1cbfa34bf6abd74673a
[ "MIT" ]
3
2021-12-22T11:42:01.000Z
2022-03-06T13:01:14.000Z
07 Model Deployment/client.py
shekarroy15/AIML-Projects
48945108c728de1095e5b1cbfa34bf6abd74673a
[ "MIT" ]
null
null
null
07 Model Deployment/client.py
shekarroy15/AIML-Projects
48945108c728de1095e5b1cbfa34bf6abd74673a
[ "MIT" ]
null
null
null
import requests import json url="http://localhost:8111/api" data=json.dumps({'sl':3.2,'sw':7.3,'pl':4.5,'pw':2.1}) r=requests.post(url,data) print(r.json())
22.428571
54
0.675159
32
157
3.3125
0.71875
0
0
0
0
0
0
0
0
0
0
0.080537
0.050955
157
6
55
26.166667
0.630872
0
0
0
0
0
0.210191
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0.166667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2