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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a0934637dab174d27eb3c40f6d8c121af0ad2618
| 23
|
py
|
Python
|
test69.py
|
codesAliecc/hacktoberfest2021
|
2f3e5e318ab5834131c6aab75185a1b67e748b79
|
[
"Unlicense"
] | null | null | null |
test69.py
|
codesAliecc/hacktoberfest2021
|
2f3e5e318ab5834131c6aab75185a1b67e748b79
|
[
"Unlicense"
] | null | null | null |
test69.py
|
codesAliecc/hacktoberfest2021
|
2f3e5e318ab5834131c6aab75185a1b67e748b79
|
[
"Unlicense"
] | null | null | null |
print("Hello Peoples")
| 11.5
| 22
| 0.73913
| 3
| 23
| 5.666667
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.086957
| 23
| 1
| 23
| 23
| 0.809524
| 0
| 0
| 0
| 0
| 0
| 0.565217
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0
| 0
| 0
| 1
| 1
| 1
| 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
| 1
|
0
| 5
|
a097f27f84e21f6198501e954ed16a6a84266bae
| 293
|
py
|
Python
|
swf/querysets/__init__.py
|
nstott/simpleflow
|
483602deb745a09b59ad6e24052dd5096c54fad2
|
[
"MIT"
] | null | null | null |
swf/querysets/__init__.py
|
nstott/simpleflow
|
483602deb745a09b59ad6e24052dd5096c54fad2
|
[
"MIT"
] | null | null | null |
swf/querysets/__init__.py
|
nstott/simpleflow
|
483602deb745a09b59ad6e24052dd5096c54fad2
|
[
"MIT"
] | null | null | null |
# -*- coding:utf-8 -*-
from swf.querysets.activity import ActivityTypeQuerySet # NOQA
from swf.querysets.domain import DomainQuerySet # NOQA
from swf.querysets.history import HistoryQuerySet # NOQA
from swf.querysets.workflow import WorkflowTypeQuerySet, WorkflowExecutionQuerySet # NOQA
| 41.857143
| 90
| 0.808874
| 32
| 293
| 7.40625
| 0.53125
| 0.118143
| 0.270042
| 0.253165
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.003861
| 0.116041
| 293
| 6
| 91
| 48.833333
| 0.911197
| 0.136519
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 1
| 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
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 5
|
a0a45de3fcfbc0c687308e384e02ea59e4c9f7cc
| 216
|
py
|
Python
|
services/others/lamdsh/config.py
|
X5GON/lamapi
|
0558c3b7af520ab83bdbd29e1b1b9b87bdc147b0
|
[
"BSD-2-Clause"
] | null | null | null |
services/others/lamdsh/config.py
|
X5GON/lamapi
|
0558c3b7af520ab83bdbd29e1b1b9b87bdc147b0
|
[
"BSD-2-Clause"
] | null | null | null |
services/others/lamdsh/config.py
|
X5GON/lamapi
|
0558c3b7af520ab83bdbd29e1b1b9b87bdc147b0
|
[
"BSD-2-Clause"
] | null | null | null |
from .gettrans.service import ns_lamdsh as ns_gettrans
from .search.service import ns_lamdsh as ns_search
from .knnlamdsh.service import ns_lamdsh as ns_knnlamdsh
namespaces = [ns_gettrans, ns_search, ns_knnlamdsh]
| 36
| 56
| 0.837963
| 34
| 216
| 5.058824
| 0.294118
| 0.226744
| 0.261628
| 0.366279
| 0.436047
| 0.436047
| 0
| 0
| 0
| 0
| 0
| 0
| 0.111111
| 216
| 5
| 57
| 43.2
| 0.895833
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.75
| 0
| 0.75
| 0
| 0
| 0
| 0
| null | 1
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
2641e7c6c4288fd51f8ec2854e1dc5ced9eaf1e9
| 30
|
py
|
Python
|
lib/ppweb/__main__.py
|
jrmsgit/pseudoParser
|
ee6a4bb5cbd2dfc51f14b73c4191618746cfb4a7
|
[
"BSD-3-Clause"
] | 1
|
2015-08-31T01:02:22.000Z
|
2015-08-31T01:02:22.000Z
|
lib/ppweb/__main__.py
|
jrmsgit/pseudoParser
|
ee6a4bb5cbd2dfc51f14b73c4191618746cfb4a7
|
[
"BSD-3-Clause"
] | 1
|
2015-09-29T13:30:46.000Z
|
2015-09-30T18:44:11.000Z
|
lib/ppweb/__main__.py
|
jrmsgit/pseudoParser
|
ee6a4bb5cbd2dfc51f14b73c4191618746cfb4a7
|
[
"BSD-3-Clause"
] | null | null | null |
from . import wapp
wapp.Run()
| 10
| 18
| 0.7
| 5
| 30
| 4.2
| 0.8
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.166667
| 30
| 2
| 19
| 15
| 0.84
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.5
| 0
| 0.5
| 0
| 1
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
cd02f1246ded97b4622df90591bd72e5d11339b7
| 310
|
py
|
Python
|
blog/app/controller/admin/admin.py
|
henrY2Young/flask-jwt
|
f1c47efee7fd7f271c02172371c2d9cec8adde5d
|
[
"MIT"
] | null | null | null |
blog/app/controller/admin/admin.py
|
henrY2Young/flask-jwt
|
f1c47efee7fd7f271c02172371c2d9cec8adde5d
|
[
"MIT"
] | null | null | null |
blog/app/controller/admin/admin.py
|
henrY2Young/flask-jwt
|
f1c47efee7fd7f271c02172371c2d9cec8adde5d
|
[
"MIT"
] | null | null | null |
from flask import request, jsonify, Flask, render_template
from app.controller.admin import admin
from app.controller.home import home
@admin.route('/index')
def hello():
return render_template('admin/menu.html')
@admin.route('/login11')
def login():
return render_template('admin/user/login.html')
| 31
| 58
| 0.754839
| 43
| 310
| 5.372093
| 0.488372
| 0.181818
| 0.147186
| 0.21645
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.007299
| 0.116129
| 310
| 10
| 59
| 31
| 0.835766
| 0
| 0
| 0
| 0
| 0
| 0.160772
| 0.067524
| 0
| 0
| 0
| 0
| 0
| 1
| 0.222222
| true
| 0
| 0.333333
| 0.222222
| 0.777778
| 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
| 1
| 1
| 0
| 1
| 1
| 0
| 0
|
0
| 5
|
cd179725a518eacf0d13e05fa92d640585ff3624
| 100
|
py
|
Python
|
backend/editor/admin.py
|
vframeio/vcat
|
554e94a819818131ddf5ec3db9f0ca4d2795313e
|
[
"MIT"
] | 5
|
2018-11-26T07:43:39.000Z
|
2020-03-09T08:01:39.000Z
|
backend/editor/admin.py
|
vframeio/_vcat_archived
|
554e94a819818131ddf5ec3db9f0ca4d2795313e
|
[
"MIT"
] | null | null | null |
backend/editor/admin.py
|
vframeio/_vcat_archived
|
554e94a819818131ddf5ec3db9f0ca4d2795313e
|
[
"MIT"
] | 1
|
2020-04-30T11:16:04.000Z
|
2020-04-30T11:16:04.000Z
|
from django.contrib import admin
from .models import ImageRegion
admin.site.register(ImageRegion)
| 16.666667
| 32
| 0.83
| 13
| 100
| 6.384615
| 0.692308
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.11
| 100
| 5
| 33
| 20
| 0.932584
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.666667
| 0
| 0.666667
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
cd661e10d93c26dc1c81519467ec3b8a49a23dc6
| 5,062
|
py
|
Python
|
tests/test_coding/test_monitor.py
|
piotrmaslanka/satella
|
bf4ba7a21ad2ac93a366442a2b4574dc5568b87e
|
[
"MIT"
] | 12
|
2019-12-13T10:17:38.000Z
|
2022-01-05T09:01:36.000Z
|
tests/test_coding/test_monitor.py
|
piotrmaslanka/satella
|
bf4ba7a21ad2ac93a366442a2b4574dc5568b87e
|
[
"MIT"
] | 26
|
2016-04-01T11:55:26.000Z
|
2021-12-30T17:03:59.000Z
|
tests/test_coding/test_monitor.py
|
piotrmaslanka/satella
|
bf4ba7a21ad2ac93a366442a2b4574dc5568b87e
|
[
"MIT"
] | 1
|
2021-05-31T08:45:22.000Z
|
2021-05-31T08:45:22.000Z
|
import unittest
from queue import Queue
from threading import Thread
from time import sleep
from satella.coding import Monitor
class MonitorTest(unittest.TestCase):
def test_synchronize_on(self):
class TestedMasterClass(Monitor):
def __init__(self):
self.value = 0
super().__init__()
def get_locking_class(self):
class LockingClass:
@Monitor.synchronize_on(self)
def get_value(self2):
self.value += 1
return LockingClass()
msc = TestedMasterClass()
lc = msc.get_locking_class()
class TesterThread(Thread):
def run(self):
lc.get_value()
with Monitor.acquire(msc):
TesterThread().start()
sleep(0.1)
self.assertEqual(msc.value, 0)
with Monitor.release(msc):
sleep(0.1)
self.assertEqual(msc.value, 1)
def test_release_contextmanager(self):
class TestedClass(Monitor):
def __init__(self, cqueue):
self.cqueue = cqueue
Monitor.__init__(self)
@Monitor.synchronized
def execute(self):
self.cqueue.put(1)
sleep(1)
self.cqueue.get()
class TesterThread(Thread):
def __init__(self, tc):
self.tc = tc
Thread.__init__(self)
def run(self):
self.tc.execute()
cq = Queue()
cq.put(1)
tc = TestedClass(cq)
tt = TesterThread(tc)
with Monitor.acquire(tc):
with Monitor.release(tc):
tt.start()
sleep(0.4)
self.assertEqual(cq.qsize(), 2)
def test_release_contextmanager_syntax(self):
class TestedClass(Monitor):
def __init__(self, cqueue):
self.cqueue = cqueue
Monitor.__init__(self)
@Monitor.synchronized
def execute(self):
self.cqueue.put(1)
sleep(1)
self.cqueue.get()
class TesterThread(Thread):
def __init__(self, tc):
self.tc = tc
Thread.__init__(self)
def run(self):
self.tc.execute()
cq = Queue()
cq.put(1)
tc = TestedClass(cq)
tt = TesterThread(tc)
with tc:
with Monitor.release(tc):
tt.start()
sleep(0.4)
self.assertEqual(cq.qsize(), 2)
def test_acquire_contextmanager(self):
class TestedClass(Monitor):
def __init__(self, cqueue):
self.cqueue = cqueue
Monitor.__init__(self)
@Monitor.synchronized
def execute(self):
self.cqueue.put(1)
sleep(1)
self.cqueue.get()
class TesterThread(Thread):
def __init__(self, tc):
self.tc = tc
Thread.__init__(self)
def run(self):
self.tc.execute()
cq = Queue()
cq.put(1)
tc = TestedClass(cq)
tt = TesterThread(tc)
with Monitor.acquire(tc):
tt.start()
sleep(0.4)
self.assertEqual(cq.qsize(), 1)
def test_monitoring(self):
class TestedClass(Monitor):
def __init__(self, cqueue):
self.cqueue = cqueue
Monitor.__init__(self)
@Monitor.synchronized
def execute(self):
self.cqueue.put(1)
sleep(1)
self.cqueue.get()
class TesterThread(Thread):
def __init__(self, tc):
self.tc = tc
Thread.__init__(self)
def run(self):
self.tc.execute()
q = Queue()
tc = TestedClass(q)
a, b = TesterThread(tc), TesterThread(tc)
a.start(), b.start()
while a.is_alive() or b.is_alive():
sleep(0.1)
self.assertNotEqual(q.qsize(), 2)
def test_monitoring_synchronize_on_attribute(self):
class TestedClass:
def __init__(self, cqueue):
self.cqueue = cqueue
self.monitor = Monitor()
@Monitor.synchronize_on_attribute('monitor')
def execute(self):
self.cqueue.put(1)
sleep(1)
self.cqueue.get()
class TesterThread(Thread):
def __init__(self, tc):
self.tc = tc
Thread.__init__(self)
def run(self):
self.tc.execute()
q = Queue()
tc = TestedClass(q)
a, b = TesterThread(tc), TesterThread(tc)
a.start(), b.start()
while a.is_alive() or b.is_alive():
sleep(0.1)
self.assertNotEqual(q.qsize(), 2)
| 26.925532
| 56
| 0.489332
| 503
| 5,062
| 4.703777
| 0.12326
| 0.067625
| 0.051141
| 0.065934
| 0.724007
| 0.724007
| 0.724007
| 0.6847
| 0.6847
| 0.6847
| 0
| 0.012445
| 0.412683
| 5,062
| 187
| 57
| 27.069519
| 0.783384
| 0
| 0
| 0.765101
| 0
| 0
| 0.001383
| 0
| 0
| 0
| 0
| 0
| 0.04698
| 1
| 0.201342
| false
| 0
| 0.033557
| 0
| 0.33557
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
cd7e358b6e1d9c6bbabc1c2030fce768747a169f
| 222
|
py
|
Python
|
gherkin_to_markdown/expressions/code_block_expression.py
|
LeandreArseneault/gherkin_to_markdown
|
157a6a7ba5b7f1f3a159bc163bf1b1187401243a
|
[
"MIT"
] | 6
|
2022-02-14T22:10:50.000Z
|
2022-03-10T20:42:29.000Z
|
gherkin_to_markdown/expressions/code_block_expression.py
|
LeandreArseneault/gherkin_to_markdown
|
157a6a7ba5b7f1f3a159bc163bf1b1187401243a
|
[
"MIT"
] | null | null | null |
gherkin_to_markdown/expressions/code_block_expression.py
|
LeandreArseneault/gherkin_to_markdown
|
157a6a7ba5b7f1f3a159bc163bf1b1187401243a
|
[
"MIT"
] | null | null | null |
from gherkin_to_markdown.expressions.expression import Expression
class CodeBlockExpression(Expression):
def to_markdown(self, statement: str):
return f"{statement.strip().replace(self.keyword, '```', 1)}\n"
| 31.714286
| 71
| 0.743243
| 26
| 222
| 6.230769
| 0.769231
| 0.123457
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.005155
| 0.126126
| 222
| 6
| 72
| 37
| 0.829897
| 0
| 0
| 0
| 0
| 0
| 0.238739
| 0.18018
| 0
| 0
| 0
| 0
| 0
| 1
| 0.25
| false
| 0
| 0.25
| 0.25
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 5
|
cd7f23c8902556a6b6ffed8a1b8df11e5b876f03
| 51
|
py
|
Python
|
conduit/fair/data/__init__.py
|
DavidHurst/palbolts
|
72f9ca3f82499b532f14d0e797426e1b425d3efe
|
[
"MIT"
] | 2
|
2021-07-15T20:36:25.000Z
|
2021-08-04T15:53:50.000Z
|
conduit/fair/data/__init__.py
|
DavidHurst/palbolts
|
72f9ca3f82499b532f14d0e797426e1b425d3efe
|
[
"MIT"
] | 18
|
2021-09-07T13:50:10.000Z
|
2021-12-06T19:02:23.000Z
|
conduit/fair/data/__init__.py
|
predictive-analytics-lab/pal-bolts
|
5f1932f351f2e551276b47dfeda7888772d99895
|
[
"MIT"
] | 1
|
2021-09-07T14:55:16.000Z
|
2021-09-07T14:55:16.000Z
|
from .datamodules import *
from .datasets import *
| 17
| 26
| 0.764706
| 6
| 51
| 6.5
| 0.666667
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.156863
| 51
| 2
| 27
| 25.5
| 0.906977
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
cd9181ee2779e1eb2c361eadd4959343c2d633b1
| 61
|
py
|
Python
|
or_suite/envs/finite_armed_bandit/__init__.py
|
JasmineSamadi/ORSuite
|
e2b2b0a5b497ea6566e794dcef1f176081fca4ce
|
[
"MIT"
] | 4
|
2021-12-01T10:56:17.000Z
|
2022-02-06T17:07:43.000Z
|
or_suite/envs/finite_armed_bandit/__init__.py
|
JasmineSamadi/ORSuite
|
e2b2b0a5b497ea6566e794dcef1f176081fca4ce
|
[
"MIT"
] | 2
|
2021-08-11T13:25:01.000Z
|
2022-03-20T19:23:23.000Z
|
or_suite/envs/finite_armed_bandit/__init__.py
|
JasmineSamadi/ORSuite
|
e2b2b0a5b497ea6566e794dcef1f176081fca4ce
|
[
"MIT"
] | 3
|
2021-04-02T20:24:25.000Z
|
2021-04-10T23:53:28.000Z
|
from or_suite.envs.finite_armed_bandit.finite_bandit import *
| 61
| 61
| 0.885246
| 10
| 61
| 5
| 0.8
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.04918
| 61
| 1
| 61
| 61
| 0.862069
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
26972abfa3cb32cded5a95213f8f63c6e4533059
| 139
|
py
|
Python
|
9 File Processing/3_opening_file_with.py
|
narayanants/python-mega-course
|
2ba2980ab21dfbed5f86f00695559f7831b5c566
|
[
"MIT"
] | null | null | null |
9 File Processing/3_opening_file_with.py
|
narayanants/python-mega-course
|
2ba2980ab21dfbed5f86f00695559f7831b5c566
|
[
"MIT"
] | null | null | null |
9 File Processing/3_opening_file_with.py
|
narayanants/python-mega-course
|
2ba2980ab21dfbed5f86f00695559f7831b5c566
|
[
"MIT"
] | null | null | null |
myfile = open('fruits.txt','r')
print(myfile.read())
myfile.close()
with open('fruits.txt','r') as myfile:
z = myfile.read()
print(z)
| 17.375
| 38
| 0.640288
| 22
| 139
| 4.045455
| 0.5
| 0.224719
| 0.292135
| 0.314607
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.129496
| 139
| 8
| 39
| 17.375
| 0.735537
| 0
| 0
| 0
| 0
| 0
| 0.157143
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0.333333
| 1
| 0
| 0
| null | 1
| 1
| 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
| 5
|
26ba27981a1979c0d925a44a7d06de908b0ed448
| 62
|
py
|
Python
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/idna/__init__.py
|
brianherrera/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
[
"AML"
] | 1,738
|
2017-09-21T10:59:12.000Z
|
2022-03-31T21:05:46.000Z
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/idna/__init__.py
|
ArchitectureStudios/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
[
"AML"
] | 427
|
2017-09-29T22:54:36.000Z
|
2022-02-15T19:26:50.000Z
|
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_vendor/idna/__init__.py
|
ArchitectureStudios/lumberyard
|
f85344403c1c2e77ec8c75deb2c116e97b713217
|
[
"AML"
] | 671
|
2017-09-21T08:04:01.000Z
|
2022-03-29T14:30:07.000Z
|
from .package_data import __version__
from .core import *
| 20.666667
| 39
| 0.758065
| 8
| 62
| 5.25
| 0.75
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.193548
| 62
| 2
| 40
| 31
| 0.84
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
26cf06af9be344ff181f6c64a6205781fe433496
| 94
|
py
|
Python
|
MomentumProject/testFunc.py
|
hpgit/HumanFoot
|
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
|
[
"Apache-2.0"
] | null | null | null |
MomentumProject/testFunc.py
|
hpgit/HumanFoot
|
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
|
[
"Apache-2.0"
] | null | null | null |
MomentumProject/testFunc.py
|
hpgit/HumanFoot
|
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
|
[
"Apache-2.0"
] | null | null | null |
def printFunc(dIn):
print dIn
#print "hehe"
#print "kkkk"
pass
def renderFunc(rIn):
pass
| 11.75
| 20
| 0.691489
| 14
| 94
| 4.642857
| 0.642857
| 0.246154
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.180851
| 94
| 8
| 21
| 11.75
| 0.844156
| 0.255319
| 0
| 0.4
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | null | 0.4
| 0
| null | null | 0.4
| 1
| 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
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| 0
|
0
| 5
|
f8191e6230f52e27825bfabdec92050513251496
| 47
|
py
|
Python
|
test04.py
|
kmr0877/python2perl_Converter
|
7a1638418922b73b02428693eb44c7c39e2f3dbc
|
[
"MIT"
] | null | null | null |
test04.py
|
kmr0877/python2perl_Converter
|
7a1638418922b73b02428693eb44c7c39e2f3dbc
|
[
"MIT"
] | null | null | null |
test04.py
|
kmr0877/python2perl_Converter
|
7a1638418922b73b02428693eb44c7c39e2f3dbc
|
[
"MIT"
] | null | null | null |
#!/usr/bin/python3
# put your test script here
| 15.666667
| 27
| 0.723404
| 8
| 47
| 4.25
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.025
| 0.148936
| 47
| 2
| 28
| 23.5
| 0.825
| 0.914894
| 0
| null | 0
| null | 0
| 0
| null | 0
| 0
| 0
| null | 1
| null | true
| 0
| 0
| null | null | null | 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
f83d55d346eb7c5b6f78cb00c5c36f4c2baeedc7
| 162
|
py
|
Python
|
polpos/admin.py
|
InformaticsResearchCenter/kabayan
|
98139958d6b42098c233f7a6e74bef8a0edde60d
|
[
"MIT"
] | null | null | null |
polpos/admin.py
|
InformaticsResearchCenter/kabayan
|
98139958d6b42098c233f7a6e74bef8a0edde60d
|
[
"MIT"
] | null | null | null |
polpos/admin.py
|
InformaticsResearchCenter/kabayan
|
98139958d6b42098c233f7a6e74bef8a0edde60d
|
[
"MIT"
] | null | null | null |
from django.contrib import admin
from .models import PenjadwalanProdi, PenjadwalanBAAK
admin.site.register(PenjadwalanProdi)
admin.site.register(PenjadwalanBAAK)
| 32.4
| 53
| 0.864198
| 18
| 162
| 7.777778
| 0.555556
| 0.128571
| 0.242857
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.067901
| 162
| 5
| 54
| 32.4
| 0.927152
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.5
| 0
| 0.5
| 0
| 1
| 0
| 0
| null | 0
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
3e6860235426177f6d2a4c8686da6b327b823274
| 216
|
py
|
Python
|
plugins/flytekit-k8s-pod/flytekitplugins/pod/__init__.py
|
bstadlbauer/flytekit
|
12ef34d7b6d777088ab87f9cf0d5c32355895852
|
[
"Apache-2.0"
] | null | null | null |
plugins/flytekit-k8s-pod/flytekitplugins/pod/__init__.py
|
bstadlbauer/flytekit
|
12ef34d7b6d777088ab87f9cf0d5c32355895852
|
[
"Apache-2.0"
] | null | null | null |
plugins/flytekit-k8s-pod/flytekitplugins/pod/__init__.py
|
bstadlbauer/flytekit
|
12ef34d7b6d777088ab87f9cf0d5c32355895852
|
[
"Apache-2.0"
] | null | null | null |
"""
.. currentmodule:: flytekitplugins.pod
This package contains things that are useful when extending Flytekit.
.. autosummary::
:template: custom.rst
:toctree: generated/
Pod
"""
from .task import Pod
| 15.428571
| 69
| 0.712963
| 24
| 216
| 6.416667
| 0.916667
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.180556
| 216
| 13
| 70
| 16.615385
| 0.870057
| 0.851852
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 0
| 1
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 5
|
e40f0071208c0abd014ba740dda401ca996262c2
| 86
|
py
|
Python
|
aaisp/admin.py
|
0xdc/django-aaisp-bandwidth
|
e7a50ec71438768c45eb01f51db8ad1e41426d71
|
[
"MIT"
] | null | null | null |
aaisp/admin.py
|
0xdc/django-aaisp-bandwidth
|
e7a50ec71438768c45eb01f51db8ad1e41426d71
|
[
"MIT"
] | 1
|
2017-09-13T16:48:54.000Z
|
2017-09-13T16:48:54.000Z
|
aaisp/admin.py
|
0xdc/django-aaisp-bandwidth
|
e7a50ec71438768c45eb01f51db8ad1e41426d71
|
[
"MIT"
] | null | null | null |
from django.contrib import admin
from .models import Line
admin.site.register(Line)
| 14.333333
| 32
| 0.802326
| 13
| 86
| 5.307692
| 0.692308
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.127907
| 86
| 5
| 33
| 17.2
| 0.92
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.666667
| 0
| 0.666667
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
e4145d5201f4887bb8db2b86dfb49088c4bd7b7d
| 152
|
py
|
Python
|
Replace_With_Alphabet_Position/code.py
|
brunopasseti/CodeWarsKatas
|
156e06111383b613e5bf3d522a04bc3203799e1b
|
[
"MIT"
] | null | null | null |
Replace_With_Alphabet_Position/code.py
|
brunopasseti/CodeWarsKatas
|
156e06111383b613e5bf3d522a04bc3203799e1b
|
[
"MIT"
] | null | null | null |
Replace_With_Alphabet_Position/code.py
|
brunopasseti/CodeWarsKatas
|
156e06111383b613e5bf3d522a04bc3203799e1b
|
[
"MIT"
] | null | null | null |
def alphabet_position(text):
return " ".join([str(ord(l)-ord('a')+1)
for w in text.lower() for l in w if l.isalpha() == True])
| 38
| 78
| 0.539474
| 25
| 152
| 3.24
| 0.72
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.009091
| 0.276316
| 152
| 3
| 79
| 50.666667
| 0.727273
| 0
| 0
| 0
| 0
| 0
| 0.013158
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| false
| 0
| 0
| 0.333333
| 0.666667
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 5
|
e452897742daed12c741f071b63b1d511d5c964f
| 104
|
py
|
Python
|
src/cameras/__init__.py
|
KingAbbott/devsyn
|
ef26855c5b96e489d390a32005cc75e603d32ce2
|
[
"MIT"
] | 1
|
2016-05-08T23:39:51.000Z
|
2016-05-08T23:39:51.000Z
|
src/cameras/__init__.py
|
KingAbbott/devsyn
|
ef26855c5b96e489d390a32005cc75e603d32ce2
|
[
"MIT"
] | null | null | null |
src/cameras/__init__.py
|
KingAbbott/devsyn
|
ef26855c5b96e489d390a32005cc75e603d32ce2
|
[
"MIT"
] | null | null | null |
from freelook import FreeLookCamera
from firstperson import FirstPersonCamera
from god import GodCamera
| 26
| 41
| 0.884615
| 12
| 104
| 7.666667
| 0.666667
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.115385
| 104
| 3
| 42
| 34.666667
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
e47484b7a72286f1bde6b61005e0f2d6de78dd7a
| 175
|
py
|
Python
|
semantic-clustering/semantic_clustering/transformers/__init__.py
|
zzoia/sbert_wk_sentence_embedder
|
096b149eefec25fac83aaef674421dfdfb150a68
|
[
"MIT"
] | null | null | null |
semantic-clustering/semantic_clustering/transformers/__init__.py
|
zzoia/sbert_wk_sentence_embedder
|
096b149eefec25fac83aaef674421dfdfb150a68
|
[
"MIT"
] | null | null | null |
semantic-clustering/semantic_clustering/transformers/__init__.py
|
zzoia/sbert_wk_sentence_embedder
|
096b149eefec25fac83aaef674421dfdfb150a68
|
[
"MIT"
] | null | null | null |
from .BertModelNeuron import BertModelNeuron
from .ModelAndTokenizer import ModelAndTokenizer
from .TokenizerWrapper import TokenizerWrapper
from .utils import load_model_path
| 43.75
| 48
| 0.891429
| 18
| 175
| 8.555556
| 0.5
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.085714
| 175
| 4
| 49
| 43.75
| 0.9625
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
e476d1989e233e574276177b9b89a0f7fb7de702
| 27
|
py
|
Python
|
geosnap/util/__init__.py
|
weikang9009/geosnap
|
276c99bf60657bcd2ee18cc207cf1f8344a44422
|
[
"BSD-3-Clause"
] | null | null | null |
geosnap/util/__init__.py
|
weikang9009/geosnap
|
276c99bf60657bcd2ee18cc207cf1f8344a44422
|
[
"BSD-3-Clause"
] | null | null | null |
geosnap/util/__init__.py
|
weikang9009/geosnap
|
276c99bf60657bcd2ee18cc207cf1f8344a44422
|
[
"BSD-3-Clause"
] | null | null | null |
from .cenpy_fetch import *
| 13.5
| 26
| 0.777778
| 4
| 27
| 5
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.148148
| 27
| 1
| 27
| 27
| 0.869565
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 0
| 1
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
e487a616a5b6c04554553f8546dc0f2a537a9cea
| 171
|
py
|
Python
|
olx/products/admin.py
|
skarthik21/Campus-Olx
|
eefbb584f55ebcf9aebb2e09f2b201cd45001b0a
|
[
"MIT"
] | null | null | null |
olx/products/admin.py
|
skarthik21/Campus-Olx
|
eefbb584f55ebcf9aebb2e09f2b201cd45001b0a
|
[
"MIT"
] | null | null | null |
olx/products/admin.py
|
skarthik21/Campus-Olx
|
eefbb584f55ebcf9aebb2e09f2b201cd45001b0a
|
[
"MIT"
] | null | null | null |
from products.models import Image, Owner, Product
from django.contrib import admin
admin.site.register(Owner)
admin.site.register(Product)
admin.site.register(Image)
| 28.5
| 50
| 0.80117
| 24
| 171
| 5.708333
| 0.5
| 0.19708
| 0.372263
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.105263
| 171
| 6
| 51
| 28.5
| 0.895425
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.4
| 0
| 0.4
| 0
| 1
| 0
| 0
| null | 0
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
e4a7c8138da3366a01e12415d23f08e6de071559
| 43
|
py
|
Python
|
lib/jnpr/junos/version.py
|
pamelia/py-junos-eznc
|
d97937179b161d6528cfb5930dee4276ebd71ecd
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
lib/jnpr/junos/version.py
|
pamelia/py-junos-eznc
|
d97937179b161d6528cfb5930dee4276ebd71ecd
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
lib/jnpr/junos/version.py
|
pamelia/py-junos-eznc
|
d97937179b161d6528cfb5930dee4276ebd71ecd
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
VERSION = "1.2.4.dev"
DATE = "2015-Oct-07"
| 14.333333
| 21
| 0.604651
| 9
| 43
| 2.888889
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.243243
| 0.139535
| 43
| 2
| 22
| 21.5
| 0.459459
| 0
| 0
| 0
| 0
| 0
| 0.465116
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
e4aa759b59a3de299a537428bb52eb43737c110b
| 96
|
py
|
Python
|
venv/lib/python3.8/site-packages/rope/base/taskhandle.py
|
GiulianaPola/select_repeats
|
17a0d053d4f874e42cf654dd142168c2ec8fbd11
|
[
"MIT"
] | 2
|
2022-03-13T01:58:52.000Z
|
2022-03-31T06:07:54.000Z
|
venv/lib/python3.8/site-packages/rope/base/taskhandle.py
|
DesmoSearch/Desmobot
|
b70b45df3485351f471080deb5c785c4bc5c4beb
|
[
"MIT"
] | 19
|
2021-11-20T04:09:18.000Z
|
2022-03-23T15:05:55.000Z
|
venv/lib/python3.8/site-packages/rope/base/taskhandle.py
|
DesmoSearch/Desmobot
|
b70b45df3485351f471080deb5c785c4bc5c4beb
|
[
"MIT"
] | null | null | null |
/home/runner/.cache/pip/pool/eb/cf/cf/bc25ff9aaac98d6abb8139c0525853b3b282e9c0543bc59c4f7c35c83c
| 96
| 96
| 0.895833
| 9
| 96
| 9.555556
| 0.888889
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.354167
| 0
| 96
| 1
| 96
| 96
| 0.541667
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| null | null | 0
| 0
| null | null | 0
| 1
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 1
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
e4b6272529743bf3f343ede4fdd95aa13d2cbb6c
| 320
|
py
|
Python
|
home_developer/home_developer/doctype/skjb/skjb_dashboard.py
|
erpsonic/HomeDeveloper
|
39da29bb5aec02860264aba7b24e7214f88e0f1b
|
[
"MIT"
] | null | null | null |
home_developer/home_developer/doctype/skjb/skjb_dashboard.py
|
erpsonic/HomeDeveloper
|
39da29bb5aec02860264aba7b24e7214f88e0f1b
|
[
"MIT"
] | null | null | null |
home_developer/home_developer/doctype/skjb/skjb_dashboard.py
|
erpsonic/HomeDeveloper
|
39da29bb5aec02860264aba7b24e7214f88e0f1b
|
[
"MIT"
] | null | null | null |
from frappe import _
def get_data():
return {
'fieldname': 'skjb_utj_booking',
#'non_standard_fieldnames': {
#
#},
#'internal_links': {
# 'Sales Invoice': ['items', 'sales_invoice'],
#},
'transactions': [
{
'label': _('Invoice'),
'items': ['Sales Invoice']
},
]
}
| 16.842105
| 49
| 0.525
| 27
| 320
| 5.888889
| 0.777778
| 0.226415
| 0.213836
| 0.301887
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.278125
| 320
| 19
| 50
| 16.842105
| 0.688312
| 0.3
| 0
| 0
| 0
| 0
| 0.333333
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.090909
| true
| 0
| 0.090909
| 0.090909
| 0.272727
| 0
| 1
| 0
| 0
| null | 1
| 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
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
e4ef519bc439e96560a59cc5d9a2ed82686c0cfa
| 157
|
py
|
Python
|
gamefixes/7850.py
|
manueliglesiasgarcia/protonfixes
|
d676b6bf39f6e4268b4791d3d71c6d74e2127121
|
[
"BSD-2-Clause"
] | 213
|
2018-10-06T01:40:26.000Z
|
2022-03-16T16:17:37.000Z
|
gamefixes/7850.py
|
manueliglesiasgarcia/protonfixes
|
d676b6bf39f6e4268b4791d3d71c6d74e2127121
|
[
"BSD-2-Clause"
] | 88
|
2018-10-06T17:38:56.000Z
|
2022-02-19T13:27:26.000Z
|
gamefixes/7850.py
|
manueliglesiasgarcia/protonfixes
|
d676b6bf39f6e4268b4791d3d71c6d74e2127121
|
[
"BSD-2-Clause"
] | 67
|
2018-10-09T16:57:16.000Z
|
2022-03-14T13:06:25.000Z
|
""" Game fix for Cryostasis
"""
#pylint: disable=C0103
from protonfixes import util
def main():
""" Uses physx
"""
util.protontricks('physx')
| 13.083333
| 30
| 0.636943
| 18
| 157
| 5.555556
| 0.888889
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.03252
| 0.216561
| 157
| 11
| 31
| 14.272727
| 0.780488
| 0.388535
| 0
| 0
| 0
| 0
| 0.060976
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| true
| 0
| 0.333333
| 0
| 0.666667
| 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
| 1
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
901a5b488db256c583fdc2aa039051f20c417621
| 216
|
py
|
Python
|
PyAxe/ACore.py
|
sunjinopensource/PyAxe
|
4b01d0aec83006f9ab366acbefbe7a2bcd5bee10
|
[
"MIT"
] | null | null | null |
PyAxe/ACore.py
|
sunjinopensource/PyAxe
|
4b01d0aec83006f9ab366acbefbe7a2bcd5bee10
|
[
"MIT"
] | null | null | null |
PyAxe/ACore.py
|
sunjinopensource/PyAxe
|
4b01d0aec83006f9ab366acbefbe7a2bcd5bee10
|
[
"MIT"
] | null | null | null |
class ScopeGuard:
def __init__(self, handler):
self.handler = handler
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.handler()
| 19.636364
| 53
| 0.601852
| 25
| 216
| 4.6
| 0.52
| 0.286957
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.310185
| 216
| 10
| 54
| 21.6
| 0.771812
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.428571
| false
| 0
| 0
| 0.142857
| 0.714286
| 0
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 5
|
901aef1f7c1641d5c81d1c93533be895d76b0171
| 4,328
|
py
|
Python
|
testing/impl/test_evaluator_segment.py
|
annuupadhyayPS/python-server-sdk-2
|
782dac861e81c1f5988af93019f5d1d506e8ef00
|
[
"Apache-2.0"
] | null | null | null |
testing/impl/test_evaluator_segment.py
|
annuupadhyayPS/python-server-sdk-2
|
782dac861e81c1f5988af93019f5d1d506e8ef00
|
[
"Apache-2.0"
] | null | null | null |
testing/impl/test_evaluator_segment.py
|
annuupadhyayPS/python-server-sdk-2
|
782dac861e81c1f5988af93019f5d1d506e8ef00
|
[
"Apache-2.0"
] | null | null | null |
import pytest
from testing.impl.evaluator_util import *
def _segment_matches_user(segment: dict, user: dict) -> bool:
e = EvaluatorBuilder().with_segment(segment).build()
flag = make_boolean_flag_matching_segment(segment)
result = e.evaluate(flag, user, event_factory)
return result.detail.value
def test_explicit_include_user():
s = {
"key": "test",
"included": [ "foo" ],
"version": 1
}
u = { "key": "foo" }
assert _segment_matches_user(s, u) is True
def test_explicit_exclude_user():
s = {
"key": "test",
"excluded": [ "foo" ],
"version": 1
}
u = { "key": "foo" }
assert _segment_matches_user(s, u) is False
def test_explicit_include_has_precedence():
s = {
"key": "test",
"included": [ "foo" ],
"excluded": [ "foo" ],
"version": 1
}
u = { "key": "foo" }
assert _segment_matches_user(s, u) is True
def test_matching_rule_with_no_weight():
s = {
"key": "test",
"rules": [
{
"clauses": [
{
"attribute": "email",
"op": "in",
"values": [ "test@example.com" ]
}
]
}
]
}
u = { "key": "foo", "email": "test@example.com" }
assert _segment_matches_user(s, u) is True
def test_matching_rule_with_none_weight():
s = {
"key": "test",
"rules": [
{
"clauses": [
{
"attribute": "email",
"op": "in",
"values": [ "test@example.com" ]
}
],
"weight": None
}
]
}
u = { "key": "foo", "email": "test@example.com" }
assert _segment_matches_user(s, u) is True
def test_matching_rule_with_full_rollout():
s = {
"key": "test",
"rules": [
{
"clauses": [
{
"attribute": "email",
"op": "in",
"values": [ "test@example.com" ]
}
],
"weight": 100000
}
]
}
u = { "key": "foo", "email": "test@example.com" }
assert _segment_matches_user(s, u) is True
def test_matching_rule_with_zero_rollout():
s = {
"key": "test",
"rules": [
{
"clauses": [
{
"attribute": "email",
"op": "in",
"values": [ "test@example.com" ]
}
],
"weight": 0
}
]
}
u = { "key": "foo", "email": "test@example.com" }
assert _segment_matches_user(s, u) is False
def test_matching_rule_with_multiple_clauses():
s = {
"key": "test",
"rules": [
{
"clauses": [
{
"attribute": "email",
"op": "in",
"values": [ "test@example.com" ]
},
{
"attribute": "name",
"op": "in",
"values": [ "bob" ]
}
],
"weight": 100000
}
]
}
u = { "key": "foo", "email": "test@example.com", "name": "bob" }
assert _segment_matches_user(s, u) is True
def test_non_matching_rule_with_multiple_clauses():
s = {
"key": "test",
"rules": [
{
"clauses": [
{
"attribute": "email",
"op": "in",
"values": [ "test@example.com" ]
},
{
"attribute": "name",
"op": "in",
"values": [ "bill" ]
}
],
"weight": 100000
}
]
}
u = { "key": "foo", "email": "test@example.com", "name": "bob" }
assert _segment_matches_user(s, u) is False
| 26.552147
| 68
| 0.377311
| 350
| 4,328
| 4.442857
| 0.197143
| 0.084887
| 0.108039
| 0.138907
| 0.781994
| 0.759486
| 0.759486
| 0.759486
| 0.75627
| 0.752412
| 0
| 0.009795
| 0.481054
| 4,328
| 162
| 69
| 26.716049
| 0.682547
| 0
| 0
| 0.57047
| 0
| 0
| 0.165665
| 0
| 0
| 0
| 0
| 0
| 0.060403
| 1
| 0.067114
| false
| 0
| 0.013423
| 0
| 0.087248
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 1
| 1
| 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
| 5
|
5f7d3ebab58c11484adba78b54172e568e136383
| 104
|
py
|
Python
|
bnbapp/interest/admin.py
|
Bionetbook/bionetbook
|
c92d5bbdc5c121631c2230cf93aa63977d381f30
|
[
"MIT"
] | null | null | null |
bnbapp/interest/admin.py
|
Bionetbook/bionetbook
|
c92d5bbdc5c121631c2230cf93aa63977d381f30
|
[
"MIT"
] | null | null | null |
bnbapp/interest/admin.py
|
Bionetbook/bionetbook
|
c92d5bbdc5c121631c2230cf93aa63977d381f30
|
[
"MIT"
] | null | null | null |
from django.contrib import admin
from interest.models import Interest
admin.site.register(Interest)
| 13
| 36
| 0.817308
| 14
| 104
| 6.071429
| 0.642857
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.125
| 104
| 7
| 37
| 14.857143
| 0.934066
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.666667
| 0
| 0.666667
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
5f7e26326953c64976c633b619dbcdbdb069f5e1
| 134
|
py
|
Python
|
display/__init__.py
|
Sketch98/centipede
|
20381f622410afc1fda70f18f43a421f22a08d59
|
[
"MIT"
] | null | null | null |
display/__init__.py
|
Sketch98/centipede
|
20381f622410afc1fda70f18f43a421f22a08d59
|
[
"MIT"
] | null | null | null |
display/__init__.py
|
Sketch98/centipede
|
20381f622410afc1fda70f18f43a421f22a08d59
|
[
"MIT"
] | null | null | null |
from __future__ import absolute_import
from ._tile_controller import tile_controller
from ._palette_selector import palette_selector
| 26.8
| 47
| 0.88806
| 17
| 134
| 6.352941
| 0.470588
| 0.259259
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.097015
| 134
| 4
| 48
| 33.5
| 0.892562
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 5
|
5f986a4160e3b7708c8d9cd039337d00e1762c36
| 79
|
py
|
Python
|
neuralxc/utils/__init__.py
|
semodi/neuralxc
|
2af313646e1a2f05d7400075d5d803e771935cda
|
[
"BSD-3-Clause"
] | 24
|
2019-12-12T14:08:24.000Z
|
2022-03-18T01:08:42.000Z
|
neuralxc/utils/__init__.py
|
semodi/neuralxc
|
2af313646e1a2f05d7400075d5d803e771935cda
|
[
"BSD-3-Clause"
] | 13
|
2019-05-16T17:41:12.000Z
|
2021-10-16T17:46:46.000Z
|
neuralxc/utils/__init__.py
|
semodi/neuralxc
|
2af313646e1a2f05d7400075d5d803e771935cda
|
[
"BSD-3-Clause"
] | 6
|
2020-05-15T01:32:42.000Z
|
2022-03-11T13:54:01.000Z
|
from .density_getter import SiestaDensityGetter
from .config import ConfigFile
| 26.333333
| 47
| 0.873418
| 9
| 79
| 7.555556
| 0.777778
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.101266
| 79
| 2
| 48
| 39.5
| 0.957746
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
5f9934420a45b77e03c4bb7516b2eeee803f98ff
| 136
|
py
|
Python
|
1601-1700/1672-Richest Customer Wealth/1672-Richest Customer Wealth.py
|
jiadaizhao/LeetCode
|
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
|
[
"MIT"
] | 49
|
2018-05-05T02:53:10.000Z
|
2022-03-30T12:08:09.000Z
|
1601-1700/1672-Richest Customer Wealth/1672-Richest Customer Wealth.py
|
ptx-c/LeetCode
|
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
|
[
"MIT"
] | 11
|
2017-12-15T22:31:44.000Z
|
2020-10-02T12:42:49.000Z
|
1601-1700/1672-Richest Customer Wealth/1672-Richest Customer Wealth.py
|
ptx-c/LeetCode
|
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
|
[
"MIT"
] | 28
|
2017-12-05T10:56:51.000Z
|
2022-01-26T18:18:27.000Z
|
class Solution:
def maximumWealth(self, accounts: List[List[int]]) -> int:
return max(sum(account) for account in accounts)
| 34
| 62
| 0.691176
| 18
| 136
| 5.222222
| 0.777778
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.191176
| 136
| 3
| 63
| 45.333333
| 0.854545
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| false
| 0
| 0
| 0.333333
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 5
|
5fa2ea512a9ebbee50210f97689ba99ba6c8b4e6
| 47
|
py
|
Python
|
hello.py
|
Sagar-modelling/Demo
|
a587f290b57fd862429c5ee33407c8dd2868bf42
|
[
"MIT"
] | null | null | null |
hello.py
|
Sagar-modelling/Demo
|
a587f290b57fd862429c5ee33407c8dd2868bf42
|
[
"MIT"
] | null | null | null |
hello.py
|
Sagar-modelling/Demo
|
a587f290b57fd862429c5ee33407c8dd2868bf42
|
[
"MIT"
] | null | null | null |
print("Hello Python")
print("By Sagar Kandpal")
| 23.5
| 25
| 0.744681
| 7
| 47
| 5
| 0.857143
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.085106
| 47
| 2
| 25
| 23.5
| 0.813953
| 0
| 0
| 0
| 0
| 0
| 0.583333
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0
| 0
| 0
| 1
| 1
| 1
| 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
| 1
|
0
| 5
|
39a24035f14a950d47f504c92bc169fe063e1677
| 44
|
py
|
Python
|
run.py
|
camratchford/contest_automator
|
97d03a1d5f52fa65fb7bc8105ab69615162f6989
|
[
"MIT"
] | null | null | null |
run.py
|
camratchford/contest_automator
|
97d03a1d5f52fa65fb7bc8105ab69615162f6989
|
[
"MIT"
] | null | null | null |
run.py
|
camratchford/contest_automator
|
97d03a1d5f52fa65fb7bc8105ab69615162f6989
|
[
"MIT"
] | null | null | null |
import automator
automator.enter_contests()
| 14.666667
| 26
| 0.863636
| 5
| 44
| 7.4
| 0.8
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.068182
| 44
| 3
| 26
| 14.666667
| 0.902439
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.5
| 0
| 0.5
| 0
| 1
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
39a75f9b0fec0c999b091d8be4e8c6580df32b45
| 144
|
py
|
Python
|
api/api/__main__.py
|
fcevado/minha-receita
|
ebd5cca95115d878934a0f762a8e92d3f8f5b495
|
[
"MIT"
] | 1
|
2020-08-07T18:07:38.000Z
|
2020-08-07T18:07:38.000Z
|
api/api/__main__.py
|
fcevado/minha-receita
|
ebd5cca95115d878934a0f762a8e92d3f8f5b495
|
[
"MIT"
] | null | null | null |
api/api/__main__.py
|
fcevado/minha-receita
|
ebd5cca95115d878934a0f762a8e92d3f8f5b495
|
[
"MIT"
] | null | null | null |
from api import app
from api.settings import SANIC_HOST, SANIC_PORT, SANIC_DEBUG
app.run(host=SANIC_HOST, port=SANIC_PORT, debug=SANIC_DEBUG)
| 24
| 60
| 0.819444
| 25
| 144
| 4.48
| 0.4
| 0.125
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.104167
| 144
| 5
| 61
| 28.8
| 0.868217
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.666667
| 0
| 0.666667
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
39a8ade5d3f6420bbd3cc41e4dd9579d6946a45b
| 104
|
py
|
Python
|
demos/ex_sub_package/simple_graph.py
|
nferrara100/dependency_mapping
|
b0634f2aaf3f14466d5c03dd9c57c140e7a64940
|
[
"MIT"
] | 1
|
2020-08-27T23:02:48.000Z
|
2020-08-27T23:02:48.000Z
|
demos/ex_sub_package/simple_graph.py
|
nferrara100/spaghetti
|
b0634f2aaf3f14466d5c03dd9c57c140e7a64940
|
[
"MIT"
] | null | null | null |
demos/ex_sub_package/simple_graph.py
|
nferrara100/spaghetti
|
b0634f2aaf3f14466d5c03dd9c57c140e7a64940
|
[
"MIT"
] | null | null | null |
def a():
b()
c()
def b():
d()
def c():
pass
def d():
pass
def e():
pass
| 5.2
| 8
| 0.336538
| 16
| 104
| 2.1875
| 0.4375
| 0.4
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.461538
| 104
| 19
| 9
| 5.473684
| 0.625
| 0
| 0
| 0.272727
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.454545
| true
| 0.272727
| 0
| 0
| 0.454545
| 0
| 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
| 1
| 1
| 1
| 0
| 0
| 0
| 0
|
0
| 5
|
f2d0659fbca75543a07ec876474671719c0cf3a3
| 235
|
py
|
Python
|
api/models/hotohete_settings.py
|
wen96/hotohete
|
03f0e37069875a4c3b0f3e4b4759805388c76c33
|
[
"MIT"
] | 2
|
2017-11-14T20:33:56.000Z
|
2018-02-18T19:48:18.000Z
|
api/models/hotohete_settings.py
|
wen96/hotohete
|
03f0e37069875a4c3b0f3e4b4759805388c76c33
|
[
"MIT"
] | 10
|
2017-06-18T11:35:26.000Z
|
2017-12-05T18:40:17.000Z
|
api/models/hotohete_settings.py
|
wen96/hotohete
|
03f0e37069875a4c3b0f3e4b4759805388c76c33
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class HotoheteSettings(models.Model):
key = models.CharField(max_length=255, unique=True)
value = models.CharField(max_length=255)
| 23.5
| 55
| 0.748936
| 31
| 235
| 5.451613
| 0.709677
| 0.177515
| 0.213018
| 0.284024
| 0.319527
| 0
| 0
| 0
| 0
| 0
| 0
| 0.034653
| 0.140426
| 235
| 9
| 56
| 26.111111
| 0.80198
| 0.089362
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.4
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 1
| 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
| 1
| 0
| 1
| 0
|
0
| 5
|
f2d621a3e89d6e6d918651df0de97fbe4c37e3b1
| 882
|
py
|
Python
|
setup.py
|
brianjbuck/noeval
|
685fd2b057e967d5653c25f47f9875b98d7cc78b
|
[
"MIT"
] | null | null | null |
setup.py
|
brianjbuck/noeval
|
685fd2b057e967d5653c25f47f9875b98d7cc78b
|
[
"MIT"
] | null | null | null |
setup.py
|
brianjbuck/noeval
|
685fd2b057e967d5653c25f47f9875b98d7cc78b
|
[
"MIT"
] | null | null | null |
from setuptools import setup
setup(
name="noeval",
description="Warn if `eval()` is committed to a repository",
url="https://github.com/brianjbuck/noeval",
version="1.0.0",
author="Brian Buck",
author_email="brian@thebuckpasser.com",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
],
install_requires=[],
py_modules=["noeval"],
entry_points={"console_scripts": ["noeval = noeval:main"]},
)
| 33.923077
| 70
| 0.611111
| 90
| 882
| 5.933333
| 0.588889
| 0.284644
| 0.374532
| 0.194757
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.019202
| 0.232426
| 882
| 25
| 71
| 35.28
| 0.769572
| 0
| 0
| 0
| 0
| 0
| 0.608844
| 0.026077
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0.043478
| 0.043478
| 0
| 0.043478
| 0
| 0
| 0
| 0
| null | 1
| 1
| 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
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
f2fa907fb002217a4d45f35afa5e8d464f844ed8
| 64
|
py
|
Python
|
measurement_scripts/templates/test_script_load.py
|
ajsousal/qtNE
|
37fcbc5e24ef91e25add35323d1c5cf96ee0f272
|
[
"BSD-3-Clause"
] | null | null | null |
measurement_scripts/templates/test_script_load.py
|
ajsousal/qtNE
|
37fcbc5e24ef91e25add35323d1c5cf96ee0f272
|
[
"BSD-3-Clause"
] | null | null | null |
measurement_scripts/templates/test_script_load.py
|
ajsousal/qtNE
|
37fcbc5e24ef91e25add35323d1c5cf96ee0f272
|
[
"BSD-3-Clause"
] | null | null | null |
station.psg.modulation.set('off')
print('psg modulation off')
| 12.8
| 33
| 0.734375
| 9
| 64
| 5.222222
| 0.666667
| 0.553191
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.09375
| 64
| 5
| 34
| 12.8
| 0.810345
| 0
| 0
| 0
| 0
| 0
| 0.333333
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0
| 0
| 0
| 0.5
| 1
| 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
| 1
| 0
| 0
| 0
| 0
| 1
|
0
| 5
|
f2feb02d6b563edfd20844261ad5917735b21456
| 83
|
py
|
Python
|
problem/01000~09999/09546/9546.py3.py
|
njw1204/BOJ-AC
|
1de41685725ae4657a7ff94e413febd97a888567
|
[
"MIT"
] | 1
|
2019-04-19T16:37:44.000Z
|
2019-04-19T16:37:44.000Z
|
problem/01000~09999/09546/9546.py3.py
|
njw1204/BOJ-AC
|
1de41685725ae4657a7ff94e413febd97a888567
|
[
"MIT"
] | 1
|
2019-04-20T11:42:44.000Z
|
2019-04-20T11:42:44.000Z
|
problem/01000~09999/09546/9546.py3.py
|
njw1204/BOJ-AC
|
1de41685725ae4657a7ff94e413febd97a888567
|
[
"MIT"
] | 3
|
2019-04-19T16:37:47.000Z
|
2021-10-25T00:45:00.000Z
|
for _ in range(int(input())):
a=0
for i in range(int(input())): a=a*2+1
print(a)
| 20.75
| 38
| 0.60241
| 19
| 83
| 2.578947
| 0.578947
| 0.285714
| 0.408163
| 0.612245
| 0.653061
| 0
| 0
| 0
| 0
| 0
| 0
| 0.042857
| 0.156627
| 83
| 4
| 39
| 20.75
| 0.657143
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0.25
| 1
| 0
| 0
| null | 1
| 1
| 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
| 5
|
840a458e6f5f2de0cad293523faf2367b71077a9
| 12,865
|
py
|
Python
|
app.py
|
manishkumart/Brand-Your-Business-withAI
|
f1e0cbc2e05efa3ec322a0ad36be3c4e93e2f7d6
|
[
"MIT"
] | null | null | null |
app.py
|
manishkumart/Brand-Your-Business-withAI
|
f1e0cbc2e05efa3ec322a0ad36be3c4e93e2f7d6
|
[
"MIT"
] | null | null | null |
app.py
|
manishkumart/Brand-Your-Business-withAI
|
f1e0cbc2e05efa3ec322a0ad36be3c4e93e2f7d6
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
"""
Created on Fri May 28 17:53:10 2021
@author: Manish
"""
import openai
from fake_useragent import UserAgent
import streamlit as st
import pandas as pd
import streamlit.components.v1 as stc
#import key_config
pd.options.display.max_colwidth = 10000
st.set_page_config(page_title="BYB", layout="wide", page_icon='🚀')
BYB = UserAgent()
header = {'User-Agent': str(BYB.chrome)}
openai.api_key = "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"
def run():
st.markdown("<h1 style='text-align: center; color: Black;'>Brand your Business with AI 🧠</h1>", unsafe_allow_html=True)
st.markdown("<h5 style='text-align: center; color: Black;'>Made with ❤️ by Manish <a href='https://www.linkedin.com/in/manishkumarthota'><img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAVX0lEQVR4Xu2de3RV1Z3Hv+fcBEjCQyA8Cr5AQVReIo4WLB2RVkWYLumqAm1HWl3amc7oaF0OGAUZ0GIZpmrbqUWt2hnoYNdoNSYaS6gFgQloIQJaCiQWqTxieARIIMm9d9YOTXkI7nvz2/uee87+nv9g79/v7P357fvJOeeec66HVLdZpZ3RlJwAD2OB+DAkvP7w0Qnwc1NNwX4kQAKmCSSagFgd0FwNxCoBlCPHK8Hs8XWp7MnTdnrw9YuQTExHIjEZvt9B258dSIAEgibQACR/CS85D3MnbvmswZxZAA8X5+OoPwc+7gYQC3pG3D8JkECaBBKJZvixx1F/aCZ+eHPD6aJPL4AZJQPhJ18GvEvS3CW7kwAJZBuBRGIDkrmTMO/6racO7dMCeKB4BOCXwUNhts2D4yEBEmgrgUQNkv6X8eiN60/McLIA1F9+Dyv54W8rZMaRQDYTSNQgnjvqxCOB4wK4r6wA7ZvW8LA/mwvIsZGAkIA6HTjScGXrNYHjAphRsgA+7hWmZzgJkEC2E/AwH3NvvF8N85gAjn3Vt4lX+7O9chwfCRggoL4dSOZerE4FjgmgqOQ5ANMMpGYKEiCBcBB4Fo/ceLuHf/1NF/hHdvEmn3BUjaMkASMEEqhHvLm3hwdKpsLDIiNJmYQESCBEBLzJHopKngFwW4hGzaGSAAkYIeAt9FD06logNtJIPiYhARIID4EkKjzMKK6F73cLz6g5UhIgATMEEjUeioob+UivGZzMQgKhIpBAo7oGkAzVoDlYEiABYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiA8NWMIyYBYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiA8NWMIyYBYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiA8NWMIyYBYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiA8NWMIyYBYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiA8NWMIyYBYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiA8NWMIyYBYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiA8NWMIyYBYwQoAGMomYgEwkeAAghfzThiEjBGgAIwhpKJSCB8BCiAv9Ssc/scTBjUE2P7d8ew3p3Rv1s+OrXLaWmtO9qE6n0NqNxVh/JttSjZvAd1R5vDV22OmAROIeC8AC4qLMD0MRdg8tA+6JDjp7RAGpri+OV7OzFv+TZsqT2cUgw7kUA2EnBWAPm5McwZNxB3f/58xHyvTbVpTiTx+KpqzCzfAiUFbiQQNgJOCmBgYQFenno5LunZ0Ui9Nuw+iEmL38XW2noj+ZiEBDJFwDkBjOjTBWXTrkBhfjujjGsON+LLz6/B+p11RvMyGQnYJOCUANRf/pV3fN74h7+1QEoCoxau4pGAzRXL3EYJOCOAgnYxrPnOaGOH/WeqgjoduPKpVbwmYHSZMpktAs4IYMENF+Pe0f1scTwp7/wVVbi/7A8Z2Rd3QgISAk4IQH3Vt+muMW2+2p8uYPXtwMVP/I6nAumCY/+ME3BCAM9NGoppI87OKNxn3/0It7+8IaP75M5IIF0CkRdAlw452DV9XMo3+aQL8Ez965vi6D2vHAd5x6AppMxjgUDkBTB1WB8s+tpwC+j0KScvWYclG3bqO7IHCQREIPICeOamIbjt8nMCwbtw7Xbc+crGQPbNnZJAKgQiL4C1/zAaI/t2SYWF8T4VO/bjqqdWGc/LhCRgikDkBVBb9CV0y8s1xSutPOrGoJ7fX5pWDDuTQCYJRF4AjbNvQG6sbQ/7SAvRGE+g/aw3pGkYTwLWCFAA1tACFIBFuExthEDkBfDJA+PQ3fCDP6mS5ylAqqTYLygCkRcALwIGtbS43zAQiLwA+DVgGJYhxxgUgcgLYMrQPlh8czA3At2yZB1e5I1AQa1t7jcFApEXgHrZ567p1yIvN5YCDnNd1K3Avb6/FIca+aowc1SZyTSByAtAAXv2pqH49uWZfRjo6Xc+wh2/5sNAphcs85kl4IQABnQvwPt3j0FOG1/+mS7ypvixx4G37eU7AtNlx/6ZJeCEABTS+dcPwn1X988IXfW68Blvbs7IvrgTEpAQcEYA6jXgFd8ZhcG9Okl4aWPVj4eo+/+PNCe0fdmBBIIm4IwAFOgLu+dj1R2j0KPA7BuBW4u4+9BRjFq4GlU89A96XXP/KRJwSgCKyfDPdcab0/7GuATUh/+659e2/HwYNxIICwHnBNB6JPDS1MsxxNDpgPrQT1r8e/7lD8uq5zj/SsBJAajZq/sCZo8dgHtG92vztwPqav+ClVWYvWwLz/n5oQolAWcF0FotdV1A/TioumNQXShMZVM3+Syq/BiPLd/Gr/pSAcY+WUvAeQG0VqZT+xyMH9jj2M+Df64z+nfNh3qhqNoOHGlG1b56VO6sQ3lVLUo37+Edflm7pDmwdAhQAOnQYl8SiBgBCiBiBeV0SCAdAhRAOrTYlwQiRoACiFhBOR0SSIcABZAOLfYlgYgRoAAiVlBOhwTSIUABpEOLfUkgYgQogIgVlNMhgXQIRF4Aybnj0+FhvK/3YKkoZ9jHf1aHXAzp3QmDCgvQv1s+zumSh94d27c8jHVWhxx0bJ/Tcgdmu5gH3/OQSCahbrE+Gk+g7mgzausbsedQI7YfaED1vgZsrjmEdTvreAemaFUdD6YADIE8UxrXBKB+hu36gT0w7oJCfOG8bi2PYNvY9jU0YfmHe1G+rRbFm3fjw30NNnYT+ZwUgOUSuyCAmO/hK4N64faR5+BLFxa2+eEqSSnW7NiPF9b9Gb9Yt4O3aacBkgJIA1ZbukZZAJ4HfGNYX8waOwAXdLPzlz5d5uq04WdrtuMHK6rwSX1juuHO9acALJc8qgJQL1p9/qtDMercrpYJti29eh373Le24j9WVrVcU+B2egIUgOWVEUUB/N2gXvjvrw2DeoIy27eNuw/i679aj/d2Hcz2oQYyPgrAMvaoCeCbw/u2/OVXV+zDsqkXtN712iao32rgdjIBCsDyioiSANSV/ddvvSKQi3wmyvTvb1fh/rI/IMkzgr/ipABMrKzPyBEVAfQsaIeNd40x/jJVy/g/lf6pNdvxj8UbKYG/kKEALK/AqAjgha8Ow99f1tcyrcykX/B2Ne5744PM7CzL90IBWC5QFARwac+O2PDPYxCi035tVe98ZSMWrt2u7Rf1DhSA5QpHQQA/nzQU3xqR2R9XtVwWNMYTLb/gpG4rdnmjACxXP+wC6PRvZdg9Y1zKb0y2jNNo+s2fHMbwH69w+pXuFIDRJfXpZGEXwC1L1mHJLZdZphRc+kfe2ooHl/4xuAEEvGcKwHIBwi6AF9btwK2XRevw/8SSq7sEL3nyd9ha6+ZPuVMAFMBnEti+vwHnnpVnmVKw6V/csBPqSMfFjQKwXPWwHwFYxpMV6dWNQUN+tByb9hzKivFkchAUgGXaFIBlwIbSq1Odaf/7nqFs4UlDAViuFQVgGbCh9OprwbN/sAw1h916hJgCMLSAzpSGArAM2GB69ZzA/BVVBjNmfyoKwHKNKADLgA2mV48OD/nRCoMZsz8VBWC5RhSAZcCG0w9+0q2LgRSA4QV0ajoKwDJgw+lnlv8Rc3671XDW7E1HAViuDQVgGbDh9BU79rc8I+DKRgFYrjQFYBmw4fTqdwl6PLoUexuaDGfOznQUgOW6UACWAVtIf9Oid/HrD3ZbyJx9KSkAyzWhACwDtpD+h6uqcW+pGy8MoQAsLKATU1IAlgFbSL9q+z6MXrjaQubsS0kBWK4JBWAZsIX0DU1xdJ7zJpoT0X97KAVgYQHxCMAy1Aykd+V+AArA8mLiEYBlwJbST3lxPf7nvY8tZc+etBSA5VpQAJYBW0qvflbsIQfeFEQBWFpArWldEMDOg0dRtqUGqz/aj017DkK9RKS2vgkNzfEWDHk5sZbfEzjvrDwM7tUJo8/tiusGFKJ7fjvL9Nue3pWXhFAAbV8jKUVGWQCvbd6Dx1dV47dVe6FuoElny/E9XD+gB753dT/8bb/u6YRmpO/6nXW47CdvZ2RfQe6EArBMP4oC2FJ7GLe/vAHLP9xrhN6Ei3rip18ZjLM7dzCSz0SS/Uea0HXub0ykyuocFIDl8kRNACWb92DyknVQP79tclOnAy9NHYEx53czmVaUS30VePBosyhHtgdTAJYrFCUBqA//TYvfhXqTro0tLzeGsluvwBeyRAKXPLEcH9RE+z2BFICNlXxCzqgIQB32j/jJ28b/8p+KXx0JVP7T1eibBacD1/68Asuqai2vkGDTUwCW+UdFAF985v+MnfPrkKtrAsXfHKnrZr39679aj8WV0b4XgAKwvIyiIAB1tX/if71jmdTJ6d+67Sp8sV+w1wP+peR9PLH6w4zOO9M7owAsE4+CAMY9V4HybZk9FJ44qCde/UawRwHqzUDqDUFR3igAy9UNuwDUTT7qddnpfs8vxaruE9g1/dpAbxb6z4o/4bvFm6RTyep4CsByecIugOd/vwPfeimYH8xYfPNwTBnax3KFzpxenf+r6wBR3igAy9UNuwDufGUjFq7dbpnS6dN/98rz8OOJlwayb7XTIK59ZHqyFIBl4mEXwNVPr8bKP+2zTOn06dVFQHUxMKhN3emovv2I8kYBWK5u2AVw7vxl+OjAEcuUTp/+/K55qP7eNYHsW+30nT8fwBU/XRnY/jOxYwrAMuWwC6Bgdhnqm8ze9psq8o7tYjg487pUuxvv9/6eQ7j0yeXG82ZTQgrAcjXCLgD/oVKk+aCfMaK+5yE+5wZj+dJNVL2vHv0XvJVuWKj6UwCWyxV2AUjHL8WbnDtemqLN8R8fPIK+jy1rc3wYAikAy1WSfoCC/AAoNNLxS/EGOf/a+kYUPrpUOoWsjqcALJdH+gEK8gPgugDUo8DqkeAobxSA5epSADLAQQpQvR48f3aZbAJZHk0BWC4QBSADHKQAGuMJtJ/1hmwCWR5NAVguEAUgAxykAOKJJHJmvi6bQJZHUwCWC0QByAAHKQD1AFTsIQpAVsGAo4NcQCYuooV9/NLyuz5/KT9dPI8AdISE7TwCkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNEUgI6QsJ0CkAGkAGT8dNGRF4AOANtJwGUCFIDL1efcnSdAATi/BAjAZQIUgMvV59ydJ0ABOL8ECMBlAhSAy9Xn3J0nQAE4vwQIwGUCFIDL1efcnSdAATi/BAjAZQIUgMvV59ydJ0ABOL8ECMBlAhSAy9Xn3J0nQAE4vwQIwGUCFIDL1efcnSdAATi/BAjAZQIUgMvV59ydJ0ABOL8ECMBlAhSAy9Xn3J0nQAE4vwQIwGUCFIDL1efcnSdAATi/BAjAZQIUgMvV59ydJ0ABOL8ECMBlAhSAy9Xn3J0nQAE4vwQIwGUCFIDL1efcnSdAATi/BAjAZQIUgMvV59ydJ0ABOL8ECMBlAhSAy9Xn3J0nQAE4vwQIwGUCFIDL1efcnSdAATi/BAjAZQIUgMvV59ydJ0ABOL8ECMBlAhSAy9Xn3J0nQAE4vwQIwGUCFIDL1efcnSdAATi/BAjAZQIUgMvV59ydJ+ChqLgR8HOdJ0EAJOAagQQaPRSVfgIku7s2d86XBEggUeOh6NW1QGwkYZAACThGIIkKdQ3gGQC3OTZ1TpcESADeQiWAKQAWkwYJkIBjBJK4xcOs0s5oTu4CkOfY9DldEnCXQAL1aJ/fy2shUPTas4D3bXdpcOYk4BqB5NN4ZMIdxwTwYPEAxPE+fD/HNQycLwm4RyDRBC92MeaO33ZMAC1HAaXzgeR97sHgjEnAOQLz8MiNM9Ssjwvg4eJ8NPkVAAY7h4MTJgF3CFQiN/8qPHzNkZMFoP41/Y0LEWtaBfg93OHBmZKAMwR2I54chXkTqlpnfPwIoPV/HigZDi/xJiXgzKLgRN0gsBt+4jrMmVh54nQ/LYDWIwGv6SX4/hA32HCWJBBpApWIJyed+Jf/zEcArS33vJiHgoLZiCfu4bcDkV4cnFxkCSSaAH8BcvNnt57znzrV0x8BnNir5bpAfDoSmAIf+ZFlxYmRQFQIqJt8/OQieP5j6qu+z5qWXgCt0fe/0gm5ueMBjEUyOQxeoj8Sfhf4aBcVbpwHCYSOQAKN8BMHkPSr4HmVSCbL0S6/FA9fcyiVufw/Nn3pJWGphxYAAAAASUVORK5CYII=', width='15', height='15'></a></a></h5>", unsafe_allow_html=True)
st.subheader("Project is under development 🚧, further i will be adding StackGAN to synthsize the logo decsription into an image")
company_name, headquarters_location, Industries = st.beta_columns(3)
## Company name
company_name = company_name.text_input('Enter company name')
## Location
headquarters_location = headquarters_location.text_input("Enter the location")
## Industry
Industries = Industries.text_input("Enter the industry")
#company_name = input("Input your company name:")
#headquarters_location = input('Input the location of')
#Industries = input('Input relevant industry for')
#company_name = widgets.Text(value='kishen enterprises ltd', disabled=False,description='Name')
#headquarters_location = widgets.Text(value='Tanzania', disabled=False,description='Location')
#industries = widgets.Text(value='Business Supplies & Equipment', disabled=False,description='Industries')
#display(company_name,headquarters_location,industries)
if st.button("Execute"):
try:
#graphics('index.html')
#graphics('index.html', 0)
myEntry = f"""Company's name:{company_name}\nHeadquaters location:{headquarters_location}\nIndustry:{Industries}"""
#parameters
myTokens = 600
myEngine = "davinci"
myTemp = 0.85
myTop_p = 1
myN=1
myStream = None
myLogProbs = None
myStop = "\n\n"
#Custom text input
myPrompt = f"""Generates everything that a new business needs to get started connecting with their audience.
Company's name:Apple Computer Inc.
Headquaters location:USA
Industry: Computer hardware,Computer software,Consumer electronics,Cloud computing,Digital distribution,Fabless silicon design,Semiconductors,Media,Financial technology,Artificial intelligence
Geographical focus:global
Moto:make the best products
Logo concept: an apple with a bite taken out of it. Black. No text.
Suggested company colors: black and white
Suggested company slogan:Think Different
3 product ideas:portable music player, online music store, web application store
1 free tweet: '''Apple Computer today unveiled its much-anticipated Macintosh computer, a sophisticated, affordably priced personal computer designed for business people, professionals and students in a broad range of fields.'''
Geographic targets:United States, Canada, United Kingdom
{myEntry}
"""
response = openai.Completion.create(
engine=myEngine,
prompt=myPrompt,
max_tokens=myTokens,
temperature=myTemp,
top_p=myTop_p,
n=myN,
stream = myStream,
logprobs=myLogProbs,
stop = myStop
)
result = myEntry.split('\n') + (response.choices[0].text).split('\n')
Suggestion = []
Results = []
for i in result:
Results.append(i.split(":")[0])
Suggestion.append(i.split(":")[1])
df = pd.DataFrame({"Details":Results,"Results":Suggestion})
st.table(df)
#st.dataframe(data=df, width=1700, height=1768)
except Exception as e:
st.error("Something went wrong, please try once again!!")
print(e)
elif st.button("About"):
st.header("What does this app do?")
st.subheader("Branding your Business with AI is built on top of OpenAI's GPT-3 and streamlit framework, You need to give three inputs mentioned above and the AI suggests you the followings:")
st.write("1. Company's name")
st.write("2. Headquaters location")
st.write("3. Industry")
st.write("4. Geographical focus of the company.")
st.write("5. Suggested motto for the company.")
st.write("6. Logo concept")
st.write("7. Suggested company colors.")
st.write("8. Suggested company slogan.")
st.write("9. Product ideas")
st.write("10. Free tweets that can enhance your presence on twitter.")
st.write("11. Geographic targets for the expansion of the company.")
run()
| 91.892857
| 7,611
| 0.818033
| 853
| 12,865
| 12.303634
| 0.627198
| 0.007337
| 0.076608
| 0.076608
| 0.055836
| 0.005717
| 0
| 0
| 0
| 0
| 0
| 0.09702
| 0.121104
| 12,865
| 139
| 7,612
| 92.553957
| 0.830724
| 0.05752
| 0
| 0
| 0
| 0.0625
| 0.802116
| 0.630021
| 0
| 1
| 0
| 0
| 0
| 1
| 0.0125
| false
| 0
| 0.0625
| 0
| 0.075
| 0.0125
| 0
| 0
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| null | 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
842f8fcfa3aee758875bfe1ff6f61a45a16b9d41
| 33
|
py
|
Python
|
utils/array.py
|
o0starshine0o/LearnAlgorithms
|
dae38707898edc94c58b49b0d0445341ea15fe8c
|
[
"MIT"
] | null | null | null |
utils/array.py
|
o0starshine0o/LearnAlgorithms
|
dae38707898edc94c58b49b0d0445341ea15fe8c
|
[
"MIT"
] | null | null | null |
utils/array.py
|
o0starshine0o/LearnAlgorithms
|
dae38707898edc94c58b49b0d0445341ea15fe8c
|
[
"MIT"
] | null | null | null |
StaticArray = [5, 2, 4, 6, 1, 3]
| 16.5
| 32
| 0.515152
| 7
| 33
| 2.428571
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.24
| 0.242424
| 33
| 1
| 33
| 33
| 0.44
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
8441fa31202ead8175d6a3546b1ea9790953c76b
| 130
|
py
|
Python
|
jsonrpc/__init__.py
|
escrowmycoinsnet/python-monerorpc
|
8e3064e521992b55c5e43e3f782b4f9d4634c50d
|
[
"MIT"
] | 12
|
2017-12-20T23:54:37.000Z
|
2021-06-01T04:54:26.000Z
|
jsonrpc/__init__.py
|
escrowmycoinsnet/python-monerorpc
|
8e3064e521992b55c5e43e3f782b4f9d4634c50d
|
[
"MIT"
] | 8
|
2018-01-05T10:32:14.000Z
|
2021-12-20T23:07:48.000Z
|
lib/jsonrpc/__init__.py
|
MericD/Python-Bitcoin-Transaction-Parser
|
c08c0efeb7b9ea8abea6905e5960d294abbdd6d1
|
[
"MIT"
] | 18
|
2017-12-20T23:54:43.000Z
|
2021-10-03T05:02:51.000Z
|
from .json import loads, dumps, JSONEncodeException, JSONDecodeException
from jsonrpc.proxy import ServiceProxy, JSONRPCException
| 43.333333
| 72
| 0.861538
| 13
| 130
| 8.615385
| 0.846154
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.092308
| 130
| 2
| 73
| 65
| 0.949153
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
ffbdefa274fd354b358dc46bb9a036230c5e2a32
| 122
|
py
|
Python
|
run_jira_ticket_migrate.py
|
suukit/jira-ticket-migrate
|
9d92cf7897cb6d9ff6b236364c0e311fcca65458
|
[
"MIT"
] | null | null | null |
run_jira_ticket_migrate.py
|
suukit/jira-ticket-migrate
|
9d92cf7897cb6d9ff6b236364c0e311fcca65458
|
[
"MIT"
] | 3
|
2020-10-27T21:26:12.000Z
|
2021-06-01T22:52:43.000Z
|
run_jira_ticket_migrate.py
|
suukit/jira-ticket-migrate
|
9d92cf7897cb6d9ff6b236364c0e311fcca65458
|
[
"MIT"
] | 2
|
2020-06-03T19:04:06.000Z
|
2021-11-18T12:57:06.000Z
|
#!/usr/bin/env python3
"""Runs the Jira ticket migration."""
from jira_ticket_migrate.main import main
# Run it
main()
| 13.555556
| 41
| 0.721311
| 19
| 122
| 4.526316
| 0.789474
| 0.232558
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.009615
| 0.147541
| 122
| 8
| 42
| 15.25
| 0.817308
| 0.491803
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.5
| 0
| 0.5
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 5
|
ffcd10623601894059da3e801b7dd5f49e7e3031
| 36
|
py
|
Python
|
a.py
|
MrigankSharma/TEST
|
cc2dc40edac000c2436972f7d114b1164550c521
|
[
"Apache-2.0"
] | null | null | null |
a.py
|
MrigankSharma/TEST
|
cc2dc40edac000c2436972f7d114b1164550c521
|
[
"Apache-2.0"
] | null | null | null |
a.py
|
MrigankSharma/TEST
|
cc2dc40edac000c2436972f7d114b1164550c521
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/python3
print("hello")
| 7.2
| 18
| 0.638889
| 5
| 36
| 4.6
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.03125
| 0.111111
| 36
| 4
| 19
| 9
| 0.6875
| 0.472222
| 0
| 0
| 0
| 0
| 0.294118
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0
| 0
| 0
| 1
| 1
| 1
| 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
| 1
|
0
| 5
|
ffdd38c0450afce27fe041a8278245bfe20ee2fd
| 71
|
py
|
Python
|
util/commands/bot.py
|
xrxbsx/goldmine
|
edab25451b3620e6fea9a8f1b0afcaa9e1637faa
|
[
"MIT"
] | 1
|
2021-03-31T23:07:08.000Z
|
2021-03-31T23:07:08.000Z
|
util/commands/bot.py
|
xrxbsx/goldmine
|
edab25451b3620e6fea9a8f1b0afcaa9e1637faa
|
[
"MIT"
] | null | null | null |
util/commands/bot.py
|
xrxbsx/goldmine
|
edab25451b3620e6fea9a8f1b0afcaa9e1637faa
|
[
"MIT"
] | null | null | null |
from discord.ext.commands.bot import *
from .context import ProContext
| 23.666667
| 38
| 0.816901
| 10
| 71
| 5.8
| 0.8
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.112676
| 71
| 2
| 39
| 35.5
| 0.920635
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
ffe7dbf5214cb22833730cdb36775a5b15aeb95b
| 267
|
py
|
Python
|
tests/datastructures/test_network.py
|
philianeles/compas
|
129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1
|
[
"MIT"
] | null | null | null |
tests/datastructures/test_network.py
|
philianeles/compas
|
129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1
|
[
"MIT"
] | null | null | null |
tests/datastructures/test_network.py
|
philianeles/compas
|
129a5a7e9d8832495d2bbee6ce7c6463ab50f2d1
|
[
"MIT"
] | null | null | null |
from compas.datastructures import Network
def test_add_vertex():
network = Network()
assert network.add_vertex() == 0
assert network.add_vertex(x=0, y=0, z=0) == 1
assert network.add_vertex(key=2) == 2
assert network.add_vertex(key=0, x=1) == 0
| 26.7
| 49
| 0.677903
| 43
| 267
| 4.069767
| 0.395349
| 0.257143
| 0.365714
| 0.502857
| 0.285714
| 0
| 0
| 0
| 0
| 0
| 0
| 0.046083
| 0.187266
| 267
| 9
| 50
| 29.666667
| 0.760369
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.571429
| 1
| 0.142857
| false
| 0
| 0.142857
| 0
| 0.285714
| 0
| 0
| 0
| 0
| null | 1
| 1
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
0819b00ada6006742b9d03c56dad675b6bcee3df
| 278
|
py
|
Python
|
03_software-development/exercise_pytest.py
|
benebrue/py-algorithms-4-automotive-engineering
|
eb4c137f3125e3f758bd25bffc4f2e9e5800b517
|
[
"MIT"
] | null | null | null |
03_software-development/exercise_pytest.py
|
benebrue/py-algorithms-4-automotive-engineering
|
eb4c137f3125e3f758bd25bffc4f2e9e5800b517
|
[
"MIT"
] | null | null | null |
03_software-development/exercise_pytest.py
|
benebrue/py-algorithms-4-automotive-engineering
|
eb4c137f3125e3f758bd25bffc4f2e9e5800b517
|
[
"MIT"
] | null | null | null |
from pytest import approx
from my_source import euclid
def test_simple_test():
assert(euclid([1, 1], [1, 1]) == approx(0))
def test_simple_test_2():
assert(euclid([1, 2], [5, -1]) == approx(5))
def test_simple_test_3():
assert(euclid([0, 0], [1, 1]) == approx(0))
| 25.272727
| 48
| 0.636691
| 47
| 278
| 3.574468
| 0.340426
| 0.047619
| 0.232143
| 0.303571
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.073276
| 0.165468
| 278
| 11
| 49
| 25.272727
| 0.650862
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.375
| 1
| 0.375
| true
| 0
| 0.25
| 0
| 0.625
| 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
| 1
| 1
| 0
| 0
| 0
| 1
| 0
|
0
| 5
|
082a8020784683d5be4901013682ed3625b2804d
| 24
|
py
|
Python
|
web/version.py
|
levixie/atxserver2
|
f705de3c31cfbaf1c9a8be9ab51030c70cc31d94
|
[
"MIT"
] | null | null | null |
web/version.py
|
levixie/atxserver2
|
f705de3c31cfbaf1c9a8be9ab51030c70cc31d94
|
[
"MIT"
] | null | null | null |
web/version.py
|
levixie/atxserver2
|
f705de3c31cfbaf1c9a8be9ab51030c70cc31d94
|
[
"MIT"
] | null | null | null |
__version__ = "2019.5.8"
| 24
| 24
| 0.708333
| 4
| 24
| 3.25
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.272727
| 0.083333
| 24
| 1
| 24
| 24
| 0.318182
| 0
| 0
| 0
| 0
| 0
| 0.32
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
f252e2246c42b3b338a901f2bd611624c9f6c58a
| 59
|
py
|
Python
|
pyalgo/basic_modules/algocryption_default_values/__init__.py
|
gilad-dotan/pyalgo_pkg
|
132ff3c032c3fc0ae910201611e5d2cde387eb74
|
[
"MIT"
] | 1
|
2021-04-01T08:59:30.000Z
|
2021-04-01T08:59:30.000Z
|
pyalgo/basic_modules/algocryption_default_values/__init__.py
|
gilad-dotan/pyalgo_pkg
|
132ff3c032c3fc0ae910201611e5d2cde387eb74
|
[
"MIT"
] | null | null | null |
pyalgo/basic_modules/algocryption_default_values/__init__.py
|
gilad-dotan/pyalgo_pkg
|
132ff3c032c3fc0ae910201611e5d2cde387eb74
|
[
"MIT"
] | null | null | null |
from . import Simple_Columnar_Transposition_default_values
| 29.5
| 58
| 0.915254
| 7
| 59
| 7.142857
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.067797
| 59
| 1
| 59
| 59
| 0.909091
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
f25e06eb28738cb8f1fc3b1d50ec702106da830c
| 71
|
py
|
Python
|
py_list/py_list.py
|
StanLepunK/PYTHON_basics
|
da803bd72824de281677f3ba4c5d7bd44a7460fb
|
[
"MIT"
] | null | null | null |
py_list/py_list.py
|
StanLepunK/PYTHON_basics
|
da803bd72824de281677f3ba4c5d7bd44a7460fb
|
[
"MIT"
] | null | null | null |
py_list/py_list.py
|
StanLepunK/PYTHON_basics
|
da803bd72824de281677f3ba4c5d7bd44a7460fb
|
[
"MIT"
] | null | null | null |
ma_liste = [1,2,3]
print(ma_liste)
ma_liste[0] = "truc"
print(ma_liste)
| 17.75
| 20
| 0.704225
| 15
| 71
| 3.066667
| 0.533333
| 0.608696
| 0.521739
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.0625
| 0.098592
| 71
| 4
| 21
| 17.75
| 0.65625
| 0
| 0
| 0.5
| 0
| 0
| 0.055556
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0.5
| 1
| 0
| 0
| null | 1
| 1
| 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
| 1
|
0
| 5
|
f27344493979465fe1ad647b0b646e12e8eb2f6a
| 79
|
py
|
Python
|
workaround/__init__.py
|
WorkAroundOnline/python-workaround
|
5f12c0ec683b0f8cf2ce88a8f9c9741b38327ade
|
[
"MIT"
] | null | null | null |
workaround/__init__.py
|
WorkAroundOnline/python-workaround
|
5f12c0ec683b0f8cf2ce88a8f9c9741b38327ade
|
[
"MIT"
] | null | null | null |
workaround/__init__.py
|
WorkAroundOnline/python-workaround
|
5f12c0ec683b0f8cf2ce88a8f9c9741b38327ade
|
[
"MIT"
] | null | null | null |
import workaround.api as api
from .Client import Client
from .Task import Task
| 19.75
| 28
| 0.810127
| 13
| 79
| 4.923077
| 0.538462
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.151899
| 79
| 3
| 29
| 26.333333
| 0.955224
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
f2814af0a7aa0f48cb73985d28cc4c737f793f61
| 4,563
|
py
|
Python
|
plot/box/paths_acrobot_finalPlots.py
|
architsakhadeo/Offline-Hyperparameter-Tuning-for-RL
|
94b8f205b12f0cc59ae8e19b2e6099f34be929d6
|
[
"MIT"
] | null | null | null |
plot/box/paths_acrobot_finalPlots.py
|
architsakhadeo/Offline-Hyperparameter-Tuning-for-RL
|
94b8f205b12f0cc59ae8e19b2e6099f34be929d6
|
[
"MIT"
] | null | null | null |
plot/box/paths_acrobot_finalPlots.py
|
architsakhadeo/Offline-Hyperparameter-Tuning-for-RL
|
94b8f205b12f0cc59ae8e19b2e6099f34be929d6
|
[
"MIT"
] | null | null | null |
ac_rnd = [34, 4, 43, 30, 24, 32, 40, 11, 20, 30, 3, 16, 53, 45, 0, 21, 43, 23, 44, 50, 9, 41, 37, 37, 11, 2, 26, 33, 18, 20]
basepath = "../../data/finalPlots/data/hyperparam_v5/"
basepath_new = "../../data/finalPlots/data/hyperparam_v5_newData/"
ac_true = [basepath + "acrobot/online_learning/esarsa/step15k/sweep/"]
ac_fqi_tc = [basepath + "acrobot/offline_learning/random_restarts/fqi-linear/fqi-adam/alpha_hidden_epsilon/step5k_env/optimalfixed_eps0/lambda1e-3/lockat_baseline_online/"]
ac_fqi_nn = [basepath + "acrobot/offline_learning/random_restarts/fqi/fqi-adam/alpha_hidden_epsilon/step5k_env/optimalfixed_eps0/earlystop/lambda1e-3/lockat_baseline_online/"]
# PLOT 1
ac_knnlaplace_optim_5k = [basepath + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step5k_env/data_optimal/drop0/sweep_rep1/"]
ac_knnraw_optim_5k = [basepath + "acrobot/offline_learning/knn/learning/k3/timeout500/esarsa/step5k_env/data_optimal/drop0/sweep/"]
ac_networkscaledlaplace_optim_5k = [basepath + "acrobot/offline_learning/network/learning/clip_scale_laplace_separated/timeout500/esarsa/step5k_env/data_optimal/sweep/"]
ac_networkscaledraw_optim_5k = [basepath + "acrobot/offline_learning/network/learning/clip_scale_separated/timeout500/esarsa/step5k_env/data_optimal/sweep/"]
# PLOT 2
ac_knnlaplace_avg_5k_new = [basepath_new + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step5k_env/data_suboptimal/drop0/sweep_rep1/"]
ac_knnlaplace_avg_2500_new = [basepath_new + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step2.5k_env/data_suboptimal/drop0/sweep_rep1/"]
ac_knnlaplace_avg_1k_new = [basepath_new + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step1k_env/data_suboptimal/drop0/sweep_rep1/"]
ac_knnlaplace_avg_500_new = [basepath_new + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step500_env/data_suboptimal/drop0/sweep_rep1/"]
ac_knnlaplace_optim_5k_new = [basepath_new + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step5k_env/data_optimal/drop0/sweep_rep1/"]
ac_knnlaplace_bad_5k_new = [basepath_new + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step5k_env/data_subsuboptimal/drop0/sweep_rep1/"]
# PLOT 3
acshift_true = ["../../data/hyperparam_v5/acrobot_shift/online_learning/shift/esarsa/step15k/sweep/"]
# acshift_knnlaplace_optim_5k_50kstep = [basepath + "acrobot_shift/online_learning/shift/esarsa/step50k/best/"]
# acshift_knnlaplace_optim_5k = [basepath + "acrobot_shift/online_learning/shift/esarsa/step15k/all/"]
acshift_knnlaplace_optim_5k = [basepath + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/esarsa/step5k_env/data_optimal/drop0/sweep_rep1/"]
acshift_esarsa_true_trans = ["../../data/hyperparam_v5/acrobot_shift/policy_transfer/shift/load_default/esarsa/all/"]
acshift_esarsa_calibration_trans = ["../../data/hyperparam_v5/acrobot_shift/policy_transfer/shift/load_calibration_default/esarsa/fixed_all/"]
acshift_fqi_tc_optim_5k = [basepath + "acrobot_shift/policy_transfer/shift/load_default/fqi-linear/lambda1e-3/"]
acshift_fqi_nn_optim_5k = [basepath + "acrobot_shift/policy_transfer/shift/load_default/fqi/lambda1e-3/"]
# acshift_knnlaplace_optim_5k = [basepath + "acrobot_shift/online_learning/shift/esarsa/step15k/best/"]
# acshift_esarsa_true_trans = [basepath + "acrobot_shift/policy_transfer/shift/load_default/esarsa/best/"]
# acshift_esarsa_calibration_trans = [basepath + "acrobot_shift/policy_transfer/shift/load_calibration_default/esarsa/fixed/"]
# PLOT temp
ac_dqn = [basepath + "acrobot/online_learning/dqn/step600k/sweep/"]
ac_actorcritic = [basepath + "acrobot/online_learning/ac/step30k/sweep/"]
ac_dqn_knnlaplace_optim = [basepath + "acrobot/offline_learning/knn/learning/k3_laplace/timeout2k/dqn/step5k_env/data_optimal/drop0/sweep_rep1/"]
ac_actorcritic_knnlaplace_optim = [basepath + "acrobot/offline_learning/knn/learning/k3_laplace/timeout500/ac/step5k_env/data_optimal/drop0/sweep_rep1/"]
# PLOT CEM
ac_cemlaplace_optim_5k = [basepath + "acrobot/list/CEMofflineList_KNNlaplace/esarsa/step15k/sweep/"]
ac_true_old = [basepath + "hyperparam_ap_CEM_gridsearch/data/hyperparam_ap/acrobot/online_learning/esarsa/step15k/sweep/"]
ac_knnraw_optim_5k_old = [basepath + "hyperparam_ap_CEM_gridsearch/data/hyperparam_ap/acrobot/offline_learning/k3_timeout750/esarsa/step15k/optimalfixed_eps0/sweep/"]
ac_cemraw_optim_5k_old = [basepath + "hyperparam_ap_CEM_gridsearch/data/hyperparam_ap/acrobot/list/CEMoffline_onlineEvaluation/esarsa/step15k/sweep/"]
| 93.122449
| 175
| 0.82906
| 637
| 4,563
| 5.562009
| 0.186813
| 0.084674
| 0.099351
| 0.077618
| 0.762631
| 0.721987
| 0.720011
| 0.637595
| 0.549534
| 0.467401
| 0
| 0.049275
| 0.048214
| 4,563
| 48
| 176
| 95.0625
| 0.766521
| 0.127548
| 0
| 0
| 0
| 0.433333
| 0.686146
| 0.686146
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
f2a0f3772ed1029e959be940817de8090dfd434c
| 168
|
py
|
Python
|
tests/sublime_mock.py
|
krzystof/phpunitkit
|
a483eeab24fbf04efb2c28ff16f1365dddb73594
|
[
"BSD-3-Clause"
] | null | null | null |
tests/sublime_mock.py
|
krzystof/phpunitkit
|
a483eeab24fbf04efb2c28ff16f1365dddb73594
|
[
"BSD-3-Clause"
] | null | null | null |
tests/sublime_mock.py
|
krzystof/phpunitkit
|
a483eeab24fbf04efb2c28ff16f1365dddb73594
|
[
"BSD-3-Clause"
] | null | null | null |
class sublime():
pass
class sublime_plugin():
class TextCommand(): pass
class WindowCommand(): pass
sublime = sublime()
sublime_plugin = sublime_plugin()
| 16.8
| 33
| 0.708333
| 18
| 168
| 6.444444
| 0.333333
| 0.336207
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.184524
| 168
| 9
| 34
| 18.666667
| 0.846715
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0.428571
| 0
| 0
| 0.571429
| 0
| 1
| 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
| 1
| 0
| 0
| 1
| 0
|
0
| 5
|
4b514f8985b3b13dd916113759761ed513a9f4c5
| 7,452
|
py
|
Python
|
keystone/tests/unit/test_contrib_ec2_core.py
|
10088/keystone
|
1561da645b6512decdc0d307d2ec79a8a4c9cc87
|
[
"Apache-2.0"
] | 615
|
2015-01-07T12:32:52.000Z
|
2022-03-24T03:49:47.000Z
|
keystone/tests/unit/test_contrib_ec2_core.py
|
10088/keystone
|
1561da645b6512decdc0d307d2ec79a8a4c9cc87
|
[
"Apache-2.0"
] | 11
|
2015-04-13T18:52:40.000Z
|
2021-08-21T06:13:05.000Z
|
keystone/tests/unit/test_contrib_ec2_core.py
|
10088/keystone
|
1561da645b6512decdc0d307d2ec79a8a4c9cc87
|
[
"Apache-2.0"
] | 696
|
2015-01-15T00:31:07.000Z
|
2022-03-16T09:56:00.000Z
|
# Copyright 2012 OpenStack Foundation
#
# 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 datetime
import hashlib
import http.client
from keystoneclient.contrib.ec2 import utils as ec2_utils
from oslo_utils import timeutils
from keystone.common import provider_api
from keystone.common import utils
from keystone.tests import unit
from keystone.tests.unit import test_v3
PROVIDERS = provider_api.ProviderAPIs
class EC2ContribCoreV3(test_v3.RestfulTestCase):
def setUp(self):
super(EC2ContribCoreV3, self).setUp()
self.cred_blob, self.credential = unit.new_ec2_credential(
self.user['id'], self.project_id)
PROVIDERS.credential_api.create_credential(
self.credential['id'], self.credential)
def test_valid_authentication_response_with_proper_secret(self):
signer = ec2_utils.Ec2Signer(self.cred_blob['secret'])
timestamp = utils.isotime(timeutils.utcnow())
credentials = {
'access': self.cred_blob['access'],
'secret': self.cred_blob['secret'],
'host': 'localhost',
'verb': 'GET',
'path': '/',
'params': {
'SignatureVersion': '2',
'Action': 'Test',
'Timestamp': timestamp
},
}
credentials['signature'] = signer.generate(credentials)
resp = self.post(
'/ec2tokens',
body={'credentials': credentials},
expected_status=http.client.OK)
self.assertValidProjectScopedTokenResponse(resp, self.user)
def test_valid_authentication_response_with_signature_v4(self):
signer = ec2_utils.Ec2Signer(self.cred_blob['secret'])
timestamp = utils.isotime(timeutils.utcnow())
hashed_payload = (
'GET\n'
'/\n'
'Action=Test\n'
'host:localhost\n'
'x-amz-date:' + timestamp + '\n'
'\n'
'host;x-amz-date\n'
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
)
body_hash = hashlib.sha256(hashed_payload.encode()).hexdigest()
amz_credential = (
'AKIAIOSFODNN7EXAMPLE/%s/us-east-1/iam/aws4_request,' %
timestamp[:8])
credentials = {
'access': self.cred_blob['access'],
'secret': self.cred_blob['secret'],
'host': 'localhost',
'verb': 'GET',
'path': '/',
'params': {
'Action': 'Test',
'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
'X-Amz-SignedHeaders': 'host,x-amz-date,',
'X-Amz-Credential': amz_credential
},
'headers': {
'X-Amz-Date': timestamp
},
'body_hash': body_hash
}
credentials['signature'] = signer.generate(credentials)
resp = self.post(
'/ec2tokens',
body={'credentials': credentials},
expected_status=http.client.OK)
self.assertValidProjectScopedTokenResponse(resp, self.user)
def test_authenticate_with_empty_body_returns_bad_request(self):
self.post(
'/ec2tokens',
body={},
expected_status=http.client.BAD_REQUEST)
def test_authenticate_without_json_request_returns_bad_request(self):
self.post(
'/ec2tokens',
body='not json',
expected_status=http.client.BAD_REQUEST)
def test_authenticate_without_request_body_returns_bad_request(self):
self.post(
'/ec2tokens',
expected_status=http.client.BAD_REQUEST)
def test_authenticate_without_proper_secret_returns_unauthorized(self):
signer = ec2_utils.Ec2Signer('totally not the secret')
timestamp = utils.isotime(timeutils.utcnow())
credentials = {
'access': self.cred_blob['access'],
'secret': 'totally not the secret',
'host': 'localhost',
'verb': 'GET',
'path': '/',
'params': {
'SignatureVersion': '2',
'Action': 'Test',
'Timestamp': timestamp
},
}
credentials['signature'] = signer.generate(credentials)
self.post(
'/ec2tokens',
body={'credentials': credentials},
expected_status=http.client.UNAUTHORIZED)
def test_authenticate_expired_request(self):
self.config_fixture.config(
group='credential',
auth_ttl=5
)
signer = ec2_utils.Ec2Signer(self.cred_blob['secret'])
past = timeutils.utcnow() - datetime.timedelta(minutes=10)
timestamp = utils.isotime(past)
credentials = {
'access': self.cred_blob['access'],
'secret': self.cred_blob['secret'],
'host': 'localhost',
'verb': 'GET',
'path': '/',
'params': {
'SignatureVersion': '2',
'Action': 'Test',
'Timestamp': timestamp
},
}
credentials['signature'] = signer.generate(credentials)
self.post(
'/ec2tokens',
body={'credentials': credentials},
expected_status=http.client.UNAUTHORIZED)
def test_authenticate_expired_request_v4(self):
self.config_fixture.config(
group='credential',
auth_ttl=5
)
signer = ec2_utils.Ec2Signer(self.cred_blob['secret'])
past = timeutils.utcnow() - datetime.timedelta(minutes=10)
timestamp = utils.isotime(past)
hashed_payload = (
'GET\n'
'/\n'
'Action=Test\n'
'host:localhost\n'
'x-amz-date:' + timestamp + '\n'
'\n'
'host;x-amz-date\n'
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
)
body_hash = hashlib.sha256(hashed_payload.encode()).hexdigest()
amz_credential = (
'AKIAIOSFODNN7EXAMPLE/%s/us-east-1/iam/aws4_request,' %
timestamp[:8])
credentials = {
'access': self.cred_blob['access'],
'secret': self.cred_blob['secret'],
'host': 'localhost',
'verb': 'GET',
'path': '/',
'params': {
'Action': 'Test',
'X-Amz-Algorithm': 'AWS4-HMAC-SHA256',
'X-Amz-SignedHeaders': 'host,x-amz-date,',
'X-Amz-Credential': amz_credential
},
'headers': {
'X-Amz-Date': timestamp
},
'body_hash': body_hash
}
credentials['signature'] = signer.generate(credentials)
self.post(
'/ec2tokens',
body={'credentials': credentials},
expected_status=http.client.UNAUTHORIZED)
| 34.985915
| 78
| 0.56978
| 710
| 7,452
| 5.829577
| 0.242254
| 0.02706
| 0.04059
| 0.034791
| 0.740759
| 0.734235
| 0.717565
| 0.717565
| 0.686156
| 0.686156
| 0
| 0.02999
| 0.310923
| 7,452
| 212
| 79
| 35.150943
| 0.776047
| 0.074879
| 0
| 0.751381
| 0
| 0
| 0.183285
| 0.03343
| 0
| 0
| 0
| 0
| 0.01105
| 1
| 0.049724
| false
| 0
| 0.049724
| 0
| 0.104972
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 1
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
4b7677f36b02e5b1fc6470e397cb0afc8d981fea
| 166
|
py
|
Python
|
depynd/__init__.py
|
y-takashina/relatepy
|
9ac5eb2878d9cf76fb8a92e7c1cde854c745ab3c
|
[
"MIT"
] | 10
|
2019-09-27T00:38:52.000Z
|
2022-03-24T04:34:12.000Z
|
depynd/__init__.py
|
y-takashina/relatepy
|
9ac5eb2878d9cf76fb8a92e7c1cde854c745ab3c
|
[
"MIT"
] | 23
|
2018-02-01T05:18:11.000Z
|
2018-10-18T09:15:35.000Z
|
depynd/__init__.py
|
y-takashina/relatepy
|
9ac5eb2878d9cf76fb8a92e7c1cde854c745ab3c
|
[
"MIT"
] | 2
|
2019-03-26T04:26:18.000Z
|
2020-01-20T03:39:25.000Z
|
from depynd import (
information,
feature_selection,
markov_networks,
)
__all__ = [
'information',
'feature_selection',
'markov_networks',
]
| 13.833333
| 24
| 0.656627
| 14
| 166
| 7.214286
| 0.642857
| 0.356436
| 0.534653
| 0.653465
| 0.811881
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.240964
| 166
| 11
| 25
| 15.090909
| 0.801587
| 0
| 0
| 0
| 0
| 0
| 0.259036
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.1
| 0
| 0.1
| 0
| 1
| 0
| 0
| null | 1
| 1
| 1
| 1
| 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
| 5
|
4bbbdc4bb8c6868703775022cab582259a73d0ba
| 64
|
py
|
Python
|
py_tdlib/constructors/file_type_unknown.py
|
Mr-TelegramBot/python-tdlib
|
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
|
[
"MIT"
] | 24
|
2018-10-05T13:04:30.000Z
|
2020-05-12T08:45:34.000Z
|
py_tdlib/constructors/file_type_unknown.py
|
MrMahdi313/python-tdlib
|
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
|
[
"MIT"
] | 3
|
2019-06-26T07:20:20.000Z
|
2021-05-24T13:06:56.000Z
|
py_tdlib/constructors/file_type_unknown.py
|
MrMahdi313/python-tdlib
|
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
|
[
"MIT"
] | 5
|
2018-10-05T14:29:28.000Z
|
2020-08-11T15:04:10.000Z
|
from ..factory import Type
class fileTypeUnknown(Type):
pass
| 10.666667
| 28
| 0.765625
| 8
| 64
| 6.125
| 0.875
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.15625
| 64
| 5
| 29
| 12.8
| 0.907407
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0.333333
| 0.333333
| 0
| 0.666667
| 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
| 1
| 1
| 1
| 0
| 0
| 0
|
0
| 5
|
4bc3e98ebf11e3257ce8d7fa626f28762efc1b00
| 199
|
py
|
Python
|
Mundo I/D012 - 5 por cento de desconto.py
|
Orecruta/Exercicios-Python
|
129a15930ea22df1f0a7d6bd39a7ac28be515034
|
[
"MIT"
] | null | null | null |
Mundo I/D012 - 5 por cento de desconto.py
|
Orecruta/Exercicios-Python
|
129a15930ea22df1f0a7d6bd39a7ac28be515034
|
[
"MIT"
] | null | null | null |
Mundo I/D012 - 5 por cento de desconto.py
|
Orecruta/Exercicios-Python
|
129a15930ea22df1f0a7d6bd39a7ac28be515034
|
[
"MIT"
] | null | null | null |
print('====== DESAFIO 012 - 5% DE DESCONTO ======')
p = float(input('Qual o preço da roupa? R$'))
d = p - (p/100*5)
print(f'De R${p}, você irá pagar R${d:.2f} na roupa por causa dos 5% de desconto!')
| 49.75
| 83
| 0.58794
| 39
| 199
| 3
| 0.666667
| 0.051282
| 0.188034
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.060606
| 0.170854
| 199
| 4
| 83
| 49.75
| 0.648485
| 0
| 0
| 0
| 0
| 0.25
| 0.7
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0.5
| 0
| 0
| 0
| null | 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
|
0
| 5
|
29d1351df7609670cb0cc4afc6f98e9dde5ff879
| 142
|
py
|
Python
|
sql/__init__.py
|
txgyy/ipproxytool
|
59db3c4394abaf3df4a31ac35d297a1c7f929f65
|
[
"MIT"
] | 11
|
2018-07-24T10:45:54.000Z
|
2021-06-30T08:42:18.000Z
|
sql/__init__.py
|
txgyy/ipproxytool
|
59db3c4394abaf3df4a31ac35d297a1c7f929f65
|
[
"MIT"
] | 3
|
2021-03-18T20:24:09.000Z
|
2021-12-13T19:44:52.000Z
|
sql/__init__.py
|
txgyy/ipproxytool
|
59db3c4394abaf3df4a31ac35d297a1c7f929f65
|
[
"MIT"
] | 4
|
2018-11-07T07:15:47.000Z
|
2020-04-15T14:15:18.000Z
|
#-*- coding: utf-8 -*-
import sql.sql_base
from sql.mysql import MySql
from sql.mongodb import Mongodb
from sql.sql_manager import SqlManager
| 23.666667
| 38
| 0.78169
| 23
| 142
| 4.73913
| 0.478261
| 0.192661
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.008065
| 0.126761
| 142
| 6
| 38
| 23.666667
| 0.870968
| 0.147887
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
29f87aa29e845f3b816e68a5371dd310fc200e9a
| 2,323
|
py
|
Python
|
obfsproxy/test/int_tests/test_pits.py
|
aallai/pyobfsproxy
|
9c88a40f0475a0c510f14d92a10437321ac14da5
|
[
"BSD-3-Clause"
] | 1
|
2016-12-17T11:26:46.000Z
|
2016-12-17T11:26:46.000Z
|
obfsproxy/test/int_tests/test_pits.py
|
aallai/pyobfsproxy
|
9c88a40f0475a0c510f14d92a10437321ac14da5
|
[
"BSD-3-Clause"
] | null | null | null |
obfsproxy/test/int_tests/test_pits.py
|
aallai/pyobfsproxy
|
9c88a40f0475a0c510f14d92a10437321ac14da5
|
[
"BSD-3-Clause"
] | null | null | null |
import os
import logging
import twisted.trial.unittest
import pits
class PITSTest(twisted.trial.unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
self.treader.cleanup()
def _doTest(self, transport_name, test_case_file):
self.treader = pits.TestReader(self.assertTrue, test_case_file)
return self.treader.do_test(
('%s' % transport_name,
'client',
'127.0.0.1:%d' % pits.CLIENT_OBFSPORT,
'--dest=127.0.0.1:%d' % pits.SERVER_OBFSPORT),
('%s' % transport_name,
'server',
'127.0.0.1:%d' % pits.SERVER_OBFSPORT,
'--dest=127.0.0.1:%d' % self.treader.pits.get_pits_inbound_address().port))
def _doTest_shared_secret(self, transport_name, test_case_file):
self.treader = pits.TestReader(self.assertTrue, test_case_file)
return self.treader.do_test(
('%s' % transport_name,
'client',
'127.0.0.1:%d' % pits.CLIENT_OBFSPORT,
'--shared-secret=test',
'--dest=127.0.0.1:%d' % pits.SERVER_OBFSPORT),
('%s' % transport_name,
'server',
'127.0.0.1:%d' % pits.SERVER_OBFSPORT,
'--shared-secret=test',
'--dest=127.0.0.1:%d' % self.treader.pits.get_pits_inbound_address().port))
# XXX This is pretty ridiculous. Find a smarter way to make up for the
# absense of load_tests().
def test_dummy_1(self):
return self._doTest("dummy", "../test_case.pits")
def test_dummy_2(self):
return self._doTest("dummy", "../test_case_simple.pits")
def test_obfs2_1(self):
return self._doTest("obfs2", "../test_case.pits")
def test_obfs2_2(self):
return self._doTest("obfs2", "../test_case_simple.pits")
def test_obfs2_shared_secret_1(self):
return self._doTest_shared_secret("obfs2", "../test_case.pits")
def test_obfs2_shared_secret_2(self):
return self._doTest_shared_secret("obfs2", "../test_case_simple.pits")
def test_obfs3_1(self):
return self._doTest("obfs3", "../test_case.pits")
def test_obfs3_2(self):
return self._doTest("obfs3", "../test_case_simple.pits")
if __name__ == '__main__':
from unittest import main
main()
| 33.666667
| 88
| 0.611279
| 306
| 2,323
| 4.362745
| 0.222222
| 0.07191
| 0.029963
| 0.035955
| 0.758802
| 0.73633
| 0.718352
| 0.500375
| 0.500375
| 0.432959
| 0
| 0.038702
| 0.24365
| 2,323
| 68
| 89
| 34.161765
| 0.721116
| 0.040034
| 0
| 0.423077
| 0
| 0
| 0.183206
| 0.043107
| 0
| 0
| 0
| 0
| 0.038462
| 1
| 0.230769
| false
| 0.019231
| 0.096154
| 0.153846
| 0.538462
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 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
| 1
| 0
|
0
| 5
|
d9b52b61ebe9747a41bbf93bd610ce703fe9b610
| 45
|
py
|
Python
|
srv/responses/__init__.py
|
atomicfruitcake/gnutty
|
b96493dfb6fa5010e67e104e9baca5a5e06373ab
|
[
"MIT"
] | null | null | null |
srv/responses/__init__.py
|
atomicfruitcake/gnutty
|
b96493dfb6fa5010e67e104e9baca5a5e06373ab
|
[
"MIT"
] | null | null | null |
srv/responses/__init__.py
|
atomicfruitcake/gnutty
|
b96493dfb6fa5010e67e104e9baca5a5e06373ab
|
[
"MIT"
] | null | null | null |
"""!
@author atomicfruitcake
@date 2020
"""
| 7.5
| 23
| 0.644444
| 4
| 45
| 7.25
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.105263
| 0.155556
| 45
| 5
| 24
| 9
| 0.657895
| 0.822222
| 0
| null | 0
| null | 0
| 0
| null | 0
| 0
| 0
| null | 1
| null | true
| 0
| 0
| null | null | null | 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
d9b9f5c2f53cd5e6c472076078c22c0e59e80ee6
| 55
|
py
|
Python
|
Scripts/Commands/date.py
|
SeboTime/Sebo-Dos
|
4dbc9481bcc497c5f9f77ec665cbe3263c262f1f
|
[
"Apache-2.0"
] | 1
|
2021-12-26T12:09:42.000Z
|
2021-12-26T12:09:42.000Z
|
Scripts/Commands/date.py
|
SeboTime/Sebo-Dos
|
4dbc9481bcc497c5f9f77ec665cbe3263c262f1f
|
[
"Apache-2.0"
] | null | null | null |
Scripts/Commands/date.py
|
SeboTime/Sebo-Dos
|
4dbc9481bcc497c5f9f77ec665cbe3263c262f1f
|
[
"Apache-2.0"
] | null | null | null |
import datetime
print("")
print(datetime.date.today())
| 13.75
| 28
| 0.745455
| 7
| 55
| 5.857143
| 0.714286
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.072727
| 55
| 4
| 28
| 13.75
| 0.803922
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.333333
| 0
| 0.333333
| 0.666667
| 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
| 1
| 0
| 1
| 0
| 0
| 1
|
0
| 5
|
d9c07d42fbf6aa7132b681df0c30ef8698eeef7f
| 54
|
py
|
Python
|
hello-world-jack-s.py
|
egriswol/astr-119-section-assignments
|
6cbeb0397b6a1a9102e8efa771e8d9ed1d3fab18
|
[
"MIT"
] | 2
|
2018-09-28T18:46:05.000Z
|
2018-09-28T19:00:27.000Z
|
hello-world-jack-s.py
|
egriswol/astr-119-section-assignments
|
6cbeb0397b6a1a9102e8efa771e8d9ed1d3fab18
|
[
"MIT"
] | 67
|
2018-09-26T06:39:43.000Z
|
2018-10-03T15:32:12.000Z
|
hello-world-jack-s.py
|
egriswol/astr-119-section-assignments
|
6cbeb0397b6a1a9102e8efa771e8d9ed1d3fab18
|
[
"MIT"
] | 62
|
2018-09-27T20:12:32.000Z
|
2018-10-03T23:53:47.000Z
|
#!/usr/bin/env python3
print("Hello from Jack Soto.")
| 18
| 30
| 0.703704
| 9
| 54
| 4.222222
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.020833
| 0.111111
| 54
| 3
| 30
| 18
| 0.770833
| 0.388889
| 0
| 0
| 0
| 0
| 0.636364
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0
| 0
| 0
| 1
| 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
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 1
|
0
| 5
|
d9df971acd713ba51d1158094340b0a6492442e6
| 75
|
py
|
Python
|
the-python-standard-library-by-example/sysconfig/sysconfig_get_platform.py
|
gottaegbert/penter
|
8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d
|
[
"MIT"
] | 13
|
2020-01-04T07:37:38.000Z
|
2021-08-31T05:19:58.000Z
|
the-python-standard-library-by-example/sysconfig/sysconfig_get_platform.py
|
gottaegbert/penter
|
8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d
|
[
"MIT"
] | 3
|
2020-06-05T22:42:53.000Z
|
2020-08-24T07:18:54.000Z
|
the-python-standard-library-by-example/sysconfig/sysconfig_get_platform.py
|
gottaegbert/penter
|
8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d
|
[
"MIT"
] | 9
|
2020-10-19T04:53:06.000Z
|
2021-08-31T05:20:01.000Z
|
# -*- coding: utf-8 -*-
import sysconfig
print(sysconfig.get_platform())
| 12.5
| 31
| 0.68
| 9
| 75
| 5.555556
| 0.888889
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.015385
| 0.133333
| 75
| 5
| 32
| 15
| 0.753846
| 0.28
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.5
| 0
| 0.5
| 0.5
| 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
| 1
| 0
| 1
| 0
| 0
| 1
|
0
| 5
|
d9e2f682dcba9afb4dfd2269f661dcc502ea666a
| 66
|
py
|
Python
|
ark_nlp/processor/tokenizer/__init__.py
|
Zrealshadow/ark-nlp
|
159045d17747524bd4e9af7f65f1d0283e8098e6
|
[
"Apache-2.0"
] | 258
|
2021-09-04T14:01:13.000Z
|
2022-03-31T16:34:52.000Z
|
ark_nlp/processor/tokenizer/__init__.py
|
Zrealshadow/ark-nlp
|
159045d17747524bd4e9af7f65f1d0283e8098e6
|
[
"Apache-2.0"
] | 17
|
2022-01-13T04:46:02.000Z
|
2022-03-31T16:34:07.000Z
|
ark_nlp/processor/tokenizer/__init__.py
|
Zrealshadow/ark-nlp
|
159045d17747524bd4e9af7f65f1d0283e8098e6
|
[
"Apache-2.0"
] | 36
|
2021-11-17T06:18:45.000Z
|
2022-03-30T11:32:26.000Z
|
from ark_nlp.processor.tokenizer._tokenizer import BaseTokenizer
| 33
| 65
| 0.878788
| 8
| 66
| 7
| 0.875
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.075758
| 66
| 1
| 66
| 66
| 0.918033
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
8abf9539bcd030271a0b06219cc53a1e22a22304
| 55,465
|
py
|
Python
|
sdk/python/pulumi_azure/iot/_inputs.py
|
aangelisc/pulumi-azure
|
71dd9c75403146e16f7480e5a60b08bc0329660e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_azure/iot/_inputs.py
|
aangelisc/pulumi-azure
|
71dd9c75403146e16f7480e5a60b08bc0329660e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
sdk/python/pulumi_azure/iot/_inputs.py
|
aangelisc/pulumi-azure
|
71dd9c75403146e16f7480e5a60b08bc0329660e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'IoTHubEndpointArgs',
'IoTHubEnrichmentArgs',
'IoTHubFallbackRouteArgs',
'IoTHubFileUploadArgs',
'IoTHubIpFilterRuleArgs',
'IoTHubRouteArgs',
'IoTHubSharedAccessPolicyArgs',
'IoTHubSkuArgs',
'IotHubDpsLinkedHubArgs',
'IotHubDpsSkuArgs',
'SecurityDeviceGroupAllowRuleArgs',
'SecurityDeviceGroupRangeRuleArgs',
'SecuritySolutionRecommendationsEnabledArgs',
'TimeSeriesInsightsGen2EnvironmentStorageArgs',
'TimeSeriesInsightsReferenceDataSetKeyPropertyArgs',
]
@pulumi.input_type
class IoTHubEndpointArgs:
def __init__(__self__, *,
connection_string: pulumi.Input[str],
name: pulumi.Input[str],
type: pulumi.Input[str],
batch_frequency_in_seconds: Optional[pulumi.Input[int]] = None,
container_name: Optional[pulumi.Input[str]] = None,
encoding: Optional[pulumi.Input[str]] = None,
file_name_format: Optional[pulumi.Input[str]] = None,
max_chunk_size_in_bytes: Optional[pulumi.Input[int]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] connection_string: The connection string for the endpoint.
:param pulumi.Input[str] name: The name of the endpoint. The name must be unique across endpoint types. The following names are reserved: `events`, `operationsMonitoringEvents`, `fileNotifications` and `$default`.
:param pulumi.Input[str] type: The type of the endpoint. Possible values are `AzureIotHub.StorageContainer`, `AzureIotHub.ServiceBusQueue`, `AzureIotHub.ServiceBusTopic` or `AzureIotHub.EventHub`.
:param pulumi.Input[int] batch_frequency_in_seconds: Time interval at which blobs are written to storage. Value should be between 60 and 720 seconds. Default value is 300 seconds. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
:param pulumi.Input[str] container_name: The name of storage container in the storage account. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
:param pulumi.Input[str] encoding: Encoding that is used to serialize messages to blobs. Supported values are 'avro' and 'avrodeflate'. Default value is 'avro'. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
:param pulumi.Input[str] file_name_format: File name format for the blob. Default format is ``{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}``. All parameters are mandatory but can be reordered. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
:param pulumi.Input[int] max_chunk_size_in_bytes: Maximum number of bytes for each blob written to storage. Value should be between 10485760(10MB) and 524288000(500MB). Default value is 314572800(300MB). This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
:param pulumi.Input[str] resource_group_name: The resource group in which the endpoint will be created.
"""
pulumi.set(__self__, "connection_string", connection_string)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "type", type)
if batch_frequency_in_seconds is not None:
pulumi.set(__self__, "batch_frequency_in_seconds", batch_frequency_in_seconds)
if container_name is not None:
pulumi.set(__self__, "container_name", container_name)
if encoding is not None:
pulumi.set(__self__, "encoding", encoding)
if file_name_format is not None:
pulumi.set(__self__, "file_name_format", file_name_format)
if max_chunk_size_in_bytes is not None:
pulumi.set(__self__, "max_chunk_size_in_bytes", max_chunk_size_in_bytes)
if resource_group_name is not None:
pulumi.set(__self__, "resource_group_name", resource_group_name)
@property
@pulumi.getter(name="connectionString")
def connection_string(self) -> pulumi.Input[str]:
"""
The connection string for the endpoint.
"""
return pulumi.get(self, "connection_string")
@connection_string.setter
def connection_string(self, value: pulumi.Input[str]):
pulumi.set(self, "connection_string", value)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The name of the endpoint. The name must be unique across endpoint types. The following names are reserved: `events`, `operationsMonitoringEvents`, `fileNotifications` and `$default`.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def type(self) -> pulumi.Input[str]:
"""
The type of the endpoint. Possible values are `AzureIotHub.StorageContainer`, `AzureIotHub.ServiceBusQueue`, `AzureIotHub.ServiceBusTopic` or `AzureIotHub.EventHub`.
"""
return pulumi.get(self, "type")
@type.setter
def type(self, value: pulumi.Input[str]):
pulumi.set(self, "type", value)
@property
@pulumi.getter(name="batchFrequencyInSeconds")
def batch_frequency_in_seconds(self) -> Optional[pulumi.Input[int]]:
"""
Time interval at which blobs are written to storage. Value should be between 60 and 720 seconds. Default value is 300 seconds. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
"""
return pulumi.get(self, "batch_frequency_in_seconds")
@batch_frequency_in_seconds.setter
def batch_frequency_in_seconds(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "batch_frequency_in_seconds", value)
@property
@pulumi.getter(name="containerName")
def container_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of storage container in the storage account. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
"""
return pulumi.get(self, "container_name")
@container_name.setter
def container_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "container_name", value)
@property
@pulumi.getter
def encoding(self) -> Optional[pulumi.Input[str]]:
"""
Encoding that is used to serialize messages to blobs. Supported values are 'avro' and 'avrodeflate'. Default value is 'avro'. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
"""
return pulumi.get(self, "encoding")
@encoding.setter
def encoding(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "encoding", value)
@property
@pulumi.getter(name="fileNameFormat")
def file_name_format(self) -> Optional[pulumi.Input[str]]:
"""
File name format for the blob. Default format is ``{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}``. All parameters are mandatory but can be reordered. This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
"""
return pulumi.get(self, "file_name_format")
@file_name_format.setter
def file_name_format(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "file_name_format", value)
@property
@pulumi.getter(name="maxChunkSizeInBytes")
def max_chunk_size_in_bytes(self) -> Optional[pulumi.Input[int]]:
"""
Maximum number of bytes for each blob written to storage. Value should be between 10485760(10MB) and 524288000(500MB). Default value is 314572800(300MB). This attribute is mandatory for endpoint type `AzureIotHub.StorageContainer`.
"""
return pulumi.get(self, "max_chunk_size_in_bytes")
@max_chunk_size_in_bytes.setter
def max_chunk_size_in_bytes(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "max_chunk_size_in_bytes", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> Optional[pulumi.Input[str]]:
"""
The resource group in which the endpoint will be created.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "resource_group_name", value)
@pulumi.input_type
class IoTHubEnrichmentArgs:
def __init__(__self__, *,
endpoint_names: pulumi.Input[Sequence[pulumi.Input[str]]],
key: pulumi.Input[str],
value: pulumi.Input[str]):
"""
:param pulumi.Input[Sequence[pulumi.Input[str]]] endpoint_names: The list of endpoints which will be enriched.
:param pulumi.Input[str] key: The key of the enrichment.
:param pulumi.Input[str] value: The value of the enrichment. Value can be any static string, the name of the IoT hub sending the message (use `$iothubname`) or information from the device twin (ex: `$twin.tags.latitude`)
"""
pulumi.set(__self__, "endpoint_names", endpoint_names)
pulumi.set(__self__, "key", key)
pulumi.set(__self__, "value", value)
@property
@pulumi.getter(name="endpointNames")
def endpoint_names(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:
"""
The list of endpoints which will be enriched.
"""
return pulumi.get(self, "endpoint_names")
@endpoint_names.setter
def endpoint_names(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]):
pulumi.set(self, "endpoint_names", value)
@property
@pulumi.getter
def key(self) -> pulumi.Input[str]:
"""
The key of the enrichment.
"""
return pulumi.get(self, "key")
@key.setter
def key(self, value: pulumi.Input[str]):
pulumi.set(self, "key", value)
@property
@pulumi.getter
def value(self) -> pulumi.Input[str]:
"""
The value of the enrichment. Value can be any static string, the name of the IoT hub sending the message (use `$iothubname`) or information from the device twin (ex: `$twin.tags.latitude`)
"""
return pulumi.get(self, "value")
@value.setter
def value(self, value: pulumi.Input[str]):
pulumi.set(self, "value", value)
@pulumi.input_type
class IoTHubFallbackRouteArgs:
def __init__(__self__, *,
condition: Optional[pulumi.Input[str]] = None,
enabled: Optional[pulumi.Input[bool]] = None,
endpoint_names: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
source: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] condition: The condition that is evaluated to apply the routing rule. If no condition is provided, it evaluates to true by default. For grammar, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language.
:param pulumi.Input[bool] enabled: Used to specify whether the fallback route is enabled.
:param pulumi.Input[Sequence[pulumi.Input[str]]] endpoint_names: The endpoints to which messages that satisfy the condition are routed. Currently only 1 endpoint is allowed.
:param pulumi.Input[str] source: The source that the routing rule is to be applied to, such as `DeviceMessages`. Possible values include: `RoutingSourceInvalid`, `RoutingSourceDeviceMessages`, `RoutingSourceTwinChangeEvents`, `RoutingSourceDeviceLifecycleEvents`, `RoutingSourceDeviceJobLifecycleEvents`.
"""
if condition is not None:
pulumi.set(__self__, "condition", condition)
if enabled is not None:
pulumi.set(__self__, "enabled", enabled)
if endpoint_names is not None:
pulumi.set(__self__, "endpoint_names", endpoint_names)
if source is not None:
pulumi.set(__self__, "source", source)
@property
@pulumi.getter
def condition(self) -> Optional[pulumi.Input[str]]:
"""
The condition that is evaluated to apply the routing rule. If no condition is provided, it evaluates to true by default. For grammar, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language.
"""
return pulumi.get(self, "condition")
@condition.setter
def condition(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "condition", value)
@property
@pulumi.getter
def enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Used to specify whether the fallback route is enabled.
"""
return pulumi.get(self, "enabled")
@enabled.setter
def enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "enabled", value)
@property
@pulumi.getter(name="endpointNames")
def endpoint_names(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
The endpoints to which messages that satisfy the condition are routed. Currently only 1 endpoint is allowed.
"""
return pulumi.get(self, "endpoint_names")
@endpoint_names.setter
def endpoint_names(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "endpoint_names", value)
@property
@pulumi.getter
def source(self) -> Optional[pulumi.Input[str]]:
"""
The source that the routing rule is to be applied to, such as `DeviceMessages`. Possible values include: `RoutingSourceInvalid`, `RoutingSourceDeviceMessages`, `RoutingSourceTwinChangeEvents`, `RoutingSourceDeviceLifecycleEvents`, `RoutingSourceDeviceJobLifecycleEvents`.
"""
return pulumi.get(self, "source")
@source.setter
def source(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "source", value)
@pulumi.input_type
class IoTHubFileUploadArgs:
def __init__(__self__, *,
connection_string: pulumi.Input[str],
container_name: pulumi.Input[str],
default_ttl: Optional[pulumi.Input[str]] = None,
lock_duration: Optional[pulumi.Input[str]] = None,
max_delivery_count: Optional[pulumi.Input[int]] = None,
notifications: Optional[pulumi.Input[bool]] = None,
sas_ttl: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] connection_string: The connection string for the Azure Storage account to which files are uploaded.
:param pulumi.Input[str] container_name: The name of the root container where you upload files. The container need not exist but should be creatable using the connection_string specified.
:param pulumi.Input[str] default_ttl: The period of time for which a file upload notification message is available to consume before it is expired by the IoT hub, specified as an [ISO 8601 timespan duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This value must be between 1 minute and 48 hours, and evaluates to 'PT1H' by default.
:param pulumi.Input[str] lock_duration: The lock duration for the file upload notifications queue, specified as an [ISO 8601 timespan duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This value must be between 5 and 300 seconds, and evaluates to 'PT1M' by default.
:param pulumi.Input[int] max_delivery_count: The number of times the IoT hub attempts to deliver a file upload notification message. It evaluates to 10 by default.
:param pulumi.Input[bool] notifications: Used to specify whether file notifications are sent to IoT Hub on upload. It evaluates to false by default.
:param pulumi.Input[str] sas_ttl: The period of time for which the SAS URI generated by IoT Hub for file upload is valid, specified as an [ISO 8601 timespan duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This value must be between 1 minute and 24 hours, and evaluates to 'PT1H' by default.
"""
pulumi.set(__self__, "connection_string", connection_string)
pulumi.set(__self__, "container_name", container_name)
if default_ttl is not None:
pulumi.set(__self__, "default_ttl", default_ttl)
if lock_duration is not None:
pulumi.set(__self__, "lock_duration", lock_duration)
if max_delivery_count is not None:
pulumi.set(__self__, "max_delivery_count", max_delivery_count)
if notifications is not None:
pulumi.set(__self__, "notifications", notifications)
if sas_ttl is not None:
pulumi.set(__self__, "sas_ttl", sas_ttl)
@property
@pulumi.getter(name="connectionString")
def connection_string(self) -> pulumi.Input[str]:
"""
The connection string for the Azure Storage account to which files are uploaded.
"""
return pulumi.get(self, "connection_string")
@connection_string.setter
def connection_string(self, value: pulumi.Input[str]):
pulumi.set(self, "connection_string", value)
@property
@pulumi.getter(name="containerName")
def container_name(self) -> pulumi.Input[str]:
"""
The name of the root container where you upload files. The container need not exist but should be creatable using the connection_string specified.
"""
return pulumi.get(self, "container_name")
@container_name.setter
def container_name(self, value: pulumi.Input[str]):
pulumi.set(self, "container_name", value)
@property
@pulumi.getter(name="defaultTtl")
def default_ttl(self) -> Optional[pulumi.Input[str]]:
"""
The period of time for which a file upload notification message is available to consume before it is expired by the IoT hub, specified as an [ISO 8601 timespan duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This value must be between 1 minute and 48 hours, and evaluates to 'PT1H' by default.
"""
return pulumi.get(self, "default_ttl")
@default_ttl.setter
def default_ttl(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "default_ttl", value)
@property
@pulumi.getter(name="lockDuration")
def lock_duration(self) -> Optional[pulumi.Input[str]]:
"""
The lock duration for the file upload notifications queue, specified as an [ISO 8601 timespan duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This value must be between 5 and 300 seconds, and evaluates to 'PT1M' by default.
"""
return pulumi.get(self, "lock_duration")
@lock_duration.setter
def lock_duration(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "lock_duration", value)
@property
@pulumi.getter(name="maxDeliveryCount")
def max_delivery_count(self) -> Optional[pulumi.Input[int]]:
"""
The number of times the IoT hub attempts to deliver a file upload notification message. It evaluates to 10 by default.
"""
return pulumi.get(self, "max_delivery_count")
@max_delivery_count.setter
def max_delivery_count(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "max_delivery_count", value)
@property
@pulumi.getter
def notifications(self) -> Optional[pulumi.Input[bool]]:
"""
Used to specify whether file notifications are sent to IoT Hub on upload. It evaluates to false by default.
"""
return pulumi.get(self, "notifications")
@notifications.setter
def notifications(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "notifications", value)
@property
@pulumi.getter(name="sasTtl")
def sas_ttl(self) -> Optional[pulumi.Input[str]]:
"""
The period of time for which the SAS URI generated by IoT Hub for file upload is valid, specified as an [ISO 8601 timespan duration](https://en.wikipedia.org/wiki/ISO_8601#Durations). This value must be between 1 minute and 24 hours, and evaluates to 'PT1H' by default.
"""
return pulumi.get(self, "sas_ttl")
@sas_ttl.setter
def sas_ttl(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "sas_ttl", value)
@pulumi.input_type
class IoTHubIpFilterRuleArgs:
def __init__(__self__, *,
action: pulumi.Input[str],
ip_mask: pulumi.Input[str],
name: pulumi.Input[str]):
"""
:param pulumi.Input[str] action: The desired action for requests captured by this rule. Possible values are `Accept`, `Reject`
:param pulumi.Input[str] ip_mask: The IP address range in CIDR notation for the rule.
:param pulumi.Input[str] name: The name of the filter.
"""
pulumi.set(__self__, "action", action)
pulumi.set(__self__, "ip_mask", ip_mask)
pulumi.set(__self__, "name", name)
@property
@pulumi.getter
def action(self) -> pulumi.Input[str]:
"""
The desired action for requests captured by this rule. Possible values are `Accept`, `Reject`
"""
return pulumi.get(self, "action")
@action.setter
def action(self, value: pulumi.Input[str]):
pulumi.set(self, "action", value)
@property
@pulumi.getter(name="ipMask")
def ip_mask(self) -> pulumi.Input[str]:
"""
The IP address range in CIDR notation for the rule.
"""
return pulumi.get(self, "ip_mask")
@ip_mask.setter
def ip_mask(self, value: pulumi.Input[str]):
pulumi.set(self, "ip_mask", value)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The name of the filter.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@pulumi.input_type
class IoTHubRouteArgs:
def __init__(__self__, *,
enabled: pulumi.Input[bool],
endpoint_names: pulumi.Input[Sequence[pulumi.Input[str]]],
name: pulumi.Input[str],
source: pulumi.Input[str],
condition: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[bool] enabled: Used to specify whether a route is enabled.
:param pulumi.Input[Sequence[pulumi.Input[str]]] endpoint_names: The list of endpoints to which messages that satisfy the condition are routed.
:param pulumi.Input[str] name: The name of the route.
:param pulumi.Input[str] source: The source that the routing rule is to be applied to, such as `DeviceMessages`. Possible values include: `RoutingSourceInvalid`, `RoutingSourceDeviceMessages`, `RoutingSourceTwinChangeEvents`, `RoutingSourceDeviceLifecycleEvents`, `RoutingSourceDeviceJobLifecycleEvents`.
:param pulumi.Input[str] condition: The condition that is evaluated to apply the routing rule. If no condition is provided, it evaluates to true by default. For grammar, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language.
"""
pulumi.set(__self__, "enabled", enabled)
pulumi.set(__self__, "endpoint_names", endpoint_names)
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "source", source)
if condition is not None:
pulumi.set(__self__, "condition", condition)
@property
@pulumi.getter
def enabled(self) -> pulumi.Input[bool]:
"""
Used to specify whether a route is enabled.
"""
return pulumi.get(self, "enabled")
@enabled.setter
def enabled(self, value: pulumi.Input[bool]):
pulumi.set(self, "enabled", value)
@property
@pulumi.getter(name="endpointNames")
def endpoint_names(self) -> pulumi.Input[Sequence[pulumi.Input[str]]]:
"""
The list of endpoints to which messages that satisfy the condition are routed.
"""
return pulumi.get(self, "endpoint_names")
@endpoint_names.setter
def endpoint_names(self, value: pulumi.Input[Sequence[pulumi.Input[str]]]):
pulumi.set(self, "endpoint_names", value)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The name of the route.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def source(self) -> pulumi.Input[str]:
"""
The source that the routing rule is to be applied to, such as `DeviceMessages`. Possible values include: `RoutingSourceInvalid`, `RoutingSourceDeviceMessages`, `RoutingSourceTwinChangeEvents`, `RoutingSourceDeviceLifecycleEvents`, `RoutingSourceDeviceJobLifecycleEvents`.
"""
return pulumi.get(self, "source")
@source.setter
def source(self, value: pulumi.Input[str]):
pulumi.set(self, "source", value)
@property
@pulumi.getter
def condition(self) -> Optional[pulumi.Input[str]]:
"""
The condition that is evaluated to apply the routing rule. If no condition is provided, it evaluates to true by default. For grammar, see: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-query-language.
"""
return pulumi.get(self, "condition")
@condition.setter
def condition(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "condition", value)
@pulumi.input_type
class IoTHubSharedAccessPolicyArgs:
def __init__(__self__, *,
key_name: Optional[pulumi.Input[str]] = None,
permissions: Optional[pulumi.Input[str]] = None,
primary_key: Optional[pulumi.Input[str]] = None,
secondary_key: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] key_name: The name of the shared access policy.
:param pulumi.Input[str] permissions: The permissions assigned to the shared access policy.
:param pulumi.Input[str] primary_key: The primary key.
:param pulumi.Input[str] secondary_key: The secondary key.
"""
if key_name is not None:
pulumi.set(__self__, "key_name", key_name)
if permissions is not None:
pulumi.set(__self__, "permissions", permissions)
if primary_key is not None:
pulumi.set(__self__, "primary_key", primary_key)
if secondary_key is not None:
pulumi.set(__self__, "secondary_key", secondary_key)
@property
@pulumi.getter(name="keyName")
def key_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the shared access policy.
"""
return pulumi.get(self, "key_name")
@key_name.setter
def key_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "key_name", value)
@property
@pulumi.getter
def permissions(self) -> Optional[pulumi.Input[str]]:
"""
The permissions assigned to the shared access policy.
"""
return pulumi.get(self, "permissions")
@permissions.setter
def permissions(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "permissions", value)
@property
@pulumi.getter(name="primaryKey")
def primary_key(self) -> Optional[pulumi.Input[str]]:
"""
The primary key.
"""
return pulumi.get(self, "primary_key")
@primary_key.setter
def primary_key(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "primary_key", value)
@property
@pulumi.getter(name="secondaryKey")
def secondary_key(self) -> Optional[pulumi.Input[str]]:
"""
The secondary key.
"""
return pulumi.get(self, "secondary_key")
@secondary_key.setter
def secondary_key(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "secondary_key", value)
@pulumi.input_type
class IoTHubSkuArgs:
def __init__(__self__, *,
capacity: pulumi.Input[int],
name: pulumi.Input[str]):
"""
:param pulumi.Input[int] capacity: The number of provisioned IoT Hub units.
:param pulumi.Input[str] name: The name of the sku. Possible values are `B1`, `B2`, `B3`, `F1`, `S1`, `S2`, and `S3`.
"""
pulumi.set(__self__, "capacity", capacity)
pulumi.set(__self__, "name", name)
@property
@pulumi.getter
def capacity(self) -> pulumi.Input[int]:
"""
The number of provisioned IoT Hub units.
"""
return pulumi.get(self, "capacity")
@capacity.setter
def capacity(self, value: pulumi.Input[int]):
pulumi.set(self, "capacity", value)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The name of the sku. Possible values are `B1`, `B2`, `B3`, `F1`, `S1`, `S2`, and `S3`.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@pulumi.input_type
class IotHubDpsLinkedHubArgs:
def __init__(__self__, *,
connection_string: pulumi.Input[str],
location: pulumi.Input[str],
allocation_weight: Optional[pulumi.Input[int]] = None,
apply_allocation_policy: Optional[pulumi.Input[bool]] = None,
hostname: Optional[pulumi.Input[str]] = None):
"""
:param pulumi.Input[str] connection_string: The connection string to connect to the IoT Hub. Changing this forces a new resource.
:param pulumi.Input[str] location: The location of the IoT hub. Changing this forces a new resource.
:param pulumi.Input[int] allocation_weight: The weight applied to the IoT Hub. Defaults to 0.
:param pulumi.Input[bool] apply_allocation_policy: Determines whether to apply allocation policies to the IoT Hub. Defaults to false.
:param pulumi.Input[str] hostname: The IoT Hub hostname.
"""
pulumi.set(__self__, "connection_string", connection_string)
pulumi.set(__self__, "location", location)
if allocation_weight is not None:
pulumi.set(__self__, "allocation_weight", allocation_weight)
if apply_allocation_policy is not None:
pulumi.set(__self__, "apply_allocation_policy", apply_allocation_policy)
if hostname is not None:
pulumi.set(__self__, "hostname", hostname)
@property
@pulumi.getter(name="connectionString")
def connection_string(self) -> pulumi.Input[str]:
"""
The connection string to connect to the IoT Hub. Changing this forces a new resource.
"""
return pulumi.get(self, "connection_string")
@connection_string.setter
def connection_string(self, value: pulumi.Input[str]):
pulumi.set(self, "connection_string", value)
@property
@pulumi.getter
def location(self) -> pulumi.Input[str]:
"""
The location of the IoT hub. Changing this forces a new resource.
"""
return pulumi.get(self, "location")
@location.setter
def location(self, value: pulumi.Input[str]):
pulumi.set(self, "location", value)
@property
@pulumi.getter(name="allocationWeight")
def allocation_weight(self) -> Optional[pulumi.Input[int]]:
"""
The weight applied to the IoT Hub. Defaults to 0.
"""
return pulumi.get(self, "allocation_weight")
@allocation_weight.setter
def allocation_weight(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "allocation_weight", value)
@property
@pulumi.getter(name="applyAllocationPolicy")
def apply_allocation_policy(self) -> Optional[pulumi.Input[bool]]:
"""
Determines whether to apply allocation policies to the IoT Hub. Defaults to false.
"""
return pulumi.get(self, "apply_allocation_policy")
@apply_allocation_policy.setter
def apply_allocation_policy(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "apply_allocation_policy", value)
@property
@pulumi.getter
def hostname(self) -> Optional[pulumi.Input[str]]:
"""
The IoT Hub hostname.
"""
return pulumi.get(self, "hostname")
@hostname.setter
def hostname(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "hostname", value)
@pulumi.input_type
class IotHubDpsSkuArgs:
def __init__(__self__, *,
capacity: pulumi.Input[int],
name: pulumi.Input[str]):
"""
:param pulumi.Input[int] capacity: The number of provisioned IoT Device Provisioning Service units.
:param pulumi.Input[str] name: The name of the sku. Currently can only be set to `S1`.
"""
pulumi.set(__self__, "capacity", capacity)
pulumi.set(__self__, "name", name)
@property
@pulumi.getter
def capacity(self) -> pulumi.Input[int]:
"""
The number of provisioned IoT Device Provisioning Service units.
"""
return pulumi.get(self, "capacity")
@capacity.setter
def capacity(self, value: pulumi.Input[int]):
pulumi.set(self, "capacity", value)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The name of the sku. Currently can only be set to `S1`.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@pulumi.input_type
class SecurityDeviceGroupAllowRuleArgs:
def __init__(__self__, *,
connection_to_ip_not_alloweds: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
local_user_not_alloweds: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None,
process_not_alloweds: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None):
"""
:param pulumi.Input[Sequence[pulumi.Input[str]]] connection_to_ip_not_alloweds: Specifies which Ip is not allowed to be connected to in current device group.
:param pulumi.Input[Sequence[pulumi.Input[str]]] local_user_not_alloweds: Specifies which local user is not allowed to Login in current device group.
:param pulumi.Input[Sequence[pulumi.Input[str]]] process_not_alloweds: Specifies which process is not allowed to be executed in current device group.
"""
if connection_to_ip_not_alloweds is not None:
pulumi.set(__self__, "connection_to_ip_not_alloweds", connection_to_ip_not_alloweds)
if local_user_not_alloweds is not None:
pulumi.set(__self__, "local_user_not_alloweds", local_user_not_alloweds)
if process_not_alloweds is not None:
pulumi.set(__self__, "process_not_alloweds", process_not_alloweds)
@property
@pulumi.getter(name="connectionToIpNotAlloweds")
def connection_to_ip_not_alloweds(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Specifies which Ip is not allowed to be connected to in current device group.
"""
return pulumi.get(self, "connection_to_ip_not_alloweds")
@connection_to_ip_not_alloweds.setter
def connection_to_ip_not_alloweds(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "connection_to_ip_not_alloweds", value)
@property
@pulumi.getter(name="localUserNotAlloweds")
def local_user_not_alloweds(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Specifies which local user is not allowed to Login in current device group.
"""
return pulumi.get(self, "local_user_not_alloweds")
@local_user_not_alloweds.setter
def local_user_not_alloweds(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "local_user_not_alloweds", value)
@property
@pulumi.getter(name="processNotAlloweds")
def process_not_alloweds(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
"""
Specifies which process is not allowed to be executed in current device group.
"""
return pulumi.get(self, "process_not_alloweds")
@process_not_alloweds.setter
def process_not_alloweds(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]):
pulumi.set(self, "process_not_alloweds", value)
@pulumi.input_type
class SecurityDeviceGroupRangeRuleArgs:
def __init__(__self__, *,
duration: pulumi.Input[str],
max: pulumi.Input[int],
min: pulumi.Input[int],
type: pulumi.Input[str]):
"""
:param pulumi.Input[str] duration: Specifies the time range. represented in ISO 8601 duration format.
:param pulumi.Input[int] max: The maximum threshold in the given time window.
:param pulumi.Input[int] min: The minimum threshold in the given time window.
:param pulumi.Input[str] type: The type of supported rule type. Possible Values are `ActiveConnectionsNotInAllowedRange`, `AmqpC2DMessagesNotInAllowedRange`, `MqttC2DMessagesNotInAllowedRange`, `HttpC2DMessagesNotInAllowedRange`, `AmqpC2DRejectedMessagesNotInAllowedRange`, `MqttC2DRejectedMessagesNotInAllowedRange`, `HttpC2DRejectedMessagesNotInAllowedRange`, `AmqpD2CMessagesNotInAllowedRange`, `MqttD2CMessagesNotInAllowedRange`, `HttpD2CMessagesNotInAllowedRange`, `DirectMethodInvokesNotInAllowedRange`, `FailedLocalLoginsNotInAllowedRange`, `FileUploadsNotInAllowedRange`, `QueuePurgesNotInAllowedRange`, `TwinUpdatesNotInAllowedRange` and `UnauthorizedOperationsNotInAllowedRange`.
"""
pulumi.set(__self__, "duration", duration)
pulumi.set(__self__, "max", max)
pulumi.set(__self__, "min", min)
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def duration(self) -> pulumi.Input[str]:
"""
Specifies the time range. represented in ISO 8601 duration format.
"""
return pulumi.get(self, "duration")
@duration.setter
def duration(self, value: pulumi.Input[str]):
pulumi.set(self, "duration", value)
@property
@pulumi.getter
def max(self) -> pulumi.Input[int]:
"""
The maximum threshold in the given time window.
"""
return pulumi.get(self, "max")
@max.setter
def max(self, value: pulumi.Input[int]):
pulumi.set(self, "max", value)
@property
@pulumi.getter
def min(self) -> pulumi.Input[int]:
"""
The minimum threshold in the given time window.
"""
return pulumi.get(self, "min")
@min.setter
def min(self, value: pulumi.Input[int]):
pulumi.set(self, "min", value)
@property
@pulumi.getter
def type(self) -> pulumi.Input[str]:
"""
The type of supported rule type. Possible Values are `ActiveConnectionsNotInAllowedRange`, `AmqpC2DMessagesNotInAllowedRange`, `MqttC2DMessagesNotInAllowedRange`, `HttpC2DMessagesNotInAllowedRange`, `AmqpC2DRejectedMessagesNotInAllowedRange`, `MqttC2DRejectedMessagesNotInAllowedRange`, `HttpC2DRejectedMessagesNotInAllowedRange`, `AmqpD2CMessagesNotInAllowedRange`, `MqttD2CMessagesNotInAllowedRange`, `HttpD2CMessagesNotInAllowedRange`, `DirectMethodInvokesNotInAllowedRange`, `FailedLocalLoginsNotInAllowedRange`, `FileUploadsNotInAllowedRange`, `QueuePurgesNotInAllowedRange`, `TwinUpdatesNotInAllowedRange` and `UnauthorizedOperationsNotInAllowedRange`.
"""
return pulumi.get(self, "type")
@type.setter
def type(self, value: pulumi.Input[str]):
pulumi.set(self, "type", value)
@pulumi.input_type
class SecuritySolutionRecommendationsEnabledArgs:
def __init__(__self__, *,
acr_authentication: Optional[pulumi.Input[bool]] = None,
agent_send_unutilized_msg: Optional[pulumi.Input[bool]] = None,
baseline: Optional[pulumi.Input[bool]] = None,
edge_hub_mem_optimize: Optional[pulumi.Input[bool]] = None,
edge_logging_option: Optional[pulumi.Input[bool]] = None,
inconsistent_module_settings: Optional[pulumi.Input[bool]] = None,
install_agent: Optional[pulumi.Input[bool]] = None,
ip_filter_deny_all: Optional[pulumi.Input[bool]] = None,
ip_filter_permissive_rule: Optional[pulumi.Input[bool]] = None,
open_ports: Optional[pulumi.Input[bool]] = None,
permissive_firewall_policy: Optional[pulumi.Input[bool]] = None,
permissive_input_firewall_rules: Optional[pulumi.Input[bool]] = None,
permissive_output_firewall_rules: Optional[pulumi.Input[bool]] = None,
privileged_docker_options: Optional[pulumi.Input[bool]] = None,
shared_credentials: Optional[pulumi.Input[bool]] = None,
vulnerable_tls_cipher_suite: Optional[pulumi.Input[bool]] = None):
"""
:param pulumi.Input[bool] acr_authentication: Is Principal Authentication enabled for the ACR repository? Defaults to `true`.
:param pulumi.Input[bool] agent_send_unutilized_msg: Is Agent send underutilized messages enabled? Defaults to `true`.
:param pulumi.Input[bool] baseline: Is Security related system configuration issues identified? Defaults to `true`.
:param pulumi.Input[bool] edge_hub_mem_optimize: Is IoT Edge Hub memory optimized? Defaults to `true`.
:param pulumi.Input[bool] edge_logging_option: Is logging configured for IoT Edge module? Defaults to `true`.
:param pulumi.Input[bool] inconsistent_module_settings: Is inconsistent module settings enabled for SecurityGroup? Defaults to `true`.
:param pulumi.Input[bool] install_agent: is Azure IoT Security agent installed? Defaults to `true`.
:param pulumi.Input[bool] ip_filter_deny_all: Is Default IP filter policy denied? Defaults to `true`.
:param pulumi.Input[bool] ip_filter_permissive_rule: Is IP filter rule source allowable IP range too large? Defaults to `true`.
:param pulumi.Input[bool] open_ports: Is any ports open on the device? Defaults to `true`.
:param pulumi.Input[bool] permissive_firewall_policy: Does firewall policy exist which allow necessary communication to/from the device? Defaults to `true`.
:param pulumi.Input[bool] permissive_input_firewall_rules: Is only necessary addresses or ports are permitted in? Defaults to `true`.
:param pulumi.Input[bool] permissive_output_firewall_rules: Is only necessary addresses or ports are permitted out? Defaults to `true`.
:param pulumi.Input[bool] privileged_docker_options: Is high level permissions are needed for the module? Defaults to `true`.
:param pulumi.Input[bool] shared_credentials: Is any credentials shared among devices? Defaults to `true`.
:param pulumi.Input[bool] vulnerable_tls_cipher_suite: Does TLS cipher suite need to be updated? Defaults to `true`.
"""
if acr_authentication is not None:
pulumi.set(__self__, "acr_authentication", acr_authentication)
if agent_send_unutilized_msg is not None:
pulumi.set(__self__, "agent_send_unutilized_msg", agent_send_unutilized_msg)
if baseline is not None:
pulumi.set(__self__, "baseline", baseline)
if edge_hub_mem_optimize is not None:
pulumi.set(__self__, "edge_hub_mem_optimize", edge_hub_mem_optimize)
if edge_logging_option is not None:
pulumi.set(__self__, "edge_logging_option", edge_logging_option)
if inconsistent_module_settings is not None:
pulumi.set(__self__, "inconsistent_module_settings", inconsistent_module_settings)
if install_agent is not None:
pulumi.set(__self__, "install_agent", install_agent)
if ip_filter_deny_all is not None:
pulumi.set(__self__, "ip_filter_deny_all", ip_filter_deny_all)
if ip_filter_permissive_rule is not None:
pulumi.set(__self__, "ip_filter_permissive_rule", ip_filter_permissive_rule)
if open_ports is not None:
pulumi.set(__self__, "open_ports", open_ports)
if permissive_firewall_policy is not None:
pulumi.set(__self__, "permissive_firewall_policy", permissive_firewall_policy)
if permissive_input_firewall_rules is not None:
pulumi.set(__self__, "permissive_input_firewall_rules", permissive_input_firewall_rules)
if permissive_output_firewall_rules is not None:
pulumi.set(__self__, "permissive_output_firewall_rules", permissive_output_firewall_rules)
if privileged_docker_options is not None:
pulumi.set(__self__, "privileged_docker_options", privileged_docker_options)
if shared_credentials is not None:
pulumi.set(__self__, "shared_credentials", shared_credentials)
if vulnerable_tls_cipher_suite is not None:
pulumi.set(__self__, "vulnerable_tls_cipher_suite", vulnerable_tls_cipher_suite)
@property
@pulumi.getter(name="acrAuthentication")
def acr_authentication(self) -> Optional[pulumi.Input[bool]]:
"""
Is Principal Authentication enabled for the ACR repository? Defaults to `true`.
"""
return pulumi.get(self, "acr_authentication")
@acr_authentication.setter
def acr_authentication(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "acr_authentication", value)
@property
@pulumi.getter(name="agentSendUnutilizedMsg")
def agent_send_unutilized_msg(self) -> Optional[pulumi.Input[bool]]:
"""
Is Agent send underutilized messages enabled? Defaults to `true`.
"""
return pulumi.get(self, "agent_send_unutilized_msg")
@agent_send_unutilized_msg.setter
def agent_send_unutilized_msg(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "agent_send_unutilized_msg", value)
@property
@pulumi.getter
def baseline(self) -> Optional[pulumi.Input[bool]]:
"""
Is Security related system configuration issues identified? Defaults to `true`.
"""
return pulumi.get(self, "baseline")
@baseline.setter
def baseline(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "baseline", value)
@property
@pulumi.getter(name="edgeHubMemOptimize")
def edge_hub_mem_optimize(self) -> Optional[pulumi.Input[bool]]:
"""
Is IoT Edge Hub memory optimized? Defaults to `true`.
"""
return pulumi.get(self, "edge_hub_mem_optimize")
@edge_hub_mem_optimize.setter
def edge_hub_mem_optimize(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "edge_hub_mem_optimize", value)
@property
@pulumi.getter(name="edgeLoggingOption")
def edge_logging_option(self) -> Optional[pulumi.Input[bool]]:
"""
Is logging configured for IoT Edge module? Defaults to `true`.
"""
return pulumi.get(self, "edge_logging_option")
@edge_logging_option.setter
def edge_logging_option(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "edge_logging_option", value)
@property
@pulumi.getter(name="inconsistentModuleSettings")
def inconsistent_module_settings(self) -> Optional[pulumi.Input[bool]]:
"""
Is inconsistent module settings enabled for SecurityGroup? Defaults to `true`.
"""
return pulumi.get(self, "inconsistent_module_settings")
@inconsistent_module_settings.setter
def inconsistent_module_settings(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "inconsistent_module_settings", value)
@property
@pulumi.getter(name="installAgent")
def install_agent(self) -> Optional[pulumi.Input[bool]]:
"""
is Azure IoT Security agent installed? Defaults to `true`.
"""
return pulumi.get(self, "install_agent")
@install_agent.setter
def install_agent(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "install_agent", value)
@property
@pulumi.getter(name="ipFilterDenyAll")
def ip_filter_deny_all(self) -> Optional[pulumi.Input[bool]]:
"""
Is Default IP filter policy denied? Defaults to `true`.
"""
return pulumi.get(self, "ip_filter_deny_all")
@ip_filter_deny_all.setter
def ip_filter_deny_all(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "ip_filter_deny_all", value)
@property
@pulumi.getter(name="ipFilterPermissiveRule")
def ip_filter_permissive_rule(self) -> Optional[pulumi.Input[bool]]:
"""
Is IP filter rule source allowable IP range too large? Defaults to `true`.
"""
return pulumi.get(self, "ip_filter_permissive_rule")
@ip_filter_permissive_rule.setter
def ip_filter_permissive_rule(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "ip_filter_permissive_rule", value)
@property
@pulumi.getter(name="openPorts")
def open_ports(self) -> Optional[pulumi.Input[bool]]:
"""
Is any ports open on the device? Defaults to `true`.
"""
return pulumi.get(self, "open_ports")
@open_ports.setter
def open_ports(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "open_ports", value)
@property
@pulumi.getter(name="permissiveFirewallPolicy")
def permissive_firewall_policy(self) -> Optional[pulumi.Input[bool]]:
"""
Does firewall policy exist which allow necessary communication to/from the device? Defaults to `true`.
"""
return pulumi.get(self, "permissive_firewall_policy")
@permissive_firewall_policy.setter
def permissive_firewall_policy(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "permissive_firewall_policy", value)
@property
@pulumi.getter(name="permissiveInputFirewallRules")
def permissive_input_firewall_rules(self) -> Optional[pulumi.Input[bool]]:
"""
Is only necessary addresses or ports are permitted in? Defaults to `true`.
"""
return pulumi.get(self, "permissive_input_firewall_rules")
@permissive_input_firewall_rules.setter
def permissive_input_firewall_rules(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "permissive_input_firewall_rules", value)
@property
@pulumi.getter(name="permissiveOutputFirewallRules")
def permissive_output_firewall_rules(self) -> Optional[pulumi.Input[bool]]:
"""
Is only necessary addresses or ports are permitted out? Defaults to `true`.
"""
return pulumi.get(self, "permissive_output_firewall_rules")
@permissive_output_firewall_rules.setter
def permissive_output_firewall_rules(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "permissive_output_firewall_rules", value)
@property
@pulumi.getter(name="privilegedDockerOptions")
def privileged_docker_options(self) -> Optional[pulumi.Input[bool]]:
"""
Is high level permissions are needed for the module? Defaults to `true`.
"""
return pulumi.get(self, "privileged_docker_options")
@privileged_docker_options.setter
def privileged_docker_options(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "privileged_docker_options", value)
@property
@pulumi.getter(name="sharedCredentials")
def shared_credentials(self) -> Optional[pulumi.Input[bool]]:
"""
Is any credentials shared among devices? Defaults to `true`.
"""
return pulumi.get(self, "shared_credentials")
@shared_credentials.setter
def shared_credentials(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "shared_credentials", value)
@property
@pulumi.getter(name="vulnerableTlsCipherSuite")
def vulnerable_tls_cipher_suite(self) -> Optional[pulumi.Input[bool]]:
"""
Does TLS cipher suite need to be updated? Defaults to `true`.
"""
return pulumi.get(self, "vulnerable_tls_cipher_suite")
@vulnerable_tls_cipher_suite.setter
def vulnerable_tls_cipher_suite(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "vulnerable_tls_cipher_suite", value)
@pulumi.input_type
class TimeSeriesInsightsGen2EnvironmentStorageArgs:
def __init__(__self__, *,
key: pulumi.Input[str],
name: pulumi.Input[str]):
"""
:param pulumi.Input[str] key: Access key of storage account for Azure IoT Time Series Insights Gen2 Environment
:param pulumi.Input[str] name: Name of storage account for Azure IoT Time Series Insights Gen2 Environment
"""
pulumi.set(__self__, "key", key)
pulumi.set(__self__, "name", name)
@property
@pulumi.getter
def key(self) -> pulumi.Input[str]:
"""
Access key of storage account for Azure IoT Time Series Insights Gen2 Environment
"""
return pulumi.get(self, "key")
@key.setter
def key(self, value: pulumi.Input[str]):
pulumi.set(self, "key", value)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
Name of storage account for Azure IoT Time Series Insights Gen2 Environment
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@pulumi.input_type
class TimeSeriesInsightsReferenceDataSetKeyPropertyArgs:
def __init__(__self__, *,
name: pulumi.Input[str],
type: pulumi.Input[str]):
"""
:param pulumi.Input[str] name: The name of the key property. Changing this forces a new resource to be created.
:param pulumi.Input[str] type: The data type of the key property. Valid values include `Bool`, `DateTime`, `Double`, `String`. Changing this forces a new resource to be created.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The name of the key property. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@property
@pulumi.getter
def type(self) -> pulumi.Input[str]:
"""
The data type of the key property. Valid values include `Bool`, `DateTime`, `Double`, `String`. Changing this forces a new resource to be created.
"""
return pulumi.get(self, "type")
@type.setter
def type(self, value: pulumi.Input[str]):
pulumi.set(self, "type", value)
| 44.693795
| 697
| 0.675237
| 6,630
| 55,465
| 5.474661
| 0.067873
| 0.097887
| 0.066342
| 0.037166
| 0.868915
| 0.774692
| 0.714935
| 0.6573
| 0.612007
| 0.525718
| 0
| 0.004961
| 0.21857
| 55,465
| 1,240
| 698
| 44.729839
| 0.832495
| 0.334175
| 0
| 0.419786
| 1
| 0
| 0.111539
| 0.047914
| 0
| 0
| 0
| 0
| 0
| 1
| 0.209893
| false
| 0
| 0.006684
| 0
| 0.331551
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 1
| 1
| 1
| 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
| 5
|
8ad640cb5196aa8c01bb8185c38eb42b210b240a
| 63
|
py
|
Python
|
run.py
|
surbina/devaluometro
|
2632fcd352a062dd700abdd70d3837d8b3cfbed6
|
[
"MIT"
] | null | null | null |
run.py
|
surbina/devaluometro
|
2632fcd352a062dd700abdd70d3837d8b3cfbed6
|
[
"MIT"
] | null | null | null |
run.py
|
surbina/devaluometro
|
2632fcd352a062dd700abdd70d3837d8b3cfbed6
|
[
"MIT"
] | null | null | null |
from server.app.App import app
app.run(port=5000, debug=True)
| 15.75
| 30
| 0.761905
| 12
| 63
| 4
| 0.75
| 0.25
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.071429
| 0.111111
| 63
| 3
| 31
| 21
| 0.785714
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.5
| 0
| 0.5
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 5
|
76d0b57a96af8e94256f736b63d48c22ce9657c6
| 4,367
|
py
|
Python
|
raymon/tests/profiling/test_buildable.py
|
pbonte/raymon
|
83912d7a5ff22d61289688828169a7178fa34a2d
|
[
"MIT"
] | null | null | null |
raymon/tests/profiling/test_buildable.py
|
pbonte/raymon
|
83912d7a5ff22d61289688828169a7178fa34a2d
|
[
"MIT"
] | null | null | null |
raymon/tests/profiling/test_buildable.py
|
pbonte/raymon
|
83912d7a5ff22d61289688828169a7178fa34a2d
|
[
"MIT"
] | null | null | null |
from raymon.profiling.components import DataType
import pytest
import json
from raymon import ModelProfile
from raymon import InputComponent
from raymon import IntStats, FloatStats, CategoricStats
from raymon.profiling.extractors.vision.similarity import FixedSubpatchSimilarity
def test_stats_none():
stats = FloatStats()
jcr = stats.to_jcr()
for attr in FloatStats._attrs:
assert jcr["state"][attr] is None
def test_stats_partial_none():
params = dict(min=0, max=1, mean=0.5, std=0.02, invalids=0.1, percentiles=list(range(101)), samplesize=10)
stats = FloatStats(**params)
jcr = stats.to_jcr()
for attr in FloatStats._attrs:
assert jcr["state"][attr] == params[attr]
def test_num_stats_build():
stats = FloatStats()
assert not stats.is_built()
stats = FloatStats(
min=0,
max=1,
mean=0.5,
std=0.02,
)
assert not stats.is_built()
stats = FloatStats(min=0, max=1, mean=0.5, percentiles=range(101), invalids=0)
assert not stats.is_built()
stats = FloatStats(min=0, max=1, std=0.02, percentiles=range(101), invalids=0)
assert not stats.is_built()
stats = FloatStats(min=0, mean=0.5, std=0.02, percentiles=range(101), invalids=0)
assert not stats.is_built()
stats = FloatStats(max=1, mean=0.5, std=0.02, percentiles=range(101), invalids=0)
assert not stats.is_built()
stats = FloatStats(min=0, max=1, mean=0.5, std=0.02, percentiles=range(101))
assert not stats.is_built()
stats = FloatStats(min=0, max=1, mean=0.5, std=0.02, percentiles=range(101), invalids=0, samplesize=10)
assert stats.is_built()
def test_cat_stats_build():
stats = CategoricStats()
assert not stats.is_built()
stats = CategoricStats(frequencies={"a": 0.5, "b": 0.5}, invalids=0.1)
assert not stats.is_built()
stats = CategoricStats(frequencies={"a": 0.5, "b": 0.5}, samplesize=10)
assert not stats.is_built()
stats = CategoricStats(invalids=0.1, samplesize=10)
assert not stats.is_built()
stats = CategoricStats(frequencies={"a": 0.5, "b": 0.5}, invalids=0.1, samplesize=10)
assert stats.is_built()
def test_subpatchsimilarity_extractor_buildable():
with pytest.raises(ValueError):
extractor = FixedSubpatchSimilarity(patch=None)
extractor = FixedSubpatchSimilarity(patch={"x0": 0, "y0": 0, "x1": 64, "y1": 64})
assert not extractor.is_built()
extractor = FixedSubpatchSimilarity(
patch={"x0": 0, "y0": 0, "x1": 64, "y1": 64}, refs=["adf8d224cb8786cc"], nrefs=1
)
assert extractor.is_built()
def test_component_buildable():
extractor = FixedSubpatchSimilarity(
patch={"x0": 0, "y0": 0, "x1": 64, "y1": 64}, refs=["adf8d224cb8786cc"], nrefs=1
)
stats = FloatStats(min=0, max=1)
component = InputComponent(name="testcomponent", extractor=extractor, stats=stats, dtype=DataType.FLOAT)
assert not stats.is_built()
assert extractor.is_built()
assert not component.is_built()
extractor = FixedSubpatchSimilarity(
patch={"x0": 0, "y0": 0, "x1": 64, "y1": 64}, refs=["adf8d224cb8786cc"], nrefs=1
)
stats = FloatStats(min=0, max=1, mean=0.5, std=0.02, percentiles=range(101), invalids=0, samplesize=10)
component = InputComponent(name="testcomponent", extractor=extractor, stats=stats, dtype=DataType.FLOAT)
assert stats.is_built()
assert extractor.is_built()
assert component.is_built()
def test_schema_buildable():
extractor = FixedSubpatchSimilarity(
patch={"x0": 0, "y0": 0, "x1": 64, "y1": 64}, refs=["adf8d224cb8786cc"], nrefs=1
)
stats = FloatStats(min=0, max=1)
component = InputComponent(name="testcomponent", extractor=extractor, stats=stats, dtype=DataType.FLOAT)
schema = ModelProfile(name="Testing", version="1.0.0", components=[component])
assert not schema.is_built()
extractor = FixedSubpatchSimilarity(
patch={"x0": 0, "y0": 0, "x1": 64, "y1": 64}, refs=["adf8d224cb8786cc"], nrefs=1
)
stats = FloatStats(min=0, max=1, mean=0.5, std=0.02, percentiles=range(101), invalids=0, samplesize=10)
component = InputComponent(name="testcomponent", extractor=extractor, stats=stats, dtype=DataType.FLOAT)
schema = ModelProfile(name="Testing", version="1.0.0", components=[component, component])
assert schema.is_built()
| 38.646018
| 110
| 0.680559
| 588
| 4,367
| 4.977891
| 0.134354
| 0.055005
| 0.061496
| 0.065596
| 0.760506
| 0.759481
| 0.756064
| 0.756064
| 0.70755
| 0.685685
| 0
| 0.067975
| 0.171285
| 4,367
| 112
| 111
| 38.991071
| 0.740812
| 0
| 0
| 0.467391
| 0
| 0
| 0.050378
| 0
| 0
| 0
| 0
| 0
| 0.271739
| 1
| 0.076087
| false
| 0
| 0.076087
| 0
| 0.152174
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 1
| 1
| 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
| 5
|
76f51d1c90ba4437817019482b0e53e65e43bbb0
| 1,074
|
py
|
Python
|
torabot/core/backends/base.py
|
Answeror/torabot
|
b6260190ec1f0dc8bf3f7ba3512c0522668c59ed
|
[
"MIT"
] | 42
|
2015-01-20T10:45:08.000Z
|
2021-04-17T05:10:27.000Z
|
torabot/core/backends/base.py
|
Answeror/torabot
|
b6260190ec1f0dc8bf3f7ba3512c0522668c59ed
|
[
"MIT"
] | 4
|
2015-01-23T05:40:44.000Z
|
2016-12-19T03:52:20.000Z
|
torabot/core/backends/base.py
|
Answeror/torabot
|
b6260190ec1f0dc8bf3f7ba3512c0522668c59ed
|
[
"MIT"
] | 8
|
2015-05-07T03:51:05.000Z
|
2019-03-20T05:40:47.000Z
|
import abc
class Backend(metaclass=abc.ABCMeta):
@abc.abstractmethod
def has_query_bi_kind_and_text(self, kind, text):
pass
def has_filled_query_bi_kind_and_text(self, kind, text):
q = self.get_query_bi_kind_and_text(kind, text)
return bool(q and q.result)
@abc.abstractmethod
def get_query_bi_kind_and_text(self, kind, text):
pass
@abc.abstractmethod
def set_next_sync_time_bi_kind_and_text(self, kind, text, time):
pass
@abc.abstractmethod
def get_or_add_query_bi_kind_and_text(self, kind, text):
pass
@abc.abstractmethod
def touch_query_bi_id(self, id):
pass
@abc.abstractmethod
def add_one_query_changes(self, id, changes):
pass
@abc.abstractmethod
def set_query_result(self, id, result):
pass
@abc.abstractmethod
def is_query_active_bi_id(self, id):
pass
@abc.abstractmethod
def set_next_sync_time(self, id, time):
pass
@abc.abstractmethod
def get_query_bi_id(self, id):
pass
| 21.918367
| 68
| 0.671322
| 154
| 1,074
| 4.337662
| 0.220779
| 0.254491
| 0.299401
| 0.287425
| 0.676647
| 0.636228
| 0.441617
| 0.404192
| 0.212575
| 0.161677
| 0
| 0
| 0.248603
| 1,074
| 48
| 69
| 22.375
| 0.827757
| 0
| 0
| 0.571429
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.314286
| false
| 0.285714
| 0.028571
| 0
| 0.4
| 0
| 0
| 0
| 0
| null | 1
| 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
| 1
| 0
| 1
| 0
| 0
| 0
| 0
|
0
| 5
|
76fcbb07e1723645b2f7bc0ac1e119337fc978cb
| 17,593
|
py
|
Python
|
tensorflow/python/keras/layers/lstm_test.py
|
fraudies/tensorflow
|
a42423e302b71893bbd24aa896869941013c07fb
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/python/keras/layers/lstm_test.py
|
fraudies/tensorflow
|
a42423e302b71893bbd24aa896869941013c07fb
|
[
"Apache-2.0"
] | null | null | null |
tensorflow/python/keras/layers/lstm_test.py
|
fraudies/tensorflow
|
a42423e302b71893bbd24aa896869941013c07fb
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for LSTM layer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.keras import keras_parameterized
from tensorflow.python.keras import testing_utils
from tensorflow.python.platform import test
from tensorflow.python.training import adam
from tensorflow.python.training import gradient_descent
class LSTMLayerTest(test.TestCase):
@tf_test_util.run_in_graph_and_eager_modes
def test_return_sequences_LSTM(self):
num_samples = 2
timesteps = 3
embedding_dim = 4
units = 2
testing_utils.layer_test(
keras.layers.LSTM,
kwargs={'units': units,
'return_sequences': True},
input_shape=(num_samples, timesteps, embedding_dim))
def test_static_shape_inference_LSTM(self):
# Github issue: 15165
timesteps = 3
embedding_dim = 4
units = 2
model = keras.models.Sequential()
inputs = keras.layers.Dense(embedding_dim,
input_shape=(timesteps, embedding_dim))
model.add(inputs)
layer = keras.layers.LSTM(units, return_sequences=True)
model.add(layer)
outputs = model.layers[-1].output
self.assertEqual(outputs.shape.as_list(), [None, timesteps, units])
@tf_test_util.run_in_graph_and_eager_modes
def test_dynamic_behavior_LSTM(self):
num_samples = 2
timesteps = 3
embedding_dim = 4
units = 2
layer = keras.layers.LSTM(units, input_shape=(None, embedding_dim))
model = keras.models.Sequential()
model.add(layer)
model.compile(
'rmsprop', 'mse', run_eagerly=testing_utils.should_run_eagerly())
x = np.random.random((num_samples, timesteps, embedding_dim))
y = np.random.random((num_samples, units))
model.train_on_batch(x, y)
@tf_test_util.run_in_graph_and_eager_modes
def test_dropout_LSTM(self):
num_samples = 2
timesteps = 3
embedding_dim = 4
units = 2
testing_utils.layer_test(
keras.layers.LSTM,
kwargs={'units': units,
'dropout': 0.1,
'recurrent_dropout': 0.1},
input_shape=(num_samples, timesteps, embedding_dim))
@tf_test_util.run_in_graph_and_eager_modes
def test_implementation_mode_LSTM(self):
num_samples = 2
timesteps = 3
embedding_dim = 4
units = 2
for mode in [0, 1, 2]:
testing_utils.layer_test(
keras.layers.LSTM,
kwargs={'units': units,
'implementation': mode},
input_shape=(num_samples, timesteps, embedding_dim))
def test_statefulness_LSTM(self):
num_samples = 2
timesteps = 3
embedding_dim = 4
units = 2
layer_class = keras.layers.LSTM
with self.cached_session():
model = keras.models.Sequential()
model.add(
keras.layers.Embedding(
4,
embedding_dim,
mask_zero=True,
input_length=timesteps,
batch_input_shape=(num_samples, timesteps)))
layer = layer_class(
units, return_sequences=False, stateful=True, weights=None)
model.add(layer)
model.compile(optimizer='sgd', loss='mse')
out1 = model.predict(np.ones((num_samples, timesteps)))
self.assertEqual(out1.shape, (num_samples, units))
# train once so that the states change
model.train_on_batch(
np.ones((num_samples, timesteps)), np.ones((num_samples, units)))
out2 = model.predict(np.ones((num_samples, timesteps)))
# if the state is not reset, output should be different
self.assertNotEqual(out1.max(), out2.max())
# check that output changes after states are reset
# (even though the model itself didn't change)
layer.reset_states()
out3 = model.predict(np.ones((num_samples, timesteps)))
self.assertNotEqual(out2.max(), out3.max())
# check that container-level reset_states() works
model.reset_states()
out4 = model.predict(np.ones((num_samples, timesteps)))
self.assertAllClose(out3, out4, atol=1e-5)
# check that the call to `predict` updated the states
out5 = model.predict(np.ones((num_samples, timesteps)))
self.assertNotEqual(out4.max(), out5.max())
# Check masking
layer.reset_states()
left_padded_input = np.ones((num_samples, timesteps))
left_padded_input[0, :1] = 0
left_padded_input[1, :2] = 0
out6 = model.predict(left_padded_input)
layer.reset_states()
right_padded_input = np.ones((num_samples, timesteps))
right_padded_input[0, -1:] = 0
right_padded_input[1, -2:] = 0
out7 = model.predict(right_padded_input)
self.assertAllClose(out7, out6, atol=1e-5)
def test_regularizers_LSTM(self):
embedding_dim = 4
layer_class = keras.layers.LSTM
with self.cached_session():
layer = layer_class(
5,
return_sequences=False,
weights=None,
input_shape=(None, embedding_dim),
kernel_regularizer=keras.regularizers.l1(0.01),
recurrent_regularizer=keras.regularizers.l1(0.01),
bias_regularizer='l2',
activity_regularizer='l1')
layer.build((None, None, 2))
self.assertEqual(len(layer.losses), 3)
x = keras.backend.variable(np.ones((2, 3, 2)))
layer(x)
self.assertEqual(len(layer.get_losses_for(x)), 1)
def test_constraints_LSTM(self):
embedding_dim = 4
layer_class = keras.layers.LSTM
with self.cached_session():
k_constraint = keras.constraints.max_norm(0.01)
r_constraint = keras.constraints.max_norm(0.01)
b_constraint = keras.constraints.max_norm(0.01)
layer = layer_class(
5,
return_sequences=False,
weights=None,
input_shape=(None, embedding_dim),
kernel_constraint=k_constraint,
recurrent_constraint=r_constraint,
bias_constraint=b_constraint)
layer.build((None, None, embedding_dim))
self.assertEqual(layer.cell.kernel.constraint, k_constraint)
self.assertEqual(layer.cell.recurrent_kernel.constraint, r_constraint)
self.assertEqual(layer.cell.bias.constraint, b_constraint)
@tf_test_util.run_in_graph_and_eager_modes
def test_with_masking_layer_LSTM(self):
layer_class = keras.layers.LSTM
inputs = np.random.random((2, 3, 4))
targets = np.abs(np.random.random((2, 3, 5)))
targets /= targets.sum(axis=-1, keepdims=True)
model = keras.models.Sequential()
model.add(keras.layers.Masking(input_shape=(3, 4)))
model.add(layer_class(units=5, return_sequences=True, unroll=False))
model.compile(
loss='categorical_crossentropy',
optimizer='rmsprop',
run_eagerly=testing_utils.should_run_eagerly())
model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1)
def test_masking_with_stacking_LSTM(self):
inputs = np.random.random((2, 3, 4))
targets = np.abs(np.random.random((2, 3, 5)))
targets /= targets.sum(axis=-1, keepdims=True)
model = keras.models.Sequential()
model.add(keras.layers.Masking(input_shape=(3, 4)))
lstm_cells = [keras.layers.LSTMCell(10), keras.layers.LSTMCell(5)]
model.add(keras.layers.RNN(lstm_cells, return_sequences=True, unroll=False))
model.compile(
loss='categorical_crossentropy',
optimizer='rmsprop',
run_eagerly=testing_utils.should_run_eagerly())
model.fit(inputs, targets, epochs=1, batch_size=2, verbose=1)
def test_from_config_LSTM(self):
layer_class = keras.layers.LSTM
for stateful in (False, True):
l1 = layer_class(units=1, stateful=stateful)
l2 = layer_class.from_config(l1.get_config())
assert l1.get_config() == l2.get_config()
def test_specify_initial_state_keras_tensor(self):
num_states = 2
timesteps = 3
embedding_dim = 4
units = 3
num_samples = 2
with self.cached_session():
# Test with Keras tensor
inputs = keras.Input((timesteps, embedding_dim))
initial_state = [keras.Input((units,)) for _ in range(num_states)]
layer = keras.layers.LSTM(units)
if len(initial_state) == 1:
output = layer(inputs, initial_state=initial_state[0])
else:
output = layer(inputs, initial_state=initial_state)
assert initial_state[0] in layer._inbound_nodes[0].input_tensors
model = keras.models.Model([inputs] + initial_state, output)
model.compile(loss='categorical_crossentropy', optimizer='adam')
inputs = np.random.random((num_samples, timesteps, embedding_dim))
initial_state = [np.random.random((num_samples, units))
for _ in range(num_states)]
targets = np.random.random((num_samples, units))
model.train_on_batch([inputs] + initial_state, targets)
def test_specify_initial_state_non_keras_tensor(self):
num_states = 2
timesteps = 3
embedding_dim = 4
units = 3
num_samples = 2
with self.cached_session():
# Test with non-Keras tensor
inputs = keras.Input((timesteps, embedding_dim))
initial_state = [keras.backend.random_normal_variable(
(num_samples, units), 0, 1)
for _ in range(num_states)]
layer = keras.layers.LSTM(units)
output = layer(inputs, initial_state=initial_state)
model = keras.models.Model(inputs, output)
model.compile(loss='categorical_crossentropy', optimizer='adam')
inputs = np.random.random((num_samples, timesteps, embedding_dim))
targets = np.random.random((num_samples, units))
model.train_on_batch(inputs, targets)
def test_reset_states_with_values(self):
num_states = 2
timesteps = 3
embedding_dim = 4
units = 3
num_samples = 2
with self.cached_session():
layer = keras.layers.LSTM(units, stateful=True)
layer.build((num_samples, timesteps, embedding_dim))
layer.reset_states()
assert len(layer.states) == num_states
assert layer.states[0] is not None
self.assertAllClose(
keras.backend.eval(layer.states[0]),
np.zeros(keras.backend.int_shape(layer.states[0])),
atol=1e-4)
state_shapes = [keras.backend.int_shape(state) for state in layer.states]
values = [np.ones(shape) for shape in state_shapes]
if len(values) == 1:
values = values[0]
layer.reset_states(values)
self.assertAllClose(
keras.backend.eval(layer.states[0]),
np.ones(keras.backend.int_shape(layer.states[0])),
atol=1e-4)
# Test with invalid data
with self.assertRaises(ValueError):
layer.reset_states([1] * (len(layer.states) + 1))
def test_specify_state_with_masking(self):
num_states = 2
timesteps = 3
embedding_dim = 4
units = 3
num_samples = 2
with self.cached_session():
inputs = keras.Input((timesteps, embedding_dim))
_ = keras.layers.Masking()(inputs)
initial_state = [keras.Input((units,)) for _ in range(num_states)]
output = keras.layers.LSTM(units)(inputs, initial_state=initial_state)
model = keras.models.Model([inputs] + initial_state, output)
model.compile(
loss='categorical_crossentropy',
optimizer='rmsprop',
run_eagerly=testing_utils.should_run_eagerly())
inputs = np.random.random((num_samples, timesteps, embedding_dim))
initial_state = [np.random.random((num_samples, units))
for _ in range(num_states)]
targets = np.random.random((num_samples, units))
model.train_on_batch([inputs] + initial_state, targets)
def test_return_state(self):
num_states = 2
timesteps = 3
embedding_dim = 4
units = 3
num_samples = 2
with self.cached_session():
inputs = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim))
layer = keras.layers.LSTM(units, return_state=True, stateful=True)
outputs = layer(inputs)
state = outputs[1:]
assert len(state) == num_states
model = keras.models.Model(inputs, state[0])
inputs = np.random.random((num_samples, timesteps, embedding_dim))
state = model.predict(inputs)
self.assertAllClose(keras.backend.eval(layer.states[0]), state, atol=1e-4)
def test_state_reuse(self):
timesteps = 3
embedding_dim = 4
units = 3
num_samples = 2
with self.cached_session():
inputs = keras.Input(batch_shape=(num_samples, timesteps, embedding_dim))
layer = keras.layers.LSTM(units, return_state=True, return_sequences=True)
outputs = layer(inputs)
output, state = outputs[0], outputs[1:]
output = keras.layers.LSTM(units)(output, initial_state=state)
model = keras.models.Model(inputs, output)
inputs = np.random.random((num_samples, timesteps, embedding_dim))
outputs = model.predict(inputs)
def test_initial_states_as_other_inputs(self):
timesteps = 3
embedding_dim = 4
units = 3
num_samples = 2
num_states = 2
layer_class = keras.layers.LSTM
# Test with Keras tensor
main_inputs = keras.Input((timesteps, embedding_dim))
initial_state = [keras.Input((units,)) for _ in range(num_states)]
inputs = [main_inputs] + initial_state
layer = layer_class(units)
output = layer(inputs)
assert initial_state[0] in layer._inbound_nodes[0].input_tensors
model = keras.models.Model(inputs, output)
model.compile(loss='categorical_crossentropy',
optimizer=adam.AdamOptimizer(),
run_eagerly=testing_utils.should_run_eagerly())
main_inputs = np.random.random((num_samples, timesteps, embedding_dim))
initial_state = [np.random.random((num_samples, units))
for _ in range(num_states)]
targets = np.random.random((num_samples, units))
model.train_on_batch([main_inputs] + initial_state, targets)
def test_regularizers_LSTM(self):
embedding_dim = 4
layer_class = keras.layers.LSTM
layer = layer_class(
5,
return_sequences=False,
weights=None,
input_shape=(None, embedding_dim),
kernel_regularizer=keras.regularizers.l1(0.01),
recurrent_regularizer=keras.regularizers.l1(0.01),
bias_regularizer='l2',
activity_regularizer='l1')
layer.build((None, None, 2))
self.assertEqual(len(layer.losses), 3)
x = keras.backend.variable(np.ones((2, 3, 2)))
layer(x)
if context.executing_eagerly():
self.assertEqual(len(layer.losses), 4)
else:
self.assertEqual(len(layer.get_losses_for(x)), 1)
def test_statefulness_LSTM(self):
num_samples = 2
timesteps = 3
embedding_dim = 4
units = 2
layer_class = keras.layers.LSTM
model = keras.models.Sequential()
model.add(
keras.layers.Embedding(
4,
embedding_dim,
mask_zero=True,
input_length=timesteps,
batch_input_shape=(num_samples, timesteps)))
layer = layer_class(
units, return_sequences=False, stateful=True, weights=None)
model.add(layer)
model.compile(optimizer=gradient_descent.GradientDescentOptimizer(0.01),
loss='mse', run_eagerly=testing_utils.should_run_eagerly())
out1 = model.predict(np.ones((num_samples, timesteps)))
self.assertEqual(out1.shape, (num_samples, units))
# train once so that the states change
model.train_on_batch(
np.ones((num_samples, timesteps)), np.ones((num_samples, units)))
out2 = model.predict(np.ones((num_samples, timesteps)))
# if the state is not reset, output should be different
self.assertNotEqual(out1.max(), out2.max())
# check that output changes after states are reset
# (even though the model itself didn't change)
layer.reset_states()
out3 = model.predict(np.ones((num_samples, timesteps)))
self.assertNotEqual(out2.max(), out3.max())
# check that container-level reset_states() works
model.reset_states()
out4 = model.predict(np.ones((num_samples, timesteps)))
self.assertAllClose(out3, out4, atol=1e-5)
# check that the call to `predict` updated the states
out5 = model.predict(np.ones((num_samples, timesteps)))
self.assertNotEqual(out4.max(), out5.max())
# Check masking
layer.reset_states()
left_padded_input = np.ones((num_samples, timesteps))
left_padded_input[0, :1] = 0
left_padded_input[1, :2] = 0
out6 = model.predict(left_padded_input)
layer.reset_states()
right_padded_input = np.ones((num_samples, timesteps))
right_padded_input[0, -1:] = 0
right_padded_input[1, -2:] = 0
out7 = model.predict(right_padded_input)
self.assertAllClose(out7, out6, atol=1e-5)
if __name__ == '__main__':
test.main()
| 35.469758
| 80
| 0.672199
| 2,278
| 17,593
| 4.979807
| 0.118525
| 0.050247
| 0.051922
| 0.025388
| 0.769041
| 0.729813
| 0.714563
| 0.678156
| 0.662906
| 0.635755
| 0
| 0.019153
| 0.213551
| 17,593
| 495
| 81
| 35.541414
| 0.800737
| 0.078099
| 0
| 0.73028
| 0
| 0
| 0.017143
| 0.008912
| 0
| 0
| 0
| 0
| 0.07888
| 0
| null | null | 0
| 0.02799
| null | null | 0.002545
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
0a26b7b72b76188004cbf88f886d17500655a525
| 58
|
py
|
Python
|
apps/process/serializes/__init__.py
|
kane-zh/MES_server
|
d8d28768a054eee6433e3900908afd331fd92281
|
[
"Apache-2.0"
] | null | null | null |
apps/process/serializes/__init__.py
|
kane-zh/MES_server
|
d8d28768a054eee6433e3900908afd331fd92281
|
[
"Apache-2.0"
] | null | null | null |
apps/process/serializes/__init__.py
|
kane-zh/MES_server
|
d8d28768a054eee6433e3900908afd331fd92281
|
[
"Apache-2.0"
] | null | null | null |
from apps.process.serializes.basicinfor_serialize import *
| 58
| 58
| 0.87931
| 7
| 58
| 7.142857
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.051724
| 58
| 1
| 58
| 58
| 0.909091
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
6a56793ce5479c5fb4645a2ef7b9998d9739552e
| 38,300
|
py
|
Python
|
fbpcs/private_computation_cli/tests/test_pl_instance_runner.py
|
bliud/fbpcs
|
35a479fb7f3673a11ccfb012bf882b1de00b0b28
|
[
"MIT"
] | 63
|
2021-08-18T01:50:22.000Z
|
2022-03-25T06:44:36.000Z
|
fbpcs/private_computation_cli/tests/test_pl_instance_runner.py
|
bliud/fbpcs
|
35a479fb7f3673a11ccfb012bf882b1de00b0b28
|
[
"MIT"
] | 672
|
2021-08-18T05:20:32.000Z
|
2022-03-31T23:30:13.000Z
|
fbpcs/private_computation_cli/tests/test_pl_instance_runner.py
|
bliud/fbpcs
|
35a479fb7f3673a11ccfb012bf882b1de00b0b28
|
[
"MIT"
] | 61
|
2021-08-18T20:02:30.000Z
|
2022-03-31T22:44:17.000Z
|
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
from typing import Any, Optional, List, Tuple, Type
from unittest import TestCase
from unittest.mock import patch, PropertyMock
import requests
from fbpcs.pl_coordinator.pl_graphapi_utils import (
GRAPHAPI_INSTANCE_STATUSES,
)
from fbpcs.pl_coordinator.pl_instance_runner import (
PLInstanceRunner,
PLInstanceCalculationException,
)
from fbpcs.private_computation.entity.private_computation_instance import (
AggregationType,
AttributionRule,
PrivateComputationGameType,
)
from fbpcs.private_computation.entity.private_computation_instance import (
PrivateComputationInstance,
)
from fbpcs.private_computation.entity.private_computation_instance import (
PrivateComputationRole,
)
from fbpcs.private_computation.entity.private_computation_status import (
PrivateComputationInstanceStatus,
)
from fbpcs.private_computation.stage_flows.private_computation_base_stage_flow import (
PrivateComputationBaseStageFlow,
)
from fbpcs.private_computation.stage_flows.private_computation_stage_flow import (
PrivateComputationStageFlow,
)
class TestPlInstanceRunner(TestCase):
@patch("logging.Logger")
@patch("fbpcs.pl_coordinator.pl_graphapi_utils.PLGraphAPIClient")
def setUp(
self,
mock_graph_api_client,
mock_logger,
):
self.mock_graph_api_client = mock_graph_api_client
self.mock_logger = mock_logger
self.num_shards = 2
self.instance_id = "123"
@patch(
"fbpcs.pl_coordinator.pc_calc_instance.PrivateLiftCalcInstance.wait_valid_status"
)
@patch("fbpcs.pl_coordinator.pc_partner_instance.get_instance")
def test_ready_for_stage(self, mock_get_instance, mock_wait_valid_status) -> None:
for (
publisher_status,
partner_status,
stage,
publisher_ready_for_stage_expected,
partner_ready_for_stage_expected,
) in self._get_stage_ready_data():
with self.subTest(
publisher_status=publisher_status,
partner_status=partner_status,
stage=stage,
publisher_ready_for_stage_expected=publisher_ready_for_stage_expected,
partner_ready_for_stage_expected=partner_ready_for_stage_expected,
):
self.mock_graph_api_client.get_instance.return_value = (
self._get_graph_api_output(publisher_status)
)
mock_get_instance.return_value = self._get_pc_instance(partner_status)
runner = self._get_runner(type(stage))
publisher_ready_for_stage_actual = runner.publisher.ready_for_stage(
stage
)
partner_ready_for_stage_actual = runner.partner.ready_for_stage(stage)
self.assertEqual(
publisher_ready_for_stage_expected, publisher_ready_for_stage_actual
)
self.assertEqual(
partner_ready_for_stage_expected, partner_ready_for_stage_actual
)
@patch(
"fbpcs.pl_coordinator.pc_calc_instance.PrivateLiftCalcInstance.wait_valid_status"
)
@patch("fbpcs.pl_coordinator.pc_partner_instance.get_instance")
def test_get_valid_stage(self, mock_get_instance, mock_wait_valid_status) -> None:
for (
publisher_status,
partner_status,
stage,
_,
_,
) in self._get_valid_stage_data():
with self.subTest(
publisher_status=publisher_status,
partner_status=partner_status,
stage=stage,
):
self.mock_graph_api_client.get_instance.return_value = (
self._get_graph_api_output(publisher_status)
)
mock_get_instance.return_value = self._get_pc_instance(partner_status)
runner = self._get_runner(
PrivateComputationStageFlow if not stage else type(stage)
)
runner.publisher.status = GRAPHAPI_INSTANCE_STATUSES[publisher_status]
runner.partner.status = partner_status
valid_stage = runner.get_valid_stage()
self.assertEqual(valid_stage, stage)
@patch(
"fbpcs.pl_coordinator.pc_calc_instance.PrivateLiftCalcInstance.wait_valid_status"
)
@patch("fbpcs.pl_coordinator.pc_partner_instance.get_instance")
def test_should_invoke(self, mock_get_instance, mock_wait_valid_status) -> None:
for (
publisher_status,
partner_status,
stage,
publisher_should_invoke_expected,
partner_should_invoke_expected,
) in self._get_valid_stage_data():
with self.subTest(
publisher_status=publisher_status,
partner_status=partner_status,
stage=stage,
publisher_should_invoke_expected=publisher_should_invoke_expected,
partner_should_invoke_expected=partner_should_invoke_expected,
):
# there is one row in the dataset that has no next stage
if stage is None:
continue
self.mock_graph_api_client.get_instance.return_value = (
self._get_graph_api_output(publisher_status)
)
mock_get_instance.return_value = self._get_pc_instance(partner_status)
runner = self._get_runner(type(stage))
publisher_should_invoke_actual = (
runner.publisher.should_invoke_operation(stage)
)
partner_should_invoke_actual = runner.partner.should_invoke_operation(
stage
)
self.assertEqual(
publisher_should_invoke_expected, publisher_should_invoke_actual
)
self.assertEqual(
partner_should_invoke_expected, partner_should_invoke_actual
)
@patch("fbpcs.pl_coordinator.pc_partner_instance.run_stage")
@patch(
"fbpcs.pl_coordinator.pc_calc_instance.PrivateLiftCalcInstance.wait_stage_start"
)
@patch(
"fbpcs.pl_coordinator.pl_instance_runner.PLInstanceRunner.wait_stage_complete"
)
@patch("fbpcs.pl_coordinator.pc_partner_instance.get_instance")
def test_run_stage(
self,
mock_get_instance,
mock_wait_stage_complete,
mock_wait_stage_start,
mock_run_stage,
) -> None:
for (
publisher_status,
partner_status,
stage,
publisher_should_invoke_expected,
partner_should_invoke_expected,
) in self._get_valid_stage_data():
with self.subTest(
publisher_status=publisher_status,
partner_status=partner_status,
stage=stage,
publisher_should_invoke_expected=publisher_should_invoke_expected,
partner_should_invoke_expected=partner_should_invoke_expected,
):
# there is one row in the dataset that has no next stage
if stage is None:
continue
mock_run_stage.call_count = 0
mock_wait_stage_start.call_count = 0
self.mock_graph_api_client.invoke_operation.call_count = 0
self.mock_graph_api_client.get_instance.return_value = (
self._get_graph_api_output(publisher_status)
)
mock_get_instance.return_value = self._get_pc_instance(partner_status)
runner = self._get_runner(type(stage))
runner.run_stage(stage)
if stage.is_joint_stage:
mock_wait_stage_start.assert_called()
else:
mock_wait_stage_start.assert_not_called()
if publisher_should_invoke_expected:
self.mock_graph_api_client.invoke_operation.assert_called_with(
self.instance_id, "NEXT"
)
else:
self.mock_graph_api_client.invoke_operation.assert_not_called()
if partner_should_invoke_expected:
mock_run_stage.assert_called()
else:
mock_run_stage.assert_not_called()
@patch("fbpcs.pl_coordinator.pc_calc_instance.sleep")
@patch("fbpcs.pl_coordinator.pc_partner_instance.get_instance")
def test_wait_stage_start(self, mock_get_instance, mock_sleep) -> None:
for (
stage,
statuses,
result,
) in self._get_wait_stage_start_data():
with self.subTest(
stage=stage,
statuses=statuses,
result=result,
):
self.mock_graph_api_client.get_instance.side_effect = (
self._get_graph_api_output(status) for status in statuses
)
mock_get_instance.return_value = self._get_pc_instance(
stage.previous_stage.completed_status
)
runner = self._get_runner(type(stage))
if not result:
with self.assertRaises(PLInstanceCalculationException):
runner.publisher.wait_stage_start(stage)
else:
runner.publisher.wait_stage_start(stage)
@patch("fbpcs.pl_coordinator.pc_partner_instance.cancel_current_stage")
@patch("fbpcs.pl_coordinator.pl_instance_runner.sleep")
@patch("fbpcs.pl_coordinator.pc_partner_instance.get_instance")
def test_wait_stage_completed(
self, mock_get_instance, mock_sleep, mock_cancel_current_stage
) -> None:
for (
stage,
publisher_statuses,
partner_statuses,
result,
) in self._get_wait_stage_completed():
with self.subTest(
stage=stage,
publisher_statuses=publisher_statuses,
partner_statuses=partner_statuses,
result=result,
):
self.mock_graph_api_client.get_instance.side_effect = (
self._get_graph_api_output(status) for status in publisher_statuses
)
mock_get_instance.side_effect = (
self._get_pc_instance(status) for status in partner_statuses
)
runner = self._get_runner(type(stage))
if not result:
with self.assertRaises(PLInstanceCalculationException):
runner.wait_stage_complete(stage)
else:
runner.wait_stage_complete(stage)
@patch("fbpcs.pl_coordinator.pc_calc_instance.sleep")
@patch("fbpcs.pl_coordinator.pc_partner_instance.get_instance")
def test_wait_until_not_timeout(self, mock_get_instance, mock_sleep) -> None:
stage = PrivateComputationStageFlow.PREPARE
self.mock_graph_api_client.invoke_operation.call_count = 0
self.mock_graph_api_client.get_instance.side_effect = (
self._get_graph_api_output(status)
for status in (
"TIMEOUT",
"TIMEOUT",
"PROCESSING_REQUEST",
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
)
)
mock_get_instance.return_value = self._get_pc_instance(
stage.previous_stage.completed_status
)
runner = self._get_runner(PrivateComputationStageFlow)
self.mock_graph_api_client.invoke_operation.assert_called_with(
self.instance_id, "NEXT"
)
self.assertEqual(stage.started_status, runner.publisher.status)
# make sure that run next is only being called when the status is timeout
self.mock_graph_api_client.invoke_operation.call_count = 0
self.mock_graph_api_client.get_instance.side_effect = (
self._get_graph_api_output("PREPARE_DATA_COMPLETED") for _ in range(2)
)
runner = self._get_runner(PrivateComputationStageFlow)
self.mock_graph_api_client.invoke_operation.assert_not_called()
self.assertEqual(stage.completed_status, runner.publisher.status)
def _get_runner(
self, stage_flow: Type[PrivateComputationBaseStageFlow]
) -> PLInstanceRunner:
return PLInstanceRunner(
config={},
instance_id=self.instance_id,
input_path="fake_input_path",
game_type=PrivateComputationGameType.LIFT,
attribution_rule=AttributionRule.LAST_CLICK_1D,
aggregation_type=AggregationType.MEASUREMENT,
num_mpc_containers=self.num_shards,
num_pid_containers=self.num_shards,
logger=self.mock_logger,
client=self.mock_graph_api_client,
num_tries=2,
dry_run=False,
stage_flow=stage_flow,
)
def _get_graph_api_output(self, status: str) -> requests.Response:
data = {"status": status, "server_ips": ["xxx" for _ in range(self.num_shards)]}
r = requests.Response()
r.status_code = 200
# pyre-ignore
type(r).text = PropertyMock(return_value=json.dumps(data))
def json_func(**kwargs) -> Any:
return data
r.json = json_func
return r
def _get_pc_instance(
self, status: PrivateComputationInstanceStatus
) -> PrivateComputationInstance:
return PrivateComputationInstance(
instance_id=self.instance_id,
role=PrivateComputationRole.PARTNER,
instances=[],
status=status,
status_update_ts=1600000000,
num_pid_containers=self.num_shards,
num_mpc_containers=self.num_shards,
num_files_per_mpc_container=40,
game_type=PrivateComputationGameType.LIFT,
input_path="456",
output_dir="789",
)
def _get_stage_ready_data(
self,
) -> List[
Tuple[
str,
PrivateComputationInstanceStatus,
PrivateComputationBaseStageFlow,
bool,
bool,
]
]:
"""
Tuple represents:
* publisher status
* partner status
* stage
* is the stage ready for publisher
* is the stage ready for partner
"""
return [
(
"CREATED",
PrivateComputationInstanceStatus.CREATED,
PrivateComputationStageFlow.CREATED.next_stage,
True,
True,
),
(
"ID_MATCH_STARTED",
PrivateComputationStageFlow.ID_MATCH.previous_stage.completed_status,
PrivateComputationStageFlow.ID_MATCH,
True,
True,
),
(
"ID_MATCH_STARTED",
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationStageFlow.ID_MATCH,
True,
True,
),
(
"ID_MATCH_STARTED",
PrivateComputationInstanceStatus.ID_MATCHING_FAILED,
PrivateComputationStageFlow.ID_MATCH,
True,
True,
),
(
"ID_MATCH_STARTED",
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationStageFlow.ID_MATCH,
True,
True,
),
(
"ID_MATCH_COMPLETED",
PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED,
PrivateComputationStageFlow.ID_MATCH,
False,
False,
),
(
"ID_MATCH_COMPLETED",
PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED,
PrivateComputationStageFlow.ID_MATCH.next_stage,
True,
True,
),
(
"COMPUTATION_STARTED",
PrivateComputationStageFlow.COMPUTE.previous_stage.completed_status,
PrivateComputationStageFlow.COMPUTE,
True,
True,
),
(
"COMPUTATION_STARTED",
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationStageFlow.COMPUTE,
True,
True,
),
(
"COMPUTATION_STARTED",
PrivateComputationInstanceStatus.COMPUTATION_FAILED,
PrivateComputationStageFlow.COMPUTE,
True,
True,
),
(
"COMPUTATION_STARTED",
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationStageFlow.COMPUTE,
True,
True,
),
(
"COMPUTATION_COMPLETED",
PrivateComputationInstanceStatus.COMPUTATION_COMPLETED,
PrivateComputationStageFlow.COMPUTE,
False,
False,
),
(
"COMPUTATION_COMPLETED",
PrivateComputationInstanceStatus.COMPUTATION_COMPLETED,
PrivateComputationStageFlow.COMPUTE.next_stage,
True,
True,
),
(
"AGGREGATION_STARTED",
PrivateComputationStageFlow.AGGREGATE.previous_stage.completed_status,
PrivateComputationStageFlow.AGGREGATE,
True,
True,
),
(
"AGGREGATION_STARTED",
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationStageFlow.AGGREGATE,
True,
True,
),
(
"AGGREGATION_STARTED",
PrivateComputationInstanceStatus.AGGREGATION_FAILED,
PrivateComputationStageFlow.AGGREGATE,
True,
True,
),
(
"AGGREGATION_STARTED",
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationStageFlow.AGGREGATE,
True,
True,
),
(
"RESULT_READY",
PrivateComputationInstanceStatus.AGGREGATION_COMPLETED,
PrivateComputationStageFlow.AGGREGATE,
False,
False,
),
####################### NON JOINT STAGE TEST #################################3
(
"ID_MATCHING_POST_PROCESS_COMPLETED",
PrivateComputationStageFlow.PREPARE.previous_stage.completed_status,
PrivateComputationStageFlow.PREPARE,
True,
True,
),
(
"PREPARE_DATA_STARTED",
PrivateComputationStageFlow.PREPARE.previous_stage.completed_status,
PrivateComputationStageFlow.PREPARE,
True,
True,
),
(
"PREPARE_DATA_STARTED",
PrivateComputationStageFlow.PREPARE.started_status,
PrivateComputationStageFlow.PREPARE,
True,
True,
),
(
"PREPARE_DATA_COMPLETED",
PrivateComputationStageFlow.PREPARE.started_status,
PrivateComputationStageFlow.PREPARE,
False,
True,
),
(
"PREPARE_DATA_COMPLETED",
PrivateComputationStageFlow.PREPARE.failed_status,
PrivateComputationStageFlow.PREPARE,
False,
True,
),
(
"PREPARE_DATA_STARTED",
PrivateComputationStageFlow.PREPARE.completed_status,
PrivateComputationStageFlow.PREPARE,
True,
False,
),
(
"PREPARE_DATA_FAILED",
PrivateComputationStageFlow.PREPARE.completed_status,
PrivateComputationStageFlow.PREPARE,
True,
False,
),
(
"PREPARE_DATA_COMPLETED",
PrivateComputationStageFlow.PREPARE.completed_status,
PrivateComputationStageFlow.COMPUTE,
True,
True,
),
]
def _get_valid_stage_data(
self,
) -> List[
Tuple[
str,
PrivateComputationInstanceStatus,
Optional[PrivateComputationBaseStageFlow],
bool,
bool,
]
]:
"""
Tuple represents:
* publisher status
* partner status
* valid stage
* publisher should invoke
* partner should invoke
"""
return [
(
"CREATED",
PrivateComputationInstanceStatus.CREATED,
PrivateComputationStageFlow.CREATED.next_stage,
True,
True,
),
(
"ID_MATCH_STARTED",
PrivateComputationStageFlow.ID_MATCH.previous_stage.completed_status,
PrivateComputationStageFlow.ID_MATCH,
False,
True,
),
(
"ID_MATCH_STARTED",
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationStageFlow.ID_MATCH,
False,
False,
),
(
"ID_MATCH_FAILED",
PrivateComputationInstanceStatus.ID_MATCHING_FAILED,
PrivateComputationStageFlow.ID_MATCH,
True,
True,
),
(
"ID_MATCH_COMPLETED",
PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED,
PrivateComputationStageFlow.ID_MATCH.next_stage,
True,
True,
),
(
"COMPUTATION_STARTED",
PrivateComputationStageFlow.COMPUTE.previous_stage.completed_status,
PrivateComputationStageFlow.COMPUTE,
False,
True,
),
(
"COMPUTATION_STARTED",
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationStageFlow.COMPUTE,
False,
False,
),
(
"COMPUTATION_FAILED",
PrivateComputationInstanceStatus.COMPUTATION_FAILED,
PrivateComputationStageFlow.COMPUTE,
True,
True,
),
(
"COMPUTATION_COMPLETED",
PrivateComputationInstanceStatus.COMPUTATION_COMPLETED,
PrivateComputationStageFlow.COMPUTE.next_stage,
True,
True,
),
(
"AGGREGATION_STARTED",
PrivateComputationStageFlow.AGGREGATE.previous_stage.completed_status,
PrivateComputationStageFlow.AGGREGATE,
False,
True,
),
(
"AGGREGATION_STARTED",
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationStageFlow.AGGREGATE,
False,
False,
),
(
"AGGREGATION_FAILED",
PrivateComputationInstanceStatus.AGGREGATION_FAILED,
PrivateComputationStageFlow.AGGREGATE,
True,
True,
),
(
"RESULT_READY",
PrivateComputationInstanceStatus.AGGREGATION_COMPLETED,
None,
False,
False,
),
####################### NON JOINT STAGE TEST #################################3
(
"ID_MATCHING_POST_PROCESS_COMPLETED",
PrivateComputationStageFlow.PREPARE.previous_stage.completed_status,
PrivateComputationStageFlow.PREPARE,
True,
True,
),
(
"PREPARE_DATA_STARTED",
PrivateComputationStageFlow.PREPARE.previous_stage.completed_status,
PrivateComputationStageFlow.PREPARE,
False,
True,
),
(
"PREPARE_DATA_STARTED",
PrivateComputationStageFlow.PREPARE.started_status,
PrivateComputationStageFlow.PREPARE,
False,
False,
),
(
"PREPARE_DATA_COMPLETED",
PrivateComputationStageFlow.PREPARE.started_status,
PrivateComputationStageFlow.PREPARE,
False,
False,
),
(
"PREPARE_DATA_COMPLETED",
PrivateComputationStageFlow.PREPARE.failed_status,
PrivateComputationStageFlow.PREPARE,
False,
True,
),
(
"PREPARE_DATA_STARTED",
PrivateComputationStageFlow.PREPARE.completed_status,
PrivateComputationStageFlow.PREPARE,
False,
False,
),
(
"PREPARE_DATA_FAILED",
PrivateComputationStageFlow.PREPARE.completed_status,
PrivateComputationStageFlow.PREPARE,
True,
False,
),
(
"PREPARE_DATA_COMPLETED",
PrivateComputationStageFlow.PREPARE.completed_status,
PrivateComputationStageFlow.COMPUTE,
True,
True,
),
]
def _get_wait_stage_start_data(
self,
) -> List[Tuple[PrivateComputationBaseStageFlow, List[str], bool,]]:
"""
Tuple represents:
* stage
* order of the publisher statuses
* Does it succeed
"""
return [
(
PrivateComputationStageFlow.ID_MATCH,
[
"CREATED",
"CREATED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"ID_MATCH_STARTED",
"ID_MATCH_STARTED",
],
True,
),
(
PrivateComputationStageFlow.ID_MATCH,
[
"CREATED",
"CREATED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"ID_MATCH_FAILED",
"ID_MATCH_FAILED",
],
False,
),
(
PrivateComputationStageFlow.COMPUTE,
[
"ID_MATCH_COMPLETED",
"ID_MATCH_COMPLETED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"COMPUTATION_STARTED",
"COMPUTATION_STARTED",
],
True,
),
(
PrivateComputationStageFlow.COMPUTE,
[
"ID_MATCH_COMPLETED",
"ID_MATCH_COMPLETED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"COMPUTATION_FAILED",
"COMPUTATION_FAILED",
],
False,
),
(
PrivateComputationStageFlow.AGGREGATE,
[
"COMPUTATION_COMPLETED",
"COMPUTATION_COMPLETED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"AGGREGATION_STARTED",
"AGGREGATION_STARTED",
],
True,
),
(
PrivateComputationStageFlow.AGGREGATE,
[
"COMPUTATION_COMPLETED",
"COMPUTATION_COMPLETED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"AGGREGATION_FAILED",
"AGGREGATION_FAILED",
],
False,
),
(
PrivateComputationStageFlow.PREPARE,
[
"ID_MATCH_COMPLETED",
"ID_MATCH_COMPLETED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
],
True,
),
(
PrivateComputationStageFlow.PREPARE,
[
"ID_MATCH_COMPLETED",
"ID_MATCH_COMPLETED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"PREPARE_DATA_FAILED",
"PREPARE_DATA_FAILED",
],
False,
),
(
PrivateComputationStageFlow.PREPARE,
[
"ID_MATCH_COMPLETED",
"ID_MATCH_COMPLETED",
"PROCESSING_REQUEST",
"PROCESSING_REQUEST",
"TIMEOUT",
"TIMEOUT",
],
False,
),
]
def _get_wait_stage_completed(
self,
) -> List[
Tuple[
PrivateComputationBaseStageFlow,
List[str],
List[PrivateComputationInstanceStatus],
bool,
]
]:
"""
Tuple represents:
* stage
* order of the publisher statuses
* order of the partner statuses
* Does it succeed
"""
return [
(
PrivateComputationStageFlow.ID_MATCH,
[
"ID_MATCH_STARTED",
"ID_MATCH_STARTED",
"ID_MATCH_STARTED",
"ID_MATCH_COMPLETED",
"ID_MATCH_COMPLETED",
],
[
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED,
PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED,
PrivateComputationInstanceStatus.ID_MATCHING_COMPLETED,
],
True,
),
(
PrivateComputationStageFlow.ID_MATCH,
[
"ID_MATCH_STARTED",
"ID_MATCH_STARTED",
"ID_MATCH_STARTED",
"ID_MATCH_FAILED",
"ID_MATCH_FAILED",
],
[
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationInstanceStatus.ID_MATCHING_STARTED,
PrivateComputationInstanceStatus.ID_MATCHING_FAILED,
PrivateComputationInstanceStatus.ID_MATCHING_FAILED,
],
False,
),
(
PrivateComputationStageFlow.COMPUTE,
[
"COMPUTATION_STARTED",
"COMPUTATION_STARTED",
"COMPUTATION_COMPLETED",
"COMPUTATION_COMPLETED",
"COMPUTATION_COMPLETED",
],
[
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationInstanceStatus.COMPUTATION_COMPLETED,
PrivateComputationInstanceStatus.COMPUTATION_COMPLETED,
],
True,
),
(
PrivateComputationStageFlow.COMPUTE,
[
"COMPUTATION_STARTED",
"COMPUTATION_STARTED",
"COMPUTATION_STARTED",
"COMPUTATION_FAILED",
"COMPUTATION_FAILED",
],
[
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationInstanceStatus.COMPUTATION_STARTED,
PrivateComputationInstanceStatus.COMPUTATION_FAILED,
PrivateComputationInstanceStatus.COMPUTATION_FAILED,
PrivateComputationInstanceStatus.COMPUTATION_FAILED,
],
False,
),
(
PrivateComputationStageFlow.AGGREGATE,
[
"AGGREGATION_STARTED",
"AGGREGATION_STARTED",
"AGGREGATION_STARTED",
"RESULT_READY",
"RESULT_READY",
],
[
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationInstanceStatus.AGGREGATION_COMPLETED,
PrivateComputationInstanceStatus.AGGREGATION_COMPLETED,
PrivateComputationInstanceStatus.AGGREGATION_COMPLETED,
],
True,
),
(
PrivateComputationStageFlow.AGGREGATE,
[
"AGGREGATION_STARTED",
"AGGREGATION_STARTED",
"AGGREGATION_STARTED",
"AGGREGATION_FAILED",
"AGGREGATION_FAILED",
],
[
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationInstanceStatus.AGGREGATION_STARTED,
PrivateComputationInstanceStatus.AGGREGATION_FAILED,
PrivateComputationInstanceStatus.AGGREGATION_FAILED,
],
False,
),
(
PrivateComputationStageFlow.PREPARE,
[
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
"PREPARE_DATA_COMPLETED",
"PREPARE_DATA_COMPLETED",
],
[
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_COMPLETED,
PrivateComputationInstanceStatus.PREPARE_DATA_COMPLETED,
PrivateComputationInstanceStatus.PREPARE_DATA_COMPLETED,
],
True,
),
(
PrivateComputationStageFlow.PREPARE,
[
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
"PREPARE_DATA_FAILED",
"PREPARE_DATA_FAILED",
],
[
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_FAILED,
PrivateComputationInstanceStatus.PREPARE_DATA_FAILED,
],
False,
),
(
PrivateComputationStageFlow.PREPARE,
[
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
"PREPARE_DATA_STARTED",
"TIMEOUT",
"TIMEOUT",
],
[
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_STARTED,
PrivateComputationInstanceStatus.PREPARE_DATA_FAILED,
PrivateComputationInstanceStatus.PREPARE_DATA_FAILED,
],
False,
),
]
| 36.406844
| 91
| 0.531697
| 2,607
| 38,300
| 7.416187
| 0.080936
| 0.029016
| 0.026999
| 0.017689
| 0.828696
| 0.793214
| 0.744336
| 0.703476
| 0.625272
| 0.584928
| 0
| 0.001586
| 0.407285
| 38,300
| 1,051
| 92
| 36.441484
| 0.850095
| 0.024439
| 0
| 0.720165
| 0
| 0
| 0.103472
| 0.04147
| 0
| 0
| 0
| 0
| 0.01749
| 1
| 0.016461
| false
| 0
| 0.013374
| 0.003086
| 0.039095
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 1
| 1
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
6a71a3f8f053349fca85ecf5e833eb0754706542
| 89
|
py
|
Python
|
loggers/logging_practice.py
|
foxtreme/automate_boring_stuff
|
6ee91947727ac107b5c3d2f3f114031d6c36d4c7
|
[
"MIT"
] | null | null | null |
loggers/logging_practice.py
|
foxtreme/automate_boring_stuff
|
6ee91947727ac107b5c3d2f3f114031d6c36d4c7
|
[
"MIT"
] | null | null | null |
loggers/logging_practice.py
|
foxtreme/automate_boring_stuff
|
6ee91947727ac107b5c3d2f3f114031d6c36d4c7
|
[
"MIT"
] | null | null | null |
from logging_decorator import logger
@logger
def naive_division(a, b):
return a/b
| 11.125
| 36
| 0.741573
| 14
| 89
| 4.571429
| 0.785714
| 0.0625
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.191011
| 89
| 7
| 37
| 12.714286
| 0.888889
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.25
| false
| 0
| 0.25
| 0.25
| 0.75
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 5
|
6a7bbcfead2793834fd4162c0d8ac449f1998998
| 301
|
py
|
Python
|
CanvasPlus/assets/__init__.py
|
Luke-zhang-04/Canvas-Plus
|
7d86991c79ac8f3385b6a7771effd20c92157c73
|
[
"MIT"
] | 4
|
2020-04-01T02:24:13.000Z
|
2021-06-01T05:24:58.000Z
|
CanvasPlus/assets/__init__.py
|
Luke-zhang-04/Canvas-Plus
|
7d86991c79ac8f3385b6a7771effd20c92157c73
|
[
"MIT"
] | 1
|
2020-05-10T12:52:32.000Z
|
2020-05-10T12:52:32.000Z
|
CanvasPlus/assets/__init__.py
|
Luke-zhang-04/Canvas-Plus
|
7d86991c79ac8f3385b6a7771effd20c92157c73
|
[
"MIT"
] | 3
|
2020-05-05T14:54:59.000Z
|
2021-01-12T15:04:28.000Z
|
"""Luke-zhang-04
CanvasPlus (https://github.com/Luke-zhang-04/CanvasPlus)
Copyright (C) 2020 Luke Zhang
"""
from CanvasPlus.assets.widgetwindows import WidgetWindows
from CanvasPlus.assets.asynctransformations import AsyncTransformations
from CanvasPlus.assets.transformations import Transformations
| 33.444444
| 71
| 0.840532
| 34
| 301
| 7.441176
| 0.470588
| 0.106719
| 0.237154
| 0.166008
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.028674
| 0.07309
| 301
| 8
| 72
| 37.625
| 0.878136
| 0.332226
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 1
| 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
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 5
|
6ab98c4246dca7bc2b81cfdb5d8d837bc9d55ee5
| 807
|
py
|
Python
|
home/board/migrations/0003_rename_field.py
|
he0119/smart-home
|
bdd3a59a8c46c0fdc07ac3049bf589c7f95a2683
|
[
"MIT"
] | null | null | null |
home/board/migrations/0003_rename_field.py
|
he0119/smart-home
|
bdd3a59a8c46c0fdc07ac3049bf589c7f95a2683
|
[
"MIT"
] | 223
|
2020-02-21T06:16:56.000Z
|
2022-03-01T22:24:19.000Z
|
home/board/migrations/0003_rename_field.py
|
he0119/smart-home
|
bdd3a59a8c46c0fdc07ac3049bf589c7f95a2683
|
[
"MIT"
] | null | null | null |
# Generated by Django 3.1.4 on 2020-12-23 11:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("board", "0002_add_is_pin"),
]
operations = [
migrations.RenameField(
model_name="comment",
old_name="date_created",
new_name="created_at",
),
migrations.RenameField(
model_name="comment",
old_name="date_modified",
new_name="edited_at",
),
migrations.RenameField(
model_name="topic",
old_name="date_created",
new_name="created_at",
),
migrations.RenameField(
model_name="topic",
old_name="date_modified",
new_name="edited_at",
),
]
| 23.735294
| 47
| 0.541512
| 80
| 807
| 5.175
| 0.4625
| 0.202899
| 0.251208
| 0.289855
| 0.676329
| 0.676329
| 0.676329
| 0.676329
| 0.437198
| 0.309179
| 0
| 0.036122
| 0.348203
| 807
| 33
| 48
| 24.454545
| 0.750951
| 0.055762
| 0
| 0.740741
| 1
| 0
| 0.173684
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.037037
| 0
| 0.148148
| 0
| 0
| 0
| 0
| null | 1
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
6ad9ad3371634d0d15274255948323f44bb337e3
| 154
|
py
|
Python
|
bitmovin/resources/enums/h264_interlace_mode.py
|
camberbridge/bitmovin-python
|
3af4c6e79b0291fda05fd1ceeb5bed1bba9f3c95
|
[
"Unlicense"
] | 44
|
2016-12-12T17:37:23.000Z
|
2021-03-03T09:48:48.000Z
|
bitmovin/resources/enums/h264_interlace_mode.py
|
camberbridge/bitmovin-python
|
3af4c6e79b0291fda05fd1ceeb5bed1bba9f3c95
|
[
"Unlicense"
] | 38
|
2017-01-09T14:45:45.000Z
|
2022-02-27T18:04:33.000Z
|
bitmovin/resources/enums/h264_interlace_mode.py
|
camberbridge/bitmovin-python
|
3af4c6e79b0291fda05fd1ceeb5bed1bba9f3c95
|
[
"Unlicense"
] | 27
|
2017-02-02T22:49:31.000Z
|
2019-11-21T07:04:57.000Z
|
import enum
class H264InterlaceMode(enum.Enum):
NONE = 'NONE'
TOP_FIELD_FIRST = 'TOP_FIELD_FIRST'
BOTTOM_FIELD_FIRST = 'BOTTOM_FIELD_FIRST'
| 19.25
| 45
| 0.74026
| 20
| 154
| 5.3
| 0.45
| 0.377358
| 0.245283
| 0.396226
| 0.396226
| 0
| 0
| 0
| 0
| 0
| 0
| 0.023622
| 0.175325
| 154
| 7
| 46
| 22
| 0.811024
| 0
| 0
| 0
| 0
| 0
| 0.24026
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.2
| 0
| 1
| 0
| 1
| 0
| 0
| null | 1
| 1
| 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
| 5
|
6adda19a03b8f82e364ffec337d3982fd735cda3
| 101
|
py
|
Python
|
python-programming/main_import_example.py
|
geekmj/fml
|
ead2c16be7865eda03183b5e11622f64bf81cab7
|
[
"Unlicense"
] | null | null | null |
python-programming/main_import_example.py
|
geekmj/fml
|
ead2c16be7865eda03183b5e11622f64bf81cab7
|
[
"Unlicense"
] | null | null | null |
python-programming/main_import_example.py
|
geekmj/fml
|
ead2c16be7865eda03183b5e11622f64bf81cab7
|
[
"Unlicense"
] | null | null | null |
import other_import_example as o
print(o.sum(4, 5))
print(o.subtract(5, 7))
print(o.multiply(6, 6))
| 16.833333
| 32
| 0.712871
| 21
| 101
| 3.333333
| 0.619048
| 0.257143
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.066667
| 0.108911
| 101
| 5
| 33
| 20.2
| 0.711111
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.25
| 0
| 0.25
| 0.75
| 1
| 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
| 1
| 0
| 0
| 0
| 0
| 1
|
0
| 5
|
6aeb6e5557e9696d5ee972ac43111be2e2994b65
| 16,482
|
py
|
Python
|
Oblig1/packages/studies.py
|
fabiorodp/IN5550_Neural_Methods_in_Natural_Language_Processing
|
4d3b2ed56b56e016413ae1544e19ad2a2c0ef047
|
[
"MIT"
] | null | null | null |
Oblig1/packages/studies.py
|
fabiorodp/IN5550_Neural_Methods_in_Natural_Language_Processing
|
4d3b2ed56b56e016413ae1544e19ad2a2c0ef047
|
[
"MIT"
] | null | null | null |
Oblig1/packages/studies.py
|
fabiorodp/IN5550_Neural_Methods_in_Natural_Language_Processing
|
4d3b2ed56b56e016413ae1544e19ad2a2c0ef047
|
[
"MIT"
] | null | null | null |
# Author: Fabio Rodrigues Pereira
# E-mail: fabior@uio.no
# Author: Per Morten Halvorsen
# E-mail: pmhalvor@uio.no
# Author: Eivind Grønlie Guren
# E-mail: eivindgg@ifi.uio.no
from sklearn.metrics import accuracy_score, precision_score
from sklearn.metrics import recall_score, f1_score
from packages.ann_models import MLPModel_wl
from packages.preprocessing import BOW
import pandas as pd
import numpy as np
import torch
import time
class ActivationFunctionStudy:
@staticmethod
def _generate_metrics(par_1, par_2):
training_time = np.empty(
shape=(len(par_1), len(par_2)),
dtype=float
)
searching_accScore = np.empty(
shape=(len(par_1), len(par_2)),
dtype=float
)
searching_prcScore = np.empty(
shape=(len(par_1), len(par_2)),
dtype=float
)
searching_rclScore = np.empty(
shape=(len(par_1), len(par_2)),
dtype=float
)
searching_f1Score = np.empty(
shape=(len(par_1), len(par_2)),
dtype=float
)
return (training_time, searching_accScore, searching_prcScore,
searching_rclScore, searching_f1Score)
@staticmethod
def _load_data(url, pos, bow_type, vocab_size, verbose, random_state,
train_size):
tensors = BOW(
bow_type=bow_type,
vocab_size=vocab_size,
verbose=verbose,
random_state=random_state
)
tensors.fit_transform(
url=url,
pos=pos,
train_prop=train_size
)
return (tensors.X_train, tensors.X_test, tensors.y_train,
tensors.y_test)
@staticmethod
def _fit_predict(X_train, y_train, X_test, batch_size, n_hl,
num_features, n_classes, dropout, epochs, units,
bias, lr, momentum, device, weights_init,
hl_actfunct, out_actfunct, loss_funct,
verbose, random_state):
model = MLPModel_wl(
n_hl=n_hl,
num_features=num_features,
n_classes=n_classes,
dropout=dropout,
epochs=epochs,
units=units,
bias=bias,
lr=lr,
momentum=momentum,
device=device,
weights_init=weights_init,
hl_actfunct=hl_actfunct,
out_actfunct=out_actfunct,
loss_funct=loss_funct,
random_state=random_state,
verbose=verbose
)
print("Fitting data...") if verbose is True else None
t0 = time.time()
model.fit(
loader=(X_train, y_train),
verbose=verbose,
batch_size=batch_size
)
t1 = time.time()
print(f"Fitting done in {t1-t0}s.") if verbose is True else None
y_pred = model.predict_classes(X_test.to(device))
y_pred = y_pred.to(torch.device("cpu"))
return model, y_pred, t0, t1
@staticmethod
def _save_metrics(metrics, par_1, par_2, path_filename):
for idx, metric in enumerate(metrics):
df = pd.DataFrame(
metric,
index=par_1,
columns=par_2
)
df.to_csv(f'{path_filename}_{idx}.csv')
def __init__(self, par_1, par_2, random_state, verbose, device,
out_path_filename):
# seeding
if random_state is not None:
torch.manual_seed(random_state)
np.random.seed(random_state)
self.out_path_filename = out_path_filename
self.random_state = random_state
self.verbose = verbose
self.device = device
self.par_1 = par_1
self.par_2 = par_2
(self.searching_accScore, self.searching_prcScore,
self.searching_rclScore, self.searching_f1Score,
self.training_time) = self._generate_metrics(
par_1=par_1,
par_2=par_2
)
def _store_metrics(self, c_idx, r_idx, t0, t1, y_test, y_pred):
self.training_time[c_idx][r_idx] = t1 - t0
test_acc = accuracy_score(y_test, y_pred)
print(f"Test Acc: {test_acc}.") if self.verbose is True else None
self.searching_accScore[c_idx][r_idx] = test_acc
self.searching_prcScore[c_idx][r_idx] = precision_score(
y_test,
y_pred,
average="macro",
zero_division=0)
self.searching_rclScore[c_idx][r_idx] = recall_score(
y_test,
y_pred,
average="macro",
zero_division=0)
f1_s = f1_score(
y_test,
y_pred,
average="macro",
zero_division=0)
print(f"Test F1: {f1_s}.") if self.verbose is True else None
self.searching_f1Score[c_idx][r_idx] = f1_s
def run(self, url, pos, bow_type, vocab_size, batch_size,
train_size, n_hl, dropout, epochs, units, bias, lr,
momentum, weights_init, loss_funct):
X_train, X_test, y_train, y_test = self._load_data(
url=url,
pos=pos,
bow_type=bow_type,
vocab_size=vocab_size,
verbose=self.verbose,
random_state=self.random_state,
train_size=train_size,
)
for c_idx, col in enumerate(self.par_1):
for r_idx, row in enumerate(self.par_2):
model, y_pred, t0, t1 = self._fit_predict(
X_train=X_train,
y_train=y_train,
X_test=X_test,
batch_size=batch_size,
n_hl=n_hl,
num_features=X_train.shape[1],
n_classes=20,
dropout=dropout,
epochs=epochs,
units=units,
bias=bias,
lr=lr,
momentum=momentum,
device=self.device,
weights_init=weights_init,
hl_actfunct=col,
out_actfunct=row,
loss_funct=loss_funct,
verbose=self.verbose,
random_state=self.random_state
)
self._store_metrics(
c_idx=c_idx,
r_idx=r_idx,
t0=t0,
t1=t1,
y_test=y_test,
y_pred=y_pred
)
metrics_ = (self.training_time, self.searching_accScore,
self.searching_prcScore, self.searching_rclScore,
self.searching_f1Score)
self._save_metrics(
metrics=metrics_,
par_1=self.par_1,
par_2=self.par_2,
path_filename=self.out_path_filename
)
return self
class BoWStudy(ActivationFunctionStudy):
def __init__(self, par_1, par_2, random_state, verbose, device,
out_path_filename):
super().__init__(par_1, par_2, random_state, verbose, device,
out_path_filename)
def run(self, url, pos, batch_size, train_size, hl_actfunct, out_actfunct,
n_hl, dropout, epochs, units, bias, lr, momentum,
weights_init, loss_funct, bow_type=None, vocab_size=None):
for c_idx, col in enumerate(self.par_1):
for r_idx, row in enumerate(self.par_2):
X_train, X_test, y_train, y_test = self._load_data(
url=url,
pos=pos,
bow_type=row,
vocab_size=col,
verbose=self.verbose,
random_state=self.random_state,
train_size=train_size,
)
model, y_pred, t0, t1 = self._fit_predict(
X_train=X_train,
y_train=y_train,
X_test=X_test,
batch_size=batch_size,
n_hl=n_hl,
num_features=X_train.shape[1],
n_classes=20,
dropout=dropout,
epochs=epochs,
units=units,
bias=bias,
lr=lr,
momentum=momentum,
device=self.device,
weights_init=weights_init,
hl_actfunct=hl_actfunct,
out_actfunct=out_actfunct,
loss_funct=loss_funct,
verbose=self.verbose,
random_state=self.random_state
)
self._store_metrics(
c_idx=c_idx,
r_idx=r_idx,
t0=t0,
t1=t1,
y_test=y_test,
y_pred=y_pred
)
metrics_ = (self.training_time, self.searching_accScore,
self.searching_prcScore, self.searching_rclScore,
self.searching_f1Score)
self._save_metrics(
metrics=metrics_,
par_1=self.par_1,
par_2=self.par_2,
path_filename=self.out_path_filename
)
return self
class HlUnitsStudy(ActivationFunctionStudy):
def __init__(self, par_1, par_2, random_state, verbose, device,
out_path_filename):
super().__init__(par_1, par_2, random_state, verbose, device,
out_path_filename)
def run(self, url, pos, batch_size, train_size, hl_actfunct, out_actfunct,
dropout, epochs, bias, lr, momentum, weights_init,
loss_funct, bow_type, vocab_size, n_hl=None, units=None):
X_train, X_test, y_train, y_test = self._load_data(
url=url,
pos=pos,
bow_type=bow_type,
vocab_size=vocab_size,
verbose=self.verbose,
random_state=self.random_state,
train_size=train_size,
)
for c_idx, col in enumerate(self.par_1):
for r_idx, row in enumerate(self.par_2):
model, y_pred, t0, t1 = self._fit_predict(
X_train=X_train,
y_train=y_train,
X_test=X_test,
batch_size=batch_size,
n_hl=col,
num_features=X_train.shape[1],
n_classes=20,
dropout=dropout,
epochs=epochs,
units=row,
bias=bias,
lr=lr,
momentum=momentum,
device=self.device,
weights_init=weights_init,
hl_actfunct=hl_actfunct,
out_actfunct=out_actfunct,
loss_funct=loss_funct,
verbose=self.verbose,
random_state=self.random_state
)
self._store_metrics(
c_idx=c_idx,
r_idx=r_idx,
t0=t0,
t1=t1,
y_test=y_test,
y_pred=y_pred
)
metrics_ = (self.training_time, self.searching_accScore,
self.searching_prcScore, self.searching_rclScore,
self.searching_f1Score)
self._save_metrics(
metrics=metrics_,
par_1=self.par_1,
par_2=self.par_2,
path_filename=self.out_path_filename
)
return self
class LrMmtStudy(ActivationFunctionStudy):
def __init__(self, par_1, par_2, random_state, verbose, device,
out_path_filename):
super().__init__(par_1, par_2, random_state, verbose, device,
out_path_filename)
def run(self, url, pos, batch_size, train_size, hl_actfunct, out_actfunct,
dropout, epochs, bias, weights_init, loss_funct,
bow_type, vocab_size, n_hl, units, lr=None, momentum=None):
X_train, X_test, y_train, y_test = self._load_data(
url=url,
pos=pos,
bow_type=bow_type,
vocab_size=vocab_size,
verbose=self.verbose,
random_state=self.random_state,
train_size=train_size,
)
for c_idx, col in enumerate(self.par_1):
for r_idx, row in enumerate(self.par_2):
model, y_pred, t0, t1 = self._fit_predict(
X_train=X_train,
y_train=y_train,
X_test=X_test,
batch_size=batch_size,
n_hl=n_hl,
num_features=X_train.shape[1],
n_classes=20,
dropout=dropout,
epochs=epochs,
units=units,
bias=bias,
lr=col,
momentum=row,
device=self.device,
weights_init=weights_init,
hl_actfunct=hl_actfunct,
out_actfunct=out_actfunct,
loss_funct=loss_funct,
verbose=self.verbose,
random_state=self.random_state
)
self._store_metrics(
c_idx=c_idx,
r_idx=r_idx,
t0=t0,
t1=t1,
y_test=y_test,
y_pred=y_pred
)
metrics_ = (self.training_time, self.searching_accScore,
self.searching_prcScore, self.searching_rclScore,
self.searching_f1Score)
self._save_metrics(
metrics=metrics_,
par_1=self.par_1,
par_2=self.par_2,
path_filename=self.out_path_filename
)
return self
class EpochsBatchesStudy(ActivationFunctionStudy):
def __init__(self, par_1, par_2, random_state, verbose, device,
out_path_filename):
super().__init__(par_1, par_2, random_state, verbose, device,
out_path_filename)
def run(self, url, pos, train_size, hl_actfunct, out_actfunct,
dropout, bias, weights_init, loss_funct,
bow_type, vocab_size, n_hl, units, lr, momentum,
epochs=None, batch_size=None):
X_train, X_test, y_train, y_test = self._load_data(
url=url,
pos=pos,
bow_type=bow_type,
vocab_size=vocab_size,
verbose=self.verbose,
random_state=self.random_state,
train_size=train_size,
)
for c_idx, col in enumerate(self.par_1):
for r_idx, row in enumerate(self.par_2):
model, y_pred, t0, t1 = self._fit_predict(
X_train=X_train,
y_train=y_train,
X_test=X_test,
batch_size=row,
n_hl=n_hl,
num_features=X_train.shape[1],
n_classes=20,
dropout=dropout,
epochs=col,
units=units,
bias=bias,
lr=lr,
momentum=momentum,
device=self.device,
weights_init=weights_init,
hl_actfunct=hl_actfunct,
out_actfunct=out_actfunct,
loss_funct=loss_funct,
verbose=self.verbose,
random_state=self.random_state
)
self._store_metrics(
c_idx=c_idx,
r_idx=r_idx,
t0=t0,
t1=t1,
y_test=y_test,
y_pred=y_pred
)
metrics_ = (self.training_time, self.searching_accScore,
self.searching_prcScore, self.searching_rclScore,
self.searching_f1Score)
self._save_metrics(
metrics=metrics_,
par_1=self.par_1,
par_2=self.par_2,
path_filename=self.out_path_filename
)
return self
| 31.635317
| 78
| 0.511892
| 1,823
| 16,482
| 4.279759
| 0.083379
| 0.056396
| 0.017047
| 0.017431
| 0.762753
| 0.744425
| 0.726609
| 0.721866
| 0.721866
| 0.704435
| 0
| 0.014987
| 0.412996
| 16,482
| 520
| 79
| 31.696154
| 0.791421
| 0.010375
| 0
| 0.681604
| 0
| 0
| 0.007361
| 0.001533
| 0
| 0
| 0
| 0
| 0
| 1
| 0.035377
| false
| 0
| 0.018868
| 0
| 0.084906
| 0.009434
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 1
| 1
| 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
| 5
|
0a7302203998c867dd6f655e6dd83c7553e0d89c
| 176
|
py
|
Python
|
ci/test_notebooks.py
|
sotarokatayama/nmpcsolver
|
7ee1710d4c8d2f4bceea70d5a2560d12eec29c8f
|
[
"MIT"
] | 65
|
2019-09-17T07:00:14.000Z
|
2022-03-30T07:09:14.000Z
|
ci/test_notebooks.py
|
sotarokatayama/nmpcsolver
|
7ee1710d4c8d2f4bceea70d5a2560d12eec29c8f
|
[
"MIT"
] | 12
|
2018-12-19T19:20:43.000Z
|
2019-08-27T20:16:45.000Z
|
ci/test_notebooks.py
|
sotarokatayama/nmpcsolver
|
7ee1710d4c8d2f4bceea70d5a2560d12eec29c8f
|
[
"MIT"
] | 15
|
2019-09-16T16:07:58.000Z
|
2022-03-13T10:39:41.000Z
|
def test_cartpole():
import cartpole
def test_hexacopter():
import hexacopter
def test_pendubot():
import pendubot
def test_mobilerobot():
import mobilerobot
| 16
| 23
| 0.738636
| 20
| 176
| 6.3
| 0.35
| 0.222222
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.193182
| 176
| 11
| 24
| 16
| 0.887324
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.5
| true
| 0
| 0.5
| 0
| 1
| 0
| 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
| 1
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 5
|
0ab50520803fb46f795a649cfaef4842f866decf
| 5,094
|
py
|
Python
|
tests/test_utils.py
|
frankhood/django-url-tools
|
254b72775ca3a654eafa4601e4b275124b5b739e
|
[
"MIT"
] | null | null | null |
tests/test_utils.py
|
frankhood/django-url-tools
|
254b72775ca3a654eafa4601e4b275124b5b739e
|
[
"MIT"
] | null | null | null |
tests/test_utils.py
|
frankhood/django-url-tools
|
254b72775ca3a654eafa4601e4b275124b5b739e
|
[
"MIT"
] | null | null | null |
from __future__ import absolute_import, print_function, unicode_literals
from django.test import TestCase, override_settings
from django.contrib.sites.models import Site
from url_toolkit.utils import make_absolute_url, get_current_site_absolute, append_querystring
class UtilsTest(TestCase):
def setUp(self):
super().setUp()
self.site, _created = Site.objects.get_or_create(pk=1)
def test_make_absolute_url(self):
with self.subTest("test_make_absolute_url_with_absolute_path"):
url = 'http://test.com'
self.assertEqual(make_absolute_url(url), url)
with self.subTest("test_make_absolute_url_without_absolute_path_and_is_secure"):
url = '/test/'
secure = True
self.assertEqual(make_absolute_url(url, secure), 'https://' + str(self.site) + url)
with self.subTest("test_make_absolute_url_without_absolute_path_and_not_secure"):
url = '/test/'
secure = False
self.assertEqual(make_absolute_url(url, secure), 'http://' + str(self.site) + url)
with self.subTest("test_make_absolute_url_without_absolute_path_and_none_secure"):
url = '/test/'
secure = None
self.assertEqual(make_absolute_url(url, secure), 'http://' + str(self.site) + url)
@override_settings(SITE_BASE_URL="https://exemple.com/")
def test_make_absolute_url_with_SITE_BASE_URL(self):
with self.subTest("test_make_absolute_url_without_absolute_path_and_none_secure"):
url = '/test/'
secure = None
self.assertEqual(make_absolute_url(url, secure), "https://exemple.com" + url)
def test_get_current_site_absolute(self):
with self.subTest("test_get_current_site_absolute_without_request_and_secure_false"):
self.assertEqual(get_current_site_absolute(), 'http://' + str(self.site))
with self.subTest("test_get_current_site_absolute_without_request_and_secure_true"):
self.assertEqual(get_current_site_absolute(secure=True), 'https://' + str(self.site))
with self.subTest("test_get_current_site_absolute_without_request_and_secure_true_and_not_absolute_path_in_site"):
if '://' in self.site.domain:
self.site.domain = self.site.domain.split('://')[1]
self.assertEqual(get_current_site_absolute(secure=True), 'https://' + str(self.site))
with self.subTest("test_get_current_site_absolute_without_request_and_secure_true_and_not_absolute_path_in_site"):
if '://' in self.site.domain:
self.site.domain = self.site.domain.split('://')[1]
self.assertEqual(get_current_site_absolute(secure=True), 'https://' + str(self.site))
with self.subTest("test_get_current_site_absolute_without_request_and_secure_true_and_not_absolute_path_in_site"):
if '://' in self.site.domain:
self.site.domain = self.site.domain.split('://')[1]
self.assertEqual(get_current_site_absolute(secure=True), 'https://' + str(self.site))
with self.subTest("test_get_current_site_absolute_without_request_and_secure_true_and_not_absolute_path_in_site"):
self.site.domain = self.site.domain + '/'
self.assertEqual(get_current_site_absolute(secure=True), 'https://' + str(self.site)[:-1])
self.site.domain = str(self.site.domain)[:-1]
with self.subTest("test_get_current_site_absolute_with_request"):
from django.test.client import RequestFactory
request = RequestFactory().request()
self.assertEqual(request.is_secure(), False)
self.assertEqual(get_current_site_absolute(request, secure=True), 'http://' + str(self.site))
with self.subTest("test_get_current_site_absolute_with_slash_at_end"):
self.site.domain = self.site.domain + '/'
self.assertEqual(get_current_site_absolute(secure=True), 'https://' + str(self.site)[:-1])
self.site.domain = str(self.site.domain)[:-1]
def test_append_querystring(self):
with self.subTest("test_append_querystring_without_next_url"):
self.assertEqual(append_querystring(None, key=0), None)
with self.subTest("test_append_querystring_with_next_url"):
self.assertEqual(append_querystring('test', key=0), "test?key=0")
with self.subTest("test_append_querystring_with_next_url_no_kwargs"):
self.assertEqual(append_querystring('test'), "test")
with self.subTest("test_append_querystring_next_url_with_?"):
self.assertEqual(append_querystring('test?', key=0), "test?&key=0")
with self.subTest("test_append_querystring_next_url_with_multiple_args"):
self.assertEqual(append_querystring('test', key=0, key1=1, key2=2), "test?key=0&key1=1&key2=2")
with self.subTest("test_append_querystring_next_url_with_multiple_args"):
self.assertEqual(append_querystring('test?key3=3', key=0, key1=1, key2=2), "test?key3=3&key=0&key1=1&key2=2")
| 51.454545
| 122
| 0.690224
| 664
| 5,094
| 4.920181
| 0.115964
| 0.071013
| 0.087236
| 0.110499
| 0.807775
| 0.77135
| 0.738292
| 0.728497
| 0.68595
| 0.611264
| 0
| 0.008935
| 0.187083
| 5,094
| 98
| 123
| 51.979592
| 0.780005
| 0
| 0
| 0.438356
| 0
| 0
| 0.27828
| 0.232129
| 0
| 0
| 0
| 0
| 0.273973
| 1
| 0.068493
| false
| 0
| 0.068493
| 0
| 0.150685
| 0.013699
| 0
| 0
| 0
| null | 0
| 0
| 0
| 1
| 1
| 1
| 1
| 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
| 5
|
0ac2d3a3ee8bd2b98bc85dd8be3af2e77f1ab4bd
| 78
|
py
|
Python
|
curiosity/utils/error.py
|
neuroailab/curiosity_deprecated
|
65f7cde13b07cdac52eed39535a94e7544c396b8
|
[
"Apache-2.0"
] | null | null | null |
curiosity/utils/error.py
|
neuroailab/curiosity_deprecated
|
65f7cde13b07cdac52eed39535a94e7544c396b8
|
[
"Apache-2.0"
] | 2
|
2017-11-18T00:53:33.000Z
|
2017-11-18T00:53:40.000Z
|
curiosity/utils/error.py
|
neuroailab/curiosity_deprecated
|
65f7cde13b07cdac52eed39535a94e7544c396b8
|
[
"Apache-2.0"
] | null | null | null |
class HiLossError(Exception):
pass
class NoChangeError(Exception):
pass
| 11.142857
| 31
| 0.769231
| 8
| 78
| 7.5
| 0.625
| 0.433333
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.153846
| 78
| 6
| 32
| 13
| 0.909091
| 0
| 0
| 0.5
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0.5
| 0
| 0
| 0.5
| 0
| 1
| 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
| 1
| 1
| 0
| 0
| 0
| 0
|
0
| 5
|
0ad5b686b8dd5aa751a135f5f32ba5959f0494d1
| 24
|
py
|
Python
|
BattleCity-NES/views/InitialPage.py
|
iOsnaaente/Kata-train_Code
|
22cdf9d087bad879875c1f70029bda0771242c50
|
[
"MIT"
] | null | null | null |
BattleCity-NES/views/InitialPage.py
|
iOsnaaente/Kata-train_Code
|
22cdf9d087bad879875c1f70029bda0771242c50
|
[
"MIT"
] | null | null | null |
BattleCity-NES/views/InitialPage.py
|
iOsnaaente/Kata-train_Code
|
22cdf9d087bad879875c1f70029bda0771242c50
|
[
"MIT"
] | null | null | null |
#! usr/bin/dev python
| 8
| 22
| 0.625
| 4
| 24
| 3.75
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.208333
| 24
| 2
| 23
| 12
| 0.789474
| 0.833333
| 0
| null | 0
| null | 0
| 0
| null | 0
| 0
| 0
| null | 1
| null | true
| 0
| 0
| null | null | null | 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
0aeecbf40a58ecc911e0ae499c637bbfd06beca0
| 80
|
py
|
Python
|
src/templates/classic/tests/test_main.py
|
pyansys/create-python-project
|
e289b5042fd95ca99c6d29e107e2114a5b9a7b15
|
[
"MIT"
] | 4
|
2022-02-08T12:37:49.000Z
|
2022-03-29T04:45:10.000Z
|
src/templates/classic/tests/test_main.py
|
pyansys/create-python-project
|
e289b5042fd95ca99c6d29e107e2114a5b9a7b15
|
[
"MIT"
] | 26
|
2022-02-08T12:48:52.000Z
|
2022-03-28T08:58:47.000Z
|
src/templates/classic/tests/test_main.py
|
pyansys/create-python-project
|
e289b5042fd95ca99c6d29e107e2114a5b9a7b15
|
[
"MIT"
] | 1
|
2022-03-16T12:57:24.000Z
|
2022-03-16T12:57:24.000Z
|
import pytest
@pytest.mark.smoke
def test_expected_to_pass():
assert True
| 11.428571
| 28
| 0.7625
| 12
| 80
| 4.833333
| 0.916667
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.1625
| 80
| 6
| 29
| 13.333333
| 0.865672
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.25
| 1
| 0.25
| true
| 0.25
| 0.25
| 0
| 0.5
| 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
| 1
| 1
| 1
| 0
| 0
| 0
| 0
|
0
| 5
|
7c14086e60b0c9da30993f576344996a979b0a93
| 187
|
py
|
Python
|
time_helpers.py
|
dstansby/solarsynoptic
|
e8f2a4d58d8beb3fd5e8d85f6294148653e79e50
|
[
"BSD-2-Clause"
] | 2
|
2020-07-27T15:19:16.000Z
|
2021-04-27T09:44:28.000Z
|
time_helpers.py
|
dstansby/solarsynoptic
|
e8f2a4d58d8beb3fd5e8d85f6294148653e79e50
|
[
"BSD-2-Clause"
] | 2
|
2022-01-10T17:33:00.000Z
|
2022-01-17T19:50:07.000Z
|
time_helpers.py
|
dstansby/solarsynoptic
|
e8f2a4d58d8beb3fd5e8d85f6294148653e79e50
|
[
"BSD-2-Clause"
] | null | null | null |
from datetime import datetime
def start_of_day(dtime):
"""
Return a datetime at time 00:00:00 on the given date.
"""
return datetime(dtime.year, dtime.month, dtime.day)
| 20.777778
| 57
| 0.684492
| 29
| 187
| 4.344828
| 0.655172
| 0.063492
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.040816
| 0.213904
| 187
| 8
| 58
| 23.375
| 0.816327
| 0.283422
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| false
| 0
| 0.333333
| 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
| 1
| 0
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
7c6d315f515582aba789b460eca42deb226d210b
| 129
|
py
|
Python
|
1_languages/python/src/modules/combine/functions/string_funcs.py
|
praisetompane/3_programming
|
dd3e2e89a36a613d895fdbdd9c03845cb648fddf
|
[
"MIT"
] | null | null | null |
1_languages/python/src/modules/combine/functions/string_funcs.py
|
praisetompane/3_programming
|
dd3e2e89a36a613d895fdbdd9c03845cb648fddf
|
[
"MIT"
] | null | null | null |
1_languages/python/src/modules/combine/functions/string_funcs.py
|
praisetompane/3_programming
|
dd3e2e89a36a613d895fdbdd9c03845cb648fddf
|
[
"MIT"
] | null | null | null |
"""this is a module doc"""
#set values to expose as interface
__all__ = ['concatenate']
def concatenate(x, y):
return x + y
| 18.428571
| 34
| 0.666667
| 20
| 129
| 4.1
| 0.85
| 0.04878
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.20155
| 129
| 7
| 35
| 18.428571
| 0.796117
| 0.418605
| 0
| 0
| 0
| 0
| 0.157143
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| false
| 0
| 0
| 0.333333
| 0.666667
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 5
|
7c8ee74341338cd230a7a7a50aa7a8662c810288
| 2,161
|
py
|
Python
|
exercises/triangle/triangle_test.py
|
Alexhans/python
|
41287dda364e11edbaeda7cc50994d951007e835
|
[
"MIT"
] | 2
|
2019-07-25T04:40:24.000Z
|
2020-12-18T21:29:02.000Z
|
exercises/triangle/triangle_test.py
|
toroad/python
|
ce085c81a82ae5fb460fe166323dbbaa5a2588c5
|
[
"MIT"
] | null | null | null |
exercises/triangle/triangle_test.py
|
toroad/python
|
ce085c81a82ae5fb460fe166323dbbaa5a2588c5
|
[
"MIT"
] | null | null | null |
import unittest
from triangle import is_equilateral, is_isosceles, is_scalene
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0
class is_equilateralTests(unittest.TestCase):
def test_true_if_all_sides_are_equal(self):
self.assertIs(is_equilateral([2, 2, 2]), True)
def test_false_if_any_side_is_unequal(self):
self.assertIs(is_equilateral([2, 3, 2]), False)
def test_false_if_no_sides_are_equal(self):
self.assertIs(is_equilateral([5, 4, 6]), False)
def test_false_if_all_sides_are_zero(self):
self.assertIs(is_equilateral([0, 0, 0]), False)
def test_sides_may_be_floats(self):
self.assertIs(is_equilateral([0.5, 0.5, 0.5]), True)
class is_isoscelesTests(unittest.TestCase):
def test_true_if_last_two_sides_are_equal(self):
self.assertIs(is_isosceles([3, 4, 4]), True)
def test_true_if_first_two_sides_are_equal(self):
self.assertIs(is_isosceles([4, 4, 3]), True)
def test_true_if_first_and_last_sides_are_equal(self):
self.assertIs(is_isosceles([4, 3, 4]), True)
def test_is_equilateral_triangles_are_also_is_isosceles(self):
self.assertIs(is_isosceles([4, 4, 4]), True)
def test_false_if_no_sides_are_equal(self):
self.assertIs(is_isosceles([2, 3, 4]), False)
def test_violation_of_triangle_inequality_not_is_isosceles(self):
self.assertIs(is_isosceles([1, 1, 3]), False)
def test_sides_may_be_floats(self):
self.assertIs(is_isosceles([0.5, 0.4, 0.5]), True)
class is_scaleneTests(unittest.TestCase):
def test_true_if_no_sides_are_equal(self):
self.assertIs(is_scalene([5, 4, 6]), True)
def test_false_if_all_sides_are_equal(self):
self.assertIs(is_scalene([4, 4, 4]), False)
def test_false_if_two_sides_are_equal(self):
self.assertIs(is_scalene([4, 4, 3]), False)
def test_violation_of_triangle_inequality_not_is_scalene(self):
self.assertIs(is_scalene([7, 3, 2]), False)
def test_sides_may_be_floats(self):
self.assertIs(is_scalene([0.5, 0.4, 0.6]), True)
if __name__ == '__main__':
unittest.main()
| 32.253731
| 75
| 0.711708
| 341
| 2,161
| 4.117302
| 0.175953
| 0.084758
| 0.193732
| 0.217949
| 0.784188
| 0.685897
| 0.543447
| 0.462251
| 0.433048
| 0.222222
| 0
| 0.034981
| 0.16659
| 2,161
| 66
| 76
| 32.742424
| 0.744586
| 0.033781
| 0
| 0.121951
| 0
| 0
| 0.003835
| 0
| 0
| 0
| 0
| 0
| 0.414634
| 1
| 0.414634
| false
| 0
| 0.04878
| 0
| 0.536585
| 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
| 1
| 0
| 1
| 0
| 0
| 0
| 0
| 1
| 0
|
0
| 5
|
7caa5bf7e6ca3919c72cfc4bac657ebc4f0c71e5
| 13,521
|
py
|
Python
|
river/facto/fm.py
|
fox-ds/river
|
9ce947ebfc012ec7059de0a09c765b2da7fc1d25
|
[
"BSD-3-Clause"
] | null | null | null |
river/facto/fm.py
|
fox-ds/river
|
9ce947ebfc012ec7059de0a09c765b2da7fc1d25
|
[
"BSD-3-Clause"
] | null | null | null |
river/facto/fm.py
|
fox-ds/river
|
9ce947ebfc012ec7059de0a09c765b2da7fc1d25
|
[
"BSD-3-Clause"
] | null | null | null |
import collections
import functools
import itertools
import typing
import numpy as np
from river import base, optim, utils
from .base import BaseFM
__all__ = ["FMClassifier", "FMRegressor"]
class FM(BaseFM):
"""Factorization machine base class."""
def __init__(
self,
n_factors,
weight_optimizer,
latent_optimizer,
loss,
sample_normalization,
l1_weight,
l2_weight,
l1_latent,
l2_latent,
intercept,
intercept_lr,
weight_initializer,
latent_initializer,
clip_gradient,
seed,
):
super().__init__(
n_factors=n_factors,
weight_optimizer=weight_optimizer,
latent_optimizer=latent_optimizer,
loss=loss,
sample_normalization=sample_normalization,
l1_weight=l1_weight,
l2_weight=l2_weight,
l1_latent=l1_latent,
l2_latent=l2_latent,
intercept=intercept,
intercept_lr=intercept_lr,
weight_initializer=weight_initializer,
latent_initializer=latent_initializer,
clip_gradient=clip_gradient,
seed=seed,
)
def _init_latents(self):
random_latents = functools.partial(
self.latent_initializer, shape=self.n_factors
)
return collections.defaultdict(random_latents)
def _interaction_names(self, x):
return [f"{j1} - {j2}" for j1, j2 in itertools.combinations(x.keys(), 2)]
def _interaction_combination_keys(self, x):
return itertools.combinations(x.keys(), 2)
def _interaction_val(self, x, combination):
return functools.reduce(lambda x, y: x * y, (x[j] for j in combination))
def _interaction_coefficient(self, combination):
j1, j2 = combination
return np.dot(self.latents[j1], self.latents[j2])
def _calculate_weights_gradients(self, x, g_loss):
# For notational convenience
w, l1, l2, sign = self.weights, self.l1_weight, self.l2_weight, utils.math.sign
return {j: g_loss * xj + l1 * sign(w[j]) + l2 * w[j] for j, xj in x.items()}
def _update_latents(self, x, g_loss):
# For notational convenience
v, l1, l2, sign = self.latents, self.l1_latent, self.l2_latent, utils.math.sign
# Precompute feature independent sum for time efficiency
precomputed_sum = {
f: sum(v[j][f] * xj for j, xj in x.items()) for f in range(self.n_factors)
}
# Calculate each latent factor gradient before updating any
gradients = {}
for j, xj in x.items():
gradients[j] = {
f: g_loss * (xj * precomputed_sum[f] - v[j][f] * xj**2)
+ l1 * sign(v[j][f])
+ l2 * v[j][f]
for f in range(self.n_factors)
}
# Finally update the latent weights
for j in x.keys():
self.latents[j] = self.latent_optimizer.step(w=v[j], g=gradients[j])
class FMRegressor(FM, base.Regressor):
"""Factorization Machine for regression.
The model equation is defined as:
$$\\hat{y}(x) = w_{0} + \\sum_{j=1}^{p} w_{j} x_{j} + \\sum_{j=1}^{p} \\sum_{j'=j+1}^{p} \\langle \\mathbf{v}_j, \\mathbf{v}_{j'} \\rangle x_{j} x_{j'}$$
Where $\\mathbf{v}_j$ and $\\mathbf{v}_{j'}$ are $j$ and $j'$ latent vectors, respectively.
For more efficiency, this model automatically one-hot encodes strings features considering them
as categorical variables.
Parameters
----------
n_factors
Dimensionality of the factorization or number of latent factors.
weight_optimizer
The sequential optimizer used for updating the feature weights. Note that
the intercept is handled separately.
latent_optimizer
The sequential optimizer used for updating the latent factors.
loss
The loss function to optimize for.
sample_normalization
Whether to divide each element of `x` by `x`'s L2-norm.
l1_weight
Amount of L1 regularization used to push weights towards 0.
l2_weight
Amount of L2 regularization used to push weights towards 0.
l1_latent
Amount of L1 regularization used to push latent weights towards 0.
l2_latent
Amount of L2 regularization used to push latent weights towards 0.
intercept
Initial intercept value.
intercept_lr
Learning rate scheduler used for updating the intercept. An instance of
`optim.schedulers.Constant` is used if a `float` is passed. No intercept will be used
if this is set to 0.
weight_initializer
Weights initialization scheme. Defaults to `optim.initializers.Zeros()`.
latent_initializer
Latent factors initialization scheme. Defaults to
`optim.initializers.Normal(mu=.0, sigma=.1, random_state=self.random_state)`.
clip_gradient
Clips the absolute value of each gradient value.
seed
Randomization seed used for reproducibility.
Attributes
----------
weights
The current weights assigned to the features.
latents
The current latent weights assigned to the features.
Examples
--------
>>> from river import facto
>>> dataset = (
... ({'user': 'Alice', 'item': 'Superman'}, 8),
... ({'user': 'Alice', 'item': 'Terminator'}, 9),
... ({'user': 'Alice', 'item': 'Star Wars'}, 8),
... ({'user': 'Alice', 'item': 'Notting Hill'}, 2),
... ({'user': 'Alice', 'item': 'Harry Potter '}, 5),
... ({'user': 'Bob', 'item': 'Superman'}, 8),
... ({'user': 'Bob', 'item': 'Terminator'}, 9),
... ({'user': 'Bob', 'item': 'Star Wars'}, 8),
... ({'user': 'Bob', 'item': 'Notting Hill'}, 2)
... )
>>> model = facto.FMRegressor(
... n_factors=10,
... intercept=5,
... seed=42,
... )
>>> for x, y in dataset:
... _ = model.learn_one(x, y)
>>> model.predict_one({'Bob': 1, 'Harry Potter': 1})
5.236504
>>> report = model.debug_one({'Bob': 1, 'Harry Potter': 1})
>>> print(report)
Name Value Weight Contribution
Intercept 1.00000 5.23426 5.23426
Bob - Harry Potter 1.00000 0.00224 0.00224
Harry Potter 1.00000 0.00000 0.00000
Bob 1.00000 0.00000 0.00000
References
----------
[^1]: [Rendle, S., 2010, December. Factorization machines. In 2010 IEEE International Conference on Data Mining (pp. 995-1000). IEEE.](https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf)
[^2]: [Rendle, S., 2012, May. Factorization Machines with libFM. In ACM Transactions on Intelligent Systems and Technology 3, 3, Article 57, 22 pages.](https://analyticsconsultores.com.mx/wp-content/uploads/2019/03/Factorization-Machines-with-libFM-Steffen-Rendle-University-of-Konstanz2012-.pdf)
"""
def __init__(
self,
n_factors=10,
weight_optimizer: optim.Optimizer = None,
latent_optimizer: optim.Optimizer = None,
loss: optim.losses.RegressionLoss = None,
sample_normalization=False,
l1_weight=0.0,
l2_weight=0.0,
l1_latent=0.0,
l2_latent=0.0,
intercept=0.0,
intercept_lr: typing.Union[optim.schedulers.Scheduler, float] = 0.01,
weight_initializer: optim.initializers.Initializer = None,
latent_initializer: optim.initializers.Initializer = None,
clip_gradient=1e12,
seed: int = None,
):
super().__init__(
n_factors=n_factors,
weight_optimizer=weight_optimizer,
latent_optimizer=latent_optimizer,
loss=optim.losses.Squared() if loss is None else loss,
sample_normalization=sample_normalization,
l1_weight=l1_weight,
l2_weight=l2_weight,
l1_latent=l1_latent,
l2_latent=l2_latent,
intercept=intercept,
intercept_lr=intercept_lr,
weight_initializer=weight_initializer,
latent_initializer=latent_initializer,
clip_gradient=clip_gradient,
seed=seed,
)
def predict_one(self, x):
x = self._ohe_cat_features(x)
return self._raw_dot(x)
class FMClassifier(FM, base.Classifier):
"""Factorization Machine for binary classification.
The model equation is defined as:
$$\\hat{y}(x) = w_{0} + \\sum_{j=1}^{p} w_{j} x_{j} + \\sum_{j=1}^{p} \\sum_{j'=j+1}^{p} \\langle \\mathbf{v}_j, \\mathbf{v}_{j'} \\rangle x_{j} x_{j'}$$
Where $\\mathbf{v}_j$ and $\\mathbf{v}_{j'}$ are $j$ and $j'$ latent vectors, respectively.
For more efficiency, this model automatically one-hot encodes strings features considering them
as categorical variables.
Parameters
----------
n_factors
Dimensionality of the factorization or number of latent factors.
weight_optimizer
The sequential optimizer used for updating the feature weights. Note that the intercept is
handled separately.
latent_optimizer
The sequential optimizer used for updating the latent factors.
loss
The loss function to optimize for.
sample_normalization
Whether to divide each element of `x` by `x`'s L2-norm.
l1_weight
Amount of L1 regularization used to push weights towards 0.
l2_weight
Amount of L2 regularization used to push weights towards 0.
l1_latent
Amount of L1 regularization used to push latent weights towards 0.
l2_latent
Amount of L2 regularization used to push latent weights towards 0.
intercept
Initial intercept value.
intercept_lr
Learning rate scheduler used for updating the intercept. An instance of
`optim.schedulers.Constant` is used if a `float` is passed. No intercept will be used
if this is set to 0.
weight_initializer
Weights initialization scheme. Defaults to `optim.initializers.Zeros()`.
latent_initializer
Latent factors initialization scheme. Defaults to
`optim.initializers.Normal(mu=.0, sigma=.1, random_state=self.random_state)`.
clip_gradient
Clips the absolute value of each gradient value.
seed
Randomization seed used for reproducibility.
Attributes
----------
weights
The current weights assigned to the features.
latents
The current latent weights assigned to the features.
Examples
--------
>>> from river import facto
>>> dataset = (
... ({'user': 'Alice', 'item': 'Superman'}, True),
... ({'user': 'Alice', 'item': 'Terminator'}, True),
... ({'user': 'Alice', 'item': 'Star Wars'}, True),
... ({'user': 'Alice', 'item': 'Notting Hill'}, False),
... ({'user': 'Alice', 'item': 'Harry Potter '}, True),
... ({'user': 'Bob', 'item': 'Superman'}, True),
... ({'user': 'Bob', 'item': 'Terminator'}, True),
... ({'user': 'Bob', 'item': 'Star Wars'}, True),
... ({'user': 'Bob', 'item': 'Notting Hill'}, False)
... )
>>> model = facto.FMClassifier(
... n_factors=10,
... seed=42,
... )
>>> for x, y in dataset:
... _ = model.learn_one(x, y)
>>> model.predict_one({'Bob': 1, 'Harry Potter': 1})
True
References
----------
[^1]: [Rendle, S., 2010, December. Factorization machines. In 2010 IEEE International Conference on Data Mining (pp. 995-1000). IEEE.](https://www.csie.ntu.edu.tw/~b97053/paper/Rendle2010FM.pdf)
[^2]: [Rendle, S., 2012, May. Factorization Machines with libFM. In ACM Transactions on Intelligent Systems and Technology 3, 3, Article 57, 22 pages.](https://analyticsconsultores.com.mx/wp-content/uploads/2019/03/Factorization-Machines-with-libFM-Steffen-Rendle-University-of-Konstanz2012-.pdf)
"""
def __init__(
self,
n_factors=10,
weight_optimizer: optim.Optimizer = None,
latent_optimizer: optim.Optimizer = None,
loss: optim.losses.BinaryLoss = None,
sample_normalization=False,
l1_weight=0.0,
l2_weight=0.0,
l1_latent=0.0,
l2_latent=0.0,
intercept=0.0,
intercept_lr: typing.Union[optim.schedulers.Scheduler, float] = 0.01,
weight_initializer: optim.initializers.Initializer = None,
latent_initializer: optim.initializers.Initializer = None,
clip_gradient=1e12,
seed: int = None,
):
super().__init__(
n_factors=n_factors,
weight_optimizer=weight_optimizer,
latent_optimizer=latent_optimizer,
loss=optim.losses.Log() if loss is None else loss,
sample_normalization=sample_normalization,
l1_weight=l1_weight,
l2_weight=l2_weight,
l1_latent=l1_latent,
l2_latent=l2_latent,
intercept=intercept,
intercept_lr=intercept_lr,
weight_initializer=weight_initializer,
latent_initializer=latent_initializer,
clip_gradient=clip_gradient,
seed=seed,
)
def predict_proba_one(self, x):
x = self._ohe_cat_features(x)
p = utils.math.sigmoid(self._raw_dot(x)) # Convert logit to probability
return {False: 1.0 - p, True: p}
| 35.581579
| 300
| 0.612011
| 1,635
| 13,521
| 4.912538
| 0.174924
| 0.015936
| 0.016185
| 0.023904
| 0.790712
| 0.745144
| 0.733068
| 0.708665
| 0.708665
| 0.701693
| 0
| 0.033692
| 0.271208
| 13,521
| 379
| 301
| 35.675462
| 0.781409
| 0.526292
| 0
| 0.541935
| 0
| 0
| 0.005927
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.077419
| false
| 0
| 0.045161
| 0.019355
| 0.193548
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 1
| 1
| 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
| 5
|
7ce4d216ac7dc23fc5b4d6096460bd7eab312c0e
| 18,082
|
py
|
Python
|
venus/db/yasdl/parsetab.py
|
nagylzs/python-venus-lib
|
336d20532c32e874ab0a43cf866092b9e55dded5
|
[
"Apache-2.0"
] | null | null | null |
venus/db/yasdl/parsetab.py
|
nagylzs/python-venus-lib
|
336d20532c32e874ab0a43cf866092b9e55dded5
|
[
"Apache-2.0"
] | 1
|
2019-02-15T13:40:49.000Z
|
2019-02-15T13:40:49.000Z
|
venus/db/yasdl/parsetab.py
|
nagylzs/python-venus-lib
|
336d20532c32e874ab0a43cf866092b9e55dded5
|
[
"Apache-2.0"
] | null | null | null |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'yasdABSTRACT ALL ARROW AS COLON CONSTRAINT DELETE DOT EQUALS FALSE FIELD FIELDS FIELDSET FINAL FLOAT INDEX INT LBRACE LBRACKET MINUS NAME NONE PLUS PROPERTY RBRACE RBRACKET REQUIRE REQUIRED SCHEMA SEMICOLON STRING TRUE USEdotted_name : SCHEMA DOT simple_dotted_namedotted_name : simple_dotted_namesimple_dotted_name : NAME DOT simple_dotted_namesimple_dotted_name : NAME min_classesmin_classes : min_classes : LBRACKET minclassitems RBRACKET minclassitems : minclassitem minclassitems minclassitems : minclassitem minclassitem : SCHEMA minclassitem : FIELDSET minclassitem : FIELD minclassitem : INDEX minclassitem : PROPERTY imp_name : EQUALS dotted_nameimp_name : dotted_nameschema_name : NAMEschema_name : NAME DOT schema_nameyasd : SCHEMA schema_name LBRACE uses defs RBRACE uses : use uses uses : use use : USE schema_name AS NAME SEMICOLON\n | REQUIRE schema_name AS NAME SEMICOLON\n | USE STRING AS NAME SEMICOLON\n | REQUIRE STRING AS NAME SEMICOLON\n use : USE NAME SEMICOLON\n | REQUIRE NAME SEMICOLONuse : modifiers : modifier modifiersmodifiers : modifiermodifier : modifier : ABSTRACT\n | FINAL\n | REQUIREDdefs : def defs defs : def def : fielddef\n | fieldsetdef\n | simpleprop\n defs : fielddef : modifiers FIELD NAME typedef fieldpropsfielddef : modifiers FIELD NAME typedef ARROW imp_name fieldpropsfieldprops : SEMICOLONfieldprops : LBRACE simpleprops RBRACE fieldsetdef : modifiers FIELDSET NAME typedef SEMICOLONfieldsetdef : modifiers FIELDSET NAME typedef LBRACE fsitems RBRACE fsitems : fsitem fsitems fsitems : fsitem fsitem : simpleprop fsitem : fielddef\n | fieldsetdef\n | indexdef fsitem : deletiondeletion : DELETE NAME SEMICOLONindexdef : INDEX NAME LBRACE idxitems RBRACE idxitems : idxitem idxitems idxitems : idxitem idxitem : simpleprop indexdef : CONSTRAINT NAME LBRACE constraintitems RBRACE constraintitems : constraintitem constraintitems constraintitems : constraintitem constraintitem : simpleprop typedef : COLON typedef_items typedef : typedef_items : imp_name typedef_items typedef_items : imp_name indexdef : INDEX NAME indexpropsindexprops : LBRACE simpleprops RBRACE simpleprops : simpleprop simplepropssimpleprops : simpleprop simpleprops : simpleprop : NAME propvalues SEMICOLONsimpleprop : FIELDS idxfields SEMICOLONidxfields : idxfield idxfieldsidxfields : idxfieldidxfield : PLUS dotted_nameidxfield : MINUS dotted_nameidxfield : dotted_namepropvalues : propvalue propvaluespropvalues : propvalue propvalues : propvalue : FLOATpropvalue : INTpropvalue : NONEpropvalue : ALLpropvalue : STRINGpropvalue : TRUEpropvalue : FALSEpropvalue : imp_name'
_lr_action_items = {'SCHEMA':([0,18,19,35,37,38,39,40,41,42,43,44,45,46,47,49,51,52,53,54,65,66,69,73,74,80,82,84,85,86,87,88,89,90,96,100,103,],[2,48,48,-5,48,-81,-82,-83,-84,-85,-86,-87,-88,48,-15,-2,48,48,-77,48,-4,85,-14,-75,-76,48,-3,85,-9,-10,-11,-12,-13,-1,48,48,-6,]),'$end':([1,31,],[0,-18,]),'NAME':([2,5,6,7,8,9,10,13,14,15,16,18,19,24,33,34,35,37,38,39,40,41,42,43,44,45,46,47,49,51,52,53,54,56,57,58,59,60,61,64,65,67,69,70,71,73,74,80,82,90,91,92,93,94,95,96,97,98,100,101,102,103,107,110,111,112,113,114,115,116,117,118,119,120,122,127,128,129,130,133,134,136,137,138,139,141,142,],[4,-27,4,18,-20,26,29,18,-36,-37,-38,35,35,-19,62,63,-5,35,-81,-82,-83,-84,-85,-86,-87,-88,35,-15,-2,35,35,-77,35,75,-25,76,77,-26,78,35,-4,-71,-14,35,-72,-75,-76,35,-3,-1,-21,-23,-22,-24,-40,35,-42,18,35,-44,18,-6,18,18,-48,-49,-50,-51,-52,124,125,126,-41,-43,-45,18,-66,18,-53,18,18,18,-61,-54,-67,-57,-58,]),'LBRACE':([3,4,11,35,47,49,62,63,65,69,79,81,82,90,99,100,103,105,108,124,125,],[5,-16,-17,-5,-15,-2,-63,-63,-4,-14,98,102,-3,-1,-62,-65,-6,98,-64,127,129,]),'AS':([4,11,25,26,27,28,29,30,],[-16,-17,56,-16,58,59,-16,61,]),'DOT':([4,26,29,35,48,],[6,6,6,64,70,]),'USE':([5,8,57,60,91,92,93,94,],[9,9,-25,-26,-21,-23,-22,-24,]),'REQUIRE':([5,8,57,60,91,92,93,94,],[10,10,-25,-26,-21,-23,-22,-24,]),'FIELDS':([5,7,8,13,14,15,16,24,57,60,67,71,91,92,93,94,95,97,98,101,102,107,110,111,112,113,114,115,119,120,122,127,128,129,130,133,134,136,137,138,139,141,142,],[-27,19,-20,19,-36,-37,-38,-19,-25,-26,-71,-72,-21,-23,-22,-24,-40,-42,19,-44,19,19,19,-48,-49,-50,-51,-52,-41,-43,-45,19,-66,19,-53,19,19,19,-61,-54,-67,-57,-58,]),'ABSTRACT':([5,7,8,13,14,15,16,20,21,22,23,24,57,60,67,71,91,92,93,94,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[-27,21,-20,21,-36,-37,-38,21,-31,-32,-33,-19,-25,-26,-71,-72,-21,-23,-22,-24,-40,-42,-44,21,21,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'FINAL':([5,7,8,13,14,15,16,20,21,22,23,24,57,60,67,71,91,92,93,94,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[-27,22,-20,22,-36,-37,-38,22,-31,-32,-33,-19,-25,-26,-71,-72,-21,-23,-22,-24,-40,-42,-44,22,22,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'REQUIRED':([5,7,8,13,14,15,16,20,21,22,23,24,57,60,67,71,91,92,93,94,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[-27,23,-20,23,-36,-37,-38,23,-31,-32,-33,-19,-25,-26,-71,-72,-21,-23,-22,-24,-40,-42,-44,23,23,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'RBRACE':([5,7,8,12,13,14,15,16,24,32,57,60,67,71,91,92,93,94,95,97,98,101,106,107,109,110,111,112,113,114,115,119,120,121,122,123,127,128,130,131,132,133,134,135,136,137,138,139,140,141,142,143,],[-27,-39,-20,31,-35,-36,-37,-38,-19,-34,-25,-26,-71,-72,-21,-23,-22,-24,-40,-42,-70,-44,120,-69,122,-47,-48,-49,-50,-51,-52,-41,-43,-68,-45,-46,-70,-66,-53,138,139,-56,-57,142,-60,-61,-54,-67,-55,-57,-58,-59,]),'FIELD':([5,7,8,13,14,15,16,17,20,21,22,23,24,55,57,60,66,67,71,84,85,86,87,88,89,91,92,93,94,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[-27,-30,-20,-30,-36,-37,-38,33,-29,-31,-32,-33,-19,-28,-25,-26,87,-71,-72,87,-9,-10,-11,-12,-13,-21,-23,-22,-24,-40,-42,-44,-30,-30,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'FIELDSET':([5,7,8,13,14,15,16,17,20,21,22,23,24,55,57,60,66,67,71,84,85,86,87,88,89,91,92,93,94,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[-27,-30,-20,-30,-36,-37,-38,34,-29,-31,-32,-33,-19,-28,-25,-26,86,-71,-72,86,-9,-10,-11,-12,-13,-21,-23,-22,-24,-40,-42,-44,-30,-30,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'STRING':([9,10,18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,82,90,103,],[27,30,42,-5,42,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,-3,-1,-6,]),'SEMICOLON':([18,26,29,35,36,37,38,39,40,41,42,43,44,45,47,49,50,51,53,62,63,65,68,69,72,73,74,75,76,77,78,79,81,82,90,99,100,103,105,108,126,],[-80,57,60,-5,67,-79,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,71,-74,-77,-63,-63,-4,-78,-14,-73,-75,-76,91,92,93,94,97,101,-3,-1,-62,-65,-6,97,-64,130,]),'FLOAT':([18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,82,90,103,],[38,-5,38,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,-3,-1,-6,]),'INT':([18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,82,90,103,],[39,-5,39,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,-3,-1,-6,]),'NONE':([18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,82,90,103,],[40,-5,40,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,-3,-1,-6,]),'ALL':([18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,82,90,103,],[41,-5,41,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,-3,-1,-6,]),'TRUE':([18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,82,90,103,],[43,-5,43,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,-3,-1,-6,]),'FALSE':([18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,82,90,103,],[44,-5,44,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,-3,-1,-6,]),'EQUALS':([18,35,37,38,39,40,41,42,43,44,45,47,49,65,69,80,82,90,96,100,103,],[46,-5,46,-81,-82,-83,-84,-85,-86,-87,-88,-15,-2,-4,-14,46,-3,-1,46,46,-6,]),'PLUS':([19,35,49,51,53,65,73,74,82,90,103,],[52,-5,-2,52,-77,-4,-75,-76,-3,-1,-6,]),'MINUS':([19,35,49,51,53,65,73,74,82,90,103,],[54,-5,-2,54,-77,-4,-75,-76,-3,-1,-6,]),'ARROW':([35,47,49,62,65,69,79,82,90,99,100,103,108,],[-5,-15,-2,-63,-4,-14,96,-3,-1,-62,-65,-6,-64,]),'LBRACKET':([35,],[66,]),'COLON':([62,63,],[80,80,]),'INDEX':([66,67,71,84,85,86,87,88,89,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[88,-71,-72,88,-9,-10,-11,-12,-13,-40,-42,-44,116,116,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'PROPERTY':([66,84,85,86,87,88,89,],[89,89,-9,-10,-11,-12,-13,]),'CONSTRAINT':([67,71,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[-71,-72,-40,-42,-44,117,117,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'DELETE':([67,71,95,97,101,102,110,111,112,113,114,115,119,120,122,128,130,138,139,142,],[-71,-72,-40,-42,-44,118,118,-48,-49,-50,-51,-52,-41,-43,-45,-66,-53,-54,-67,-58,]),'RBRACKET':([83,84,85,86,87,88,89,104,],[103,-8,-9,-10,-11,-12,-13,-7,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'yasd':([0,],[1,]),'schema_name':([2,6,9,10,],[3,11,25,28,]),'uses':([5,8,],[7,24,]),'use':([5,8,],[8,8,]),'defs':([7,13,],[12,32,]),'def':([7,13,],[13,13,]),'fielddef':([7,13,102,110,],[14,14,112,112,]),'fieldsetdef':([7,13,102,110,],[15,15,113,113,]),'simpleprop':([7,13,98,102,107,110,127,129,133,134,136,],[16,16,107,111,107,111,134,137,141,107,137,]),'modifiers':([7,13,20,102,110,],[17,17,55,17,17,]),'modifier':([7,13,20,102,110,],[20,20,20,20,20,]),'propvalues':([18,37,],[36,68,]),'propvalue':([18,37,],[37,37,]),'imp_name':([18,37,80,96,100,],[45,45,100,105,100,]),'dotted_name':([18,19,37,46,51,52,54,80,96,100,],[47,53,47,69,53,73,74,47,47,47,]),'simple_dotted_name':([18,19,37,46,51,52,54,64,70,80,96,100,],[49,49,49,49,49,49,49,82,90,49,49,49,]),'idxfields':([19,51,],[50,72,]),'idxfield':([19,51,],[51,51,]),'min_classes':([35,],[65,]),'typedef':([62,63,],[79,81,]),'minclassitems':([66,84,],[83,104,]),'minclassitem':([66,84,],[84,84,]),'fieldprops':([79,105,],[95,119,]),'typedef_items':([80,100,],[99,108,]),'simpleprops':([98,107,127,134,],[106,121,132,121,]),'fsitems':([102,110,],[109,123,]),'fsitem':([102,110,],[110,110,]),'indexdef':([102,110,],[114,114,]),'deletion':([102,110,],[115,115,]),'indexprops':([124,],[128,]),'idxitems':([127,133,],[131,140,]),'idxitem':([127,133,],[133,133,]),'constraintitems':([129,136,],[135,143,]),'constraintitem':([129,136,],[136,136,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> yasd","S'",1,None,None,None),
('dotted_name -> SCHEMA DOT simple_dotted_name','dotted_name',3,'p_dotted_name_absolute_1','yacc.py',37),
('dotted_name -> simple_dotted_name','dotted_name',1,'p_dotted_name_simple_dotted_name','yacc.py',45),
('simple_dotted_name -> NAME DOT simple_dotted_name','simple_dotted_name',3,'p_dotted_name_dotted_name','yacc.py',50),
('simple_dotted_name -> NAME min_classes','simple_dotted_name',2,'p_dotted_name_name','yacc.py',59),
('min_classes -> <empty>','min_classes',0,'p_min_classes_empty','yacc.py',71),
('min_classes -> LBRACKET minclassitems RBRACKET','min_classes',3,'p_min_classes_items','yacc.py',76),
('minclassitems -> minclassitem minclassitems','minclassitems',2,'p_minclassitems_item','yacc.py',81),
('minclassitems -> minclassitem','minclassitems',1,'p_minclassitems_single','yacc.py',86),
('minclassitem -> SCHEMA','minclassitem',1,'p_minclassitem_schema','yacc.py',91),
('minclassitem -> FIELDSET','minclassitem',1,'p_minclassitem_fieldset','yacc.py',96),
('minclassitem -> FIELD','minclassitem',1,'p_minclassitem_field','yacc.py',101),
('minclassitem -> INDEX','minclassitem',1,'p_minclassitem_index','yacc.py',106),
('minclassitem -> PROPERTY','minclassitem',1,'p_minclassitem_property','yacc.py',111),
('imp_name -> EQUALS dotted_name','imp_name',2,'p_imp_name_eq_dotted_name','yacc.py',116),
('imp_name -> dotted_name','imp_name',1,'p_imp_name_dotted_name','yacc.py',123),
('schema_name -> NAME','schema_name',1,'p_schema_simple_name','yacc.py',130),
('schema_name -> NAME DOT schema_name','schema_name',3,'p_schema_package_name','yacc.py',139),
('yasd -> SCHEMA schema_name LBRACE uses defs RBRACE','yasd',6,'p_yasd','yacc.py',148),
('uses -> use uses','uses',2,'p_uses','yacc.py',155),
('uses -> use','uses',1,'p_uses_use','yacc.py',160),
('use -> USE schema_name AS NAME SEMICOLON','use',5,'p_use_as','yacc.py',165),
('use -> REQUIRE schema_name AS NAME SEMICOLON','use',5,'p_use_as','yacc.py',166),
('use -> USE STRING AS NAME SEMICOLON','use',5,'p_use_as','yacc.py',167),
('use -> REQUIRE STRING AS NAME SEMICOLON','use',5,'p_use_as','yacc.py',168),
('use -> USE NAME SEMICOLON','use',3,'p_use','yacc.py',179),
('use -> REQUIRE NAME SEMICOLON','use',3,'p_use','yacc.py',180),
('use -> <empty>','use',0,'p_use_empty','yacc.py',190),
('modifiers -> modifier modifiers','modifiers',2,'p_modifiers_modifiers','yacc.py',195),
('modifiers -> modifier','modifiers',1,'p_modifiers_modifier','yacc.py',200),
('modifier -> <empty>','modifier',0,'p_modifier_empty','yacc.py',205),
('modifier -> ABSTRACT','modifier',1,'p_modifier','yacc.py',210),
('modifier -> FINAL','modifier',1,'p_modifier','yacc.py',211),
('modifier -> REQUIRED','modifier',1,'p_modifier','yacc.py',212),
('defs -> def defs','defs',2,'p_defs','yacc.py',217),
('defs -> def','defs',1,'p_defs_def','yacc.py',222),
('def -> fielddef','def',1,'p_def','yacc.py',227),
('def -> fieldsetdef','def',1,'p_def','yacc.py',228),
('def -> simpleprop','def',1,'p_def','yacc.py',229),
('defs -> <empty>','defs',0,'p_defs_empty','yacc.py',238),
('fielddef -> modifiers FIELD NAME typedef fieldprops','fielddef',5,'p_fielddef_simple','yacc.py',243),
('fielddef -> modifiers FIELD NAME typedef ARROW imp_name fieldprops','fielddef',7,'p_fielddef_ref','yacc.py',257),
('fieldprops -> SEMICOLON','fieldprops',1,'p_fieldprops_empty','yacc.py',278),
('fieldprops -> LBRACE simpleprops RBRACE','fieldprops',3,'p_fieldprops','yacc.py',283),
('fieldsetdef -> modifiers FIELDSET NAME typedef SEMICOLON','fieldsetdef',5,'p_fieldsetdef_simple','yacc.py',288),
('fieldsetdef -> modifiers FIELDSET NAME typedef LBRACE fsitems RBRACE','fieldsetdef',7,'p_fieldsetdef_complex','yacc.py',302),
('fsitems -> fsitem fsitems','fsitems',2,'p_fsitems_many','yacc.py',316),
('fsitems -> fsitem','fsitems',1,'p_fsitems_one','yacc.py',321),
('fsitem -> simpleprop','fsitem',1,'p_fsitem_simpleprop','yacc.py',326),
('fsitem -> fielddef','fsitem',1,'p_fsitem_defs','yacc.py',331),
('fsitem -> fieldsetdef','fsitem',1,'p_fsitem_defs','yacc.py',332),
('fsitem -> indexdef','fsitem',1,'p_fsitem_defs','yacc.py',333),
('fsitem -> deletion','fsitem',1,'p_fsitem_deletion','yacc.py',338),
('deletion -> DELETE NAME SEMICOLON','deletion',3,'p_deletion','yacc.py',343),
('indexdef -> INDEX NAME LBRACE idxitems RBRACE','indexdef',5,'p_indexdef','yacc.py',350),
('idxitems -> idxitem idxitems','idxitems',2,'p_idxitems_many','yacc.py',358),
('idxitems -> idxitem','idxitems',1,'p_idxitems_one','yacc.py',363),
('idxitem -> simpleprop','idxitem',1,'p_idxitem_simpleprop','yacc.py',368),
('indexdef -> CONSTRAINT NAME LBRACE constraintitems RBRACE','indexdef',5,'p_constraintdef','yacc.py',373),
('constraintitems -> constraintitem constraintitems','constraintitems',2,'p_constraintitems_many','yacc.py',381),
('constraintitems -> constraintitem','constraintitems',1,'p_constraintitems_one','yacc.py',386),
('constraintitem -> simpleprop','constraintitem',1,'p_constraintitem_simpleprop','yacc.py',396),
('typedef -> COLON typedef_items','typedef',2,'p_typedef','yacc.py',400),
('typedef -> <empty>','typedef',0,'p_typedef_empty','yacc.py',405),
('typedef_items -> imp_name typedef_items','typedef_items',2,'p_typedef_items_many','yacc.py',410),
('typedef_items -> imp_name','typedef_items',1,'p_typedef_items_one','yacc.py',415),
('indexdef -> INDEX NAME indexprops','indexdef',3,'p_indexdef_simple','yacc.py',420),
('indexprops -> LBRACE simpleprops RBRACE','indexprops',3,'p_indexprops','yacc.py',434),
('simpleprops -> simpleprop simpleprops','simpleprops',2,'p_simpleprops_many','yacc.py',439),
('simpleprops -> simpleprop','simpleprops',1,'p_simpleprops_one','yacc.py',444),
('simpleprops -> <empty>','simpleprops',0,'p_simpleprops_empty','yacc.py',449),
('simpleprop -> NAME propvalues SEMICOLON','simpleprop',3,'p_simpleprop_one','yacc.py',454),
('simpleprop -> FIELDS idxfields SEMICOLON','simpleprop',3,'p_simpleprop_fields','yacc.py',461),
('idxfields -> idxfield idxfields','idxfields',2,'p_idxfields_many','yacc.py',468),
('idxfields -> idxfield','idxfields',1,'p_idxfields_one','yacc.py',473),
('idxfield -> PLUS dotted_name','idxfield',2,'p_idxfield_asc','yacc.py',478),
('idxfield -> MINUS dotted_name','idxfield',2,'p_idxfield_desc','yacc.py',486),
('idxfield -> dotted_name','idxfield',1,'p_idxfield_simple','yacc.py',494),
('propvalues -> propvalue propvalues','propvalues',2,'p_propvalues_many','yacc.py',503),
('propvalues -> propvalue','propvalues',1,'p_propvalues_one','yacc.py',508),
('propvalues -> <empty>','propvalues',0,'p_propvalues_empty','yacc.py',513),
('propvalue -> FLOAT','propvalue',1,'p_propvalue_float','yacc.py',518),
('propvalue -> INT','propvalue',1,'p_propvalue_int','yacc.py',524),
('propvalue -> NONE','propvalue',1,'p_propvalue_none','yacc.py',530),
('propvalue -> ALL','propvalue',1,'p_propvalue_all','yacc.py',535),
('propvalue -> STRING','propvalue',1,'p_propvalue_string','yacc.py',540),
('propvalue -> TRUE','propvalue',1,'p_propvalue_true','yacc.py',546),
('propvalue -> FALSE','propvalue',1,'p_propvalue_false','yacc.py',552),
('propvalue -> imp_name','propvalue',1,'p_propvalue_imp_name','yacc.py',558),
]
| 151.94958
| 6,063
| 0.657283
| 3,298
| 18,082
| 3.502123
| 0.110673
| 0.045714
| 0.008831
| 0.011775
| 0.373939
| 0.301472
| 0.252641
| 0.21645
| 0.1929
| 0.181818
| 0
| 0.242993
| 0.06277
| 18,082
| 118
| 6,064
| 153.237288
| 0.438544
| 0.004646
| 0
| 0.018519
| 1
| 0.009259
| 0.472628
| 0.029901
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 5
|
6b31f8d6c81d7ba320ccc09e1b95b7bf9708c1b5
| 33
|
py
|
Python
|
aliyunpy/__init__.py
|
jokimina/aliyunpy
|
fbfda8a7dc7e89cc79621bee31622ea9547944fa
|
[
"MIT"
] | 1
|
2019-07-26T01:31:26.000Z
|
2019-07-26T01:31:26.000Z
|
aliyunpy/__init__.py
|
jokimina/aliyunpy
|
fbfda8a7dc7e89cc79621bee31622ea9547944fa
|
[
"MIT"
] | null | null | null |
aliyunpy/__init__.py
|
jokimina/aliyunpy
|
fbfda8a7dc7e89cc79621bee31622ea9547944fa
|
[
"MIT"
] | null | null | null |
from .client import AliyunClient
| 16.5
| 32
| 0.848485
| 4
| 33
| 7
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.121212
| 33
| 1
| 33
| 33
| 0.965517
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 0
| 1
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
86254f0c4a68eed389c21d76b25fb376aab81584
| 167
|
py
|
Python
|
trails/feeds/__init__.py
|
gallypette/maltrail
|
1a863c287ce94ba128ef023bab0d5166fe8a4519
|
[
"MIT"
] | null | null | null |
trails/feeds/__init__.py
|
gallypette/maltrail
|
1a863c287ce94ba128ef023bab0d5166fe8a4519
|
[
"MIT"
] | null | null | null |
trails/feeds/__init__.py
|
gallypette/maltrail
|
1a863c287ce94ba128ef023bab0d5166fe8a4519
|
[
"MIT"
] | 1
|
2019-12-06T08:37:05.000Z
|
2019-12-06T08:37:05.000Z
|
#!/usr/bin/env python
"""
Copyright (c) 2014-2019 Maltrail developers (https://github.com/stamparm/maltrail/)
See the file 'LICENSE' for copying permission
"""
pass
| 18.555556
| 83
| 0.730539
| 23
| 167
| 5.304348
| 0.956522
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.054422
| 0.11976
| 167
| 8
| 84
| 20.875
| 0.77551
| 0.898204
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 1
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| 0
| 0
|
0
| 5
|
8625ba37d730d87c21b01664ffadedecb50e229e
| 130
|
py
|
Python
|
seabridge_app/seabridge_app/doctype/company/company_dashboard.py
|
Sagarikanaik96/Test2
|
c778c3a33ad5c8836cf147c79ac5e6f694b73b29
|
[
"MIT"
] | null | null | null |
seabridge_app/seabridge_app/doctype/company/company_dashboard.py
|
Sagarikanaik96/Test2
|
c778c3a33ad5c8836cf147c79ac5e6f694b73b29
|
[
"MIT"
] | null | null | null |
seabridge_app/seabridge_app/doctype/company/company_dashboard.py
|
Sagarikanaik96/Test2
|
c778c3a33ad5c8836cf147c79ac5e6f694b73b29
|
[
"MIT"
] | null | null | null |
from __future__ import unicode_literals
from frappe import _
def get_dashboard_data(data):
return {
'fieldname': 'company'
}
| 16.25
| 39
| 0.769231
| 16
| 130
| 5.75
| 0.8125
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.153846
| 130
| 7
| 40
| 18.571429
| 0.836364
| 0
| 0
| 0
| 0
| 0
| 0.123077
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.166667
| false
| 0
| 0.333333
| 0.166667
| 0.666667
| 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
| 1
| 1
| 1
| 0
|
0
| 5
|
864f2866d854157bc0ee3eb769d32da0d53adb00
| 160
|
py
|
Python
|
pymatgen/analysis/magnetism/__init__.py
|
frssp/pymatgen
|
bdd977f065b66191557c7398b31a1571bc541fdb
|
[
"MIT"
] | 5
|
2019-04-11T20:57:38.000Z
|
2021-12-01T05:00:42.000Z
|
pymatgen/analysis/magnetism/__init__.py
|
darnoceloc/pymatgen
|
5cc42912a12a265a603df7e34c856561f76edc1f
|
[
"MIT"
] | 3
|
2017-07-18T01:13:41.000Z
|
2019-04-29T18:17:30.000Z
|
pymatgen/analysis/magnetism/__init__.py
|
darnoceloc/pymatgen
|
5cc42912a12a265a603df7e34c856561f76edc1f
|
[
"MIT"
] | 3
|
2019-10-14T19:47:34.000Z
|
2020-07-02T08:10:45.000Z
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from pymatgen.analysis.magnetism.analyzer import *
| 32
| 50
| 0.78125
| 22
| 160
| 5.681818
| 0.909091
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.007246
| 0.1375
| 160
| 5
| 50
| 32
| 0.898551
| 0.6375
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
8670dd8f9dfb23cf52c98787279cdbe1985464a1
| 113
|
py
|
Python
|
test/unit/__init__.py
|
uk-gov-mirror/hmrc.service-manager
|
6d6fcc4a1d25d094e7d0c798fc4219cf20a6f234
|
[
"Apache-2.0"
] | 52
|
2015-02-04T21:09:11.000Z
|
2022-02-23T15:48:06.000Z
|
test/unit/__init__.py
|
uk-gov-mirror/hmrc.service-manager
|
6d6fcc4a1d25d094e7d0c798fc4219cf20a6f234
|
[
"Apache-2.0"
] | 57
|
2015-01-08T10:17:16.000Z
|
2021-11-18T14:56:51.000Z
|
test/unit/__init__.py
|
uk-gov-mirror/hmrc.service-manager
|
6d6fcc4a1d25d094e7d0c798fc4219cf20a6f234
|
[
"Apache-2.0"
] | 50
|
2015-02-02T16:12:13.000Z
|
2021-11-13T09:19:32.000Z
|
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__) + "/" + "../../servicemanager"))
| 22.6
| 90
| 0.690265
| 15
| 113
| 4.933333
| 0.6
| 0.162162
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.088496
| 113
| 4
| 91
| 28.25
| 0.718447
| 0
| 0
| 0
| 0
| 0
| 0.185841
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.666667
| 0
| 0.666667
| 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
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 5
|
8685181a6060d0d5c48770bec594bfe42ad1d5cf
| 649
|
py
|
Python
|
data/contacts.py
|
valeriia-karpenko/python_training
|
5b621a4c14f57a57695932cf8b2d6741fd452edb
|
[
"Apache-2.0"
] | null | null | null |
data/contacts.py
|
valeriia-karpenko/python_training
|
5b621a4c14f57a57695932cf8b2d6741fd452edb
|
[
"Apache-2.0"
] | null | null | null |
data/contacts.py
|
valeriia-karpenko/python_training
|
5b621a4c14f57a57695932cf8b2d6741fd452edb
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf-8 -*-
from model.contact import Contact
testdata = [
Contact(firstname="Ivan", lastname="Ivanov", homephone="781236223", email="ivanov@gmail.com",
mobilephone="+79119685588", workphone="88124568995", secondaryphone="88124568988",
address="Spb Nevskiy 36-89", email2="ivanov@mail.ru", email3="ivanov@ya.ru"),
Contact(firstname="firstname1", lastname="lastname1", homephone="781236223", email="ivanov@gmail.com",
mobilephone="+79119685588", workphone="88124568995", secondaryphone="88124568988",
address="Spb Nevskiy 36-89", email2="ivanov@mail.ru", email3="ivanov@ya.ru")
]
| 49.923077
| 106
| 0.681048
| 69
| 649
| 6.405797
| 0.507246
| 0.072398
| 0.104072
| 0.131222
| 0.719457
| 0.719457
| 0.719457
| 0.719457
| 0.719457
| 0.719457
| 0
| 0.1787
| 0.146379
| 649
| 12
| 107
| 54.083333
| 0.619134
| 0.032357
| 0
| 0.222222
| 0
| 0
| 0.372204
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.111111
| 0
| 0.111111
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 1
| 1
| 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
| 5
|
86a41988f370926b360e4d584350982dd63bcc69
| 75
|
py
|
Python
|
snorkel/contrib/snark/models/__init__.py
|
Conengmo/snorkel
|
36868e8a84de19b94e1c4b8eceaa64969a61a46b
|
[
"Apache-2.0"
] | 30
|
2019-08-22T19:27:59.000Z
|
2022-03-13T22:03:15.000Z
|
snorkel/contrib/snark/models/__init__.py
|
Conengmo/snorkel
|
36868e8a84de19b94e1c4b8eceaa64969a61a46b
|
[
"Apache-2.0"
] | 2
|
2019-08-22T16:51:58.000Z
|
2022-03-21T02:59:18.000Z
|
snorkel/contrib/snark/models/__init__.py
|
Conengmo/snorkel
|
36868e8a84de19b94e1c4b8eceaa64969a61a46b
|
[
"Apache-2.0"
] | 31
|
2019-08-22T19:28:08.000Z
|
2022-03-23T12:50:49.000Z
|
from __future__ import absolute_import
class SparkModel(object):
pass
| 15
| 38
| 0.8
| 9
| 75
| 6.111111
| 0.888889
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.16
| 75
| 4
| 39
| 18.75
| 0.873016
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0.333333
| 0.333333
| 0
| 0.666667
| 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
| 1
| 1
| 1
| 0
| 0
| 0
|
0
| 5
|
86cc580f74ee716c02a78cf25a560759a0c7441d
| 124
|
py
|
Python
|
SphinxBot/__init__.py
|
corentinalcoy/sphinx-bot
|
29424f627508f4099f706493f0d00020304bf243
|
[
"MIT"
] | null | null | null |
SphinxBot/__init__.py
|
corentinalcoy/sphinx-bot
|
29424f627508f4099f706493f0d00020304bf243
|
[
"MIT"
] | 6
|
2021-03-19T03:35:31.000Z
|
2022-02-10T08:52:55.000Z
|
SphinxBot/__init__.py
|
corentinalcoy/sphinx-bot
|
29424f627508f4099f706493f0d00020304bf243
|
[
"MIT"
] | 1
|
2019-11-28T18:12:19.000Z
|
2019-11-28T18:12:19.000Z
|
from __future__ import unicode_literals, absolute_import
from .celery import app as celery_app
__all__ = ('celery_app', )
| 20.666667
| 56
| 0.798387
| 17
| 124
| 5.117647
| 0.588235
| 0.206897
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.137097
| 124
| 5
| 57
| 24.8
| 0.813084
| 0
| 0
| 0
| 0
| 0
| 0.080645
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.666667
| 0
| 0.666667
| 0
| 1
| 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
| 1
| 0
| 1
| 0
|
0
| 5
|
86dfb5cfb67cb51a9f729ee596c0586a6d18fc88
| 44
|
py
|
Python
|
repeating_timer/__init__.py
|
TheQuinbox/repeating_timer
|
1456f2804d08eed3f8374c90876f6a817a006ff2
|
[
"MIT"
] | null | null | null |
repeating_timer/__init__.py
|
TheQuinbox/repeating_timer
|
1456f2804d08eed3f8374c90876f6a817a006ff2
|
[
"MIT"
] | null | null | null |
repeating_timer/__init__.py
|
TheQuinbox/repeating_timer
|
1456f2804d08eed3f8374c90876f6a817a006ff2
|
[
"MIT"
] | null | null | null |
from .repeating_timer import RepeatingTimer
| 22
| 43
| 0.886364
| 5
| 44
| 7.6
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.090909
| 44
| 1
| 44
| 44
| 0.95
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 0
| 1
| 1
| 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
| 1
| 0
| 0
| 0
|
0
| 5
|
81278324ede676334f161ff7b5846555036b2c51
| 246
|
py
|
Python
|
server/problem_sets/static/data/sqlite/sqlite_serializable.py
|
iiridescent/problem-sets
|
e906fe7509cd158ecdb5920853636339d4d531c3
|
[
"MIT"
] | null | null | null |
server/problem_sets/static/data/sqlite/sqlite_serializable.py
|
iiridescent/problem-sets
|
e906fe7509cd158ecdb5920853636339d4d531c3
|
[
"MIT"
] | 5
|
2021-03-09T10:36:59.000Z
|
2022-02-26T14:36:08.000Z
|
server/problem_sets/static/data/sqlite/sqlite_serializable.py
|
vinhowe/problem-sets
|
e906fe7509cd158ecdb5920853636339d4d531c3
|
[
"MIT"
] | null | null | null |
# Copyright (c) 2019 Thomas Howe
from abc import ABC, abstractmethod
class SQLiteSerializable(ABC):
@abstractmethod
def to_sqlite_row(cls):
pass
@classmethod
@abstractmethod
def from_sqlite_row(cls):
pass
| 16.4
| 35
| 0.678862
| 28
| 246
| 5.821429
| 0.642857
| 0.208589
| 0.147239
| 0.196319
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.021858
| 0.256098
| 246
| 14
| 36
| 17.571429
| 0.868852
| 0.121951
| 0
| 0.444444
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.222222
| false
| 0.222222
| 0.111111
| 0
| 0.444444
| 0
| 1
| 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
| 1
| 0
| 1
| 0
| 0
| 0
| 0
|
0
| 5
|
812c71f91ce2d6c88bbd1ff41cc5aa4e032db75b
| 283
|
py
|
Python
|
UNetGAN/unetgan/data.py
|
gcinbis/deep-generative-models-spring20
|
d377bd63d5e79539477cca47c71462e5cc12adfa
|
[
"MIT"
] | 18
|
2020-07-06T10:47:26.000Z
|
2021-05-30T11:43:17.000Z
|
UNetGAN/unetgan/data.py
|
gcinbis/deep-generative-models-course-projects
|
d377bd63d5e79539477cca47c71462e5cc12adfa
|
[
"MIT"
] | 1
|
2022-03-12T00:39:12.000Z
|
2022-03-12T00:39:12.000Z
|
UNetGAN/unetgan/data.py
|
gcinbis/deep-generative-models-spring20
|
d377bd63d5e79539477cca47c71462e5cc12adfa
|
[
"MIT"
] | 2
|
2020-07-13T20:46:44.000Z
|
2020-10-01T13:15:25.000Z
|
import torchvision.datasets.celeba as celeba
class CelebA(celeba.CelebA):
""" A simple wrapper around torch.datasets.celebA.
We shouldn't need to do anything about the data, but it may be useful to
store data-dependent things here in the future.
"""
pass
| 28.3
| 76
| 0.706714
| 42
| 283
| 4.761905
| 0.785714
| 0.14
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.226148
| 283
| 9
| 77
| 31.444444
| 0.913242
| 0.590106
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0.333333
| 0.333333
| 0
| 0.666667
| 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
| 1
| 1
| 1
| 0
| 1
| 0
|
0
| 5
|
d4f8416bc6b4fc79c6db21b077f6da5238ce5227
| 165,254
|
py
|
Python
|
sanic_openapi3e/oas_types.py
|
endafarrell/openapi-sanic3e
|
cfb4bcb7e983693e5abb781c23dba3931a1caadd
|
[
"MIT"
] | 7
|
2021-01-14T19:28:48.000Z
|
2021-09-19T07:39:02.000Z
|
sanic_openapi3e/oas_types.py
|
endafarrell/sanic-openapi3e
|
cfb4bcb7e983693e5abb781c23dba3931a1caadd
|
[
"MIT"
] | 24
|
2019-03-04T09:18:27.000Z
|
2021-01-20T10:17:04.000Z
|
sanic_openapi3e/oas_types.py
|
endafarrell/sanic-openapi3e
|
cfb4bcb7e983693e5abb781c23dba3931a1caadd
|
[
"MIT"
] | null | null | null |
# pylint: disable=too-many-lines
"""
OpenAPI Spec 3.0.2 types, though without any `Specification Extensions
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specificationExtensions>`_
Some terms in the spec are unsuitable for python, they have been changed in the code:
* `in` -> `_in`
* `type` -> `_type`
* `format` -> `_format`
* `$ref` -> `_ref`
* `license` -> `_license`
Given that these changes were already needed, some others were also added to keep with PEP8 naming conventions in this
code:
* `operationId` -> `operation_id`
*
In (many) other examples, terms using camelCase were changed to use underscores. Eg `readOnly` -> `read_only`.
Limitations
-----------
This implementation has some known limitations:
* Phrases in the spec like "MUST be in the format of a URL.", or "MUST be in the format of an email address." are noted,
in the docs, but not checked.
* There is no accommodation for Specification Extensions.
* Schema.items is not well understood, your mileage may vary.
* SecurityScheme (specifically the REQUIREDs) are not well understood, and so no validation checks on REQUIRED fields
are done.
"""
# pylint: disable=too-few-public-methods
import copy
import functools
import json
import re
import traceback
import warnings
from collections import OrderedDict
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union
import sanic.router
def _assert_type(element: Any, types: Sequence[Any], name: str, clazz: Type[Any]) -> None:
"""
Utility to help assert types are only as expected.
:param element: The element being checked
:param types: The allowed types
:param name: The name of the element
:param clazz: The class containing the element
"""
assert isinstance(types, tuple)
assert isinstance(name, str)
if element is not None and not isinstance(element, types):
raise TypeError("Incorrect type ({}) for {}.{}, [{}]".format(type(element), clazz.__qualname__, name, types))
def _assert_required(element, name, clazz, why=""):
assert isinstance(name, str)
if not element:
raise AssertionError("For `{}`, the field `{}` is required{}.".format(clazz.__qualname__, name, why))
def _assert_strictly_greater_than_zero(element, name, clazz):
assert isinstance(name, str)
if element is not None:
assert isinstance(element, int), "For `{}`, the field `{}` must be an int if supplied.".format(
clazz.__qualname__, name
)
assert element > 0, "For `{}`, the field `{}` must be strictly greater than 0: {} is not".format(
clazz.__qualname__, name, element
)
@functools.lru_cache(maxsize=64)
def simple_snake2camel(string: str) -> str:
if "_" not in string:
return string.strip()
first, *rest = string.strip().lower().split("_")
return first + "".join(ele.capitalize() for ele in rest)
@functools.lru_cache(maxsize=64)
def openapi_keyname(key: str) -> str:
"""
Returns the OpenAPI name for keys.
"""
return {
"_format": "format",
"_in": "in",
"_license": "license",
"_not": "not",
"_ref": "$ref",
"_type": "type",
"additional_properties": "additionalProperties",
"all_of": "allOf",
"any_of": "anyOf",
"bearer_format": "bearerFormat",
"dollar_ref": "$ref",
"exclusive_maximum": "exclusiveMaximum",
"exclusive_minimum": "exclusiveMinimum",
"external_docs": "externalDocs",
"max_items": "maxItems",
"max_length": "maxLength",
"max_properties": "maxProperties",
"min_items": "minItems",
"min_length": "minLength",
"min_properties": "minProperties",
"multiple_of": "multipleOf",
"one_of": "oneOf",
"operation_id": "operationId",
"property_name": "propertyName",
"read_only": "readOnly",
"request_body": "requestBody",
"security_schemes": "securitySchemes",
"terms_of_service": "termsOfService",
"unique_items": "uniqueItems",
"write_only": "writeOnly",
}.get(key, simple_snake2camel(key))
def default_operation_id_fn(method: str, uri: str, route: sanic.router.Route) -> str:
uri_for_operation_id: str = uri
for parameter in route.parameters:
uri_for_operation_id = re.sub("<" + parameter.name + ".*?>", parameter.name, uri_for_operation_id)
return "{}~~{}".format(method.upper(), uri_for_operation_id).replace("/", "~")
def camel_case_operation_id_fn(method: str, uri: str, route: sanic.router.Route) -> str:
if hasattr(route.handler, "__class__") and hasattr(route.handler, "handlers"):
# These are `sanic.view.CompositeView`s and while seen in the wild, getting a test case for this is
# surprisingly difficult
_method_handler = route.handler.handlers.get(method.upper())
if _method_handler:
handler_name = method + "_" + _method_handler.__name__
else:
raise ValueError(f"No {method.upper()} handler found for {uri} handlers: {route.handler.handlers}")
elif hasattr(route.handler, "__name__"):
if len(route.methods) > 1:
# This fn will be called many times, once per method, but we should prefix the handler_name with this
# prefix to make the operationIds globally unique. If the route is only used by one method, use that
# handler's name.
handler_name = method + "_" + route.handler.__name__
else:
handler_name = route.handler.__name__
else:
raise NotImplementedError()
return simple_snake2camel(handler_name)
NoneType = type(None)
class OObject:
"""A base object for sanic_openapi3e. Internal."""
@staticmethod
def _as_yamlable_object(
value: Any, sort=False, opt_key: Optional[str] = None
) -> Union[Dict, str, bytes, int, float, List, NoneType]:
if isinstance(value, OObject):
return value.as_yamlable_object(sort=sort, opt_key=opt_key)
if isinstance(value, (str, bytes, int, float, type(None))):
return value
if isinstance(value, list):
if sort:
value = sorted(value)
return [OObject._as_yamlable_object(v, sort=sort, opt_key=opt_key) for v in value]
if isinstance(value, (dict, OrderedDict)):
items = list(value.items())
if sort:
items = sorted(items)
return {
key2: OObject._as_yamlable_object(value2, sort=sort, opt_key=f"{opt_key}.{key2}")
for key2, value2 in items
}
raise TypeError(f"{type(value)}, value={value} opt_key={opt_key}")
def as_yamlable_object( # pylint: disable=too-many-branches
self, sort=False, opt_key: Optional[str] = None
) -> Dict:
_repr = {}
if not hasattr(self, "__dict__"):
raise TypeError(str(opt_key) + " " + self.__class__.__qualname__ + " " + repr(self))
for key, value in self.__dict__.items():
key2 = openapi_keyname(key)
# Schema classes have many keys with bool where their default is false. Don't send them out.
if self.__class__.__qualname__ == "Schema" and value is False:
if key2 in {
"nullable",
"readOnly",
"writeOnly",
" deprecated",
"exclusiveMaximum",
"exclusiveMinimum",
"uniqueItems",
}:
continue
# Allow False bools, but not other falsy values - UNLESS:
# 1: self is a SecurityRequirement
# 2: self is an Operation and key is security
# as an empty list has special meaning for these.
if (value is not False) and (not value):
if value == [] and self.__class__.__qualname__ == "SecurityRequirement":
pass
elif value == [] and key == "security" and self.__class__.__qualname__ == "Operation":
pass
else:
continue
if key.startswith("x_"):
continue
if key == "deprecated" and value is False:
# By default, items in specs are `deprecated: false` - these are not desirable in the specs
continue
value2: Union[Dict, List, str, bytes, int, float, bool, NoneType]
if value is False or value is True:
value2 = value
############################################################################################################
# List of yamlable objects for element in value
elif key2 == "parameters" and self.__class__ in (PathItem, Operation):
value2 = [OObject.as_yamlable_object(e, sort=sort, opt_key=f"{opt_key}.{key2}") for e in value]
############################################################################################################
# dicts of yamlable objects for items() value
elif key2 == "responses" and self.__class__ == Components:
value2 = {
key3: value3.as_yamlable_object(opt_key=f"{opt_key}.{key2}") for key3, value3 in value.items()
}
elif key2 == "examples":
value2 = {
key3: OObject._as_yamlable_object(value3, opt_key=f"{opt_key}.{key2}")
for key3, value3 in value.items()
}
############################################################################################################
# paths are a special case
elif key2 == "paths":
value2 = {
uri: OObject.as_yamlable_object(path_item, opt_key=f"{opt_key}.{uri}")
for uri, path_item in value._paths # pylint: disable=protected-access
}
############################################################################################################
# sort the schemas
elif key2 == "schemas":
# Everyone wants sorted schema entries! Note that as `dict`s, they require OObject._as_yamlable_object
value2 = OObject._as_yamlable_object(value, sort=True, opt_key=f"{opt_key}.{key2}")
############################################################################################################
# default - for known OObjects
elif isinstance(value, OObject) and hasattr(value, "__dict__"):
value2 = OObject.as_yamlable_object(value, sort=sort, opt_key=f"{opt_key}.{key}")
else:
# Note how this uses the OObject._as_yamlable_object
value2 = OObject._as_yamlable_object(value, opt_key=f"{opt_key}.{key2}")
_repr[key2] = value2
if sort:
# Note: py36 does not have any (eternally dependable) ordering for dicts, but py37+
# remembers insert-order.
return {key: value for key, value in sorted(_repr.items())} # pylint: disable=unnecessary-comprehension
return _repr
def __repr__(self):
return "{}({})".format(
self.__class__.__qualname__, json.dumps(self.as_yamlable_object(sort=True), sort_keys=True),
)
# --------------------------------------------------------------- #
# Primitive data types
# --------------------------------------------------------------- #
class OType(OObject):
"""A sanic_openapi3e class to hold OpenAPI types. Internal."""
name: str = "otype"
formats: List[str] = []
# --------------------------------------------------------------- #
# Info Object
# --------------------------------------------------------------- #
class Contact(OObject):
"""Contact information for the exposed API."""
def __init__(
self, name: Optional[str] = None, url: Optional[str] = None, email: Optional[str] = None,
):
"""
Contact information for the exposed API.
:param name: The identifying name of the contact person/organization.
:param url: The URL pointing to the contact information. MUST be in the format of a URL.
:param email: The email address of the contact person/organization. MUST be in the format of an email address.
"""
_assert_type(name, (str,), "name", self.__class__)
_assert_type(url, (str,), "url", self.__class__)
_assert_type(email, (str,), "email", self.__class__)
self.name = name
"""The identifying name of the contact person/organization."""
self.url = url
"""The URL pointing to the contact information. MUST be in the format of a URL."""
self.email = email
"""The email address of the contact person/organization. MUST be in the format of an email address."""
class License(OObject):
"""License information for the exposed API."""
def __init__(self, name: str, url: Optional[str] = None):
"""
License information for the exposed API.
:param name: REQUIRED. The license name used for the API.
:param url: A URL to the license used for the API. MUST be in the format of a URL.
"""
_assert_type(name, (str,), "name", self.__class__)
_assert_type(url, (str,), "url", self.__class__)
_assert_required(name, "name", self.__class__)
self.name = name
"""REQUIRED. The license name used for the API."""
self.url = url
"""A URL to the license used for the API. MUST be in the format of a URL."""
class Info(OObject):
"""
The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be
presented in editing or documentation generation tools for convenience.
"""
def __init__( # pylint: disable=too-many-arguments
self,
title: str,
version: str,
description: Optional[str] = None,
terms_of_service: Optional[str] = None,
contact: Optional[Contact] = None,
_license: Optional[License] = None,
):
"""
The object provides metadata about the API. The metadata MAY be used by the clients if needed, and MAY be
presented in editing or documentation generation tools for convenience.
:param title: REQUIRED. The title of the application.
:param description: A short description of the application. CommonMark syntax MAY be used for rich text
representation.
:param terms_of_service: A URL to the Terms of Service for the API. MUST be in the format of a URL.
:param contact: The contact information for the exposed API.
:param _license: The license information for the exposed API.
:param version: REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification
version or the API implementation version).
"""
_assert_type(title, (str,), "title", self.__class__)
_assert_type(description, (str,), "description", self.__class__)
_assert_type(terms_of_service, (str,), "terms_of_service", self.__class__)
_assert_type(contact, (Contact,), "contact", self.__class__)
_assert_type(_license, (License,), "_license", self.__class__)
_assert_type(version, (str,), "version", self.__class__)
_assert_required(title, "title", self.__class__)
_assert_required(version, "version", self.__class__)
self.title = title
"""REQUIRED. The title of the application."""
self.version = version
"""
REQUIRED. The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the
API implementation version).
"""
self.description = description
"""A short description of the application. CommonMark syntax MAY be used for rich text representation."""
self.terms_of_service = terms_of_service
"""A URL to the Terms of Service for the API. MUST be in the format of a URL."""
self.contact = contact
"""The contact information for the exposed API."""
self.license = _license
"""The license information for the exposed API."""
# --------------------------------------------------------------- #
# Server Object. Since v3
# --------------------------------------------------------------- #
class ServerVariable(OObject):
"""An object representing a Server Variable for server URL template substitution."""
def __init__(self, default: str, enum: List[str] = None, description: Optional[str] = None):
"""
An object representing a Server Variable for server URL template substitution.
:param enum:
:param default: REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value
is not supplied. Note this behavior is different than the Schema Object's treatment of default values,
because in those cases parameter values are optional.
:param description: An optional description for the server variable. CommonMark syntax MAY be used for rich text
representation.
"""
_assert_type(enum, (list,), "enum", self.__class__)
_assert_type(default, (str,), "default", self.__class__)
_assert_type(description, (str,), "description", self.__class__)
_assert_required(default, "default", self.__class__)
if enum:
# All strings
if {type(e) for e in enum} != {type("str")}:
raise AssertionError("For `{}`, all enum values must be str.".format(self.__class__.__qualname__))
# All unique
if len(set(enum)) != len(enum):
raise AssertionError("For `{}`, all enum values must be unique.".format(self.__class__.__qualname__))
self.enum = enum
"""An enumeration of string values to be used if the substitution options are from a limited set."""
self.default = default
"""
REQUIRED. The default value to use for substitution, which SHALL be sent if an alternate value is not supplied.
Note this behavior is different than the Schema Object's treatment of default values, because in those cases
parameter values are optional.
"""
self.description = description
"""
An optional description for the server variable. CommonMark syntax MAY be used for rich text representation.
"""
class Server(OObject):
"""An object representing a Server."""
def __init__(
self, url: str, description: Optional[str] = None, variables: Optional[Dict[str, ServerVariable]] = None,
):
"""
An object representing a Server.
:param url: REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to
indicate that the host location is relative to the location where the OpenAPI document is being served.
Variable substitutions will be made when a variable is named in ``{brackets}``.
:param description: An optional string describing the host designated by the URL. CommonMark syntax MAY be used
for rich text representation.
:param variables: A map between a variable name and its value. The value is used for substitution in the
server's URL template.
"""
_assert_type(url, (str,), "url", self.__class__)
_assert_type(description, (str,), "description", self.__class__)
_assert_type(variables, (str,), "variables", self.__class__)
_assert_required(url, "url", self.__class__)
self.url = url
"""
REQUIRED. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the
host location is relative to the location where the OpenAPI document is being served. Variable substitutions
will be made when a variable is named in {brackets}."""
self.description = description
"""
An optional string describing the host designated by the URL. CommonMark syntax MAY be used for rich text
representation.
"""
self.variables = variables
"""
A map between a variable name and its value. The value is used for substitution in the server's URL template.
"""
# --------------------------------------------------------------- #
# Components Object. Since v3
# --------------------------------------------------------------- #
class Reference(OObject):
"""
A simple object to allow referencing other components in the specification, internally and externally.
The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules.
For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not
by the JSON Schema specification.
"""
def __init__(self, _ref: str):
"""
A simple object to allow referencing other components in the specification, internally and externally.
The Reference Object is defined by JSON Reference and follows the same structure, behavior and rules.
For this specification, reference resolution is accomplished as defined by the JSON Reference specification and
not by the JSON Schema specification.
:param _ref: REQUIRED. The reference string.
"""
_assert_type(_ref, (str,), "_ref ($ref)", self.__class__)
_assert_required(_ref, "_ref ($ref)", self.__class__)
self.dollar_ref = _ref
"""REQUIRED. The reference string."""
class Discriminator(OObject):
"""
When request bodies or response payloads may be one of a number of different schemas, a discriminator object can be
used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema
which is used to inform the consumer of the specification of an alternative schema based on the value associated
with it.
When using the discriminator, inline schemas will not be considered.
Note: in sanic_openapi3e, this object is not well tested.
"""
def __init__(self, property_name: str, mapping: Optional[Dict[str, str]] = None):
"""
When request bodies or response payloads may be one of a number of different schemas, a discriminator object can
be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a
schema which is used to inform the consumer of the specification of an alternative schema based on the value
associated with it.
When using the discriminator, inline schemas will not be considered.
:param property_name: REQUIRED. The name of the property in the payload that will hold the discriminator value.
:param mapping: An object to hold mappings between payload values and schema names or references.
"""
_assert_type(property_name, (str,), "property_name", self.__class__)
_assert_type(mapping, (dict,), "mapping", self.__class__)
_assert_required(property_name, "property_name", self.__class__)
if mapping:
for m_name, m_value in mapping.items():
if not isinstance(m_value, str):
raise AssertionError(
"For `{}.mapping[{}]` the value must be a str.".format(self.__class__.__qualname__, m_name)
)
self.property_name = property_name
"""REQUIRED. The name of the property in the payload that will hold the discriminator value."""
self.mapping = mapping
"""An object to hold mappings between payload values and schema names or references."""
class XML(OObject):
"""
A metadata object that allows for more fine-tuned XML model definitions.
When using arrays, XML element names are not inferred (for singular/plural forms) and the name property SHOULD be
used to add that information. See examples for expected behavior.
"""
def __init__( # pylint: disable=too-many-arguments
self,
name: Optional[str] = None,
namespace: Optional[str] = None,
prefix: Optional[str] = None,
attribute: bool = False,
wrapped: bool = False,
):
"""
A metadata object that allows for more fine-tuned XML model definitions.
When using arrays, XML element names are not inferred (for singular/plural forms) and the name property SHOULD
be used to add that information. See examples for expected behavior.
:param name: Replaces the name of the element/attribute used for the described schema property. When defined
within items, it will affect the name of the individual XML elements within the list. When defined alongside
type being array (outside the items), it will affect the wrapping element and only if wrapped is true. If
wrapped is false, it will be ignored.
:param namespace: The URI of the namespace definition. Value MUST be in the form of an absolute URI.
:param prefix: The prefix to be used for the name.
:param attribute: Declares whether the property definition translates to an attribute instead of an element.
Default value is false.
:param wrapped: MAY be used only for an array definition. Signifies whether the array is wrapped (for example,
<books><book/><book/></books>) or unwrapped (<book/><book/>). Default value is false. The definition takes
effect only when defined alongside type being array (outside the items).
"""
_assert_type(name, (str,), "name", self.__class__)
_assert_type(namespace, (str,), "namespace", self.__class__)
_assert_type(prefix, (str,), "prefix", self.__class__)
_assert_type(attribute, (bool,), "attribute", self.__class__)
_assert_type(wrapped, (bool,), "wrapped", self.__class__)
self.name = name
"""
Replaces the name of the element/attribute used for the described schema property. When defined within items, it
will affect the name of the individual XML elements within the list. When defined alongside type being array
(outside the items), it will affect the wrapping element and only if wrapped is true. If wrapped is false, it
will be ignored.
"""
self.namespace = namespace
"""The URI of the namespace definition. Value MUST be in the form of an absolute URI."""
self.prefix = prefix
"""The prefix to be used for the name."""
self.attribute = attribute
"""
Declares whether the property definition translates to an attribute instead of an element. Default value is
false.
"""
self.wrapped = wrapped
"""
MAY be used only for an array definition. Signifies whether the array is wrapped (for example,
``(<books><book/><book/></books>``) or unwrapped (``<book/><book/>``). Default value is false. The definition
takes effect only when defined alongside type being array (outside the items).
"""
class ExternalDocumentation(OObject):
"""Allows referencing an external resource for extended documentation."""
def __init__(self, url: str, description: Optional[str] = None):
"""
Allows referencing an external resource for extended documentation.
:param url: REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL.
:param description: A short description of the target documentation. CommonMark syntax MAY be used for rich text
representation.
"""
_assert_type(description, (str,), "name", self.__class__)
_assert_type(url, (str,), "url", self.__class__)
_assert_required(url, "url", self.__class__)
self.description = description
"""
A short description of the target documentation. CommonMark syntax MAY be used for rich text representation.
"""
self.url = url
"""REQUIRED. The URL for the target documentation. Value MUST be in the format of a URL."""
class Example(OObject):
"""
In the `spec <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#example-object>`_ there is
no top-line description, but there is supplemental doc.
In all cases, the example value is expected to be compatible with the type schema of its associated value. Tooling
implementations MAY choose to validate compatibility automatically, and reject the example value(s) if incompatible.
"""
def __init__(
self,
summary: Optional[str] = None,
description: Optional[str] = None,
value: Optional[Any] = None,
external_value: Optional[str] = None,
):
"""
In the `spec <https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#example-object>`_ there
is no top-line description, but there is supplemental doc.
In all cases, the example value is expected to be compatible with the type schema of its associated value.
Tooling implementations MAY choose to validate compatibility automatically, and reject the example value(s) if
incompatible.
:param summary: Short description for the example.
:param description: Long description for the example. CommonMark syntax MAY be used for rich text
representation.
:param value: Embedded literal example. The value field and externalValue field are mutually exclusive. To
represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to
contain the example, escaping where necessary.
:param external_value: A URL that points to the literal example. This provides the capability to reference
examples that cannot easily be included in JSON or YAML documents. The value field and externalValue field
are mutually exclusive.
"""
_assert_type(summary, (str,), "summary", self.__class__)
_assert_type(description, (str,), "description", self.__class__)
# Note: value can be Any
_assert_type(external_value, (str,), "external_value", self.__class__)
assert not (value and external_value)
# Assignment and docs
self.summary = summary
"""Short description for the example."""
self.description = description
"""Long description for the example. CommonMark syntax MAY be used for rich text representation."""
self.value = value
"""
Embedded literal example. The value field and externalValue field are mutually exclusive. To represent examples
of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example,
escaping where necessary.
"""
self.external_value = external_value
"""
A URL that points to the literal example. This provides the capability to reference examples that cannot easily
be included in JSON or YAML documents. The value field and externalValue field are mutually exclusive.
"""
class Header(OObject): # pylint: disable=too-many-instance-attributes
"""
The Header Object follows the structure of the Parameter Object with the following changes:
- name MUST NOT be specified, it is given in the corresponding headers map.
- o-in (`in`) MUST NOT be specified, it is implicitly in header.
- All traits that are affected by the location MUST be applicable to a location of header (for example, style).
"""
def __init__( # pylint: disable=too-many-arguments, too-many-locals
self,
description: Optional[str] = None,
required: bool = False,
deprecated: bool = False,
allow_empty_value: bool = False,
style: Optional[str] = None,
explode: bool = False,
allow_reserved: bool = False,
schema: Optional[Union["Schema", Reference]] = None,
example: Optional[Any] = None,
examples: Optional[Dict[str, Union[Example, Reference]]] = None,
content: Optional[Dict[str, "MediaType"]] = None,
):
"""
The Header Object follows the structure of the Parameter Object with the following changes:
- name MUST NOT be specified, it is given in the corresponding headers map.
- o-in (`in`) MUST NOT be specified, it is implicitly in header.
- All traits that are affected by the location MUST be applicable to a location of header (for example, style).
:param description: A brief description of the parameter. This could contain examples of use. CommonMark syntax
MAY be used for rich text representation.
:param required: Determines whether this parameter is mandatory. If the parameter ``_in`` is "path", this
property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default
value is false. Note that this is not checked by sanic-openapi3e.
:param deprecated: Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.
:param allow_empty_value: Sets the ability to pass empty-valued parameters. This is valid only for query
parameters and allows sending a parameter with an empty value. Default value is false. If style is used,
and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored.
:param style: Describes how the parameter value will be serialized depending on the type of the parameter value.
Default values (based on value of in): for query - form; for path - simple; for header - simple; for
cookie - form.
:param explode: When this is true, parameter values of type array or object generate separate parameters for
each value of the array or key-value pair of the map. For other types of parameters this property has no
effect. When style is form, the default value is true. For all other styles, the default value is false.
:param allow_reserved: Determines whether the parameter value SHOULD allow reserved characters, as defined by
RFC3986 ``:/?#[]@!$&'()*+,;=`` to be included without percent-encoding. This property only applies to
parameters with an `_in` value of query. The default value is false.
:param schema: The schema defining the type used for the parameter.
:param example: Example of the media type. The example SHOULD match the specified schema and encoding properties
if present. The example object is mutually exclusive of the examples object. Furthermore, if referencing a
schema which contains an example, the example value SHALL override the example provided by the schema. To
represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can
contain the example with escaping where necessary.
:param examples: Examples of the media type. Each example SHOULD contain a value in the correct format as
specified in the parameter encoding. The examples object is mutually exclusive of the example object.
Furthermore, if referencing a schema which contains an example, the examples value SHALL override the
example provided by the schema.
:param content: A map containing the representations for the parameter. The key is the media type and the value
describes it. The map MUST only contain one entry.
"""
_assert_type(description, (str,), "description", self.__class__)
_assert_type(required, (bool,), "required", self.__class__)
_assert_type(deprecated, (bool,), "deprecated", self.__class__)
_assert_type(allow_empty_value, (bool,), "allow_empty_value", self.__class__)
_assert_type(style, (str,), "style", self.__class__)
_assert_type(explode, (bool,), "explode", self.__class__)
_assert_type(allow_reserved, (bool,), "allow_reserved", self.__class__)
_assert_type(schema, (Schema, Reference), "schema", self.__class__)
# Note: examples is specified to be "Any"
_assert_type(examples, (dict,), "examples", self.__class__)
_assert_type(content, (dict,), "content", self.__class__)
# Validations.
assert not (example and examples)
if examples:
for ex_name, ex in examples.items():
if not isinstance(ex, (Example, Reference)):
raise AssertionError(
"For `{}.examples`, values must be an `Example` or a `Reference`. For {} it is a {}".format(
self.__class__.__qualname__, ex_name, type(ex)
)
)
if content:
if len(list(content.values())) != 1:
raise AssertionError("For `{}.content` MUST only contain one entry".format(self.__class__.__qualname__))
for c_name, media_type in content.items():
if not isinstance(media_type, MediaType):
raise TypeError(
"For `{}.content`, values must be a `MediaType`. For {} it is a {}".format(
self.__class__.__qualname__, c_name, type(media_type)
)
)
# Assignments and docs
self.description = description
"""
A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich
text representation.
"""
self.required = required
"""
Determines whether this parameter is mandatory. If the parameter location is "path", this property is REQUIRED
and its value MUST be true. Otherwise, the property MAY be included and its default value is false.
"""
self.deprecated = deprecated
"""Specifies that a parameter is deprecated and SHOULD be transitioned out of usage."""
self.allow_empty_value = allow_empty_value
"""
Sets the ability to pass empty-valued parameters. This is valid only for query parameters and allows sending a
parameter with an empty value. Default value is false. If style is used, and if behavior is n/a (cannot be
serialized), the value of allowEmptyValue SHALL be ignored.
"""
self.style = style
"""
Describes how the parameter value will be serialized depending on the type of the parameter value. Default
values (based on value of in): for query - form; for path - simple; for header - simple; for cookie - form.
"""
self.explode = explode
"""
When this is true, parameter values of type array or object generate separate parameters for each value of the
array or key-value pair of the map. For other types of parameters this property has no effect. When style is
form, the default value is true. For all other styles, the default value is false.
"""
self.allow_reserved = allow_reserved
"""
Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986
``:/?#[]@!$&'()*+,;=`` to be included without percent-encoding. This property only applies to parameters with an
in value of query. The default value is false."""
self.schema = schema
"""The schema defining the type used for the parameter."""
self.example = example
"""
Example of the media type. The example SHOULD match the specified schema and encoding properties if present. The
example object is mutually exclusive of the examples object. Furthermore, if referencing a schema which contains
an example, the example value SHALL override the example provided by the schema. To represent examples of media
types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping
where necessary.
"""
self.examples = examples
"""
Examples of the media type. Each example SHOULD contain a value in the correct format as specified in the
parameter encoding. The examples object is mutually exclusive of the example object. Furthermore, if referencing
a schema which contains an example, the examples value SHALL override the example provided by the schema.
"""
self.content = content
"""
A map containing the representations for the parameter. The key is the media type and the value describes it.
The map MUST only contain one entry.
"""
class Encoding(OObject):
"""A single encoding definition applied to a single schema property."""
def __init__( # pylint: disable=too-many-arguments
self,
content_type: Optional[str] = None,
headers: Optional[Dict[str, Union[Header, Reference]]] = None,
style: Optional[str] = None,
explode: bool = False,
allow_reserved=False,
):
"""
A single encoding definition applied to a single schema property.
:param content_type: The Content-Type for encoding a specific property. Default value depends on the property
type:
* for string with format being binary – `application/octet-stream`;
* for other primitive types – `text/plain`;
* for object - `application/json`;
* for array – the default is defined based on the inner type.
The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or
a comma-separated list of the two types.
:param headers: A map allowing additional information to be provided as headers, for example
`Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This
property SHALL be ignored if the request body media type is not a multipart.
:param style: Describes how a specific property value will be serialized depending on its type. See Parameter
Object for details on the style property. The behavior follows the same values as query parameters, including
default values. This property SHALL be ignored if the request body media type is not
`application/x-www-form-urlencoded`.
:param explode: When this is true, property values of type array or object generate separate parameters for each
value of the array, or key-value-pair of the map. For other types of properties this property has no effect.
When style is form, the default value is true. For all other styles, the default value is false. This
property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
:param allow_reserved: Determines whether the parameter value SHOULD allow reserved characters, as defined by
RFC3986 ``:/?#[]@!$&'()*+,;=`` to be included without percent-encoding. The default value is false. This
property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded.
"""
_assert_type(content_type, (str,), "content_type", self.__class__)
_assert_type(headers, (dict,), "headers", self.__class__)
_assert_type(style, (str,), "style", self.__class__)
_assert_type(explode, (bool,), "explode", self.__class__)
_assert_type(allow_reserved, (bool,), "allow_reserved", self.__class__)
if headers:
for _header_name, header_spec in headers.items():
assert isinstance(header_spec, (Header, Reference))
if style:
assert style in ("matrix", "label", "form", "simple", "spaceDelimited", "pipeDelimited", "deepObject",)
# TODO - add (where?) check that the style is suitable for this type+location.
if explode is None:
explode = bool(style == "form")
_assert_type(explode, (bool,), "explode", self.__class__)
_assert_type(allow_reserved, (bool,), "allow_reserved", self.__class__)
# Assignment and docs
self.content_type = content_type
"""
The Content-Type for encoding a specific property. Default value depends on the property type:
* for `string` with `format` being `binary` – `application/octet-stream`;
* for other primitive types – `text/plain`;
* for object - `application/json`;
* for array – the default is defined based on the inner type.
The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a
comma-separated list of the two types.
"""
self.headers = headers
"""
A map allowing additional information to be provided as headers, for example `Content-Disposition`. Content-Type
is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body
media type is not a multipart.
"""
self.explode = explode
"""
When this is true, property values of type array or object generate separate parameters for each value of the
array, or key-value-pair of the map. For other types of properties this property has no effect. When style is
form, the default value is true. For all other styles, the default value is false. This property SHALL be
ignored if the request body media type is not application/x-www-form-urlencoded.
"""
self.allow_reserved = allow_reserved
"""
Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986
``:/?#[]@!$&'()*+,;=`` to be included without percent-encoding. The default value is false. This property SHALL
be ignored if the request body media type is not application/x-www-form-urlencoded.
"""
class MediaType(OObject):
"""Each Media Type Object provides schema and examples for the media type identified by its key."""
def __init__(
self,
schema: Optional[Union["Schema", Reference]] = None,
example: Optional[Any] = None,
examples: Optional[Dict[str, Union[Example, Reference]]] = None,
encoding: Optional[Dict[str, Encoding]] = None,
):
"""
Each Media Type Object provides schema and examples for the media type identified by its key.
:param schema: The schema defining the content of the request, response, or parameter.
:param example: Example of the media type. The example object SHOULD be in the correct format as specified by
the media type. The example field is mutually exclusive of the examples field. Furthermore, if referencing a
schema which contains an example, the example value SHALL override the example provided by the schema.
:param examples: Examples of the media type. Each example object SHOULD match the media type and specified
schema if present. The examples field is mutually exclusive of the example field. Furthermore, if
referencing a schema which contains an example, the examples value SHALL override the example provided by
the schema.
:param encoding: A map between a property name and its encoding information. The key, being the property name,
MUST exist in the schema as a property. The encoding object SHALL only apply to requestBody objects when the
media type is multipart or application/x-www-form-urlencoded.
"""
_assert_type(schema, (Schema, Reference), "schema", self.__class__)
# Note: example is specified as "Any"
_assert_type(examples, (dict,), "examples", self.__class__)
_assert_type(encoding, (dict,), "encoding", self.__class__)
# validations
assert not (example and examples)
if examples:
for ex_name, ex in examples.items():
if not isinstance(ex, (Example, Reference)):
raise AssertionError(
"For `{}.examples, values should be an `Example` or a `Reference`. For {} it is a {}".format(
self.__class__.__qualname__, ex_name, ex
)
)
if encoding:
for e_name, enc in encoding.items():
if not isinstance(enc, Encoding):
raise AssertionError(
"For `{}.encoding, values should be an `Encoding`. For {} it is a {}".format(
self.__class__.__qualname__, e_name, type(enc)
)
)
# Assignment and Docs
if not schema:
warnings.warn(
"A MediaType without a schema is not shown in Swagger. {}".format(
{"encoding": encoding, "example": example, "examples": examples, "schema": schema}
)
)
traceback.print_stack()
self.schema = schema
"""The schema defining the content of the request, response, or parameter."""
self.example = example
"""
Example of the media type. The example object SHOULD be in the correct format as specified by the media type.
The example field is mutually exclusive of the examples field. Furthermore, if referencing a schema which
contains an example, the example value SHALL override the example provided by the schema.
"""
self.examples = examples
"""
Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The
examples field is mutually exclusive of the example field. Furthermore, if referencing a schema which contains
an example, the examples value SHALL override the example provided by the schema.
"""
self.encoding = encoding
"""
A map between a property name and its encoding information. The key, being the property name, MUST exist in the
schema as a property. The encoding object SHALL only apply to requestBody objects when the media type is
multipart or application/x-www-form-urlencoded.
"""
class Schema(OObject): # pylint: disable=too-many-instance-attributes
"""
The Schema Object allows the definition of input and output data types. These types can be objects, but also
primitives and arrays. This object is an extended subset of the `JSON Schema Specification Wright Draft 00
<https://tools.ietf.org/html/draft-wright-json-schema-validation-00>`_.
For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated
otherwise, the property definitions follow the JSON Schema.
The following properties are taken directly from the JSON Schema definition and follow the same specifications:
- title
- multiple_of
- maximum
- exclusive_maximum
- minimum
- exclusive_minimum
- max_length
- min_length
- pattern
- max_items
- min_items
- unique_items
- max_properties
- min_properties
- required
- enum
The following properties are taken from the JSON Schema definition but their definitions were adjusted to the
OpenAPI Specification.
- type - Value MUST be a string. Multiple types via an array are not supported.
- all_of - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- one_of - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- any_of - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- _not - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and
not a standard JSON Schema. items MUST be present if the type is array.
- properties - Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or
referenced).
- additional_properties - Inline or referenced schema MUST be of a Schema
Object and not a standard JSON Schema. Consistent with JSON Schema.
- description - CommonMark syntax MAY be used for rich text representation.
- _format - See Data Type Formats for further details. While relying on JSON Schema's defined formats, the
OAS offers a few additional predefined formats.
- default - The default value represents what would be assumed by the consumer of the input as the value of the
schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema
Object defined at the same level. For example, if type is string, then default can be "foo" but cannot be 1.
Alternatively, any time a Schema Object can be used, a Reference Object can be used in its place. This allows
referencing definitions instead of defining them inline.
Additional properties defined by the JSON Schema specification that are not mentioned here are strictly
unsupported.
"""
Integer = None # type: Schema
"""A pre-defined Integer Schema. Very simple, no properties other than `format` of `int64`."""
Number = None # type: Schema
"""A pre-defined Number Schema. Very simple, no properties other than `format` of `double`."""
String = None # type: Schema
"""A pre-defined String Schema. Very simple, no properties."""
Integers = None # type: Schema
"""A pre-defined Integers Schema. An array of (simple) Integer elements."""
Numbers = None # type: Schema
"""A pre-defined Number Schema. An array of (simple) Number elements."""
Strings = None # type: Schema
"""A pre-defined String Schema. An array of (simple) String elements."""
Object = None # type: Schema
"""A pre-defined Object Schema."""
def __init__( # pylint: disable=too-many-arguments, too-many-locals, too-many-statements, too-many-branches
self,
_type: Optional[str] = None,
#
# The following properties are taken directly from the JSON Schema definition and follow the same
# specifications:
title: Optional[str] = None,
multiple_of: Optional[int] = None,
maximum: Optional[int] = None,
exclusive_maximum: bool = False,
minimum: Optional[int] = None,
exclusive_minimum: bool = False,
max_length: Optional[int] = None,
min_length: Optional[int] = None,
pattern: Optional[str] = None,
max_items: Optional[int] = None,
min_items: Optional[int] = None,
unique_items: bool = False,
max_properties: Optional[int] = None,
min_properties: Optional[int] = None,
required: Optional[List[str]] = None,
enum: Optional[List[Any]] = None,
#
# The following properties are taken from the JSON Schema definition but their definitions were adjusted to the
# OpenAPI Specification.
all_of: Optional[List[Union["Schema", Reference]]] = None,
one_of: Optional[List[Union["Schema", Reference]]] = None,
any_of: Optional[List[Union["Schema", Reference]]] = None,
_not: Optional[List[Union["Schema", Reference]]] = None,
items: Optional[Union["Schema", Reference]] = None,
properties: Optional[Dict[str, Union["Schema", Reference]]] = None,
additional_properties: Optional[Union[bool, "Schema", Reference]] = None,
description: Optional[str] = None,
_format: Optional[str] = None,
default: Optional[Union[str, int, float, bool]] = None,
#
# The OAS extensions.
nullable: bool = False,
discriminator: Optional[Discriminator] = None,
read_only: bool = False,
write_only: bool = False,
xml: Optional[XML] = None,
external_docs: Optional[ExternalDocumentation] = None,
example: Optional[Any] = None,
deprecated: bool = False,
#
# sanic-openapi3e extension
x_frozen: bool = False,
):
"""
The Schema Object allows the definition of input and output data types. These types can be objects, but also
primitives and arrays. This object is an extended subset of the `JSON Schema Specification Wright Draft 00
<https://tools.ietf.org/html/draft-wright-json-schema-validation-00>`_.
For more information about the properties, see JSON Schema Core and JSON Schema Validation. Unless stated
otherwise, the property definitions follow the JSON Schema.
The following properties are taken directly from the JSON Schema definition and follow the same specifications:
- title
- multiple_of
- maximum
- exclusive_maximum
- minimum
- exclusive_minimum
- max_length
- min_length
- pattern
- max_items
- min_items
- unique_items
- max_properties
- min_properties
- required
- enum
The following properties are taken from the JSON Schema definition but their definitions were adjusted to the
OpenAPI Specification.
- type - Value MUST be a string. Multiple types via an array are not supported.
- all_of - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- one_of - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- any_of - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- _not - Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
- items - Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and
not a standard JSON Schema. items MUST be present if the type is array.
- properties - Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or
referenced).
- additional_properties - Inline or referenced schema MUST be of a Schema
Object and not a standard JSON Schema. Consistent with JSON Schema.
- description - CommonMark syntax MAY be used for rich text representation.
- _format - See Data Type Formats for further details. While relying on JSON Schema's defined formats, the
OAS offers a few additional predefined formats.
- default - The default value represents what would be assumed by the consumer of the input as the value of the
schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema
Object defined at the same level. For example, if type is string, then default can be "foo" but cannot be 1.
Alternatively, any time a Schema Object can be used, a Reference Object can be used in its place. This allows
referencing definitions instead of defining them inline.
Additional properties defined by the JSON Schema specification that are not mentioned here are strictly
unsupported.
:param title: Can be used to decorate a user interface with information about the data produced by this user
interface. A title will preferrably [sic] be short.
:param multiple_of: The value of "multiple_of" MUST be a number, strictly greater than 0. A numeric instance is
only valid if division by this keyword's value results in an integer.
:param maximum: The value of "maximum" MUST be a number, representing an upper limit for a numeric instance. If
the instance is a number, then this keyword validates if "exclusiveMaximum" is true and instance is less
than the provided value, or else if the instance is less than or exactly equal to the provided value.
:param exclusive_maximum: The value of "exclusive_maximum" MUST be a boolean, representing whether the limit in
"maximum" is exclusive or not. An undefined value is the same as false. If "exclusive_maximum" is true,
then a numeric instance SHOULD NOT be equal to the value specified in "maximum". If "exclusive_maximum" is
false (or not specified), then a numeric instance MAY be equal to the value of "maximum".
:param minimum: The value of "minimum" MUST be a number, representing a lower limit for a numeric instance. If
the instance is a number, then this keyword validates if "exclusive_minimum" is true and instance is greater
than the provided value, or else if the instance is greater than or exactly equal to the provided value.
:param exclusive_minimum: The value of "exclusive_minimum" MUST be a boolean, representing whether the limit in
"minimum" is exclusive or not. An undefined value is the same as false. If "exclusive_minimum" is true,
then a numeric instance SHOULD NOT be equal to the value specified in "minimum". If "exclusive_minimum" is
false (or not specified), then a numeric instance MAY be equal to the value of "minimum".
:param max_length: The value of this keyword MUST be a non-negative integer. The value of this keyword MUST be
an integer. This integer MUST be greater than, or equal to, 0. A string instance is valid against this
keyword if its length is less than, or equal to, the value of this keyword. The length of a string instance
is defined as the number of its characters as defined by RFC 7159 [RFC7159].
:param min_length: A string instance is valid against this keyword if its length is greater than, or equal to,
the value of this keyword. The length of a string instance is defined as the number of its characters as
defined by RFC 7159 [RFC7159]. The value of this keyword MUST be an integer. This integer MUST be greater
than, or equal to, 0. "min_length", if absent, may be considered as being present with integer value 0.
:param pattern: The value of this keyword MUST be a string. This string SHOULD be a valid regular expression,
according to the ECMA 262 regular expression dialect. A string instance is considered valid if the regular
expression matches the instance successfully. Recall: regular expressions are not implicitly anchored.
Note: whether or not this is a valid regular expression is not checked by sanic-openapi3e.
:param max_items: The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to,
0. An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this
keyword.
:param min_items: The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to,
0. An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this
keyword. If this keyword is not present, it may be considered present with a value of 0.
:param unique_items: The value of this keyword MUST be a boolean. If this keyword has boolean value false, the
instance validates successfully. If it has boolean value true, the instance validates successfully if all
of its elements are unique. If not present, this keyword may be considered present with boolean value false.
:param max_properties: he value of this keyword MUST be an integer. This integer MUST be greater than, or equal
to, 0. An object instance is valid against "max_properties" if its number of properties is less than, or
equal to, the value of this keyword.
:param min_properties: The value of this keyword MUST be an integer. This integer MUST be greater than, or
equal to, 0. An object instance is valid against "min_properties" if its number of properties is greater
than, or equal to, the value of this keyword. If this keyword is not present, it may be considered present
with a value of 0.
:param required: The value of this keyword MUST be an array. This array MUST have at least one element.
Elements of this array MUST be strings, and MUST be unique. An object instance is valid against this keyword
if its property set contains all elements in this keyword's array value. Note: sanic-openapi3e implements
these checks as a Set of str.
:param enum: The value of this keyword MUST be an array. This array SHOULD have at least one element.
Elements in the array SHOULD be unique. Elements in the array MAY be of any type, including null. An
instance validates successfully against this keyword if its value is equal to one of the elements in this
keyword's array value. Note: sanic-openapi3e implements these checks as a Set of Any.
:param _type: Value MUST be a string. Multiple types via an array are not supported.
:param all_of: Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
:param one_of: Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
:param any_of: Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
:param _not: Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
:param items: Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object
and not a standard JSON Schema. items MUST be present if the type is array.
:param properties: Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or
referenced).
:param additional_properties: Value can be boolean or object. Inline or referenced schema MUST be of a Schema
Object and not a standard JSON Schema. Consistent with JSON Schema, additionalProperties defaults to true.
:param description: CommonMark syntax MAY be used for rich text representation.
:param _format: See `Data Type Formats
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#dataTypeFormat>`_ for further
details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats.
:param default: The default value represents what would be assumed by the consumer of the input as the value of
the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the
Schema Object defined at the same level. For example, if type is string, then default can be "foo" but
cannot be 1.
:param nullable: Allows sending a null value for the defined schema. Default value is false.
:param discriminator: Adds support for polymorphism. The discriminator is an object name that is used to
differentiate between other schemas which may satisfy the payload description. See Composition and
Inheritance for more details.
:param read_only: Relevant only for Schema "properties" definitions. Declares the property as "read only". This
means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the
property is marked as read_only being true and is in the required list, the required will take effect on the
response only. A property MUST NOT be marked as both read_only and writeOnly being true. Default value is
false.
:param write_only: Relevant only for Schema "properties" definitions. Declares the property as "write only".
Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the
property is marked as write_only being true and is in the required list, the required will take effect on
the request only. A property MUST NOT be marked as both read_only and write_only being true. Default value
is false.
:param xml: This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional
metadata to describe the XML representation of this property.
:param external_docs: Additional external documentation for this schema.
:param example: A free-form property to include an example of an instance for this schema. To represent examples
that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with
escaping where necessary.
:param deprecated: Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value
is false.
:param x_frozen: Specifies that no modifications should be applied to this instance. Default is false.
"""
# JSON Schema definition
_assert_type(title, (str,), "title", self.__class__)
_assert_type(multiple_of, (int,), "multiple_of", self.__class__)
_assert_type(maximum, (int, float), "maximum", self.__class__)
_assert_type(exclusive_maximum, (bool,), "exclusive_maximum", self.__class__)
_assert_type(minimum, (int, float), "minimum", self.__class__)
_assert_type(exclusive_minimum, (bool,), "exclusive_minimum", self.__class__)
_assert_type(max_length, (int,), "max_length", self.__class__)
_assert_type(min_length, (int,), "min_length", self.__class__)
_assert_type(pattern, (str,), "pattern", self.__class__)
_assert_type(max_items, (int,), "max_items", self.__class__)
_assert_type(min_items, (int,), "min_items", self.__class__)
_assert_type(unique_items, (bool,), "unique_items", self.__class__)
_assert_type(max_properties, (int,), "max_properties", self.__class__)
_assert_type(min_properties, (int,), "min_properties", self.__class__)
_assert_type(required, (list,), "required", self.__class__)
_assert_type(enum, (list,), "enum", self.__class__)
# JSON Schema definition but their definitions were adjusted to the OpenAPI Specification.
if not any((all_of, one_of, any_of, _not)):
_assert_type(_type, (str,), "_type as no all_of, one_of, any_of, _not", self.__class__)
_assert_type(all_of, (list,), "all_of", self.__class__)
_assert_type(one_of, (list,), "one_of", self.__class__)
_assert_type(any_of, (list,), "any_of", self.__class__)
_assert_type(_not, (list,), "_not", self.__class__)
_assert_type(items, (Schema, Reference,), "items", self.__class__)
_assert_type(properties, (dict,), "properties", self.__class__)
_assert_type(
additional_properties, (bool, Schema, Reference), "additional_properties", self.__class__,
)
_assert_type(description, (str,), "description", self.__class__)
_assert_type(_format, (str,), "_format", self.__class__)
_assert_type(default, (str, int, float, bool), "default", self.__class__)
# The OAS extensions
_assert_type(nullable, (bool,), "nullable", self.__class__)
_assert_type(discriminator, (Discriminator,), "discriminator", self.__class__)
_assert_type(read_only, (bool,), "read_only", self.__class__)
_assert_type(write_only, (bool,), "write_only", self.__class__)
_assert_type(xml, (XML,), "xml", self.__class__)
_assert_type(external_docs, (ExternalDocumentation,), "external_docs", self.__class__)
# Note: example is defined to have the type `Any`
_assert_type(deprecated, (bool,), "deprecated", self.__class__)
_assert_strictly_greater_than_zero(multiple_of, "multiple_of", self.__class__)
_assert_strictly_greater_than_zero(max_length, "max_length", self.__class__)
_assert_strictly_greater_than_zero(min_length, "min_length", self.__class__)
_assert_strictly_greater_than_zero(max_items, "max_items", self.__class__)
_assert_strictly_greater_than_zero(min_properties, "min_properties", self.__class__)
if required is not None:
assert required, "MUST have at least one element."
assert set(type(e) for e in required) == {
type("str")
}, "For `{}.required`, all elements MUST be strings.".format(self.__class__.__qualname__)
assert len(set(required)) == len(required), "For `{}.required`, all elements MUST be unique.".format(
self.__class__.__qualname__
)
# if enum:
# if not len(enum):
# logger.warning(
# "`{}.enum` SHOULD have at least one element. {}".format(
# self.__class__.__qualname__, self
# )
# )
if _type == "array":
_assert_required(items, "items", self.__class__, " as `type=array`.")
if additional_properties is None:
if _type == "object":
additional_properties = True
if properties is not None:
for property_name, property_value in properties.items():
_assert_type(property_name, (str,), "properties.{} name".format(property_name), self.__class__)
_assert_type(property_value, (Schema, Reference), "properties.{}".format(property_name), self.__class__)
for attr, attr_name in ((all_of, "all_of"), (one_of, "one_of"), (any_of, "any_of"), (_not, "_not")):
if attr:
for idx, element in enumerate(attr):
_assert_type(element, (Schema, Reference), "{}#{}".format(attr_name, idx), self.__class__)
# Assignment and docs
self.title = title
"""
Can be used to decorate a user interface with information about the data produced by this user interface. A
title will preferrably [sic] be short.
"""
self.multiple_of = multiple_of
"""
The value of "multiple_of" MUST be a number, strictly greater than 0.
A numeric instance is only valid if division by this keyword's value results in an integer. """
self.maximum = maximum
"""
The value of "maximum" MUST be a number, representing an upper limit for a numeric instance.
If the instance is a number, then this keyword validates if "exclusiveMaximum" is true and instance is less than
the provided value, or else if the instance is less than or exactly equal to the provided value.
"""
self.exclusive_maximum = exclusive_maximum
"""
The value of "exclusive_maximum" MUST be a boolean, representing whether the limit in "maximum" is exclusive or
not. An undefined value is the same as false.
If "exclusive_maximum" is true, then a numeric instance SHOULD NOT be equal to the value specified in "maximum".
If "exclusive_maximum" is false (or not specified), then a numeric instance MAY be equal to the value of
"maximum".
"""
self.minimum = minimum
"""
The value of "minimum" MUST be a number, representing a lower limit for a numeric instance.
If the instance is a number, then this keyword validates if "exclusive_minimum" is true and instance is greater
than the provided value, or else if the instance is greater than or exactly equal to the provided value.
"""
self.exclusive_minimum = exclusive_minimum
"""
The value of "exclusive_minimum" MUST be a boolean, representing whether the limit in "minimum" is exclusive or
not. An undefined value is the same as false.
If "exclusive_minimum" is true, then a numeric instance SHOULD NOT be equal to the value specified in "minimum".
If "exclusive_minimum" is false (or not specified), then a numeric instance MAY be equal to the value of
"minimum".
"""
self.max_length = max_length
"""
The value of this keyword MUST be a non-negative integer.
The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0.
A string instance is valid against this keyword if its length is less than, or equal to, the value of this
keyword.
The length of a string instance is defined as the number of its characters as defined by RFC 7159 [RFC7159].
"""
self.min_length = min_length
"""
A string instance is valid against this keyword if its length is greater than, or equal to, the value of this
keyword.
The length of a string instance is defined as the number of its characters as defined by RFC 7159 [RFC7159].
The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0.
"min_length", if absent, may be considered as being present with integer value 0.
"""
self.pattern = pattern
"""
The value of this keyword MUST be a string. This string SHOULD be a valid regular expression, according to the
ECMA 262 regular expression dialect.
A string instance is considered valid if the regular expression matches the instance successfully. Recall:
regular expressions are not implicitly anchored.
Note: whether or not this is a valid regular expression is not checked by sanic-openapi3e.
"""
self.max_items = max_items
"""
The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0.
An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword.
"""
self.min_items = min_items
"""
The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0.
An array instance is valid against "minItems" if its size is greater than, or equal to, the value of this
keyword.
If this keyword is not present, it may be considered present with a value of 0.
"""
self.unique_items = unique_items
"""
The value of this keyword MUST be a boolean.
If this keyword has boolean value false, the instance validates successfully. If it has boolean value true, the
instance validates successfully if all of its elements are unique.
If not present, this keyword may be considered present with boolean value false.
"""
self.max_properties = max_properties
"""
The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0.
An object instance is valid against "max_properties" if its number of properties is less than, or equal to, the
value of this keyword.
"""
self.min_properties = min_properties
"""
The value of this keyword MUST be an integer. This integer MUST be greater than, or equal to, 0.
An object instance is valid against "min_properties" if its number of properties is greater than, or equal to,
the value of this keyword.
If this keyword is not present, it may be considered present with a value of 0.
"""
self.required = required
"""
The value of this keyword MUST be an array. This array MUST have at least one element. Elements of this array
MUST be strings, and MUST be unique.
An object instance is valid against this keyword if its property set contains all elements in this keyword's
array value.
"""
self.enum = enum
"""
The value of this keyword MUST be an array. This array SHOULD have at least one element. Elements in the array
SHOULD be unique.
Elements in the array MAY be of any type, including null.
An instance validates successfully against this keyword if its value is equal to one of the elements in this
keyword's array value.
"""
if _type:
# TODO - must these be in OTypeFormat.keys()?
pass
self._type: Optional[str] = _type
"""Value MUST be a string. Multiple types via an array are not supported."""
self.all_of = all_of
"""Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema."""
self.one_of = one_of
"""Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema."""
self.any_of = any_of
"""Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema."""
self._not = _not
"""Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema."""
self.items: Optional[Union[Schema, Reference]] = items
"""
Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object and not a
standard JSON Schema. items MUST be present if the type is array.
"""
# TODO - finish the definition of "items", it is incomplete. Is it supposed to be a dict of Schemae?
self.properties = properties
""" Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced)."""
self.additional_properties = additional_properties
"""
Value can be boolean or object. Inline or referenced schema MUST be of a Schema Object and not a standard JSON
Schema.
"""
self.description = description
"""CommonMark syntax MAY be used for rich text representation."""
self._format = _format
"""
See Data Type Formats for further details. While relying on JSON Schema's defined formats, the OAS offers a few
additional predefined formats.
"""
self.default = default
"""
The default value represents what would be assumed by the consumer of the input as the value of the schema if
one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object
defined at the same level. For example, if type is string, then default can be "foo" but cannot be 1.
"""
# TODO - add checks that ensure that the type of default is compatible with the _type
# The OAS extensions
self.nullable = nullable
"""Allows sending a null value for the defined schema. Default value is false."""
self.discriminator = discriminator
"""
Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other
schemas which may satisfy the payload description. See Composition and Inheritance for more details.
"""
self.read_only = read_only
"""
Relevant only for Schema "properties" definitions. Declares the property as "read only". This means that it MAY
be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as
read_only being true and is in the required list, the required will take effect on the response only. A property
MUST NOT be marked as both read_only and write_only being true. Default value is false.
"""
self.write_only = write_only
"""
Relevant only for Schema "properties" definitions. Declares the property as "write only". Therefore, it MAY be
sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as
write_only being true and is in the required list, the required will take effect on the request only. A property
MUST NOT be marked as both read_only and write_only being true. Default value is false.
"""
self.xml = xml
"""
This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to
describe the XML representation of this property.
"""
self.external_docs = external_docs
"""Additional external documentation for this schema."""
self.example = example
"""
A free-form property to include an example of an instance for this schema. To represent examples that cannot be
naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where
necessary.
"""
self.deprecated = deprecated
""" Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is false."""
self.x_frozen = x_frozen
"""Specifies that no modifications should be applied to this instance. Default is false."""
if _type == "array" and not items:
raise AssertionError(
"For `{}`, items MUST be present if the type is array.".format(self.__class__.__qualname__)
)
if _format:
# TODO - must these be in OTypeFormat[_type]?
pass
if read_only and write_only:
raise AssertionError(
"For `{}`, A property; MUST NOT be marked as both read_only and write_only being true.".format(
self.__class__.__qualname__
)
)
def add_enum(self, enum: List):
assert not self.x_frozen, "Please do not modify a frozen Schema: {}".format(self)
enum0_type: str = self.get_enum_type(enum)
if self._type:
if self._type == "array":
if self.items:
assert not isinstance(self.items, Reference), "You cannot add enums to a Reference"
assert self.items._type == enum0_type, ( # pylint: disable=protected-access
self.items,
enum0_type,
)
else:
self.items = Schema(_type=enum0_type)
else:
assert self._type == enum0_type, (self._type, enum0_type)
else:
self._type = enum0_type
self.enum = enum
def clone(self) -> "Schema":
_clone = copy.deepcopy(self)
_clone.x_frozen = False
return _clone
@classmethod
def get_enum_type(cls, enum: List) -> str:
_assert_type(enum, (list,), "enum", cls)
assert enum
enum_types = {type(e) for e in enum}
if len(enum_types) != 1:
raise AssertionError(
"For `{}`, all values of the enum/choices must be of the same type, but `{}` were seen".format(
cls.__qualname__, enum_types
)
)
# At definition, the Schema.String is set to `None`, but below (and before code gets to use it) it is set to
# `Schema(_type="string")`. This is for python3.6 reasons. Thus, mypy needs to be silenced for the next line and
# the line just before the return.
schema_string_type = Schema.String._type # pylint: disable=protected-access
assert schema_string_type
_enum_type: str = schema_string_type
enum0_schema: Optional[Schema] = {int: Schema.Integer, str: Schema.String, float: Schema.Number,}.get(
type(enum[0])
)
if enum0_schema:
enum0_schema_type = enum0_schema._type # pylint: disable=protected-access
assert enum0_schema_type
_enum_type = enum0_schema_type
return _enum_type
Schema.Integer = Schema(_type="integer", x_frozen=True)
Schema.Number = Schema(_type="number", _format="double", x_frozen=True)
Schema.String = Schema(_type="string", x_frozen=True)
Schema.Integers = Schema(_type="array", items=Schema.Integer, x_frozen=True)
Schema.Numbers = Schema(_type="array", items=Schema.Number, x_frozen=True)
Schema.Strings = Schema(_type="array", items=Schema.String, x_frozen=True)
Schema.Object = Schema(_type="object", additional_properties=True, x_frozen=True)
class Parameter(OObject): # pylint: disable=too-many-instance-attributes
"""
Describes a single operation parameter.
A unique parameter is defined by a combination of a name and location.
Parameter Locations
-------------------
There are four possible parameter locations specified by the `location` ("in" in the spec) field:
- path - Used together with Path Templating, where the parameter value is actually part of the operation's URL.
This does not include the host or base path of the API. For example, in /items/{itemId}, the path
parameter is itemId.
- query - Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.
- header - Custom headers that are expected as part of the request. Note that RFC7230 states header names are
case insensitive.
- cookie - Used to pass a specific cookie value to the API.
"""
def __init__( # pylint: disable=too-many-arguments, too-many-locals, too-many-statements
self,
name: str,
_in: str,
description: Optional[str] = None,
required: Optional[bool] = None,
deprecated: Optional[bool] = None,
allow_empty_value: Optional[bool] = None,
style: Optional[str] = None,
explode: Optional[bool] = None,
allow_reserved: Optional[bool] = None,
schema: Optional[Union[Schema, Reference]] = None,
example: Optional[Any] = None,
examples: Optional[Dict[str, Union[Example, Reference]]] = None,
content: Optional[Dict[str, MediaType]] = None,
):
"""
Describes a single operation parameter.
A unique parameter is defined by a combination of a name and location.
Parameter Locations
-------------------
There are four possible parameter locations specified by the `location` ("in" in the spec) field:
- path - Used together with Path Templating, where the parameter value is actually part of the operation's URL.
This does not include the host or base path of the API. For example, in /items/{itemId}, the path
parameter is itemId.
- query - Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id.
- header - Custom headers that are expected as part of the request. Note that RFC7230 states header names are
case insensitive.
- cookie - Used to pass a specific cookie value to the API.
:param name: REQUIRED. The name of the parameter. Parameter names are case sensitive. If in is "path", the name
field MUST correspond to the associated path segment from the path field in the Paths Object. See Path
Templating for further information. If in is "header" and the name field is "Accept", "Content-Type" or
"Authorization", the parameter definition SHALL be ignored. For all other cases, the name corresponds to the
parameter name used by the in property.
:param _in: REQUIRED. The location of the parameter. Possible values are "query", "header", "path" or
"cookie".
:param description: A brief description of the parameter. This could contain examples of use. CommonMark syntax
MAY be used for rich text representation.
:param required: Determines whether this parameter is mandatory. If the parameter location is "path", this
property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default
value is false.
:param deprecated: Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default
value is false.
:param allow_empty_value: Sets the ability to pass empty-valued parameters. This is valid only for query
parameters and allows sending a parameter with an empty value. Default value is false. If style is used, and
if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored. Use of this
property is NOT RECOMMENDED, as it is likely to be removed in a later revision.
:param style: Describes how the parameter value will be serialized depending on the type of the parameter value.
Default values (based on value of ``location``):
* for query - form;
* for path - simple;
* for header - simple;
* for cookie - form.
:param explode: When this is true, parameter values of type array or object generate separate parameters for
each value of the array or key-value pair of the map. For other types of parameters this property has no
effect. When style is form, the default value is true. For all other styles, the default value is false.
:param allow_reserved: Determines whether the parameter value SHOULD allow reserved characters, as defined by
RFC3986 ``:/?#[]@!$&'()*+,;=`` to be included without percent-encoding. This property only applies to
parameters with an in value of query. The default value is false.
:param schema: The schema defining the type used for the parameter.
:param example: Example of the media type. The example SHOULD match the specified schema and encoding
properties if present. The example field is mutually exclusive of the examples field. Furthermore, if
referencing a schema which contains an example, the example value SHALL override the example provided by the
schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string
value can contain the example with escaping where necessary.
:param examples: Examples of the media type. Each example SHOULD contain a value in the correct format as
specified in the parameter encoding. The examples field is mutually exclusive of the example field.
Furthermore, if referencing a schema which contains an example, the examples value SHALL override the
example provided by the schema.
:param content: A map containing the representations for the parameter. The key is the media type and the value
describes it. The map MUST only contain one entry.
"""
_assert_type(name, (str,), "name", self.__class__)
_assert_type(_in, (str,), "_in", self.__class__)
_assert_type(description, (str,), "description", self.__class__)
_assert_type(required, (bool,), "required", self.__class__)
_assert_type(deprecated, (bool,), "deprecated", self.__class__)
_assert_type(allow_empty_value, (bool,), "allow_empty_value", self.__class__)
_assert_type(style, (str,), "style", self.__class__)
_assert_type(explode, (bool,), "explode", self.__class__)
_assert_type(allow_reserved, (bool,), "allow_reserved", self.__class__)
_assert_type(schema, (Schema, Reference), "schema", self.__class__)
# Note: examples is specified to be "Any"
_assert_type(examples, (dict,), "examples", self.__class__)
_assert_type(content, (MediaType,), "content", self.__class__)
# validations
_assert_required(name, "name", self.__class__)
if _in == "requestBody":
raise AssertionError(
"""For `{}`, the OpenAPI spec requires a `@doc.requestBody` and not a `@doc.parameter`""".format(name)
)
if _in not in ("query", "header", "path", "cookie"):
raise AssertionError(
"""`{}._in` must be one of ("query", "header", "path" or "cookie"), not `{}`""".format(
self.__class__.__qualname__, _in
)
)
if _in == "path":
assert required is True
else:
required = required or False
assert not (example and examples)
if examples:
for ex_name, ex in examples.items():
if not isinstance(ex, (Example, Reference)):
raise AssertionError(
"For `{}.examples`, values must be either an `Example` or a `Reference`. {} is a {}".format(
self.__class__.__qualname__, ex_name, type(ex)
)
)
if content:
if len(content) != 1:
raise AssertionError("For `{}.content` MUST only contain one entry".format(self.__class__.__qualname__))
for c_name, _media_type in content.items():
if not isinstance(c_name, MediaType):
raise AssertionError(
"For `{}.content`, the value must be a `MediaType`".format(self.__class__.__qualname__)
)
# Assignments and docs
self.name = name
"""
REQUIRED. The name of the parameter. Parameter names are case sensitive. If in is "path", the name field MUST
correspond to the associated path segment from the path field in the Paths Object. See Path Templating for
further information. If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the
parameter definition SHALL be ignored. For all other cases, the name corresponds to the parameter name used by
the in property.
"""
self.description = description
"""
A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich
text representation.
"""
self._in = _in
"""REQUIRED. The location of the parameter. Possible values are "query", "header", "path" or "cookie"."""
self.description = description
"""
A brief description of the parameter. This could contain examples of use. CommonMark syntax MAY be used for rich
text representation.
"""
self.required: bool = required
"""
Determines whether this parameter is mandatory. If the parameter _in is "path", this property is REQUIRED
and its value MUST be true. Otherwise, the property MAY be included and its default value is false.
"""
self.deprecated = deprecated or False
"""Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is false."""
self.allow_empty_value = allow_empty_value
"""
Sets the ability to pass empty-valued parameters. This is valid only for query parameters and allows sending a
parameter with an empty value. Default value is false. If style is used, and if behavior is n/a (cannot be
serialized), the value of allowEmptyValue SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is
likely to be removed in a later revision.
"""
self.style = style
"""
Describes how the parameter value will be serialized depending on the type of the parameter value. Default
values (based on value of ``_in``):
* for query - form;
* for path - simple;
* for header - simple;
* for cookie - form.
"""
# ^^ TODO - set these defaults?
self.explode = explode
"""
When this is true, parameter values of type array or object generate separate parameters for each value of the
array or key-value pair of the map. For other types of parameters this property has no effect. When style is
form, the default value is true. For all other styles, the default value is false.
"""
# ^^ TODO - set these defaults?
self.allow_reserved = allow_reserved
"""
Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986
``:/?#[]@!$&'()*+,;=`` to be included without percent-encoding. This property only applies to parameters with an
``_in`` value of query. The default value is false.
"""
self.schema = schema
"""The schema defining the type used for the parameter."""
self.example = example
"""
Example of the media type. The example SHOULD match the specified schema and encoding properties if present. The
example field is mutually exclusive of the examples field. Furthermore, if referencing a schema which contains
an example, the example value SHALL override the example provided by the schema. To represent examples of media
types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping
where necessary.
"""
self.examples = examples
"""
Examples of the media type. Each example SHOULD contain a value in the correct format as specified in the
parameter encoding. The examples object is mutually exclusive of the example object. Furthermore, if referencing
a schema which contains an example, the examples value SHALL override the example provided by the schema.
"""
self.content = content
"""
A map containing the representations for the parameter. The key is the media type and the value describes it.
The map MUST only contain one entry.
"""
def __add__(self, other):
assert isinstance(other, Parameter)
_d = {}
for key, value in self.__dict__.items(): # pylint: disable=too-many-nested-blocks
if value:
_d[key] = value
other_value = getattr(other, key)
if other_value and value != other_value:
# TODO - this should be done recursively. Move __add__ up to OObject?
# eg: schema:
# Schema{"type": "integer"} != Schema{"format": "int32", "minimum": 4, "type": "integer"}
if isinstance(other_value, Reference):
# Simple replace.
# TODO - check that the ref actually exists in the components.
# TODO - check that the ref is compatible
_d[key] = other_value
elif isinstance(value, OObject):
v_d = {}
for v_k, v_v in value.__dict__.items():
if v_v:
v_d[v_k] = v_v
v_ov = getattr(other_value, v_k)
if v_ov:
assert v_v == v_ov, "{}.{}: {} != {}".format(key, v_k, v_v, v_ov)
else:
v_d[v_k] = getattr(other_value, v_k)
# TODO: this use of globals is _OK_ but it would be nice to not need it.
_d[key] = globals()[value.__class__.__qualname__](**v_d)
else:
raise AssertionError("{}: {} != {}".format(key, getattr(self, key), other_value))
else:
_d[key] = getattr(other, key)
return Parameter(**_d)
class Link(OObject):
"""
The Link object represents a possible design-time link for a response. The presence of a link does not guarantee
the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism
between responses and other operations.
Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require
link information in the runtime response.
For computing links, and providing instructions to execute them, a runtime expression is used for accessing
values in an operation and using them as parameters while invoking the linked operation.
"""
def __init__( # pylint: disable=too-many-arguments
self,
operation_ref: Optional[str] = None,
operation_id: Optional[str] = None,
parameters: Optional[Dict[str, Any]] = None,
request_body: Optional[Any] = None,
description: Optional[str] = None,
server: Optional[Server] = None,
):
"""
The Link object represents a possible design-time link for a response. The presence of a link does not guarantee
the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism
between responses and other operations.
Unlike dynamic links (i.e. links provided in the response payload), the OAS linking mechanism does not require
link information in the runtime response.
For computing links, and providing instructions to execute them, a runtime expression is used for accessing
values in an operation and using them as parameters while invoking the linked operation.
:param operation_ref: A relative or absolute reference to an OAS operation. This field is mutually exclusive of
the operationId field, and MUST point to an Operation Object. Relative operationRef values MAY be used to
locate an existing Operation Object in the OpenAPI definition.
:param operation_id: The name of an existing, resolvable OAS operation, as defined with a unique operationId.
This field is mutually exclusive of the operationRef field.
:param parameters: A map representing parameters to pass to an operation as specified with operationId or
identified via operationRef. The key is the parameter name to be used, whereas the value can be a constant
or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified
using the parameter _in [{in}.]{name} for operations that use the same parameter name in different
locations (e.g. path.id).
:param request_body: A literal value or {expression} to use as a request body when calling the target operation.
:param description: A description of the link. CommonMark syntax MAY be used for rich text representation.
:param server: A server object to be used by the target operation.
"""
# TODO docstrings
_assert_type(operation_ref, (str,), "operation_ref", self.__class__)
_assert_type(operation_id, (str,), "operation_id", self.__class__)
_assert_type(parameters, (dict,), "parameters", self.__class__)
# Note: request_body can be Any
_assert_type(description, (str,), "description", self.__class__)
_assert_type(server, (Server,), "server", self.__class__)
assert not (operation_ref and operation_id)
self.operation_ref = operation_ref
"""
A relative or absolute reference to an OAS operation. This field is mutually exclusive of the operationId field,
and MUST point to an Operation Object. Relative operationRef values MAY be used to locate an existing Operation
Object in the OpenAPI definition.
"""
self.operation_id = operation_id
"""
The name of an existing, resolvable OAS operation, as defined with a unique operationId. This field is mutually
exclusive of the operationRef field.
"""
self.parameters = parameters
"""
A map representing parameters to pass to an operation as specified with operationId or identified via
operationRef. The key is the parameter name to be used, whereas the value can be a constant or an expression to
be evaluated and passed to the linked operation. The parameter name can be qualified using the parameter
_in [{_in}.]{name} for operations that use the same parameter name in different locations (e.g.
path.id).
"""
self.request_body = request_body
""" A literal value or {expression} to use as a request body when calling the target operation."""
self.description = description
self.server = server
"""A server object to be used by the target operation."""
class Response(OObject):
"""
Describes a single response from an API Operation, including design-time, static links to operations based on the
response.
"""
# This is reset from None to a Response directly after the class definition.
DEFAULT_SUCCESS = None # type: Response
BAD_REQUEST = None # type: Response
UNAUTHORIZED = None # type: Response
FORBIDDEN = None # type: Response
NOT_FOUND = None # type: Response
METHOD_NOT_ALLOWED = None # type: Response
GONE = None # type: Response
INTERNAL_SERVER_ERROR = None # type: Response
def __init__(
self,
description: str,
headers: Optional[Dict[str, Union[Header, Reference]]] = None,
content: Optional[Dict[str, MediaType]] = None,
links: Optional[Dict[str, Union[Link, Reference]]] = None,
):
"""
Describes a single response from an API Operation, including design-time, static links to operations based on
the response.
:param description: REQUIRED. A short description of the response. CommonMark syntax MAY be used for rich text
representation.
:param headers: Maps a header name to its definition. RFC7230 states header names are case insensitive. If a
response header is defined with the name "Content-Type", it SHALL be ignored.
:param content: A map containing descriptions of potential response payloads. The key is a media type or media
type range and the value describes it. For responses that match multiple keys, only the most specific key is
applicable. e.g. ``text/plain`` overrides ``text/*``.
:param links: A map of operations links that can be followed from the response. The key of the map is a short
"""
_assert_type(description, (str,), "description", self.__class__)
_assert_type(headers, (dict,), "headers", self.__class__)
_assert_type(content, (dict,), "content", self.__class__)
_assert_type(links, (dict,), "links", self.__class__)
_assert_required(description, "description", self.__class__)
if headers:
for _header_name, header_spec in headers.items():
assert isinstance(header_spec, (Header, Reference))
if content:
for _media_type_name, media_type_spec in content.items():
assert isinstance(media_type_spec, MediaType)
if links:
for _link_name, link_spec in links.items():
assert isinstance(link_spec, (Link, Reference))
# Assignment and docs
self.description = description
"""
REQUIRED. A short description of the response. CommonMark syntax MAY be used for rich text representation.
"""
self.headers = headers
"""
Maps a header name to its definition. RFC7230 states header names are case insensitive. If a response header is
defined with the name "Content-Type", it SHALL be ignored.
"""
self.content = content
"""
A map containing descriptions of potential response payloads. The key is a media type or media type range and
the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g.
``text/plain`` overrides ``text/*``.
"""
self.links = links
"""
A map of operations links that can be followed from the response. The key of the map is a short name for the
link, following the naming constraints of the names for Component Objects.
"""
Response.DEFAULT_SUCCESS = Response(description="OK")
Response.BAD_REQUEST = Response(description="Bad Request")
Response.UNAUTHORIZED = Response(description="Unauthorized")
Response.FORBIDDEN = Response(description="Forbidden")
Response.NOT_FOUND = Response(description="Not Found")
Response.METHOD_NOT_ALLOWED = Response(description="Method Not Allowed")
Response.GONE = Response(description="Gone")
Response.INTERNAL_SERVER_ERROR = Response(description="Internal Server Error")
class RequestBody(OObject):
"""Describes a single request body."""
def __init__(
self, content: Dict[str, MediaType], description: Optional[str] = None, required: bool = False,
):
"""
Describes a single request body.
:param content: REQUIRED. The content of the request body. The key is a media type or media type range and the
value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g.
``text/plain`` overrides ``text/*``
:param description: A brief description of the request body. This could contain examples of use. CommonMark
syntax MAY be used for rich text representation.
:param required: Determines if the request body is required in the request. Defaults to false.
"""
# TODO - types
_assert_required(content, "content", self.__class__)
_assert_type(content, (dict,), "content", self.__class__)
# Assignment and docs
self.description = description
"""
A brief description of the request body. This could contain examples of use. CommonMark syntax MAY be used for
rich text representation.
"""
self.content = content
"""
REQUIRED. The content of the request body. The key is a media type or media type range and the value describes
it. For requests that match multiple keys, only the most specific key is applicable. e.g. ``text/plain``
overrides ``text/*``
"""
self.required = required
"""Determines if the request body is required in the request. Defaults to false."""
class OAuthFlow(OObject):
"""
Configuration details for a supported OAuth Flow.
Note: there is an ``Applies To`` column in the spec and its full meaning is not clear. Be advised that you may
need to check again how this applies to you. See `OAuth Flow Object
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#oauth-flow-object>`_.
Specifically unclear (and inconsistent with some other sections of the docs) is whether the "REQUIRED"
terminology only applies to the value in the ``Applies To`` column. For this reason, there is no validation that
(possibly) REQUIRED values are presented.
"""
def __init__(
self, authorization_url: str, token_url: str, scopes: Dict[str, str], refresh_url: Optional[str] = None,
):
"""
Configuration details for a supported OAuth Flow.
Note: there is an ``Applies To`` column in the spec and its full meaning is not clear. Be advised that you may
need to check again how this applies to you. See `OAuth Flow Object
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#oauth-flow-object>`_.
Specifically unclear (and inconsistent with some other sections of the docs) is whether the "REQUIRED"
terminology only applies to the value in the ``Applies To`` column. For this reason, there is no validation that
(possibly) REQUIRED values are presented.
:param authorization_url: REQUIRED (but not checked). The authorization URL to be used for this flow. This MUST
be in the form of a URL.
:param token_url: REQUIRED (but not checked). The token URL to be used for this flow. This MUST be in the form
of a URL.
:param refresh_url: The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL.
:param scopes: REQUIRED (but not checked). The available scopes for the OAuth2 security scheme. A map between
the scope name and a short description for it.
"""
# TODO - see notes above re: validation
# Assignment and docs
self.authorization_url = authorization_url
"""
REQUIRED (but not checked). The authorization URL to be used for this flow. This MUST be in the form of a URL.
"""
self.token_url = token_url
"""REQUIRED (but not checked). The token URL to be used for this flow. This MUST be in the form of a URL."""
self.refresh_url = refresh_url
"""The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL."""
self.scopes = scopes
"""
REQUIRED (but not checked). The available scopes for the OAuth2 security scheme. A map between the scope name
and a short description for it.
"""
class OAuthFlows(OObject):
"""Allows configuration of the supported OAuth Flows."""
def __init__(
self,
implicit: Optional[OAuthFlow] = None,
password: Optional[OAuthFlow] = None,
client_credentials: Optional[OAuthFlow] = None,
authorization_code: Optional[OAuthFlow] = None,
):
"""
Allows configuration of the supported OAuth Flows.
:param implicit: Configuration for the OAuth Implicit flow.
:param password: Configuration for the OAuth Resource Owner Password flow.
:param client_credentials: Configuration for the OAuth Client Credentials flow. Previously called application in
OpenAPI 2.0.
:param authorization_code: Configuration for the OAuth Authorization Code flow. Previously called accessCode in
OpenAPI 2.0.
"""
# TODO - types
# No specific validation
# Assignment and docs
self.implicit = implicit
"""Configuration for the OAuth Implicit flow"""
self.password = password
"""Configuration for the OAuth Resource Owner Password flow"""
self.client_credentials = client_credentials
"""Configuration for the OAuth Client Credentials flow. Previously called application in OpenAPI 2.0."""
self.authorization_code = authorization_code
"""Configuration for the OAuth Authorization Code flow. Previously called accessCode in OpenAPI 2.0."""
class SecurityScheme(OObject): # pylint: disable=too-many-instance-attributes
"""
Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API
key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password,
application and access code) as defined in RFC6749, and OpenID Connect Discovery.
"""
def __init__( # pylint: disable=too-many-arguments
self,
_type: str,
name: Optional[str] = None,
_in: Optional[str] = None,
scheme: Optional[str] = None,
flows: Optional[OAuthFlows] = None,
openid_connect_url: Optional[str] = None,
description: Optional[str] = None,
bearer_format=None,
):
"""
Defines a security scheme that can be used by the operations. Supported schemes are HTTP authentication, an API
key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password,
application and access code) as defined in RFC6749, and OpenID Connect Discovery.
:param _type: REQUIRED. The type of the security scheme. Valid values are "apiKey", "http", "oauth2",
"openIdConnect".
:param description: A short description for security scheme. CommonMark syntax MAY be used for rich text
representation.
:param name: REQUIRED when `_type == "apiKey"`. The name of the header, query or cookie parameter to be used.
:param _in: REQUIRED when `_type == "apiKey"`. The location of the API key. Valid values are "query", "header"
or "cookie".
:param scheme: REQUIRED when `_type == "http"`. The name of the HTTP Authorization scheme to be used in the
Authorization header as defined in RFC7235.
:param bearer_format: A hint to the client to identify how the bearer token is formatted. Bearer tokens are
usually generated by an authorization server, so this information is primarily for documentation purposes.
:param flows: REQUIRED when `_type` is `oauth2`. An object containing configuration information for the flow
types supported.
:param openid_connect_url: REQUIRED when `_type` is `openIdConnect`. OpenId Connect URL to discover OAuth2
configuration values. This MUST be in the form of a URL.
"""
# TODO - types
assert _type in {"apiKey", "http", "oauth2", "openIdConnect"}
if _type == "apiKey":
_assert_required(name, "name for _type 'apiKey'", self.__class__)
_assert_required(_in, "_id for _type 'apiKey'", self.__class__)
assert _in in {"query", "header", "cookie"}, _in
elif _type == "http":
_assert_required(scheme, "scheme for _type 'http'", self.__class__)
elif _type == "oauth2":
_assert_required(flows, "flows for _type 'oauth2'", self.__class__)
elif _type == "openIdConnect":
_assert_required(openid_connect_url, "openid_connect_url for _type 'openIdConnect'", self.__class__)
self._type = _type
"""
REQUIRED. The type of the security scheme. Valid values are "apiKey", "http", "oauth2",
"openIdConnect"."""
self.description = description
"""A short description for security scheme. CommonMark syntax MAY be used for rich text representation."""
self.name = name
"""REQUIRED when `_type == "apiKey"`. The name of the header, query or cookie parameter to be used."""
self._in = _in
"""REQUIRED when `_type == "apiKey"`. The location of the API key. Valid values are "query", "header" or
"cookie"."""
self.scheme = scheme
"""
REQUIRED when `_type == "http"`.. The name of the HTTP Authorization scheme to be used in the Authorization
header as defined in RFC7235.
"""
self.bearer_format = bearer_format
"""
A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an
authorization server, so this information is primarily for documentation purposes.
"""
self.flows = flows
"""
REQUIRED when `_type == "oauth2"`. An object containing configuration information for the flow types supported.
"""
self.openid_connect_url = openid_connect_url
"""
REQUIRED when `_type == "openIdConnect"`. OpenId Connect URL to discover OAuth2 configuration values. This MUST
be in the form of a URL.
"""
class Callback(OObject):
"""
A map of possible out-of band callbacks related to the parent operation. Each value in the map is a PathItem
Object that describes a set of requests that may be initiated by the API provider and the expected responses.
The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL
to use for the callback operation.
Note: there is a _lot_ more documentation available in the spec for callbacks. `See
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#callback-object>`_ .
"""
# TODO - may need to reimplement the ``serialise`` and ``schema``.
def __init__(self, callbacks: Dict[Any, "PathItem"]):
"""
A map of possible out-of band callbacks related to the parent operation. Each value in the map is a PathItem
Object that describes a set of requests that may be initiated by the API provider and the expected responses.
The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL
to use for the callback operation.
Note: there is a _lot_ more documentation available in the spec for callbacks. `See
<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#callback-object>`_ .
:param callbacks: A mapping of Any to a PathItem used to define a callback request and expected responses.
A `complete example
<https://github.com/OAI/OpenAPI-Specification/blob/master/examples/v3.0/callback-example.yaml>`_ is available.
"""
# TODO - types
# TODO - validations
self.__dict__ = callbacks
def __setitem__(self, key, item):
self.__dict__[key] = item
def __getitem__(self, key):
return self.__dict__[key]
def __repr__(self):
return repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __delitem__(self, key):
del self.__dict__[key]
def clear(self):
return self.__dict__.clear()
def copy(self):
return self.__dict__.copy()
def has_key(self, k):
return k in self.__dict__
def update(self, *args, **kwargs):
return self.__dict__.update(*args, **kwargs)
def keys(self):
return self.__dict__.keys()
def values(self):
return self.__dict__.values()
def items(self):
return self.__dict__.items()
def pop(self, *args):
return self.__dict__.pop(*args)
def __cmp__(self, other):
return self.__dict__.__cmp__(other)
def __contains__(self, item):
return item in self.__dict__
def __iter__(self):
return iter(self.__dict__)
class Responses(OObject):
"""
A container for the expected responses of an operation. The container maps a HTTP response code to the expected
response. The documentation is not necessarily expected to cover all possible HTTP response codes because they
may not be known in advance. However, documentation is expected to cover a successful operation response and any
known errors.
The default MAY be used as a default response object for all HTTP codes that are not covered individually by the
specification.
The Responses Object MUST contain at least one response code, and it SHOULD be the response for a successful
operation call.
"default" key in responses
--------------------------
The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to
cover undeclared responses. A Reference Object can link to a response that the OpenAPI Object's
components/responses section defines.
HTTP status code keys in responses
----------------------------------
Any HTTP status code can be used as the property name, but only one property per code, to describe the expected
response for that HTTP status code. A Reference Object can link to a response that is defined in the OpenAPI
Object's components/responses section. This field MUST be enclosed in quotation marks (for example, "200") for
compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase
wildcard character X. For example, 2XX represents all response codes between [200-299]. Only the following range
definitions are allowed: 1XX, 2XX, 3XX, 4XX, and 5XX. If a response is defined using an explicit code, the
explicit code definition takes precedence over the range definition for that code.
"""
DEFAULT_RESPONSES = {
"200": Response.DEFAULT_SUCCESS,
"400": Response.BAD_REQUEST,
# "401": Response.UNAUTHORIZED,
# "403": Response.FORBIDDEN,
"404": Response.NOT_FOUND,
# "405": Response.METHOD_NOT_ALLOWED,
# "410": Response.GONE,
"500": Response.INTERNAL_SERVER_ERROR,
}
# TODO - may need to reimplement the ``serialise`` and ``schema``.
def __init__(self, responses: Optional[Dict[str, Union[Response, Reference]]] = None, no_defaults: bool = False):
"""
A container for the expected responses of an operation. The container maps a HTTP response code to the expected
response. The documentation is not necessarily expected to cover all possible HTTP response codes because they
may not be known in advance. However, documentation is expected to cover a successful operation response and any
known errors.
The default MAY be used as a default response object for all HTTP codes that are not covered individually by the
specification.
The Responses Object MUST contain at least one response code, and it SHOULD be the response for a successful
operation call.
"default" key in responses
--------------------------
The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to
cover undeclared responses. A Reference Object can link to a response that the OpenAPI Object's
components/responses section defines.
HTTP status code keys in responses
----------------------------------
Any HTTP status code can be used as the property name, but only one property per code, to describe the expected
response for that HTTP status code. A Reference Object can link to a response that is defined in the OpenAPI
Object's components/responses section. This field MUST be enclosed in quotation marks (for example, "200") for
compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase
wildcard character X. For example, 2XX represents all response codes between [200-299]. Only the following range
definitions are allowed: 1XX, 2XX, 3XX, 4XX, and 5XX. If a response is defined using an explicit code, the
explicit code definition takes precedence over the range definition for that code.
:param responses: A mapping of response code (as str) to a Response.
:param no_defaults: If True, the defaults are not used, thus only the entries of the `responses` dict will be
used.
"""
# TODO - types
# TODO - validations
_init_responses: Dict[str, Union[Response, Reference]]
if responses:
if no_defaults:
_init_responses = responses
else:
# Start with references ...
_init_responses = {
key: Reference("#/components/responses/{}".format(key)) for key in Responses.DEFAULT_RESPONSES
}
for status_code, response in responses.items():
_init_responses[str(status_code)] = response
else:
# Use references
_init_responses = {
key: Reference("#/components/responses/{}".format(key)) for key in Responses.DEFAULT_RESPONSES
}
self.__dict__ = _init_responses
@property
def as_dict(self) -> Dict[str, Union[Response, Reference]]:
return self.__dict__
def __setitem__(self, key, item):
self.__dict__[key] = item
def __getitem__(self, key):
return self.__dict__[key]
def __repr__(self):
return repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __delitem__(self, key):
del self.__dict__[key]
def clear(self):
return self.__dict__.clear()
def copy(self):
return self.__dict__.copy()
def has_key(self, k):
return k in self.__dict__
def update(self, *args, **kwargs):
return self.__dict__.update(*args, **kwargs)
def keys(self):
return self.__dict__.keys()
def values(self):
return self.__dict__.values()
def items(self):
return self.__dict__.items()
def pop(self, *args):
return self.__dict__.pop(*args)
# def __cmp__(self, other):
# return self.__dict__.__cmp__(other)
def __contains__(self, item):
return item in self.__dict__
def __iter__(self):
return iter(self.__dict__)
class Components(OObject): # pylint: disable=too-many-instance-attributes
"""
Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components
object will have no effect on the API unless they are explicitly referenced from properties outside the
components object.
"""
def __init__( # pylint: disable=too-many-arguments
self,
schemas: Optional[Mapping[str, Union[Schema, Reference]]] = None,
responses: Optional[Dict[str, Union[Response, Reference]]] = None,
parameters: Optional[Dict[str, Union[Parameter, Reference]]] = None,
examples: Optional[Dict[str, Union[Example, Reference]]] = None,
request_bodies: Optional[Dict[str, Union[RequestBody, Reference]]] = None,
headers: Optional[Dict[str, Union[Header, Reference]]] = None,
security_schemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None,
links: Optional[Dict[str, Union[Link, Reference]]] = None,
callbacks: Optional[Dict[str, Union[Callback, Reference]]] = None,
):
"""
Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components
object will have no effect on the API unless they are explicitly referenced from properties outside the
components object.
:param schemas: An object to hold reusable Schema Objects.
:param responses: An object to hold reusable Response Objects.
:param parameters: An object to hold reusable Parameter Objects.
:param examples: An object to hold reusable Example Objects.
:param request_bodies: An object to hold reusable Request Body Objects.
:param headers: An object to hold reusable Header Objects.
:param security_schemes: An object to hold reusable Security Scheme Objects.
:param links: An object to hold reusable Link Objects.
:param callbacks: An object to hold reusable Callback Objects.
"""
_assert_type(schemas, (dict,), "schemas", self.__class__)
_assert_type(responses, (dict,), "responses", self.__class__)
_assert_type(parameters, (dict,), "parameters", self.__class__)
_assert_type(examples, (dict,), "examples", self.__class__)
_assert_type(request_bodies, (dict,), "request_bodies", self.__class__)
_assert_type(headers, (dict,), "headers", self.__class__)
_assert_type(security_schemes, (dict,), "security_schemes", self.__class__)
_assert_type(links, (dict,), "links", self.__class__)
_assert_type(callbacks, (dict,), "callbacks", self.__class__)
# TODO - value type checks
# assignment and docs
self.schemas = schemas
"""An object to hold reusable Schema Objects."""
self.responses = responses or Responses.DEFAULT_RESPONSES
"""An object to hold reusable Response Objects."""
self.parameters = parameters
"""An object to hold reusable Parameter Objects."""
self.examples = examples
"""An object to hold reusable Example Objects."""
self.request_bodies = request_bodies
"""An object to hold reusable Request Body Objects."""
self.headers = headers
"""An object to hold reusable Header Objects."""
self.security_schemes = security_schemes
"""An object to hold reusable Security Scheme Objects."""
self.links = links
"""An object to hold reusable Link Objects."""
self.callbacks = callbacks
"""An object to hold reusable Callback Objects."""
class SecurityRequirement(OObject): # pylint: disable=missing-function-docstring
"""
Lists the required security schemes to execute this operation. The name used for each property MUST correspond to a
security scheme declared in the Security Schemes under the Components Object.
Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a
request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are
required to convey security information.
When a list of Security Requirement Objects is defined on the OpenAPI Object or Operation Object, only one of
the Security Requirement Objects in the list needs to be satisfied to authorize the request.
"""
# TODO - may need to reimplement the ``serialise`` and ``schema``.
def __init__(self, names: Dict[str, List[str]]):
"""
Lists the required security schemes to execute this operation. The name used for each property MUST correspond
to a security scheme declared in the Security Schemes under the Components Object.
Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a
request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are
required to convey security information.
When a list of Security Requirement Objects is defined on the OpenAPI Object or Operation Object, only one of
the Security Requirement Objects in the list needs to be satisfied to authorize the request.
:param names: Each ``names`` dict key MUST correspond to a security scheme which is declared in the Security
Schemes under the Components Object. If the security scheme is of type "oauth2" or "openIdConnect", then the
value is a list of scope names required for the execution. For other security scheme types, the array MUST
be empty.
"""
# TODO - types
# TODO - validations
self.__dict__ = names
def __setitem__(self, key, item):
self.__dict__[key] = item
def __getitem__(self, key):
return self.__dict__[key]
def __repr__(self):
return repr(self.__dict__)
def __len__(self):
return len(self.__dict__)
def __delitem__(self, key):
del self.__dict__[key]
def clear(self):
return self.__dict__.clear()
def copy(self):
return self.__dict__.copy()
def has_key(self, k):
return k in self.__dict__
def update(self, *args, **kwargs):
return self.__dict__.update(*args, **kwargs)
def keys(self):
return self.__dict__.keys()
def values(self):
return self.__dict__.values()
def items(self):
return self.__dict__.items()
def pop(self, *args):
return self.__dict__.pop(*args)
def __cmp__(self, other):
return self.__dict__.__cmp__(other)
def __contains__(self, item):
return item in self.__dict__
def __iter__(self):
return iter(self.__dict__)
class Operation(OObject): # pylint: disable=too-many-instance-attributes
"""Describes a single API operation on a path."""
OPERATION_NAMES = frozenset(("get", "put", "post", "delete", "options", "head", "patch", "trace"))
def __init__( # pylint: disable=too-many-arguments
self,
operation_id: str,
responses: Responses,
tags: Optional[List[str]] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
external_docs: Optional[ExternalDocumentation] = None,
parameters: Optional[List[Union[Parameter, Reference]]] = None,
request_body: Optional[Union[RequestBody, Reference]] = None,
callbacks: Optional[Dict[str, Union[Callback, Reference]]] = None,
deprecated: bool = False,
security: Optional[List[SecurityRequirement]] = None,
servers: Optional[List[Server]] = None,
x_handler_route: sanic.router.Route = None,
):
"""
Describes a single API operation on a path.
:param tags: A list of tags names for API documentation control. Tags can be used for logical grouping of
operations by resources or any other qualifier.
:param summary: A short summary of what the operation does.
:param description: A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text
representation.
:param external_docs: Additional external documentation for this operation.
:param operation_id: Unique string used to identify the operation. The id MUST be unique among all operations
described in the API. The operationId value is case-sensitive. Tools and libraries MAY use the operationId
to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming
conventions.
:param parameters: A list of parameters that are applicable for this operation. If a parameter is already
defined at the Path Item, the new definition will override it but can never remove it. The list MUST NOT
include duplicated parameters. A unique parameter is defined by a combination of a name and location. The
list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's
components/parameters.
:param request_body: The request body applicable for this operation. The requestBody is only supported in HTTP
methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In
other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers.
:param responses: REQUIRED. The list of possible responses as they are returned from executing this operation.
:param callbacks: A map of possible out-of band callbacks related to the parent operation. The key is a unique
identifier for the Callback Object. Each value in the map is a Callback Object that describes a request that
may be initiated by the API provider and the expected responses. The key value used to identify the callback
object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation.
:param deprecated: Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared
operation. Default value is false.
:param security: A declaration of which security mechanisms can be used for this operation. The list of values
includes alternative security requirement objects that can be used. Only one of the security requirement
objects need to be satisfied to authorize a request. This definition overrides any declared top-level
security. To remove a top-level security declaration, an empty array can be used.
:param servers: An alternative server array to service this operation. If an alternative server object is
specified at the Path Item Object or Root level, it will be overridden by this value.
"""
# TODO - types
_assert_type(parameters, (list,), "parameters", self.__class__)
# TODO - validations
_assert_required(responses, "responses", self.__class__)
_assert_required(operation_id, "operation_id", self.__class__)
# assignment and docs
self.tags = tags
"""
A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources
or any other qualifier.
"""
self.summary = summary
"""A short summary of what the operation does."""
self.description = description
"""
A verbose explanation of the operation behavior. CommonMark syntax MAY be used for rich text representation.
"""
self.external_docs = external_docs
"""Additional external documentation for this operation."""
assert operation_id
self.operation_id = operation_id
"""
Unique string used to identify the operation. The id MUST be unique among all operations described in the API.
The operationId value is case-sensitive. Tools and libraries MAY use the operationId to uniquely identify an
operation, therefore, it is RECOMMENDED to follow common programming naming conventions.
"""
self.parameters = parameters
"""
A list of parameters that are applicable for this operation. If a parameter is already defined at the Path Item,
the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters.
A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to
link to parameters that are defined at the OpenAPI Object's components/parameters.
"""
self.request_body = request_body
"""
The request body applicable for this operation. The requestBody is only supported in HTTP methods where the HTTP
1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP
spec is vague, requestBody SHALL be ignored by consumers.
"""
self.responses = responses
"""REQUIRED. The list of possible responses as they are returned from executing this operation."""
self.callbacks = callbacks
"""
A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the
Callback Object. Each value in the map is a Callback Object that describes a request that may be initiated by
the API provider and the expected responses. The key value used to identify the callback object is an
expression, evaluated at runtime, that identifies a URL to use for the callback operation.
"""
self.deprecated = deprecated
"""
Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default
value is false.
"""
self.security = security
"""
A declaration of which security mechanisms can be used for this operation. The list of values includes
alternative security requirement objects that can be used. Only one of the security requirement objects need to
be satisfied to authorize a request. This definition overrides any declared top-level security. To remove a
top-level security declaration, an empty array can be used.
"""
self.servers = servers
"""
An alternative server array to service this operation. If an alternative server object is specified at the
PathItem Object or Root level, it will be overridden by this value.
"""
self.x_handler_route = x_handler_route
class Tag(OObject):
"""
Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per tag
defined in the Operation Object instances.
"""
def __init__(
self, name: str, description: Optional[str] = None, external_docs: Optional[ExternalDocumentation] = None,
):
"""
Adds metadata to a single tag that is used by the Operation Object. It is not mandatory to have a Tag Object per
tag defined in the Operation Object instances.
:param name: REQUIRED. The name of the tag.
:param description: A short description for the tag. CommonMark syntax MAY be used for rich text representation.
:param external_docs: An ExternalDocumentation fpr this tag.
"""
_assert_required(name, "name", self.__class__)
self.name = name
"""REQUIRED. The name of the tag."""
self.description = description
"""A short description for the tag. CommonMark syntax MAY be used for rich text representation."""
self.external_docs = external_docs
"""Additional external documentation for this tag."""
def __hash__(self):
return hash((self.name, self.description, self.external_docs))
def __eq__(self, other):
if not isinstance(other, type(self)):
raise NotImplementedError()
return (
self.name == other.name
and self.description == other.description
and self.external_docs == other.external_docs
)
def __lt__(self, other):
if not isinstance(other, type(self)):
raise NotImplementedError()
return (self.name, self.description, self.external_docs) < (other.name, other.description, other.external_docs,)
class PathItem(OObject): # pylint: disable=too-many-instance-attributes
"""
Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path
itself is still exposed to the documentation viewer but they will not know which operations and parameters are
available.
"""
def __init__( # pylint: disable=too-many-locals, too-many-arguments
self,
dollar_ref: Optional[str] = None,
summary: Optional[str] = None,
description: Optional[str] = None,
get: Optional[Operation] = None,
put: Optional[Operation] = None,
post: Optional[Operation] = None,
delete: Optional[Operation] = None,
options: Optional[Operation] = None,
head: Optional[Operation] = None,
patch: Optional[Operation] = None,
trace: Optional[Operation] = None,
servers: Optional[List[Server]] = None,
parameters: Optional[List[Union[Parameter, Reference]]] = None,
request_body: Optional[Union[RequestBody, Reference]] = None,
x_deprecated_holder: bool = False,
x_exclude: bool = False,
x_external_docs_holder: Optional[ExternalDocumentation] = None,
x_responses_holder: Optional[Dict[str, Union[Response, Reference]]] = None,
x_security_holder: Optional[List[SecurityRequirement]] = None,
x_tags_holder: Optional[List[Tag]] = None,
):
"""
Describes the operations available on a single path. A Path Item MAY be empty, due to ACL constraints. The path
itself is still exposed to the documentation viewer but they will not know which operations and parameters are
available.
:param dollar_ref: Allows for an external definition of this path item. The referenced structure MUST be in the
format of a Path Item Object. If there are conflicts between the referenced definition and this Path Item's
definition, the behavior is undefined.
:param summary: An optional, string summary, intended to apply to all operations in this path.
:param description: An optional, string description, intended to apply to all operations in this path.
CommonMark syntax MAY be used for rich text representation.
:param get: A definition of a GET operation on this path.
:param put: A definition of a PUT operation on this path.
:param post: A definition of a POST operation on this path.
:param delete: A definition of a DELETE operation on this path.
:param options: A definition of an OPTIONS operation on this path.
:param head: A definition of a HEAD operation on this path.
:param patch: A definition of a PATCH operation on this path.
:param trace: A definition of a TRACE operation on this path.
:param servers: An alternative server array to service all operations in this path.
:param parameters: A list of parameters that are applicable for all the operations described under this
path. These parameters can be overridden at the operation level, but cannot be removed there. The list
MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and
location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI
Object's components/parameters.
:param request_body: sanic-openapi3e implementation extension to allow requestBody to be defined.
:param x_deprecated_holder: sanic-openapi3e implementation extension to allow deprecated on the PathItem until
they can be passed to the Operation/s.
:param x_exclude: sanic-openapi3e extension to completly exclude the path from the spec.
:param x_external_docs_holder: sanic-openapi3e implementation extension to allow externalDocs on the PathItem
until they can be passed to the Operation/s.
:param x_responses_holder: sanic-openapi3e implementation extension to allow Responses on the PathItem until
they can be passed to the Operation/s.
:param x_security_holder: sanic-openapi3e implementation extension to allow security on the PathItem until they
can be passed to the Operation/s.
:param x_tags_holder: sanic-openapi3e implementation extension to allow tags on the PathItem until they can be
passed to the Operation/s.
"""
# TODO - validations
if x_tags_holder:
for x_tag in x_tags_holder:
_assert_type(x_tag, (Tag,), "x_tags_holder[*]", self.__class__)
# Assignment and docs
self.dollar_ref = dollar_ref
"""
Allows for an external definition of this path item. The referenced structure MUST be in the format of a Path
Item Object. If there are conflicts between the referenced definition and this Path Item's definition, the
behavior is undefined.
"""
self.summary = summary
"""An optional, string summary, intended to apply to all operations in this path."""
self.description = description
"""
An optional, string description, intended to apply to all operations in this path. CommonMark syntax MAY be used
for rich text representation.
"""
self.get = get
""" A definition of a GET operation on this path."""
self.put = put
"""A definition of a PUT operation on this path."""
self.post = post
"""A definition of a POST operation on this path."""
self.delete = delete
"""A definition of a DELETE operation on this path."""
self.options = options
"""A definition of an OPTIONS operation on this path."""
self.head = head
"""A definition of a HEAD operation on this path."""
self.patch = patch
"""A definition of an PATCH operation on this path."""
self.trace = trace
"""A definition of a TRACE operation on this path."""
self.servers = servers
"""An alternative server array to service all operations in this path."""
self.parameters: List[Union[Parameter, Reference]] = parameters if parameters is not None else []
"""
A list of parameters that are applicable for all the operations described under this path. These
parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT
include duplicated parameters. A unique parameter is defined by a combination of a name and location. The
list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's
components/parameters.
"""
self.request_body = request_body
self.x_tags_holder: List[Tag] = x_tags_holder if x_tags_holder is not None else []
self.x_security_holder = x_security_holder
self.x_deprecated_holder = x_deprecated_holder
self.x_responses_holder = Responses(x_responses_holder)
self.x_external_docs_holder = x_external_docs_holder
self.x_exclude = x_exclude
def x_operations(self) -> List[Operation]:
_ops = [self.get, self.get, self.put, self.post, self.delete, self.options, self.head, self.patch, self.trace]
return [_op for _op in _ops if _op]
class Paths(OObject):
"""
Holds the relative endpoints to the individual endpoints and their operations. The path is appended to the URL
from the Server Object in order to construct the full URL. The Paths MAY be empty, due to ACL constraints.
"""
def __init__(self, path_items: Optional[List[Tuple[str, PathItem]]] = None):
"""
Holds the relative endpoints to the individual endpoints and their operations. The path is appended to the URL
from the Server Object in order to construct the full URL. The Paths MAY be empty, due to ACL constraints.
:param path_items The endpoints
"""
self.locked: bool = False
self._paths: List[Tuple[str, PathItem]] = []
"""
A collection of your `app`'s functions and their Path Item. The field name MUST begin with a slash. The path is
appended (no relative URL resolution) to the expanded URL from the Server Object's url field in order to
construct the full URL. Path templating is allowed. When matching URLs, concrete (non-templated) endpoints would
be matched before their templated counterparts. Templated endpoints with the same hierarchy but different
templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to
decide which one to use.
"""
if path_items:
self.locked = True
self._paths = path_items
def __len__(self):
return len(self._paths)
def __getitem__(self, item: str) -> PathItem:
"""
A defaultdict interface if not locked.
:param item: What to find.
"""
for _parsed_uri, path_item in self._paths:
if _parsed_uri == item:
return path_item
if not self.locked:
path_item = PathItem()
self._paths.append((item, path_item))
return self._paths[-1][1]
raise KeyError(item)
def __contains__(self, item):
return any(_parsed_uri == item for _parsed_uri, _path_item in self._paths)
def __iter__(self):
yield from self._paths
def __setitem__(self, key, value):
if not self.locked:
for idx, _ in enumerate(self._paths):
if self._paths[idx][0] == key:
self._paths[idx] = (key, value)
break
else:
raise KeyError(key)
else:
raise ValueError("locked")
class OpenAPIv3(OObject): # pylint: disable=too-many-instance-attributes
"""The root document object of the OpenAPI document."""
version = "3.0.2"
def __init__( # pylint: disable=too-many-arguments
self,
openapi: str,
info: Info,
paths: Paths,
servers: Optional[List[Server]] = None,
components: Optional[Components] = None,
security: Optional[List[SecurityRequirement]] = None,
tags: Optional[List[Tag]] = None,
external_docs: Optional[ExternalDocumentation] = None,
):
"""
This is the root document object of the OpenAPI document.
:param openapi: REQUIRED. This string MUST be the semantic version number of the OpenAPI Specification version
that the OpenAPI document uses. The openapi field SHOULD be used by tooling specifications and clients to
interpret the OpenAPI document. This is not related to the API info.version string.
:param info: REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required.
:param servers: An array of Server Objects, which provide connectivity information to a target server. If the
servers property is not provided, or is an empty array, the default value would be a Server Object with a
url value of /.
:param paths: REQUIRED. The available endpoints and operations for the API.
:param components: An element to hold various schemas for the specification.
:param security: A declaration of which security mechanisms can be used across the API. The list of values
includes alternative security requirement objects that can be used. Only one of the security requirement
objects need to be satisfied to authorize a request. Individual operations can override this definition.
:param tags: A list of tags used by the specification with additional metadata. The order of the tags can be
used to reflect on their order by the parsing tools. Not all tags that are used by the Operation Object must
be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag
name in the list MUST be unique.
:param external_docs: Additional external documentation.
"""
_assert_type(openapi, (str,), "openapi", self.__class__)
_assert_type(info, (Info,), "info", self.__class__)
_assert_type(servers, (list,), "servers", self.__class__)
_assert_type(paths, (Paths,), "endpoints", self.__class__)
_assert_type(components, (Components,), "components", self.__class__)
_assert_type(security, (list,), "security", self.__class__)
_assert_type(tags, (list,), "tags", self.__class__)
_assert_type(external_docs, (ExternalDocumentation,), "external_docs", self.__class__)
_assert_required(openapi, "openapi", self.__class__)
_assert_required(info, "info", self.__class__)
_assert_required(paths, "endpoints", self.__class__)
# TODO - other assertions - eg `Servers`
if tags:
assert len([t.name for t in tags]) == len(tags)
self.openapi = openapi
"""
REQUIRED. This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI
document uses. The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI
document. This is not related to the API info.version string."""
self.info = info
"""REQUIRED. Provides metadata about the API. The metadata MAY be used by tooling as required."""
assert paths
self.paths = paths
"""REQUIRED. The available endpoints and operations for the API."""
self.servers = servers
"""
An array of Server Objects, which provide connectivity information to a target server. If the servers property
is not provided, or is an empty array, the default value would be a Server Object with a url value of /.
"""
self.components = components
"""An element to hold various schemas for the specification."""
self.security = security
"""
A declaration of which security mechanisms can be used across the API. The list of values includes alternative
security requirement objects that can be used. Only one of the security requirement objects need to be satisfied
to authorize a request. Individual operations can override this definition.
"""
if tags:
assert sorted({t.name for t in tags}) == sorted(t.name for t in tags)
self.tags = tags
"""
A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect
on their order by the parsing tools. Not all tags that are used by the Operation Object must be declared. The
tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list
MUST be unique.
"""
self.external_docs = external_docs
"""Additional external documentation."""
def as_yamlable_object(self, sort=False, opt_key: Optional[str] = None):
# This one is here to allow mypy to accept that the root `yaml`-able object really is always a dict. That
# annotation is found near the top of `openapi.py`.
return super().as_yamlable_object(sort=False, opt_key=".")
| 49.910601
| 122
| 0.657007
| 21,401
| 165,254
| 4.950143
| 0.053128
| 0.015292
| 0.016708
| 0.017218
| 0.798354
| 0.771395
| 0.754743
| 0.739433
| 0.714493
| 0.693906
| 0
| 0.00284
| 0.264798
| 165,254
| 3,310
| 123
| 49.92568
| 0.869065
| 0.401896
| 0
| 0.382747
| 0
| 0.00335
| 0.078478
| 0.002027
| 0
| 0
| 0
| 0.006949
| 0.177554
| 1
| 0.085427
| false
| 0.005025
| 0.007538
| 0.039363
| 0.191792
| 0.000838
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 1
| 1
| 1
| 1
| 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
| 5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.