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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8bb6a3a62314e27904dda8b95747e703d1ea0a87 | 801 | py | Python | tests/test_custom.py | tbabej/python-basehash | 9578c23074f7afef523b5f183d41dc5a1ad134c5 | [
"Apache-2.0"
] | 27 | 2015-03-12T07:32:25.000Z | 2021-11-15T09:52:40.000Z | tests/test_custom.py | tbabej/python-basehash | 9578c23074f7afef523b5f183d41dc5a1ad134c5 | [
"Apache-2.0"
] | 7 | 2015-05-28T06:07:45.000Z | 2021-08-31T18:18:00.000Z | tests/test_custom.py | tbabej/python-basehash | 9578c23074f7afef523b5f183d41dc5a1ad134c5 | [
"Apache-2.0"
] | 13 | 2015-02-25T08:50:43.000Z | 2021-12-10T13:22:42.000Z | from nose.tools import raises
from basehash import base
bhx = base('0SYv2xCbfhzGK4AW8E6QUpnjdtMOIlr')
bh6 = base('0SYv2xCbfhzGK4AW8E6QUpnjdtMOIlr', 6)
bh10 = base('0SYv2xCbfhzGK4AW8E6QUpnjdtMOIlr', 10)
def test_custom_encode_with_1234567890_SKvdr0U():
assert bhx.encode(1234567890) == 'SKvdr0U'
def test_custom_decode_with_SKvdr0U_1234567890():
assert bhx.decode('SKvdr0U') == 1234567890
def test_custom_hash_with_1234567890_10_4QxzxC4CtG():
assert bh10.hash(1234567890) == '4QxzxC4CtG'
def test_custom_unhash_with_4QxzxC4CtG_1234567890():
assert bh10.unhash('4QxzxC4CtG') == 1234567890
def test_custom_maximum_value_with_6_887503680():
assert bh6.maximum == 887503680
@raises(ValueError)
def test_custom_hash_fail_with_887503681_6():
assert bh6.hash(887503681)
| 23.558824 | 53 | 0.792759 | 95 | 801 | 6.336842 | 0.326316 | 0.069767 | 0.129568 | 0.076412 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.224576 | 0.116105 | 801 | 33 | 54 | 24.272727 | 0.625706 | 0 | 0 | 0 | 0 | 0 | 0.158552 | 0.116105 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.333333 | false | 0 | 0.111111 | 0 | 0.444444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
8bc1db130d3ea5e482575b551121968e91f00970 | 604 | py | Python | tmv/exceptions.py | brettbeeson/tmv | 0771a88d1cb06bb938555fa967eb8c44f5f846d5 | [
"MIT"
] | 1 | 2021-11-09T19:38:33.000Z | 2021-11-09T19:38:33.000Z | tmv/exceptions.py | brettbeeson/tmv | 0771a88d1cb06bb938555fa967eb8c44f5f846d5 | [
"MIT"
] | null | null | null | tmv/exceptions.py | brettbeeson/tmv | 0771a88d1cb06bb938555fa967eb8c44f5f846d5 | [
"MIT"
] | null | null | null |
class TMVError(Exception):
""" Base exception """
class CameraError(Exception):
"""" Hardware camera problem"""
class ButtonError(Exception):
""" Problem with (usually hardware) buttons """
class VideoMakerError(Exception):
""" Problem making images into a video """
class ImageError(Exception):
""" Problem with an image """
class ConfigError(TMVError):
""" TOML or config error """
class PiJuiceError(TMVError):
""" Cound't power off"""
class PowerOff(TMVError):
""" Camera can power off """
class SignalException(TMVError):
""" Camera got a sigint """
| 18.875 | 51 | 0.663907 | 63 | 604 | 6.365079 | 0.571429 | 0.119701 | 0.099751 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.195364 | 604 | 31 | 52 | 19.483871 | 0.825103 | 0.369205 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
8be8a0603ea8a60376c7b901b873d006aaa42b8e | 217 | py | Python | buoi12/bai6.py | Viet7501/viet1 | e0be1da1fb0f4736c8d0457733ccaaed9232c4e9 | [
"Apache-2.0"
] | null | null | null | buoi12/bai6.py | Viet7501/viet1 | e0be1da1fb0f4736c8d0457733ccaaed9232c4e9 | [
"Apache-2.0"
] | null | null | null | buoi12/bai6.py | Viet7501/viet1 | e0be1da1fb0f4736c8d0457733ccaaed9232c4e9 | [
"Apache-2.0"
] | null | null | null | def extract_characters(*file):
with open("file3.txt") as f:
while True:
c = f.read(1)
if not c:
break
print(c)
extract_characters('file3.txt') | 21.7 | 33 | 0.474654 | 26 | 217 | 3.884615 | 0.730769 | 0.336634 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.02381 | 0.419355 | 217 | 10 | 34 | 21.7 | 0.777778 | 0 | 0 | 0 | 0 | 0 | 0.086124 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0 | 0 | 0.125 | 0.125 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
47368eb13bd18d83673e33364f6f36cb6a7f6268 | 250 | py | Python | tests/conftest.py | starlinglab/integrity-backend | 8d2a0640d7a9f66c97d180ad76aedf968dfa43e6 | [
"MIT"
] | 1 | 2022-03-18T16:11:31.000Z | 2022-03-18T16:11:31.000Z | tests/conftest.py | starlinglab/starling-integrity-api | c39161576e852afbffe3053af468acf58207b5ae | [
"MIT"
] | 37 | 2022-01-17T22:07:17.000Z | 2022-03-31T22:11:16.000Z | tests/conftest.py | starlinglab/starling-integrity-api | c39161576e852afbffe3053af468acf58207b5ae | [
"MIT"
] | null | null | null | import pytest
@pytest.fixture
def reverse_geocode_mocker(mocker):
def patch(return_value):
mocker.patch(
"integritybackend.geocoder.Geocoder.reverse_geocode",
lambda *_: return_value,
)
return patch
| 19.230769 | 65 | 0.656 | 25 | 250 | 6.32 | 0.52 | 0.177215 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.264 | 250 | 12 | 66 | 20.833333 | 0.858696 | 0 | 0 | 0 | 0 | 0 | 0.2 | 0.2 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.111111 | 0 | 0.444444 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
473b9b6bb6c0ebffabcf56d80e1e0a5f1c27c786 | 1,071 | py | Python | webpage/forms.py | amandachen1024/Stock-Price-Predictor-Webpage | 1fc72ff4d14d8daa517455ff3e122b07ea103c9f | [
"Apache-2.0"
] | null | null | null | webpage/forms.py | amandachen1024/Stock-Price-Predictor-Webpage | 1fc72ff4d14d8daa517455ff3e122b07ea103c9f | [
"Apache-2.0"
] | null | null | null | webpage/forms.py | amandachen1024/Stock-Price-Predictor-Webpage | 1fc72ff4d14d8daa517455ff3e122b07ea103c9f | [
"Apache-2.0"
] | null | null | null |
from webpage import app
from flask import Flask, render_template
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, FloatField, SubmitField, ValidationError
from wtforms.validators import DataRequired, NumberRange
import yfinance as yf
def validate_ticker(self, ticker):
ticker = yf.Ticker(ticker.data)
try:
ticker.info
except:
raise ValidationError("Invalid Ticker Symbol")
class InputForm(FlaskForm):
ticker = StringField(label='Ticker symbol of stock: ', validators=[validate_ticker, DataRequired()])
start_price = FloatField(label='Price purchased at: ', validators=[NumberRange(min=0, message="Enter a positive value"), DataRequired()])
num_shares = IntegerField(label='Number of shares purchased: ', validators=[NumberRange(min=0, message="Enter a positive value"), DataRequired()])
future_days = IntegerField(label='Number of days into the future to predict: ', validators=[NumberRange(min=0, message="Enter a positive value"), DataRequired()])
submit = SubmitField(label='Submit')
| 42.84 | 166 | 0.755369 | 127 | 1,071 | 6.314961 | 0.456693 | 0.078554 | 0.089776 | 0.093516 | 0.235661 | 0.235661 | 0.235661 | 0.235661 | 0.235661 | 0.235661 | 0 | 0.003268 | 0.142857 | 1,071 | 24 | 167 | 44.625 | 0.87037 | 0 | 0 | 0 | 0 | 0 | 0.194574 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.055556 | false | 0 | 0.333333 | 0 | 0.722222 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
474c2ede81d87160c5dfd0601270f200beaf71ed | 547 | py | Python | exercises/constants.py | hesoyam11/optimus-type.api-server | eeb96e4acbc7e3eb67a00a21f95bc9a6c480ee37 | [
"MIT"
] | null | null | null | exercises/constants.py | hesoyam11/optimus-type.api-server | eeb96e4acbc7e3eb67a00a21f95bc9a6c480ee37 | [
"MIT"
] | 4 | 2020-07-22T20:17:26.000Z | 2020-07-22T20:23:08.000Z | exercises/constants.py | vkaidalov/optimus-type.api-server | eeb96e4acbc7e3eb67a00a21f95bc9a6c480ee37 | [
"MIT"
] | null | null | null | EN_US_CHARSET = (
"`1234567890-=\\"
"qwertyuiop[]"
"asdfghjkl;'"
"zxcvbnm,./"
"~!@#$%^&*()_+|"
"QWERTYUIOP{}"
"ASDFGHJKL:\""
"ZXCVBNM<>?"
" \n"
)
UK_UA_CHARSET = (
"'1234567890-=ґ"
"йцукенгшщзхї"
"фівапролджє"
"ячсмитьбю."
"ʼ!\"№;%:?*()_+Ґ"
"ЙЦУКЕНГШЩЗХЇ"
"ФІВАПРОЛДЖЄ"
"ЯЧСМИТЬБЮ,"
" \n"
)
RU_RU_CHARSET = (
"ё1234567890-=\\"
"йцукенгшщзхъ"
"фывапролджэ"
"ячсмитьбю."
"Ё!\"№;%:?*()_+/"
"ЙЦУКЕНГШЩЗХЪ"
"ФЫВАПРОЛДЖЭ"
"ЯЧСМИТЬБЮ,"
" \n"
)
| 15.194444 | 21 | 0.47532 | 39 | 547 | 6.538462 | 0.538462 | 0.133333 | 0.203922 | 0.258824 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.075949 | 0.277879 | 547 | 35 | 22 | 15.628571 | 0.559494 | 0 | 0 | 0.212121 | 0 | 0 | 0.49543 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
474d433e22e51ef2cce3953c5eb2b7166a937e0d | 2,412 | py | Python | ompceg/ompceg.py | omars11/ompc | 459446df9bf15946b8a16b517151a30c9aff6a33 | [
"BSD-3-Clause"
] | 11 | 2019-12-15T23:50:46.000Z | 2022-01-29T14:27:52.000Z | ompceg/ompceg.py | omars11/ompc | 459446df9bf15946b8a16b517151a30c9aff6a33 | [
"BSD-3-Clause"
] | null | null | null | ompceg/ompceg.py | omars11/ompc | 459446df9bf15946b8a16b517151a30c9aff6a33 | [
"BSD-3-Clause"
] | 5 | 2019-08-22T16:47:51.000Z | 2021-12-06T07:14:32.000Z | """OMPC extension generator.
ompceg.py [FNAME]
FNAME - .c or .cpp file
"""
import ompc
__AUTHOR__ = ompc.AUTHOR
MFUNC = \
"""function %(ret_def)s%(fname)s(%(mparams)s)
%(doc)s
%(signature)s
%(ret_val)scalllib('%(libname)s','%(fname)s'%(ppass)s);
"""
SIGNATURE = \
"""% Generated by ompc extension generator v%s
% by %s, 2007, %s
"""%(__VERSION__, __AUTHOR__, ompc.OMPC_URL)
def docs(d,p):
"""Generate documentation string for m-file."""
doc =['%% %(ret_def)s%(FNAME)s(%(mparams)s)'%p,
'%%'%p]
for x in d.split('\n'):
doc += [ re.sub(r'^\s*/(?:/|\*)\s*','% ', x) ]
if not doc[-1].strip():
del doc[-1]
return '\n'.join(doc)
def ret_val(r, params):
"""Determine the return values."""
rets = []
if 'void' not in r:
rets += ['libreturn']
for x in params:
if 'out' in x[0]:
rets += [x[2]]
res_def = ''
if len(rets) == 1:
res_def = '%s = '%rets[0]
elif len(rets) > 1:
res_def = '[%s] = '%', '.join(rets)
#return res_def, 'void' not in r and 'libreturn = ' or ''
return res_def, res_def
def main():
import sys, os, re
if len(sys.argv) < 2:
print __doc__
sys.exit()
fname = sys.argv[1]
a = open(fname,'rt').read()
rc = re.compile(r'API\s+(\w+)\s+([^\s\(]+)\(([^\)]*)\).*?\n(.*?)\n?\{',re.S|re.M)
#rp = re.compile(r'^(/\*[^\*]*\*/|)\s*(.*?)\s*([\w_\[\]\\d]+)$',re.S|re.M)
rp = re.compile(r'(?:\s*?/\*\s*\[([^\]]+)\]\s*\*/|)\s*(.*?)\s*([\w_\[\]\\d]+)(?:,|$)',re.S|re.M)
pth, fname = os.path.split(fname)
fname, fext = os.path.splitext(fname)
omcp.mkdir('lib%s'%fname)
head = []
for r,n,p,d in rc.findall(a):
head += ['%s %s(%s);'%(r,n,p)]
ps = rp.findall(p)
mparams = ', '.join([ x[2] for x in ps ])
ppass = ''
if mparams:
ppass = ', ' + mparams;
rd, rv = ret_val(r, ps)
dc = dict(ret_def=rd, ret_val=rv, fname=n, FNAME=n.upper(), params=p,
mparams=mparams, ppass=ppass, libname=fname)
doc = docs(d,dc)
dc.update(doc=doc, signature=SIGNATURE)
open('lib%s/%s.m'%(fname,n),'wt').write(MFUNC%dc)
open('%s.h'%fname,'wt').write('\n'.join(head)+'\n')
if __name__ == "":
main()
| 27.101124 | 101 | 0.465589 | 342 | 2,412 | 3.178363 | 0.295322 | 0.018399 | 0.01104 | 0.016559 | 0.114075 | 0.114075 | 0.086477 | 0.047838 | 0.036799 | 0.036799 | 0 | 0.00813 | 0.28607 | 2,412 | 88 | 102 | 27.409091 | 0.623113 | 0.053483 | 0 | 0 | 0 | 0 | 0.13748 | 0.081833 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.054545 | 0.036364 | null | null | 0.018182 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
475fcbacd5a368b8928f033e058c7d59ec4b6405 | 930 | py | Python | Torneo/apps/equipo/migrations/0001_initial.py | Estuardiaz2611/Djangotuto2 | bdb8665c7e2a95296ab85e1e986bbcdca1828fa7 | [
"MIT"
] | null | null | null | Torneo/apps/equipo/migrations/0001_initial.py | Estuardiaz2611/Djangotuto2 | bdb8665c7e2a95296ab85e1e986bbcdca1828fa7 | [
"MIT"
] | null | null | null | Torneo/apps/equipo/migrations/0001_initial.py | Estuardiaz2611/Djangotuto2 | bdb8665c7e2a95296ab85e1e986bbcdca1828fa7 | [
"MIT"
] | null | null | null | # Generated by Django 2.2.6 on 2019-10-02 17:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('liga', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Equipo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre_equipo', models.CharField(max_length=50)),
('siglas', models.CharField(max_length=5)),
('jugadores', models.IntegerField()),
('encargado', models.CharField(max_length=50)),
('telefono', models.CharField(max_length=9)),
('liga', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='liga.Liga')),
],
),
]
| 32.068966 | 128 | 0.586022 | 98 | 930 | 5.459184 | 0.571429 | 0.11215 | 0.134579 | 0.179439 | 0.097196 | 0 | 0 | 0 | 0 | 0 | 0 | 0.036928 | 0.272043 | 930 | 28 | 129 | 33.214286 | 0.753323 | 0.048387 | 0 | 0 | 1 | 0 | 0.09513 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.095238 | 0 | 0.285714 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
476c1d7a2255023089c9cadc0c1b3f3a0fd36c61 | 2,772 | py | Python | manager/basic/notify.py | Tootooroo/VerManager | 65a37ed4f864c8d6adeade52582315aeff901fbe | [
"MIT"
] | 2 | 2020-03-20T20:04:54.000Z | 2021-03-18T12:03:54.000Z | manager/basic/notify.py | Tootooroo/VerManager | 65a37ed4f864c8d6adeade52582315aeff901fbe | [
"MIT"
] | null | null | null | manager/basic/notify.py | Tootooroo/VerManager | 65a37ed4f864c8d6adeade52582315aeff901fbe | [
"MIT"
] | null | null | null | # MIT License
#
# Copyright (c) 2020 Gcom
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import abc
from typing import Optional, Dict
from manager.basic.letter import NotifyLetter
WORKER_STATE_CHANGED = "WSC"
class Notify(abc.ABC):
def __init__(self, ident: str, type: str,
content: Dict) -> None:
self.who = ident
self.type = type
self.content = content
@staticmethod
def transform(nl: NotifyLetter) -> Optional['Notify']:
type = nl.notifyType()
# type must in this Dict
assert(type in FROM_LETTER_TO_NOTIFY)
return FROM_LETTER_TO_NOTIFY[type](nl)
@abc.abstractstaticmethod
def fromLetter(nl: NotifyLetter) -> Optional['Notify']:
"""
Generate Notify from NotifyLetter
"""
@abc.abstractmethod
def toLetter(self) -> NotifyLetter:
"""
Generate NotifyLetter from Notify
"""
class WSCNotify(Notify):
ONLINE = "0"
WAITING = "1"
OFFLINE = "2"
DIRTY = "3"
CLEAN = "4"
def __init__(self, ident: str, state: str) -> None:
Notify.__init__(
self, ident, WORKER_STATE_CHANGED, {'state': state})
def fromWho(self) -> str:
return self.who
def state(self) -> str:
return self.content['state']
@staticmethod
def fromLetter(nl: NotifyLetter) -> Optional['WSCNotify']:
content = nl.notifyContent()
if 'state' not in content:
return None
return WSCNotify(nl.notifyFrom(), content['state'])
def toLetter(self) -> NotifyLetter:
return NotifyLetter(self.who, self.type, self.content)
# Dict that contain fromLetters
FROM_LETTER_TO_NOTIFY = {
WORKER_STATE_CHANGED: WSCNotify.fromLetter
}
| 29.806452 | 79 | 0.682179 | 353 | 2,772 | 5.280453 | 0.424929 | 0.04721 | 0.02897 | 0.02897 | 0.05794 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004231 | 0.232684 | 2,772 | 92 | 80 | 30.130435 | 0.87212 | 0.424964 | 0 | 0.093023 | 0 | 0 | 0.032131 | 0 | 0 | 0 | 0 | 0 | 0.023256 | 1 | 0.209302 | false | 0 | 0.069767 | 0.069767 | 0.581395 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
477f4344284c797cc3caca0564ad5357c1e3d870 | 1,239 | py | Python | R_ev3dev/help.py | thomasvolk/R_ev3dev | 53b8c83af49e88eb4766deea0a690c55d1304d6a | [
"Apache-2.0"
] | null | null | null | R_ev3dev/help.py | thomasvolk/R_ev3dev | 53b8c83af49e88eb4766deea0a690c55d1304d6a | [
"Apache-2.0"
] | null | null | null | R_ev3dev/help.py | thomasvolk/R_ev3dev | 53b8c83af49e88eb4766deea0a690c55d1304d6a | [
"Apache-2.0"
] | null | null | null | from R_ev3dev.interpreter import Command
from R_ev3dev import version
class Version(Command):
""" show version """
def invoke(self, interpreter_context, args):
return version.VERSION
class Help(Command):
""" show help """
def _doc(self, item):
return item.__doc__.strip() if item.__doc__ else ''
def _line(self, item):
return "{} - {}".format(item.name, self._doc(item).split("\n")[0])
def _overview(self, commands):
command_lines = [self._line(c) for c in commands]
return """---
R_ev3 protocol language version {}
author: Thomas Volk
license: Apache License Version 2.0
source: https://github.com/thomasvolk/R_ev3dev
possible commands:
{}
use help <command> for details
---""".format(version.VERSION, '\n '.join(command_lines))
def _details(self, command):
return """---
{}
{}
---""".format(command.name, self._doc(command))
def invoke(self, interpreter_context, args):
if len(args) > 0:
cmd = args[0]
return self._details(interpreter_context.interpreter.commands[cmd])
else:
return self._overview(interpreter_context.interpreter.commands.values())
| 23.377358 | 84 | 0.626312 | 146 | 1,239 | 5.130137 | 0.369863 | 0.096128 | 0.029373 | 0.064085 | 0.093458 | 0.093458 | 0 | 0 | 0 | 0 | 0 | 0.009524 | 0.237288 | 1,239 | 52 | 85 | 23.826923 | 0.783069 | 0.018563 | 0 | 0.21875 | 0 | 0 | 0.224626 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.1875 | false | 0 | 0.0625 | 0.125 | 0.53125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
4784404a17f8a62dd08e724089d9251399e3ef89 | 1,816 | py | Python | samplers/__init__.py | kilsenp/person-multi-task-dataset | 2f186cafa3db2c77d8c6c4309b2cadc13d4f92ab | [
"MIT"
] | 4 | 2020-10-08T03:31:36.000Z | 2021-03-06T08:06:23.000Z | reid/scripts/triplet_reid/samplers/__init__.py | VisualComputingInstitute/CROWDBOT_perception | df98f3f658c39fb3fa4ac0456f1214f7918009f6 | [
"MIT"
] | 7 | 2021-06-08T20:55:10.000Z | 2022-02-10T00:38:32.000Z | reid/scripts/triplet_reid/samplers/__init__.py | VisualComputingInstitute/CROWDBOT_perception | df98f3f658c39fb3fa4ac0456f1214f7918009f6 | [
"MIT"
] | null | null | null | from utils import import_submodules
_registered_single_sampler = {}
_registered_multi_sampler = {}
def register_multi_sampler(name):
"""
A decorator with a parameter.
This decorator returns a function which the class is passed.
"""
name = name.lower()
def _register(sampler):
if name in _registered_multi_sampler:
raise ValueError("Name {} already chosen, choose a different name.".format(name))
_registered_multi_sampler[name] = sampler
return sampler
return _register
def register_single_sampler(name):
"""
A decorator with a parameter.
This decorator returns a function which the class is passed.
"""
name = name.lower()
def _register(sampler):
if name in _registered_single_sampler:
raise ValueError("Name {} already chosen, choose a different name.".format(name))
_registered_single_sampler[name] = sampler
return sampler
return _register
def load_multi_sampler_class(name):
lower_name = name.lower()
if lower_name not in _registered_multi_sampler:
raise ValueError("Model {} not found: {}".format(name, list(_registered_multi_sampler.keys())))
return _registered_multi_sampler[lower_name]
def load_single_sampler_class(name):
lower_name = name.lower()
if lower_name not in _registered_single_sampler:
raise ValueError("Model {} not found: {}".format(name, list(_registered_single_sampler.keys())))
return _registered_single_sampler[lower_name]
def get_all_single_samplers():
return list(_registered_single_sampler.keys())
def get_all_multi_samplers():
return list(_registered_multi_sampler.keys())
def get_all_samplers():
return get_all_single_samplers() + get_all_multi_samplers()
import_submodules('samplers')
| 28.825397 | 104 | 0.721916 | 225 | 1,816 | 5.48 | 0.191111 | 0.094891 | 0.130576 | 0.034063 | 0.725061 | 0.634225 | 0.616383 | 0.616383 | 0.538524 | 0.538524 | 0 | 0 | 0.192181 | 1,816 | 62 | 105 | 29.290323 | 0.840491 | 0.09967 | 0 | 0.333333 | 0 | 0 | 0.092732 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.055556 | 0.083333 | 0.555556 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
47a704323309110e86052ccc29bb3e9715cd4c35 | 329 | py | Python | apriltags2_ros/tests/test_data_adapter_utils.py | selcukercan/apriltag2_ros | 85e02cbbab42ff639d54e67efd886a43ab10e7c3 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | apriltags2_ros/tests/test_data_adapter_utils.py | selcukercan/apriltag2_ros | 85e02cbbab42ff639d54e67efd886a43ab10e7c3 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | apriltags2_ros/tests/test_data_adapter_utils.py | selcukercan/apriltag2_ros | 85e02cbbab42ff639d54e67efd886a43ab10e7c3 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #!/usr/bin/env python
import unittest, rosunit, rospy
import numpy as np
import math
import tf.transformations as tr
from apriltags2_ros_post_process.data_adapter_utils import *
class DataAdapterUtils(unittest.TestCase):
if __name__ == '__main__':
rosunit.unitrun('apriltags2_ros', 'data_adapter_utils', DataAdapterUtils)
| 25.307692 | 77 | 0.805471 | 43 | 329 | 5.790698 | 0.697674 | 0.104418 | 0.128514 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006826 | 0.109422 | 329 | 12 | 78 | 27.416667 | 0.843003 | 0.06079 | 0 | 0 | 0 | 0 | 0.12987 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.625 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
47b2fc2a619d0c6eca19f8a56cd77dbaf6fcb98c | 241 | py | Python | pycausal_explorer/datasets/_filenames.py | gotolino/pycausal-explorer | 250309674c0657b9ccd318aea0893827da1badfe | [
"MIT"
] | 3 | 2022-01-28T12:32:43.000Z | 2022-02-12T23:26:52.000Z | pycausal_explorer/datasets/_filenames.py | gotolino/pycausal-explorer | 250309674c0657b9ccd318aea0893827da1badfe | [
"MIT"
] | 8 | 2022-02-06T19:34:47.000Z | 2022-03-11T17:24:23.000Z | pycausal_explorer/datasets/_filenames.py | gotolino/pycausal-explorer | 250309674c0657b9ccd318aea0893827da1badfe | [
"MIT"
] | null | null | null | from os import path
ROOT_DIR = path.dirname(path.abspath(__file__))
DATASETS_PATH = "data"
IHDP_SIMULATED_OUTCOMES_CSV_FILE = "ihdp_observation_data_simulated_outcomes.csv"
LALONDE_NSW_JOBS_CSV_FILE = "nsw_jobs_lalonde_exp_psid_1978.csv"
| 26.777778 | 81 | 0.846473 | 37 | 241 | 4.891892 | 0.594595 | 0.187845 | 0.220994 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018018 | 0.078838 | 241 | 8 | 82 | 30.125 | 0.797297 | 0 | 0 | 0 | 0 | 0 | 0.340249 | 0.323651 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.2 | 0 | 0.2 | 0 | 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 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
47b65098bc1a906f5524396ad3a66ff7dff07cc6 | 1,487 | py | Python | latin2cyrillic.py | 12yy296/latin2cyrillic-alphabet-converter | 4aabc2b40408bb3f35cc4bab200f7999b8dfeedd | [
"WTFPL"
] | null | null | null | latin2cyrillic.py | 12yy296/latin2cyrillic-alphabet-converter | 4aabc2b40408bb3f35cc4bab200f7999b8dfeedd | [
"WTFPL"
] | null | null | null | latin2cyrillic.py | 12yy296/latin2cyrillic-alphabet-converter | 4aabc2b40408bb3f35cc4bab200f7999b8dfeedd | [
"WTFPL"
] | null | null | null | test_text="Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz Zhzh Chch Shsh Yoyo Yaya "
replace_table=[
["by","бай"],
["By","Бай"],
["The","Дзе"],
["the","дзе"],
["t'h","дз"],
["T'h","Дз"],
["too","ту"],
["Too","Ту"],
["to","ту"],
["To","Ту"],
["ss","с"],
["cc","кс"],
["Wh","У"],
["pp","п"],
["tt","т"],
["tion","шен"],
["ph","ф"],
["Ph","Ф"],
["q","ку"],
["Q","Ку"],
["zh","ж"],
["Zh","Ж"],
["sh","ш"],
["Sh","Ш"],
["ch","ч"],
["Ch","Ч"],
["you","ю"],
["You","Ю"],
["yo","ю"],
["Yo","Ю"],
["iu","ю"],
["iu","Ю"],
["I ","Я "],
["I'm","Я'м"],
["ya","я"],
["Ya","Я"],
["a","а"],["b","б"],["c","с"],["d","д"],["e","е"],["f","ф"],["g","г"],["h","х"],["i","и"],["j","ж"],["k","к"],["l","л"],["m","м"],["n","н"],["o","о"],["p","п"],["r","р"],["s","с"],["t","т"],["u","у"],["v","в"],["w","у"],["x","с"],["y","й"],["z","з"],["A","А"],["B","Б"],["C","С"],["D","Д"],["E","Е"],["F","Ф"],["G","Г"],["H","Х"],["I","И"],["J","Ж"],["K","К"],["L","Л"],["M","М"],["N","Н"],["O","О"],["P","П"],["R","Р"],["S","С"],["T","Т"],["U","У"],["V","В"],["W","У"],["X","С"],["Y","Й"],["Z","З"],
["''",""],
['"',""],
[" ",""]
]
def main():
cyrillic=input()
for group in replace_table:
cyrillic=cyrillic.replace(group[0],group[1])
print(cyrillic)
if __name__=="__main__":
while True:
main() | 26.553571 | 504 | 0.30195 | 235 | 1,487 | 1.86383 | 0.519149 | 0.054795 | 0.018265 | 0.018265 | 0.228311 | 0.228311 | 0.228311 | 0.228311 | 0.228311 | 0.228311 | 0 | 0.001668 | 0.193679 | 1,487 | 56 | 505 | 26.553571 | 0.363636 | 0 | 0 | 0 | 0 | 0.019608 | 0.238575 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.019608 | false | 0 | 0 | 0 | 0.019608 | 0.019608 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
47bea55b879cdbb121c11d2478ee0248a9d90cda | 337 | py | Python | Chapter10/hillar_django_restful_10_02/restful01/drones/custompagination.py | weiliy/Django-RESTful-Web-Services | 0b26a84ec8005c6a2cef61671b6d009f0780a9cc | [
"MIT"
] | 95 | 2018-01-22T21:35:21.000Z | 2022-03-30T10:13:35.000Z | Chapter10/hillar_django_restful_10_02/restful01/drones/custompagination.py | weiliy/Django-RESTful-Web-Services | 0b26a84ec8005c6a2cef61671b6d009f0780a9cc | [
"MIT"
] | 6 | 2020-03-24T16:37:46.000Z | 2021-06-10T21:04:36.000Z | Chapter10/hillar_django_restful_10_02/restful01/drones/custompagination.py | weiliy/Django-RESTful-Web-Services | 0b26a84ec8005c6a2cef61671b6d009f0780a9cc | [
"MIT"
] | 73 | 2018-01-24T02:38:17.000Z | 2022-01-23T21:02:41.000Z | """
Book: Django RESTful Web Services
Author: Gaston C. Hillar - Twitter.com/gastonhillar
Publisher: Packt Publishing Ltd. - http://www.packtpub.com
"""
from rest_framework.pagination import LimitOffsetPagination
class LimitOffsetPaginationWithUpperBound(LimitOffsetPagination):
# Set the maximum limit value to 8
max_limit = 8
| 30.636364 | 65 | 0.789318 | 39 | 337 | 6.769231 | 0.897436 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006849 | 0.133531 | 337 | 10 | 66 | 33.7 | 0.89726 | 0.52819 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
47c581f3e72d4fad8d500eb73eb52b12cca9d227 | 3,907 | py | Python | api/app/users/models.py | danielamassiceti/Baobab | 354a0cf5ad05a9fb42a0522e7f212f2f5c351390 | [
"Apache-2.0"
] | null | null | null | api/app/users/models.py | danielamassiceti/Baobab | 354a0cf5ad05a9fb42a0522e7f212f2f5c351390 | [
"Apache-2.0"
] | null | null | null | api/app/users/models.py | danielamassiceti/Baobab | 354a0cf5ad05a9fb42a0522e7f212f2f5c351390 | [
"Apache-2.0"
] | null | null | null | from datetime import datetime, timedelta
from app import db, bcrypt
from app.utils.misc import make_code
def expiration_date():
return datetime.now() + timedelta(days=1)
class AppUser(db.Model):
id = db.Column(db.Integer(), primary_key=True)
email = db.Column(db.String(255), unique=True, nullable=False)
firstname = db.Column(db.String(100), nullable=False)
lastname = db.Column(db.String(100), nullable=False)
user_title = db.Column(db.String(20), nullable=False)
nationality_country_id = db.Column(db.Integer(), db.ForeignKey('country.id'), nullable=False)
residence_country_id = db.Column(db.Integer(), db.ForeignKey('country.id'), nullable=False)
user_ethnicity = db.Column(db.String(50), nullable=False)
user_gender = db.Column(db.String(20), nullable=False)
affiliation = db.Column(db.String(255), nullable=False)
department = db.Column(db.String(255), nullable=False)
user_disability = db.Column(db.String(255), nullable=False)
user_category_id = db.Column(db.Integer(), db.ForeignKey('user_category.id'), nullable=False)
password = db.Column(db.String(255), nullable=False)
active = db.Column(db.Boolean(), nullable=False)
is_admin = db.Column(db.Boolean(), nullable=False)
is_deleted = db.Column(db.Boolean(), nullable=False)
deleted_datetime_utc = db.Column(db.DateTime(), nullable=True)
nationality_country = db.relationship('Country', foreign_keys=[nationality_country_id])
residence_country = db.relationship('Country', foreign_keys=[residence_country_id])
user_category = db.relationship('UserCategory')
def __init__(self,
email,
firstname,
lastname,
user_title,
nationality_country_id,
residence_country_id,
user_ethnicity,
user_gender,
affiliation,
department,
user_disability,
user_category_id,
password,
is_admin=False):
self.email = email
self.firstname = firstname
self.lastname = lastname
self.user_title = user_title
self.nationality_country_id = nationality_country_id
self.residence_country_id = residence_country_id
self.user_ethnicity = user_ethnicity
self.user_gender = user_gender
self.affiliation = affiliation
self.department = department
self.user_disability = user_disability
self.user_category_id = user_category_id
self.set_password(password)
self.active = True
self.is_admin = is_admin
self.is_deleted = False
self.deleted_datetime_utc = None
def set_password(self, password):
self.password = bcrypt.generate_password_hash(password)
def deactivate(self):
self.active = False
class PasswordReset(db.Model):
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(db.Integer(), db.ForeignKey('app_user.id'))
code = db.Column(db.String(255), unique=True, default=make_code)
date = db.Column(db.DateTime(), default=expiration_date)
user = db.relationship(AppUser)
db.UniqueConstraint('user_id', 'code', name='uni_user_code')
def __init__(self, user):
self.user = user
class Country(db.Model):
def __init__(self, name):
self.name = name
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(100), nullable=False)
class UserCategory(db.Model):
def __init__(self, name, description=None, group=None):
self.name = name
self.description = description
self.group = group
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(100), nullable=False)
description = db.Column(db.String(500))
group = db.Column(db.String(100)) | 36.858491 | 97 | 0.663681 | 483 | 3,907 | 5.175983 | 0.15735 | 0.0896 | 0.112 | 0.096 | 0.4196 | 0.3744 | 0.3136 | 0.164 | 0.1352 | 0.1352 | 0 | 0.014163 | 0.222933 | 3,907 | 106 | 98 | 36.858491 | 0.809289 | 0 | 0 | 0.093023 | 0 | 0 | 0.024821 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.081395 | false | 0.069767 | 0.034884 | 0.011628 | 0.546512 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
47c863077ba428de564f49553125315439060107 | 7,217 | py | Python | testing/test_hookcaller.py | tlambert-forks/napari-plugin-engine | 79ee20ff57061f3a4c592601a7bc3faae398cf7b | [
"MIT"
] | 6 | 2021-01-04T10:43:34.000Z | 2021-12-20T08:37:30.000Z | testing/test_hookcaller.py | tlambert-forks/napari-plugin-engine | 79ee20ff57061f3a4c592601a7bc3faae398cf7b | [
"MIT"
] | 47 | 2020-06-26T02:54:24.000Z | 2022-03-21T19:54:51.000Z | testing/test_hookcaller.py | tlambert-forks/napari-plugin-engine | 79ee20ff57061f3a4c592601a7bc3faae398cf7b | [
"MIT"
] | 8 | 2020-04-26T23:10:06.000Z | 2021-08-13T18:07:09.000Z | import pytest
from napari_plugin_engine import (
HookImplementation,
HookImplementationMarker,
HookSpecification,
HookSpecificationMarker,
PluginValidationError,
)
example_hookspec = HookSpecificationMarker("example")
example_implementation = HookImplementationMarker("example")
@pytest.fixture
def hook_caller(pm):
class Hooks:
@example_hookspec
def method1(self, arg):
pass
pm.add_hookspecs(Hooks)
return pm.hook.method1
@pytest.fixture
def addmeth(hook_caller):
def addmeth(tryfirst=False, trylast=False, hookwrapper=False):
def wrap(func):
example_implementation(
tryfirst=tryfirst, trylast=trylast, hookwrapper=hookwrapper
)(func)
hook_caller._add_hookimpl(
HookImplementation(func, **func.example_impl)
)
return func
return wrap
return addmeth
def funcs(hookmethods):
return [hookmethod.function for hookmethod in hookmethods]
def test_adding_nonwrappers(hook_caller, addmeth):
@addmeth()
def method1():
pass
@addmeth()
def method2():
pass
@addmeth()
def method3():
pass
assert funcs(hook_caller._nonwrappers) == [method1, method2, method3]
def test_adding_nonwrappers_trylast(hook_caller, addmeth):
@addmeth()
def method1_middle():
pass
@addmeth(trylast=True)
def method1():
pass
@addmeth()
def method1_b():
pass
assert funcs(hook_caller._nonwrappers) == [
method1,
method1_middle,
method1_b,
]
def test_adding_nonwrappers_trylast3(hook_caller, addmeth):
@addmeth()
def method1_a():
pass
@addmeth(trylast=True)
def method1_b():
pass
@addmeth()
def method1_c():
pass
@addmeth(trylast=True)
def method1_d():
pass
assert funcs(hook_caller._nonwrappers) == [
method1_d,
method1_b,
method1_a,
method1_c,
]
def test_adding_nonwrappers_trylast2(hook_caller, addmeth):
@addmeth()
def method1_middle():
pass
@addmeth()
def method1_b():
pass
@addmeth(trylast=True)
def method1():
pass
assert funcs(hook_caller._nonwrappers) == [
method1,
method1_middle,
method1_b,
]
def test_adding_nonwrappers_tryfirst(hook_caller, addmeth):
@addmeth(tryfirst=True)
def method1():
pass
@addmeth()
def method1_middle():
pass
@addmeth()
def method1_b():
pass
assert funcs(hook_caller._nonwrappers) == [
method1_middle,
method1_b,
method1,
]
def test_adding_wrappers_ordering(hook_caller, addmeth):
@addmeth(hookwrapper=True)
def method1():
pass
@addmeth()
def method1_middle():
pass
@addmeth(hookwrapper=True)
def method3():
pass
assert funcs(hook_caller._nonwrappers) == [method1_middle]
assert funcs(hook_caller._wrappers) == [method1, method3]
def test_adding_wrappers_ordering_tryfirst(hook_caller, addmeth):
@addmeth(hookwrapper=True, tryfirst=True)
def method1():
pass
@addmeth(hookwrapper=True)
def method2():
pass
assert hook_caller._nonwrappers == []
assert funcs(hook_caller._wrappers) == [method2, method1]
def test_hookspec(pm):
class HookSpecification:
@example_hookspec()
def he_myhook1(arg1):
pass
@example_hookspec(firstresult=True)
def he_myhook2(arg1):
pass
@example_hookspec(firstresult=False)
def he_myhook3(arg1):
pass
pm.add_hookspecs(HookSpecification)
assert not pm.hook.he_myhook1.spec.firstresult
assert pm.hook.he_myhook2.spec.firstresult
assert not pm.hook.he_myhook3.spec.firstresult
def test_hookspec_reserved_argnames(pm):
"""Certain argument names are reserved and cannot be used in specs."""
class HookSpecificationA:
@example_hookspec()
def he_myhook1(_plugin):
pass
class HookSpecificationB:
@example_hookspec()
def he_myhook1(_skip_impls):
pass
for cls in (HookSpecificationA, HookSpecificationB):
with pytest.raises(ValueError):
pm.add_hookspecs(cls)
@pytest.mark.parametrize(
"name", ["hookwrapper", "optionalhook", "tryfirst", "trylast"]
)
@pytest.mark.parametrize("val", [True, False])
def test_hookimpl(name, val):
@example_implementation(**{name: val})
def he_myhook1(arg1):
pass
if val:
assert he_myhook1.example_impl.get(name)
else:
assert not hasattr(he_myhook1, name)
def test_hookrelay_registry(pm):
"""Verify hook caller instances are registered by name onto the relay
and can be likewise unregistered."""
class Api:
@example_hookspec
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
hook = pm.hook
assert hasattr(hook, "hello")
assert repr(hook.hello).find("hello") != -1
class Plugin:
@example_implementation
def hello(self, arg):
return arg + 1
plugin = Plugin()
pm.register(plugin)
out = hook.hello(arg=3)
assert out == [4]
assert not hasattr(hook, "world")
pm.unregister(plugin)
assert hook.hello(arg=3) == []
def test_hookrelay_registration_by_specname(pm):
"""Verify hook caller instances may also be registered by specifying a
specname option to the hookimpl"""
class Api:
@example_hookspec
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
hook = pm.hook
assert hasattr(hook, "hello")
assert len(pm.hook.hello.get_hookimpls()) == 0
class Plugin:
@example_implementation(specname="hello")
def foo(self, arg):
return arg + 1
plugin = Plugin()
pm.register(plugin)
out = hook.hello(arg=3)
assert out == [4]
def test_hookrelay_registration_by_specname_raises(pm):
"""Verify using specname still raises the types of errors during registration as it
would have without using specname."""
class Api:
@example_hookspec
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
# make sure a bad signature still raises an error when using specname
class Plugin:
@example_implementation(specname="hello")
def foo(self, arg, too, many, args):
return arg + 1
with pytest.raises(PluginValidationError):
pm.register(Plugin())
# make sure check_pending still fails if specname doesn't have a
# corresponding spec. EVEN if the function name matches one.
class Plugin2:
@example_implementation(specname="bar")
def hello(self, arg):
return arg + 1
pm.register(Plugin2())
with pytest.raises(PluginValidationError):
pm.check_pending()
def test_legacy_specimpl_opt():
impl = HookImplementation(lambda x: x)
assert impl.opts
spec = HookSpecification(type("Hook", (), {'x': lambda x: x}), 'x')
assert spec.opts
| 22.413043 | 87 | 0.63683 | 803 | 7,217 | 5.554172 | 0.209215 | 0.047085 | 0.038117 | 0.037668 | 0.471973 | 0.348655 | 0.276233 | 0.248206 | 0.245516 | 0.206502 | 0 | 0.014567 | 0.267563 | 7,217 | 321 | 88 | 22.482866 | 0.829171 | 0.083968 | 0 | 0.554585 | 0 | 0 | 0.019368 | 0 | 0 | 0 | 0 | 0 | 0.104803 | 1 | 0.235808 | false | 0.122271 | 0.008734 | 0.021834 | 0.331878 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
47ca4440334cccebbf64783bf30e97362e421d4c | 513 | py | Python | book_store/book_outlet/admin.py | goulartdev/udemy-django-course | f39ab36aacdf47d19f8c286c317cc54d8358dadc | [
"MIT"
] | null | null | null | book_store/book_outlet/admin.py | goulartdev/udemy-django-course | f39ab36aacdf47d19f8c286c317cc54d8358dadc | [
"MIT"
] | null | null | null | book_store/book_outlet/admin.py | goulartdev/udemy-django-course | f39ab36aacdf47d19f8c286c317cc54d8358dadc | [
"MIT"
] | null | null | null | from django.contrib import admin
from .models import Address, Book, Author, Country
class BookAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
list_filter = ("author", "is_bestseller", "rating")
list_display = ("title", "author", "is_bestseller", "rating")
class AuthorAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
admin.site.register(Book, BookAdmin)
admin.site.register(Author, AuthorAdmin)
admin.site.register(Address)
admin.site.register(Country)
| 27 | 65 | 0.727096 | 59 | 513 | 6.220339 | 0.457627 | 0.098093 | 0.185286 | 0.179837 | 0.201635 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.120858 | 513 | 18 | 66 | 28.5 | 0.813747 | 0 | 0 | 0 | 0 | 0 | 0.140351 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
47de0c1646fbebfd195d7ab751bd5f59438972f3 | 3,769 | py | Python | lib/download.py | danijanak/org-danipar-mwsrvinstall | f2388f445edab6fc5f4aa598d3696f69a7591604 | [
"Apache-2.0"
] | null | null | null | lib/download.py | danijanak/org-danipar-mwsrvinstall | f2388f445edab6fc5f4aa598d3696f69a7591604 | [
"Apache-2.0"
] | null | null | null | lib/download.py | danijanak/org-danipar-mwsrvinstall | f2388f445edab6fc5f4aa598d3696f69a7591604 | [
"Apache-2.0"
] | null | null | null | import logging
import sys
import os
import zipfile
import stat
import urllib2 ##remove this for python3
##import urllib.request use this for python3
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt="")
logger = logging.getLogger("swinstall.download")
class Download():
def __init__(self, url, fileName, target_loc, realm=None,user=None, passwd=None):
if fileName:
file = os.path.join(target_loc, fileName)
if not os.path.isfile(file):
Download.software(url, target_loc, realm=realm, user=user, passwd=passwd)
Download.extract(file, target_loc)
Download.setPermissions(target_loc)
else:
logger.exception("fileName not found in configuration")
@staticmethod
def setPermissions(target_loc):
logger.info("Setting up permissions on %s", target_loc)
for dirpath,dirs,fileNames in os.walk(target_loc):
for fileName in fileNames:
file = os.path.join(dirpath, fileName)
os.chmod(file, stat.S_IRWXU)
@staticmethod
def extract(file, target_loc):
logger.info("Extracting software %s. please wait...", file)
if file.rsplit('.')[-1] == 'zip':
if not os.path.isdir(file.rstrip('.zip')):
if zipfile.is_zipfile(file):
logger.info("Zip file found. please wait...")
zip = zipfile.ZipFile(file)
zip.extractall(path=target_loc)
logger.info("Software extracted to %s", target_loc)
else:
logger.debug("Software %s already found. Skipping unzip ...", file)
else:
logger.warning("File extension not supported for file %s", file)
@staticmethod
def software(url, dl_loc, realm=None, user=None, passwd=None):
## auth
if user != None and passwd != None:
auth = urllib2.HTTPBasicAuthHandler()
auth.add_password(
realm=realm,
uri=url,
user='%s'%user,
passwd=passwd
)
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
try:
fileName = url.split('/')[-1]
data = None
handle = urllib2.urlopen(url)
if not os.path.isdir(dl_loc):
os.mkdir(dl_loc)
fo = open(os.path.join(dl_loc, fileName), "wb")
size = int(handle.info()["Content-Length"])
type = str(handle.info()["Content-Type"])
dlSize = 0
blockSize = 8*1024
previous_percent = 0
while True:
buffer = handle.read(blockSize)
dlSize += len(buffer)
if not buffer:
break
fo.write(buffer)
percent = int(dlSize*100/size)
if previous_percent != percent:
previous_percent = percent
sys.stdout.write("\r%2d%% - [%d,%s]" %(percent, dlSize, fileName))
fo.close()
sys.stdout.write("\n")
logger.info("%s - successfully downloaded", os.path.join(dl_loc,fileName))
except urllib2.HTTPError, e:
if e.code == 401:
logger.exception("Authorization Failed - %s" %(e.code))
else:
logger.exception("Download failed")
except:
logger.exception("Download failed")
finally:
try:
fo.close()
except:
pass
| 38.070707 | 89 | 0.530114 | 397 | 3,769 | 4.962217 | 0.360202 | 0.050254 | 0.020305 | 0.016751 | 0.070051 | 0.053807 | 0.030457 | 0 | 0 | 0 | 0 | 0.011199 | 0.360308 | 3,769 | 98 | 90 | 38.459184 | 0.80589 | 0.018573 | 0 | 0.166667 | 0 | 0 | 0.121852 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.077778 | 0.066667 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
47ef688674e9e5e45e900ecb9b839c1fe3e6e874 | 852 | py | Python | src/raritan/rpc/idl/__init__.py | vhirtzel/apc_reboot | 06ab4ef72029b09339a04266970d1546004c9dbe | [
"MIT"
] | 1 | 2021-04-29T23:04:17.000Z | 2021-04-29T23:04:17.000Z | raritan/rpc/idl/__init__.py | vhirtzel/desktop_reboot | 553795c1727dedf4532dc97922201df3e9e2ad1e | [
"MIT"
] | null | null | null | raritan/rpc/idl/__init__.py | vhirtzel/desktop_reboot | 553795c1727dedf4532dc97922201df3e9e2ad1e | [
"MIT"
] | 2 | 2020-06-20T16:21:23.000Z | 2021-09-28T19:04:44.000Z | # SPDX-License-Identifier: BSD-3-Clause
#
# Copyright 2020 Raritan Inc. All rights reserved.
#
# This is an auto-generated file.
#
# Section generated by IdlC from "Event.idl"
#
import raritan.rpc
from raritan.rpc import Interface, Structure, ValueObject, Enumeration, typecheck, DecodeException
# value object
class Event(ValueObject):
idlType = "idl.Event:1.0.0"
def __init__(self, source):
typecheck.is_remote_obj(source, AssertionError)
self.source = source
def encode(self):
json = {}
json['source'] = Interface.encode(self.source)
return json
@classmethod
def decode(cls, json, agent):
obj = cls(
source = Interface.decode(json['source'], agent),
)
return obj
def listElements(self):
elements = ["source"]
return elements
| 22.421053 | 98 | 0.646714 | 98 | 852 | 5.561224 | 0.561224 | 0.055046 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012481 | 0.247653 | 852 | 37 | 99 | 23.027027 | 0.837754 | 0.204225 | 0 | 0 | 1 | 0 | 0.049401 | 0 | 0 | 0 | 0 | 0 | 0.05 | 1 | 0.2 | false | 0 | 0.1 | 0 | 0.55 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
9a000b18e78d1a73d8a77930cf00fc6c825669eb | 9,447 | py | Python | endas/localization/domain.py | martingu11/endas | e58be74e844efa14cbd86aba5e76dbc44fe690de | [
"MIT"
] | 1 | 2020-05-13T13:14:09.000Z | 2020-05-13T13:14:09.000Z | endas/localization/domain.py | martingu11/endas | e58be74e844efa14cbd86aba5e76dbc44fe690de | [
"MIT"
] | 16 | 2020-07-13T14:51:01.000Z | 2020-07-14T08:59:16.000Z | endas/localization/domain.py | martingu11/endas | e58be74e844efa14cbd86aba5e76dbc44fe690de | [
"MIT"
] | 1 | 2020-03-18T10:37:45.000Z | 2020-03-18T10:37:45.000Z | """
Domain-based localization of the analysis update.
"""
__all__ = [
'StateSpacePartitioning', 'GenericStateSpace1d', 'DomainLocalization'
]
from abc import ABCMeta, abstractmethod
import math
import numpy as np
import endas.localization
class StateSpacePartitioning(metaclass=ABCMeta):
"""
Abstract base class for state space partitioning schemes.
Implementations of this abstract base define how to partition the state space into local domains for localized
analysis.
"""
@property
@abstractmethod
def num_domains(self):
"""
Returns the number of local domains in the state space partitioning.
"""
pass
@abstractmethod
def get_local_observations(self, domain_id, z_coords, taper_fn):
"""
Locates observations to be used for local analysis of the given domain.
Args:
domain_id : Index of the domain for which observations should be retrieved. Domain indexes start at 0.
z_coords : Abstract description of the locations of observations in the observation vector.
taper_fn : Tapering function that defines the localization radius.
Returns:
Tuple ``(z_local, d)`` where ``z`` is a flat array of indices into the observation vector and ``d`` are
the distances of each selected observation from the domain.
The interpretation of ``z_coords`` is entirely up to the implementing class to decide and ``TypeError`` should
be raised if an unsupported type is passed. Please see the documentation of implementing classes for information
on what types of objects can be passed via ``z_coords``.
"""
pass
@abstractmethod
def get_local_state_size(self, domain_id):
"""
Returns the state vector size for the given domain.
Args:
domain_id : Index of the domain whose state size should be returned. Domain indexes start at 0.
"""
pass
@abstractmethod
def get_local_state(self, domain_id, xg):
"""
Returns local state vector (or ensemble of state vectors) for the given domain.
Args:
domain_id : Index of the domain whose local state vector be returned. Domain indexes start at 0.
xg : Global state vector or ensemble (ensemble members stored in columns).
"""
pass
@abstractmethod
def put_local_state(self, domain_id, xl, xg):
"""
Writes local state vector (or ensemble of state vectors) for the given domain back to the global state vector.
Args:
domain_id : Index of the domain whose local state vector be stored. Domain indexes start at 0.
xl : Local state vector or ensemble
xg : Global state vector or ensemble to copy the local data to
"""
pass
class GenericStateSpace1d(StateSpacePartitioning):
"""
Analysis localization assuming generic state space.
This a generic form of domain-based analysis localization where each state space variable is assigned its own
local domain. The local analysis update is therefore performed for each state variable individually. Under this
scheme, the indexes of state vector elements also act as their respective "coordinates". Furthermore, observations
are assumed to be directly related to state vector elements and their coordinates are also expressed as the indexes
of the corresponding state vector elements.
Args:
n : The number of elements in the state vector
.. note::
Please note that this localization scheme is rather arbitrary and is unlikely to be suitable for any real
geophysical system. This is especially true if non-trivial observation operators are used or in case of
multivariate data assimilation. The primarily purpose of ``GenericStateSpace1d`` is for testing analysis
localization on synthetic problems.
The localization scheme is not suitable for large state spaces as the number of local domains is equal to the
size of the state vector. This will make the localized analysis very slow for large *n*.
"""
def __init__(self, n):
assert n > 0
self._n = n
@property
def num_domains(self):
# Under this scheme each state variable has its own local domain
return self._n
def get_local_observations(self, domain_id, z_coords, taper_fn):
assert isinstance(z_coords, np.ndarray)
assert domain_id >= 0 and domain_id <= self.num_domains
r = int(math.ceil(taper_fn.support_range))
d_min = max(0, domain_id - r)
d_max = min(self._n, domain_id + r)
selected = np.where((z_coords > d_min) & (z_coords < d_max))[0]
selcoords = z_coords[selected]
dist = np.abs(np.subtract(selcoords, domain_id), dtype=np.double)
return selected, dist
def get_local_state_size(self, domain_id):
assert domain_id >= 0 and domain_id <= self.num_domains
return 1
def get_local_state(self, domain_id, xg):
assert domain_id >= 0 and domain_id <= self.num_domains
return xg[domain_id]
def put_local_state(self, domain_id, xl, xg):
assert domain_id >= 0 and domain_id <= self.num_domains
xg[domain_id] = xl
class DomainLocalization:
"""
Domain-based localization of the analysis update.
This is a general-purpose implementation of the :ref:`domain localization scheme<localization_domain>`.
Domain localization scheme works by partitioning the global state space into a set of disjoint *local domains*.
The analysis update is then done for each local domain individually and the local domains are assembled back
into a global state/ensemble afterwards.
Args:
cs : Coordinate system of the grid. Must be an instance of :class:`endas.localization.CoordinateSystem`
taper_fn : Taper function that defines the localization radius. Must be an instance of
:class:`endas.localization.TaperFn` or ``None`` (see notes below).
on_local_R_needed : Called if this class does not know how to construct localized observation error covariance
operator from the global one.
The tapering function (``taper_fn``) is required since it defines the localization radius. It is allowed to pass
``None`` during construction but the taper function must be set (via ``set_taper_fn()``) before the first analysis
update at the latest. It is allowed to replace the taper function before each analysis update with a different one.
One of the steps required from the domain localization is to construct localized versions of the global observation
operator and the observation error covariance operator. The localized versions are subsets of the global operators
that only represent observations used in the local analysis. Localization of the observation operator is done by the
:meth:`DomainLocalization.get_local_H` method, which relies on ``ObservationOperator.localize()`` being implemented.
"""
def __init__(self, ssp, taper_fn=None):
assert ssp is not None
assert isinstance(ssp, StateSpacePartitioning)
self._ssp = ssp
self._taper_fn = None
if taper_fn is not None: self.set_taper_fn(taper_fn)
@property
def ssp(self):
"""
The state space partitioning scheme.
"""
return self._ssp
@property
def taper_fn(self):
return self._taper_fn
def set_taper_fn(self, taper_fn):
"""
Sets the tapering function that defines the localization radius and how the influence of
observations is truncated with distance.
"""
assert taper_fn is not None
assert isinstance(taper_fn, endas.localization.TaperFn)
self._taper_fn = taper_fn
def get_local_H(self, Hg, obs_used):
"""
Returns localized observation operator for the given domain.
Args:
Hg : Observation operator representing all observations
obs_used : Flat array of indices into the observation vector pointing to observations to be used
Returns:
New ::class::`endas.ObservationOperator` instance or ``None`` if ``obs_used`` is an empty array.
"""
if len(obs_used) == 0: return None
Hl = Hg.localize(obs_used)
assert Hl.shape == (len(obs_used), Hg.shape[1])
return Hl
def get_local_R(self, Rg, obs_used, obs_dist):
"""
Returns localized observation error covariance operator for the given domain.
Args:
Rg : Global observation error covariance operator
obs_used : Flat array of indices into the observation vector pointing to selected observations
obs_dist : Array of distances of selected observations from the local domain
taper_fn : Tapering function instance
"""
assert len(obs_used) == len(obs_dist)
# We need to select a subset of the observation error covariance for the selected observations and apply the
# tapering function to it.
taper = np.ones(len(obs_dist), dtype=np.double)
self._taper_fn.taper(taper, obs_dist, out=taper)
return Rg.localize(obs_used, taper)
| 38.717213 | 120 | 0.681063 | 1,257 | 9,447 | 5.011138 | 0.225139 | 0.031751 | 0.01397 | 0.014288 | 0.273218 | 0.22829 | 0.197809 | 0.159708 | 0.120972 | 0.111129 | 0 | 0.002437 | 0.26167 | 9,447 | 243 | 121 | 38.876543 | 0.900645 | 0.619879 | 0 | 0.363636 | 0 | 0 | 0.019966 | 0.007445 | 0 | 0 | 0 | 0 | 0.155844 | 1 | 0.220779 | false | 0.064935 | 0.051948 | 0.025974 | 0.415584 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
9a01a6fd58e940a6083b04a72602213506ab092b | 226 | py | Python | Files/Files_part2.py | Gabicolombo/Python-exercicios | 537d46769a3556c2c35c51b335a88a89d03059a9 | [
"MIT"
] | null | null | null | Files/Files_part2.py | Gabicolombo/Python-exercicios | 537d46769a3556c2c35c51b335a88a89d03059a9 | [
"MIT"
] | null | null | null | Files/Files_part2.py | Gabicolombo/Python-exercicios | 537d46769a3556c2c35c51b335a88a89d03059a9 | [
"MIT"
] | null | null | null | file = open("nomes.txt", "r")
lines = file.readlines()
title = lines[0]
names = title.strip().split(",")
print(names)
for i in lines[1:]:
aux = i.strip().split(",")
print('{}{:>5}{:>8}'.format(aux[0], aux[1], aux[2])) | 25.111111 | 56 | 0.561947 | 36 | 226 | 3.527778 | 0.611111 | 0.15748 | 0.23622 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.036082 | 0.141593 | 226 | 9 | 56 | 25.111111 | 0.618557 | 0 | 0 | 0 | 0 | 0 | 0.105727 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.25 | 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 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9a0781dfac447f4a8ba45b8d4debd7de95b728a2 | 2,555 | py | Python | pubnub/endpoints/file_operations/download_file.py | natekspencer/pubnub-python | 453ba34104b4067077546d5d9ba3b206559494d1 | [
"MIT"
] | 146 | 2015-01-05T03:14:53.000Z | 2022-03-16T16:51:52.000Z | pubnub/endpoints/file_operations/download_file.py | natekspencer/pubnub-python | 453ba34104b4067077546d5d9ba3b206559494d1 | [
"MIT"
] | 48 | 2015-01-15T15:27:41.000Z | 2022-03-21T14:17:05.000Z | pubnub/endpoints/file_operations/download_file.py | natekspencer/pubnub-python | 453ba34104b4067077546d5d9ba3b206559494d1 | [
"MIT"
] | 128 | 2015-01-05T03:40:59.000Z | 2022-03-02T20:50:58.000Z | from pubnub.endpoints.file_operations.file_based_endpoint import FileOperationEndpoint
from pubnub.enums import HttpMethod, PNOperationType
from pubnub.crypto import PubNubFileCrypto
from pubnub.models.consumer.file import PNDownloadFileResult
from pubnub.request_handlers.requests_handler import RequestsRequestHandler
from pubnub.endpoints.file_operations.get_file_url import GetFileDownloadUrl
class DownloadFileNative(FileOperationEndpoint):
def __init__(self, pubnub):
FileOperationEndpoint.__init__(self, pubnub)
self._file_id = None
self._file_name = None
self._pubnub = pubnub
self._download_data = None
self._cipher_key = None
def cipher_key(self, cipher_key):
self._cipher_key = cipher_key
return self
def build_path(self):
return self._download_data.result.file_url
def http_method(self):
return HttpMethod.GET
def is_auth_required(self):
return False
def custom_params(self):
return {}
def file_id(self, file_id):
self._file_id = file_id
return self
def file_name(self, file_name):
self._file_name = file_name
return self
def decrypt_payload(self, data):
return PubNubFileCrypto(self._pubnub.config).decrypt(
self._cipher_key or self._pubnub.config.cipher_key,
data
)
def validate_params(self):
self.validate_subscribe_key()
self.validate_channel()
self.validate_file_name()
self.validate_file_id()
def create_response(self, envelope):
if self._cipher_key or self._pubnub.config.cipher_key:
return PNDownloadFileResult(self.decrypt_payload(envelope.content))
else:
return PNDownloadFileResult(envelope.content)
def non_json_response(self):
return True
def operation_type(self):
return PNOperationType.PNDownloadFileAction
def use_base_path(self):
return False
def build_params_callback(self):
return lambda a: {}
def name(self):
return "Downloading file"
def sync(self):
self._download_data = GetFileDownloadUrl(self._pubnub)\
.channel(self._channel)\
.file_name(self._file_name)\
.file_id(self._file_id)\
.sync()
return super(DownloadFileNative, self).sync()
def pn_async(self, callback):
return RequestsRequestHandler(self._pubnub).async_file_based_operation(self.sync, callback, "File Download")
| 29.709302 | 116 | 0.69002 | 293 | 2,555 | 5.709898 | 0.266212 | 0.048416 | 0.038852 | 0.025105 | 0.166766 | 0.076509 | 0.047818 | 0.047818 | 0.047818 | 0 | 0 | 0 | 0.235616 | 2,555 | 85 | 117 | 30.058824 | 0.856631 | 0 | 0 | 0.076923 | 0 | 0 | 0.01135 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.276923 | false | 0 | 0.092308 | 0.169231 | 0.646154 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
9a197da6c0512c69af480e96e1f959f1ae0647d6 | 12,442 | py | Python | sievelib/tests/test_factory.py | ujjwalsh/sievelib | da64d8092e96559634080317ca0a508ffe560e21 | [
"MIT"
] | 32 | 2015-11-12T11:22:08.000Z | 2021-10-23T00:22:01.000Z | sievelib/tests/test_factory.py | ujjwalsh/sievelib | da64d8092e96559634080317ca0a508ffe560e21 | [
"MIT"
] | 72 | 2015-06-24T10:50:10.000Z | 2021-05-01T10:04:52.000Z | sievelib/tests/test_factory.py | ujjwalsh/sievelib | da64d8092e96559634080317ca0a508ffe560e21 | [
"MIT"
] | 35 | 2015-08-07T11:58:51.000Z | 2022-01-20T11:13:29.000Z | import unittest
import io
from sievelib.factory import FiltersSet
from .. import parser
class FactoryTestCase(unittest.TestCase):
def setUp(self):
self.fs = FiltersSet("test")
def test_get_filter_conditions(self):
"""Test get_filter_conditions method."""
orig_conditions = [('Sender', ":is", 'toto@toto.com')]
self.fs.addfilter(
"ruleX",
orig_conditions,
[("fileinto", ":copy", "Toto"), ])
conditions = self.fs.get_filter_conditions("ruleX")
self.assertEqual(orig_conditions, conditions)
orig_conditions = [("exists", "list-help", "list-unsubscribe",
"list-subscribe", "list-owner")]
self.fs.addfilter(
"ruleY",
orig_conditions,
[("fileinto", 'List')]
)
conditions = self.fs.get_filter_conditions("ruleY")
self.assertEqual(orig_conditions, conditions)
orig_conditions = [('Sender', ":notis", 'toto@toto.com')]
self.fs.addfilter(
"ruleZ",
orig_conditions,
[("fileinto", ":copy", "Toto"), ])
conditions = self.fs.get_filter_conditions("ruleZ")
self.assertEqual(orig_conditions, conditions)
orig_conditions = [("notexists", "list-help", "list-unsubscribe",
"list-subscribe", "list-owner")]
self.fs.addfilter(
"ruleA",
orig_conditions,
[("fileinto", 'List')]
)
conditions = self.fs.get_filter_conditions("ruleA")
self.assertEqual(orig_conditions, conditions)
orig_conditions = [("envelope", ":is", ["From"], ["hello"])]
self.fs.addfilter(
"ruleB",
orig_conditions,
[("fileinto", "INBOX")]
)
conditions = self.fs.get_filter_conditions("ruleB")
self.assertEqual(orig_conditions, conditions)
orig_conditions = [("body", ":raw", ":notcontains", "matteo")]
self.fs.addfilter(
"ruleC",
orig_conditions,
[("fileinto", "INBOX")]
)
conditions = self.fs.get_filter_conditions("ruleC")
self.assertEqual(orig_conditions, conditions)
orig_conditions = [(
"currentdate", ":zone", "+0100", ":notis", "date", "2019-02-26"
)]
self.fs.addfilter(
"ruleD",
orig_conditions,
[("fileinto", "INBOX")]
)
conditions = self.fs.get_filter_conditions("ruleD")
self.assertEqual(orig_conditions, conditions)
orig_conditions = [(
"currentdate", ":zone", "+0100", ":value", "gt", "date",
"2019-02-26"
)]
self.fs.addfilter(
"ruleE",
orig_conditions,
[("fileinto", "INBOX")]
)
conditions = self.fs.get_filter_conditions("ruleE")
self.assertEqual(orig_conditions, conditions)
def test_get_filter_conditions_from_parser_result(self):
res = """require ["fileinto"];
# rule:[test]
if anyof (exists ["Subject"]) {
fileinto "INBOX";
}
"""
p = parser.Parser()
p.parse(res)
fs = FiltersSet("test", '# rule:')
fs.from_parser_result(p)
c = fs.get_filter_conditions('[test]')
self.assertEqual(c, [("exists", "Subject")])
res = """require ["date", "fileinto"];
# rule:aaa
if anyof (currentdate :zone "+0100" :is "date" ["2019-03-27"]) {
fileinto "INBOX";
}
"""
p = parser.Parser()
p.parse(res)
fs = FiltersSet("aaa", "# rule:")
fs.from_parser_result(p)
c = fs.get_filter_conditions('aaa')
self.assertEqual(
c, [('currentdate', ':zone', '+0100', ':is', 'date', '2019-03-27')]
)
res = """require ["envelope", "fileinto"];
# rule:[aaa]
if anyof (envelope :contains ["To"] ["hello@world.it"]) {
fileinto "INBOX";
}
"""
p = parser.Parser()
p.parse(res)
fs = FiltersSet("aaa", "# rule:")
fs.from_parser_result(p)
c = fs.get_filter_conditions('[aaa]')
self.assertEqual(
c, [('envelope', ':contains', ['To'], ['hello@world.it'])]
)
def test_get_filter_matchtype(self):
"""Test get_filter_matchtype method."""
self.fs.addfilter(
"ruleX",
[('Sender', ":is", 'toto@toto.com'), ],
[("fileinto", ":copy", "Toto"), ])
match_type = self.fs.get_filter_matchtype("ruleX")
self.assertEqual(match_type, "anyof")
def test_get_filter_actions(self):
"""Test get_filter_actions method."""
self.fs.addfilter(
"ruleX",
[('Sender', ":is", 'toto@toto.com'), ],
[("fileinto", ":copy", "Toto"), ])
actions = self.fs.get_filter_actions("ruleX")
self.assertIn("fileinto", actions[0])
self.assertIn(":copy", actions[0])
self.assertIn("Toto", actions[0])
self.fs.addfilter(
"ruleY",
[("Subject", ":contains", "aaa")],
[("stop",)]
)
actions = self.fs.get_filter_actions("ruleY")
self.assertIn("stop", actions[0])
def test_add_header_filter(self):
output = io.StringIO()
self.fs.addfilter(
"rule1",
[('Sender', ":is", 'toto@toto.com'), ],
[("fileinto", ":copy", "Toto"), ])
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.fs.tosieve(output)
self.assertEqual(output.getvalue(), """require ["fileinto", "copy"];
# Filter: rule1
if anyof (header :is "Sender" "toto@toto.com") {
fileinto :copy "Toto";
}
""")
output.close()
def test_use_action_with_tag(self):
output = io.StringIO()
self.fs.addfilter(
"rule1",
[('Sender', ":is", 'toto@toto.com'), ],
[("redirect", ":copy", "toto@titi.com"), ])
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.fs.tosieve(output)
self.assertEqual(output.getvalue(), """require ["copy"];
# Filter: rule1
if anyof (header :is "Sender" "toto@toto.com") {
redirect :copy "toto@titi.com";
}
""")
output.close()
def test_add_header_filter_with_not(self):
output = io.StringIO()
self.fs.addfilter(
"rule1",
[('Sender', ":notcontains", 'toto@toto.com')],
[("fileinto", 'Toto')])
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.fs.tosieve(output)
self.assertEqual(output.getvalue(), """require ["fileinto"];
# Filter: rule1
if anyof (not header :contains "Sender" "toto@toto.com") {
fileinto "Toto";
}
""")
def test_add_exists_filter(self):
output = io.StringIO()
self.fs.addfilter(
"rule1",
[('exists', "list-help", "list-unsubscribe",
"list-subscribe", "list-owner")],
[("fileinto", 'Toto')]
)
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.fs.tosieve(output)
self.assertEqual(output.getvalue(), """require ["fileinto"];
# Filter: rule1
if anyof (exists ["list-help","list-unsubscribe","list-subscribe","list-owner"]) {
fileinto "Toto";
}
""")
def test_add_exists_filter_with_not(self):
output = io.StringIO()
self.fs.addfilter(
"rule1",
[('notexists', "list-help", "list-unsubscribe",
"list-subscribe", "list-owner")],
[("fileinto", 'Toto')]
)
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.fs.tosieve(output)
self.assertEqual(output.getvalue(), """require ["fileinto"];
# Filter: rule1
if anyof (not exists ["list-help","list-unsubscribe","list-subscribe","list-owner"]) {
fileinto "Toto";
}
""")
def test_add_size_filter(self):
output = io.StringIO()
self.fs.addfilter(
"rule1",
[('size', ":over", "100k")],
[("fileinto", 'Totoéé')]
)
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.fs.tosieve(output)
self.assertEqual(output.getvalue(), """require ["fileinto"];
# Filter: rule1
if anyof (size :over 100k) {
fileinto "Totoéé";
}
""")
def test_remove_filter(self):
self.fs.addfilter("rule1",
[('Sender', ":is", 'toto@toto.com')],
[("fileinto", 'Toto')])
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.assertEqual(self.fs.removefilter("rule1"), True)
self.assertIs(self.fs.getfilter("rule1"), None)
def test_disablefilter(self):
"""
FIXME: Extra spaces are written between if and anyof, why?!
"""
self.fs.addfilter("rule1",
[('Sender', ":is", 'toto@toto.com')],
[("fileinto", 'Toto')])
self.assertIsNot(self.fs.getfilter("rule1"), None)
self.assertEqual(self.fs.disablefilter("rule1"), True)
output = io.StringIO()
self.fs.tosieve(output)
self.assertEqual(output.getvalue(), """require ["fileinto"];
# Filter: rule1
if false {
if anyof (header :is "Sender" "toto@toto.com") {
fileinto "Toto";
}
}
""")
output.close()
self.assertEqual(self.fs.is_filter_disabled("rule1"), True)
def test_add_filter_unicode(self):
"""Add a filter containing unicode data."""
name = u"Test\xe9".encode("utf-8")
self.fs.addfilter(
name,
[('Sender', ":is", 'toto@toto.com'), ],
[("fileinto", 'Toto'), ])
self.assertIsNot(self.fs.getfilter("Testé"), None)
self.assertEqual("{}".format(self.fs), """require ["fileinto"];
# Filter: Testé
if anyof (header :is "Sender" "toto@toto.com") {
fileinto "Toto";
}
""")
def test_add_body_filter(self):
"""Add a body filter."""
self.fs.addfilter(
"test",
[("body", ":raw", ":contains", "matteo")],
[("fileinto", "Toto")]
)
self.assertEqual("{}".format(self.fs), """require ["body", "fileinto"];
# Filter: test
if anyof (body :contains :raw ["matteo"]) {
fileinto "Toto";
}
""")
def test_add_notbody_filter(self):
"""Add a not body filter."""
self.fs.addfilter(
"test",
[("body", ":raw", ":notcontains", "matteo")],
[("fileinto", "Toto")]
)
self.assertEqual("{}".format(self.fs), """require ["body", "fileinto"];
# Filter: test
if anyof (not body :contains :raw ["matteo"]) {
fileinto "Toto";
}
""")
def test_add_envelope_filter(self):
"""Add a envelope filter."""
self.fs.addfilter(
"test",
[("envelope", ":is", ["From"], ["hello"])],
[("fileinto", "INBOX")]
)
self.assertEqual("{}".format(self.fs), """require ["envelope", "fileinto"];
# Filter: test
if anyof (envelope :is ["From"] ["hello"]) {
fileinto "INBOX";
}
""")
def test_add_notenvelope_filter(self):
"""Add a not envelope filter."""
self.fs.addfilter(
"test",
[("envelope", ":notis", ["From"], ["hello"])],
[("fileinto", "INBOX")]
)
self.assertEqual("{}".format(self.fs), """require ["envelope", "fileinto"];
# Filter: test
if anyof (not envelope :is ["From"] ["hello"]) {
fileinto "INBOX";
}
""")
def test_add_currentdate_filter(self):
"""Add a currentdate filter."""
self.fs.addfilter(
"test",
[("currentdate", ":zone", "+0100", ":is", "date", "2019-02-26")],
[("fileinto", "INBOX")]
)
self.assertEqual("{}".format(self.fs), """require ["date", "fileinto"];
# Filter: test
if anyof (currentdate :zone "+0100" :is "date" ["2019-02-26"]) {
fileinto "INBOX";
}
""")
self.fs.removefilter("test")
self.fs.addfilter(
"test",
[("currentdate", ":zone", "+0100", ":value", "gt", "date",
"2019-02-26")],
[("fileinto", "INBOX")]
)
self.assertEqual("{}".format(self.fs), """require ["date", "fileinto", "relational"];
# Filter: test
if anyof (currentdate :zone "+0100" :value "gt" "date" ["2019-02-26"]) {
fileinto "INBOX";
}
""")
if __name__ == "__main__":
unittest.main()
| 30.346341 | 93 | 0.536007 | 1,251 | 12,442 | 5.223022 | 0.110312 | 0.060606 | 0.059688 | 0.025253 | 0.787573 | 0.741659 | 0.707989 | 0.63667 | 0.605755 | 0.548515 | 0 | 0.015048 | 0.278974 | 12,442 | 409 | 94 | 30.420538 | 0.713298 | 0.025398 | 0 | 0.553623 | 0 | 0.014493 | 0.307456 | 0.01045 | 0 | 0 | 0 | 0.002445 | 0.124638 | 1 | 0.055072 | false | 0 | 0.011594 | 0 | 0.069565 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9a23de0a1d358b3283fda45482963be931998b54 | 183 | py | Python | python/zp/primjer_09.04.py | jasarsoft/examples | d6fddfcb8c50c31fbfe170a3edd2b6c07890f13e | [
"MIT"
] | null | null | null | python/zp/primjer_09.04.py | jasarsoft/examples | d6fddfcb8c50c31fbfe170a3edd2b6c07890f13e | [
"MIT"
] | null | null | null | python/zp/primjer_09.04.py | jasarsoft/examples | d6fddfcb8c50c31fbfe170a3edd2b6c07890f13e | [
"MIT"
] | null | null | null | x = 50
def funk():
global x
print("x je ", x)
x = 2
print("Promjena globalne vrijednost promjeljive x na ", x)
funk()
print("Vrijednost promjeljive x sada je ", x)
| 15.25 | 62 | 0.612022 | 28 | 183 | 4 | 0.5 | 0.053571 | 0.392857 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.022388 | 0.26776 | 183 | 11 | 63 | 16.636364 | 0.813433 | 0 | 0 | 0 | 0 | 0 | 0.459016 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0 | 0 | 0.125 | 0.375 | 1 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9a35654f5f0950afe73d09f623d0b06f233530c2 | 287 | py | Python | drf_signed_auth/compat.py | marcgibbons/drf_signed_auth | 39bdd3ea01a09a00fd3c9bf7c6d2ad6bb4dabba6 | [
"BSD-2-Clause"
] | 11 | 2017-10-24T13:17:25.000Z | 2022-03-08T05:55:21.000Z | drf_signed_auth/compat.py | marcgibbons/drf_signed_auth | 39bdd3ea01a09a00fd3c9bf7c6d2ad6bb4dabba6 | [
"BSD-2-Clause"
] | 1 | 2017-11-06T21:26:38.000Z | 2017-11-06T21:26:38.000Z | drf_signed_auth/compat.py | marcgibbons/drf_signed_auth | 39bdd3ea01a09a00fd3c9bf7c6d2ad6bb4dabba6 | [
"BSD-2-Clause"
] | null | null | null | # pylint: disable=W0611
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
try:
from unittest import mock
except ImportError:
import mock
try:
from importlib import reload
except ImportError:
reload = reload
| 15.944444 | 48 | 0.74216 | 35 | 287 | 6.085714 | 0.485714 | 0.098592 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.017699 | 0.212544 | 287 | 17 | 49 | 16.882353 | 0.924779 | 0.073171 | 0 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.666667 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
9a40c7e9851dd3189cd04fdfbfccc6b87f50b5ef | 1,122 | py | Python | tests/test_valid_ipaddress.py | dsgnr/portchecker | a31f0e00f16422e368de1ff93f1c98f2a8ef1800 | [
"MIT"
] | null | null | null | tests/test_valid_ipaddress.py | dsgnr/portchecker | a31f0e00f16422e368de1ff93f1c98f2a8ef1800 | [
"MIT"
] | null | null | null | tests/test_valid_ipaddress.py | dsgnr/portchecker | a31f0e00f16422e368de1ff93f1c98f2a8ef1800 | [
"MIT"
] | null | null | null | # Third Party
import pytest
# First Party
from portchecker.port_checker import is_address_valid
from tests import constants
class TestValidIPAddress:
def test_valid_public_ipv4(self):
assert is_address_valid(constants.VALID_PUBLIC_IPV4) is True
def test_valid_public_ipv6(self):
assert is_address_valid(constants.VALID_PUBLIC_IPV6) is True
def test_invalid_ipv4_failure(self):
with pytest.raises(ValueError, match=constants.NOT_VALID_IP_ERROR):
is_address_valid(constants.INVALID_PUBLIC_IPV4)
def test_invalid_ipv6_failure(self):
with pytest.raises(ValueError, match=constants.NOT_VALID_IP_ERROR):
is_address_valid(constants.INVALID_PUBLIC_IPV6)
def test_private_ipv4_failure(self):
with pytest.raises(ValueError, match=constants.NOT_PUBLIC_IP_ERROR):
is_address_valid(constants.VALID_PRIVATE_IPV4, allow_private=False)
def test_private_ipv6_failure(self):
with pytest.raises(ValueError, match=constants.NOT_PUBLIC_IP_ERROR):
is_address_valid(constants.VALID_PRIVATE_IPV6, allow_private=False)
| 36.193548 | 79 | 0.771836 | 150 | 1,122 | 5.38 | 0.24 | 0.078067 | 0.121437 | 0.171004 | 0.634449 | 0.634449 | 0.634449 | 0.634449 | 0.525403 | 0.525403 | 0 | 0.012793 | 0.163993 | 1,122 | 30 | 80 | 37.4 | 0.847548 | 0.020499 | 0 | 0.2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 1 | 0.3 | false | 0 | 0.15 | 0 | 0.5 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
9a51ecbfb5d392404d00d98521fc9f474e878f4b | 439 | py | Python | aioalice/utils/__init__.py | AlekseevAV/aioalice | 028eae49a0ebcbb4cdd3dcbcb38f5a17634af704 | [
"MIT"
] | null | null | null | aioalice/utils/__init__.py | AlekseevAV/aioalice | 028eae49a0ebcbb4cdd3dcbcb38f5a17634af704 | [
"MIT"
] | null | null | null | aioalice/utils/__init__.py | AlekseevAV/aioalice | 028eae49a0ebcbb4cdd3dcbcb38f5a17634af704 | [
"MIT"
] | null | null | null | from . import exceptions
from .json import json
from .payload import generate_json_payload
def ensure_cls(klass):
def converter(val):
if val is None:
return
if isinstance(val, dict):
return klass(**val)
if isinstance(val, list):
return [converter(v) for v in val]
if not isinstance(val, klass):
return klass(val)
return val
return converter
| 24.388889 | 46 | 0.601367 | 55 | 439 | 4.745455 | 0.418182 | 0.057471 | 0.114943 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.32574 | 439 | 17 | 47 | 25.823529 | 0.881757 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.133333 | false | 0 | 0.2 | 0 | 0.733333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
9a5dd06c049198b6a635665d2a6b1ac23b00af05 | 488 | py | Python | homepage/resume/views.py | MaxGosselin/homepage | 5897af197cccd3221071447032595fc177b24a43 | [
"MIT"
] | null | null | null | homepage/resume/views.py | MaxGosselin/homepage | 5897af197cccd3221071447032595fc177b24a43 | [
"MIT"
] | null | null | null | homepage/resume/views.py | MaxGosselin/homepage | 5897af197cccd3221071447032595fc177b24a43 | [
"MIT"
] | null | null | null | from django.shortcuts import render, render_to_response
# Create your views here.
def resume(response):
''' render the resume page '''
context = {
# 'script': script,
# 'div': div,
}
return render_to_response('resume/resume.html', context=context)
def projects(response):
''' render the projects page '''
context = {
# 'script': script,
# 'div': div,
}
return render_to_response('resume/projects.html', context=context)
| 23.238095 | 70 | 0.622951 | 54 | 488 | 5.518519 | 0.388889 | 0.080537 | 0.161074 | 0.154362 | 0.38255 | 0.38255 | 0.38255 | 0.38255 | 0.38255 | 0.38255 | 0 | 0 | 0.245902 | 488 | 20 | 71 | 24.4 | 0.809783 | 0.27459 | 0 | 0.222222 | 0 | 0 | 0.113095 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.111111 | 0 | 0.555556 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
9a69c2e4c459ddc68e48fc6ae052abadbe3347ea | 1,215 | py | Python | examples/flask-basic-auth.py | aheck/reflectrpc | 9602d3b3f06d3d8ee8549788301e43b172a597f6 | [
"MIT"
] | 33 | 2016-06-12T15:25:07.000Z | 2021-11-16T18:53:16.000Z | examples/flask-basic-auth.py | aheck/reflectrpc | 9602d3b3f06d3d8ee8549788301e43b172a597f6 | [
"MIT"
] | null | null | null | examples/flask-basic-auth.py | aheck/reflectrpc | 9602d3b3f06d3d8ee8549788301e43b172a597f6 | [
"MIT"
] | 3 | 2016-10-10T20:50:41.000Z | 2021-05-01T23:51:34.000Z | #!/usr/bin/env python3
#
# Connect to this server with: rpcsh localhost 5000 --http --http-basic-user testuser
#
import sys
import json
from functools import wraps
from flask import Flask, request, Response
sys.path.append('..')
import reflectrpc
import reflectrpc.simpleserver
import rpcexample
app = Flask(__name__)
jsonrpc = rpcexample.build_example_rpcservice()
def check_auth(username, password):
return username == 'testuser' and password == '123456'
def authenticate():
return Response('Login required', 401,
{'WWW-Authenticate': 'Basic realm="ReflectRPC"'})
def requires_auth(f):
@wraps(f)
def decorated():
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(auth.username)
return decorated
@app.route('/rpc', methods=['POST'])
@requires_auth
def rpc_handler(username):
rpcinfo = {'authenticated': True, 'username': username}
response = jsonrpc.process_request(request.get_data().decode('utf-8'),
rpcinfo)
reply = json.dumps(response)
return Response(reply, 200, mimetype='application/json-rpc')
if __name__ == '__main__':
app.run()
| 23.823529 | 85 | 0.699588 | 146 | 1,215 | 5.678082 | 0.534247 | 0.043426 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018018 | 0.177778 | 1,215 | 50 | 86 | 24.3 | 0.811812 | 0.08642 | 0 | 0 | 0 | 0 | 0.119349 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.151515 | false | 0.090909 | 0.212121 | 0.060606 | 0.545455 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
9a6d35cba50824b724f0eb6f949890ee01341641 | 789 | py | Python | algorithms/test_insertion_sort.py | fedusia/python | 528f333d1e09adf3668c3f59012f5560cbae9058 | [
"Apache-2.0"
] | null | null | null | algorithms/test_insertion_sort.py | fedusia/python | 528f333d1e09adf3668c3f59012f5560cbae9058 | [
"Apache-2.0"
] | null | null | null | algorithms/test_insertion_sort.py | fedusia/python | 528f333d1e09adf3668c3f59012f5560cbae9058 | [
"Apache-2.0"
] | null | null | null | import random
import time
import unittest
from insertion_sort import insertion_sort
class TestInsertionSort(unittest.TestCase):
def setUp(self):
self.start_time = time.time()
def tearDown(self):
t = time.time() - self.start_time
print('{:.3f}'.format(t))
def test_insertion_sort(self):
answer = [1, 2, 3]
self.assertEqual(insertion_sort([3, 2, 1]), answer)
def test_insertion_sort_signed_int(self):
answer = [-100, 50, 70, 100]
self.assertEqual(insertion_sort([50, 70, -100, 100]), answer)
def test_insertion_sort_random_1000(self):
data = [random.randint(-100, 100) for _ in range(1000)]
self.assertEqual(insertion_sort(data), sorted(data))
if __name__ == '__main__':
unittest.main()
| 26.3 | 69 | 0.656527 | 103 | 789 | 4.776699 | 0.38835 | 0.211382 | 0.097561 | 0.121951 | 0.105691 | 0 | 0 | 0 | 0 | 0 | 0 | 0.066236 | 0.215463 | 789 | 29 | 70 | 27.206897 | 0.728595 | 0 | 0 | 0 | 0 | 0 | 0.017744 | 0 | 0 | 0 | 0 | 0 | 0.142857 | 1 | 0.238095 | false | 0 | 0.190476 | 0 | 0.47619 | 0.047619 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
7bd5bf75947f48762914fd91888dac725adbed97 | 592 | py | Python | trn11com_integration/TRn11comSoapServiceWSDLAddress.py | Framras/trn11com_integration | 817e2ee685b029729d92ce00e17271f9de1f56b5 | [
"MIT"
] | 1 | 2019-12-12T23:43:06.000Z | 2019-12-12T23:43:06.000Z | trn11com_integration/TRn11comSoapServiceWSDLAddress.py | Framras/trn11com_integration | 817e2ee685b029729d92ce00e17271f9de1f56b5 | [
"MIT"
] | null | null | null | trn11com_integration/TRn11comSoapServiceWSDLAddress.py | Framras/trn11com_integration | 817e2ee685b029729d92ce00e17271f9de1f56b5 | [
"MIT"
] | 1 | 2020-01-05T19:39:19.000Z | 2020-01-05T19:39:19.000Z | # importing enum for enumerations
from enum import Enum, unique
@unique
# creating enumerations using class
class TRn11comSoapServiceWSDLAddress(Enum):
Category = "/ws/CategoryService.wsdl"
Product = "/ws/ProductService.wsdl"
Order = "/ws/OrderService.wsdl"
City = "/ws/CityService.wsdl"
ProductSelling = "/ws/ProductSellingService.wsdl"
ProductStock = "/ws/ProductStockService.wsdl"
ShipmentCompany = "/ws/ShipmentCompanyService.wsdl"
Shipment = "/ws/ShipmentService.wsdl"
Settlement = "/ws/SettlementService.wsdl"
Ticket = "/ws/TicketService.wsdl"
| 32.888889 | 55 | 0.734797 | 57 | 592 | 7.631579 | 0.578947 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003984 | 0.152027 | 592 | 17 | 56 | 34.823529 | 0.86255 | 0.109797 | 0 | 0 | 0 | 0 | 0.475191 | 0.437023 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.076923 | 0 | 0.923077 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
7bd93e1ee4989121a6b1ceb959523f9182c26db0 | 611 | py | Python | backend/core/management/commands/start_celery_local.py | bhardwajRahul/sec-filings-app | 8cf7f5956717db8fee1f9a20445986ad9cb831ca | [
"MIT"
] | 36 | 2020-12-04T08:16:38.000Z | 2022-03-22T02:30:49.000Z | backend/core/management/commands/start_celery_local.py | bhardwajRahul/sec-filings-app | 8cf7f5956717db8fee1f9a20445986ad9cb831ca | [
"MIT"
] | 1 | 2021-10-14T22:20:40.000Z | 2021-10-17T17:29:50.000Z | backend/core/management/commands/start_celery_local.py | briancaffey/sec-filings-app | 8cf7f5956717db8fee1f9a20445986ad9cb831ca | [
"MIT"
] | 16 | 2020-11-30T18:46:51.000Z | 2022-01-20T23:01:58.000Z | """
https://avilpage.com/2017/05/how-to-auto-reload-celery-workers-in-development.html
"""
import shlex
import subprocess
from django.core.management.base import BaseCommand
from django.utils import autoreload
def restart_celery_worker():
cmd = "pkill -9 celery"
subprocess.call(shlex.split(cmd))
# fmt: off
cmd = 'celery --app=backend.celery_app:app worker -Q default --concurrency=1 --loglevel=INFO' # noqa
# fmt: on
subprocess.call(shlex.split(cmd))
class Command(BaseCommand):
def handle(self, *args, **options):
autoreload.run_with_reloader(restart_celery_worker)
| 25.458333 | 104 | 0.725041 | 82 | 611 | 5.317073 | 0.658537 | 0.045872 | 0.087156 | 0.110092 | 0.123853 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015355 | 0.1473 | 611 | 23 | 105 | 26.565217 | 0.821497 | 0.171849 | 0 | 0.166667 | 0 | 0.083333 | 0.201613 | 0.056452 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.333333 | 0 | 0.583333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
7bdd02ea3174ecd376bcc4e7d409b16b1c984b70 | 1,690 | py | Python | migrations/versions/20201206_190938_63dd8a1ce0df_add_stats_table.py | geka32team/moonshot-jam-2020-back | 8680331f48dda621093430653b31c4532f9a8c9f | [
"BSD-2-Clause"
] | null | null | null | migrations/versions/20201206_190938_63dd8a1ce0df_add_stats_table.py | geka32team/moonshot-jam-2020-back | 8680331f48dda621093430653b31c4532f9a8c9f | [
"BSD-2-Clause"
] | 15 | 2020-11-06T09:30:04.000Z | 2021-09-17T14:27:21.000Z | migrations/versions/20201206_190938_63dd8a1ce0df_add_stats_table.py | geka32team/moonshot-jam-2020-back | 8680331f48dda621093430653b31c4532f9a8c9f | [
"BSD-2-Clause"
] | null | null | null | """Add stats table.
Revision ID: 63dd8a1ce0df
Revises: 93be7244a677
Create Date: 2020-12-06 19:09:38.691381
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '63dd8a1ce0df'
down_revision = '93be7244a677'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('stats',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('lvl', sa.Integer(), nullable=False),
sa.Column('hp', sa.Integer(), nullable=False),
sa.Column('exp', sa.Integer(), nullable=False),
sa.Column('strn', sa.Integer(), nullable=False),
sa.Column('vit', sa.Integer(), nullable=False),
sa.Column('dex', sa.Integer(), nullable=False),
sa.Column('acc', sa.Integer(), nullable=False),
sa.Column('dmg', sa.Integer(), nullable=False),
sa.Column('stats', sa.Integer(), nullable=False),
sa.Column('bosses_defeated', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
['user_id'], ['users.id'], name='stats_user_id', ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('user_id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('stats')
# ### end Alembic commands ###
| 36.73913 | 93 | 0.555621 | 178 | 1,690 | 5.213483 | 0.365169 | 0.103448 | 0.219828 | 0.284483 | 0.480603 | 0.480603 | 0.094828 | 0.094828 | 0 | 0 | 0 | 0.040302 | 0.295266 | 1,690 | 45 | 94 | 37.555556 | 0.738875 | 0.176331 | 0 | 0 | 0 | 0 | 0.096679 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.074074 | false | 0 | 0.074074 | 0 | 0.148148 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
7be0b1d7337aab4647a5849a4390c9aa8225725c | 312 | py | Python | pyeccodes/defs/grib2/tables/15/1_6_table.py | ecmwf/pyeccodes | dce2c72d3adcc0cb801731366be53327ce13a00b | [
"Apache-2.0"
] | 7 | 2020-04-14T09:41:17.000Z | 2021-08-06T09:38:19.000Z | pyeccodes/defs/grib2/tables/20/1_6_table.py | ecmwf/pyeccodes | dce2c72d3adcc0cb801731366be53327ce13a00b | [
"Apache-2.0"
] | null | null | null | pyeccodes/defs/grib2/tables/20/1_6_table.py | ecmwf/pyeccodes | dce2c72d3adcc0cb801731366be53327ce13a00b | [
"Apache-2.0"
] | 3 | 2020-04-30T12:44:48.000Z | 2020-12-15T08:40:26.000Z | def load(h):
return ({'abbr': 0, 'code': 0, 'title': 'Gregorian'},
{'abbr': 1, 'code': 1, 'title': '360-day'},
{'abbr': 2, 'code': 2, 'title': '365-day'},
{'abbr': 3, 'code': 3, 'title': 'Proleptic Gregorian'},
{'abbr': None, 'code': 255, 'title': 'Missing'})
| 44.571429 | 67 | 0.448718 | 37 | 312 | 3.783784 | 0.513514 | 0.185714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.075221 | 0.275641 | 312 | 6 | 68 | 52 | 0.544248 | 0 | 0 | 0 | 0 | 0 | 0.365385 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0 | 0.166667 | 0.333333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
7bf37027267a08639d237d44b58ac9bceb446652 | 627 | py | Python | test-service1/functions/get_func_with_required_query_params/handler.py | koki-nakamura22/serverless-framework-practice | b6fb96cc97ecb7a1fa167c7cccb143510466d350 | [
"MIT"
] | null | null | null | test-service1/functions/get_func_with_required_query_params/handler.py | koki-nakamura22/serverless-framework-practice | b6fb96cc97ecb7a1fa167c7cccb143510466d350 | [
"MIT"
] | null | null | null | test-service1/functions/get_func_with_required_query_params/handler.py | koki-nakamura22/serverless-framework-practice | b6fb96cc97ecb7a1fa167c7cccb143510466d350 | [
"MIT"
] | null | null | null | import json
def get_func_with_required_query_params(event, context):
body = {
"param1": event.get('queryStringParameters').get('param1'),
"param2": event.get('queryStringParameters').get('param2'),
"param3": event.get('queryStringParameters').get('param3')
}
response = {
"statusCode": 200,
"body": json.dumps(body)
}
return response
# Use this code if you don't use the http event with the LAMBDA-PROXY
# integration
"""
return {
"message": "Go Serverless v1.0! Your function executed successfully!",
"event": event
}
"""
| 25.08 | 78 | 0.60925 | 67 | 627 | 5.626866 | 0.626866 | 0.06366 | 0.230769 | 0.254642 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.023555 | 0.255183 | 627 | 24 | 79 | 26.125 | 0.783726 | 0.125997 | 0 | 0 | 0 | 0 | 0.273608 | 0.152542 | 0 | 0 | 0 | 0 | 0 | 1 | 0.083333 | false | 0 | 0.083333 | 0 | 0.25 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
7bf4c105586099760047361c48f93b55b66fdfd6 | 11,152 | py | Python | forms.py | rdriesen-vtj/vtj | e86da07e55d2a46b83b20cf8bae8900abcb9b4ee | [
"MIT"
] | null | null | null | forms.py | rdriesen-vtj/vtj | e86da07e55d2a46b83b20cf8bae8900abcb9b4ee | [
"MIT"
] | null | null | null | forms.py | rdriesen-vtj/vtj | e86da07e55d2a46b83b20cf8bae8900abcb9b4ee | [
"MIT"
] | null | null | null | #!/bin/python
# -*- coding: utf-8 -*-
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, RadioField, TextAreaField, SelectMultipleField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from models import Users, Orgs, Posts, Projs, Tasks, Etapas
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from flask_wtf.file import FileField, FileRequired, FileAllowed
class ChangePasswordForm(FlaskForm):
old_password = PasswordField('Senha antiga', validators=[DataRequired()])
password = PasswordField('Senha Nova ', validators=[DataRequired(), EqualTo('password2', message='As senhas precisam ser iguais.')])
password2 = PasswordField('Confirm new password', validators=[DataRequired()])
submit = SubmitField('Update Password')
class PasswordResetRequestForm(FlaskForm):
email = StringField('Email', validators=[DataRequired()])
submit = SubmitField('Reset de senha')
class PasswordResetForm(FlaskForm):
password = PasswordField('Senha Nova', validators=[DataRequired(), EqualTo('password2', message='As senhas precisam ser iguais.')])
password2 = PasswordField('Confirmação da Senha Nova', validators=[DataRequired()])
submit = SubmitField('Reset de senha')
class TestForm(FlaskForm):
campo1 = StringField('Campo1')
submit = SubmitField('ok')
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
class NewprojForm(FlaskForm):
titulo = StringField('Titulo', validators=[DataRequired()])
descricao = TextAreaField('Descrição', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
objetivo = StringField('Objetivo', validators=[DataRequired()])
organizacao = SelectField('Organização',coerce=int, validators=[DataRequired()])
responsavel = SelectField('Responsável',coerce=int)
status= RadioField('Status', choices=[('ATIVO','ATIVO'),('FINALIZADO','FINALIZADO'),('INATIVO','INATIVO')], validate_choice=False)
visibilidade = RadioField('Visibilidade', choices=[('PÚBLICO','PÚBLICO'),('PRIVADO','PRIVADO'),('SECRETO','SECRETO')])
icon = StringField('Icon', validators=[])
logo_url = StringField('LogoUrl', validators=[])
submit = SubmitField('Register')
class EditprojForm(FlaskForm):
titulo = StringField('Titulo', validators=[DataRequired()])
descricao = TextAreaField('Descrição', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
objetivo = StringField('Objetivo', validators=[DataRequired()])
organizacao = SelectField('Organização', validate_choice=False)
responsavel = SelectField('Responsável', validate_choice=False)
status= RadioField('Status', choices=[('ATIVO','ATIVO'),('FINALIZADO','FINALIZADO'),('INATIVO','INATIVO')], validate_choice=False)
visibilidade = RadioField('Visibilidade', choices=[('PÚBLICO','PÚBLICO'),('PRIVADO','PRIVADO'),('SECRETO','SECRETO')], validate_choice=False)
icon = StringField('Icon', validators=[])
submit = SubmitField('SALVAR')
class NewstageForm(FlaskForm):
titulo = StringField('Titulo', validators=[DataRequired()])
body = TextAreaField('Texto', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
visibilidade = RadioField('Visibilidade', choices=[('RASCUNHO','RASCUNHO'),('VISÍVEL','VISÍVEL')], validate_choice=False)
imagens = StringField('Imagens')
submit = SubmitField('SALVAR')
class NewtaskForm(FlaskForm):
titulo = StringField('Titulo', validators=[DataRequired()])
descricao = TextAreaField('Descrição', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
responsavel = SelectField('Responsável',coerce=int)
submit = SubmitField('SALVAR')
class EdittaskForm(FlaskForm):
titulo = StringField('Titulo', validators=[DataRequired()])
descricao = TextAreaField('Descrição', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
responsavel = SelectField('Responsável', validate_choice=False)
#progresso = StringField('Progresso', validators=[DataRequired()])
prog = RadioField('Progresso', choices=[('0','0%'),('10','10%'),('20','20%'),('30','30%'),('40','40%'),\
('50','50%'),('60','60%'),('70','70%'),('80','80%'),\
('90','90%'),('100','100%')], validate_choice=False)
submit = SubmitField('SALVAR')
class MsgForm(FlaskForm):
body = TextAreaField('Mensagem', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
destination = SelectMultipleField('Destino', validate_choice=False, coerce= int)
submit = SubmitField('ENVIAR')
class OrgusersForm(FlaskForm):
nome_convidado = StringField('Nome', validators=[])
sobrenome_convidado = StringField('Sobrenome', validators=[])
excluidos = SelectMultipleField('Membros', validate_choice=False, coerce= int)
submit = SubmitField('SALVAR')
class ProjusersForm(FlaskForm):
incluidos = SelectMultipleField('Membros', validate_choice=False, coerce= int)
excluidos = SelectMultipleField('Participantes', validate_choice=False, coerce= int)
editados = SelectMultipleField('Participantes', validate_choice=False, coerce= int)
editadosresp = SelectField('Participantes', validate_choice=False, coerce= int)
status = RadioField('Status', choices=[('participante','participante'),('editor','editor'),\
('administrador','administrador')],\
validate_choice=False)
statusresp = RadioField('Status', choices=[('participante','participante'),('editor','editor'),\
('administrador','administrador'),('responsável','responsável')],\
validate_choice=False)
submit = SubmitField('SUBMETER')
class ProfileForm(FlaskForm):
nome = StringField('Nome', validators=[])
sobrenome = StringField('Sobrenome', validators=[])
#username = StringField('Username', validators=[])
email = StringField('Email', validators=[])
telefone = StringField('Telefone', validators=[])
avatar = StringField('Avatar', validators=[])
photo = FileField('photo', validators=[FileAllowed(['png', 'jpg'], "wrong format!")])
genero = RadioField('Gênero', choices=[('Masculino','Masculino'),('Feminino','Feminino')])
endereco1 = StringField('Endereço (Rua e Número)', validators=[])
endereco2 = StringField('Complemento (Apt,bloco,casa...)', validators=[])
endereco3 = StringField('Bairro', validators=[])
cep = StringField('CEP', validators=[])
cidade = StringField('Cidade', validators=[])
estado = StringField('Estado', validators=[])
pais = StringField('País', validators=[])
dia = StringField('Dia', validators=[])
mes = StringField('Mês', validators=[])
ano = StringField('Ano', validators=[])
sobre_mim = TextAreaField('Sobre mim...', render_kw={"rows": 70, "cols": 11}, validators=[])
#password = PasswordField('Password', validators=[])
#org = SelectField('Organização',choices=[],validators=[])
#acao_org = RadioField('Ação', choices=[('manter','MANTER'),('entrar','ENTRAR'),('sair','SAIR')],validators=[])
#proj = SelectField('Projeto',choices=[],validators=[])
#acao_proj = RadioField('Ação', choices=[('manter','MANTER'),('entrar','ENTRAR'),('sair','SAIR')],validators=[])
submit = SubmitField('SALVAR')
class EnderecoForm(FlaskForm):
endereco1 = StringField('Endereço (Rua e Número)', validators=[])
endereco2 = StringField('Complemento (Apt,bloco,casa...)', validators=[])
endereco3 = StringField('Bairro', validators=[])
cep = StringField('CEP', validators=[])
cidade = StringField('Cidade', validators=[])
estado = StringField('Estado', validators=[])
pais = StringField('País', validators=[])
txtEndereco = StringField('txtEndereco', validators=[])
txtLatitude = StringField('txtLatitude', validators=[])
txtLongitude = StringField('txtLongitude', validators=[])
submit = SubmitField('SALVAR')
class UploadForm(FlaskForm):
imagem = FileField('imagem', validators=[FileAllowed(['gif','png', 'jpg'], "wrong format!")])
submit = SubmitField('Upload')
class RegistrationForm(FlaskForm):
nome = StringField('Nome', validators=[DataRequired()])
sobrenome = StringField('Sobrenome', validators=[DataRequired()])
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired()])
telefone = StringField('Telefone', validators=[])
avatar = StringField('Avatar',default="12", validators=[])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField('Repeat Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Continuar')
def validate_username(self, username):
user = Users.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Username existente. Por favor use um username diferente.')
def validate_email(self, email):
user = Users.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
class Registration2Form(FlaskForm):
avatar = StringField('Avatar', validators=[])
submit = SubmitField('Registrar')
class OrgcreateForm(FlaskForm):
titulo = StringField('Titulo', validators=[DataRequired()])
contato = StringField('Contato', validators=[DataRequired()])
descricao = TextAreaField('Descrição', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
logo = StringField('Logo',default="10", validators=[])
#responsavel = SelectField('Responsável',choices=[])
visibilidade = RadioField('Visibilidade', choices=[('PÚBLICO','PÚBLICO'),('PRIVADO','PRIVADO'),('SECRETO','SECRETO')])
logo_url = StringField('LogoUrl', validators=[])
submit = SubmitField('REGISTRAR')
class EditorgForm(FlaskForm):
titulo = StringField('Titulo', validators=[DataRequired()])
contato = StringField('Contato', validators=[DataRequired()])
descricao = TextAreaField('Descrição', render_kw={"rows": 70, "cols": 11}, validators=[DataRequired()])
logo = StringField('Logo',default="10", validators=[])
responsavel = SelectField('Responsável', validate_choice=False)
visibilidade = RadioField('Visibilidade', choices=[('PÚBLICO','PÚBLICO'),('PRIVADO','PRIVADO'),('SECRETO','SECRETO')])
status = RadioField('Status', choices=[('ATIVO','ATIVO'),('DESATIVADO','DESATIVADO')])
submit = SubmitField('SALVAR')
| 56.040201 | 146 | 0.666517 | 977 | 11,152 | 7.566018 | 0.239509 | 0.104167 | 0.043696 | 0.017045 | 0.627165 | 0.537338 | 0.503517 | 0.420049 | 0.393534 | 0.358631 | 0 | 0.01086 | 0.166069 | 11,152 | 198 | 147 | 56.323232 | 0.783978 | 0.052547 | 0 | 0.45625 | 0 | 0 | 0.181116 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.0125 | false | 0.08125 | 0.0375 | 0 | 0.925 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
7bf84bee55220a3a8cad45a20b4a679c9fe2d60e | 8,256 | py | Python | pysnmp/ZXR10-VSWITCH-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/ZXR10-VSWITCH-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/ZXR10-VSWITCH-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module ZXR10-VSWITCH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZXR10-VSWITCH-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:42:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion")
EntryStatus, = mibBuilder.importSymbols("RMON-MIB", "EntryStatus")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, ObjectIdentity, Unsigned32, iso, MibIdentifier, IpAddress, NotificationType, Integer32, TimeTicks, Counter32, Gauge32, Bits, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "ObjectIdentity", "Unsigned32", "iso", "MibIdentifier", "IpAddress", "NotificationType", "Integer32", "TimeTicks", "Counter32", "Gauge32", "Bits", "enterprises")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
zte = MibIdentifier((1, 3, 6, 1, 4, 1, 3902))
zxr10 = MibIdentifier((1, 3, 6, 1, 4, 1, 3902, 3))
zxr10protocol = MibIdentifier((1, 3, 6, 1, 4, 1, 3902, 3, 101))
zxr10vswitch = ModuleIdentity((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4))
if mibBuilder.loadTexts: zxr10vswitch.setLastUpdated('0408031136Z')
if mibBuilder.loadTexts: zxr10vswitch.setOrganization('ZXR10 ROS OAM group')
class DisplayString(OctetString):
pass
class VsiwtchTransMode(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2))
namedValues = NamedValues(("ip", 0), ("vlan", 1), ("mix", 2))
class VsiwtchVlanDirection(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1))
namedValues = NamedValues(("intoout", 0), ("both", 1))
zxr10vswitchIfTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1), )
if mibBuilder.loadTexts: zxr10vswitchIfTable.setStatus('current')
zxr10vswitchIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1), ).setIndexNames((0, "ZXR10-VSWITCH-MIB", "zxr10vsiwtchIfIndex"))
if mibBuilder.loadTexts: zxr10vswitchIfEntry.setStatus('current')
zxr10vsiwtchIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vsiwtchIfIndex.setStatus('current')
zxr10vswitchIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfType.setStatus('current')
zxr10vswitchIfTransType = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 3), VsiwtchTransMode()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfTransType.setStatus('current')
zxr10vswitchIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfStatus.setStatus('current')
zxr10vswitchIfAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 5), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfAddr.setStatus('current')
zxr10vswitchIfDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 1, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: zxr10vswitchIfDesc.setStatus('current')
zxr10vswitchIfTableLastchange = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 2), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchIfTableLastchange.setStatus('current')
zxr10vswitchVlanTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3), )
if mibBuilder.loadTexts: zxr10vswitchVlanTable.setStatus('current')
zxr10vsiwtchVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1), ).setIndexNames((0, "ZXR10-VSWITCH-MIB", "zxr10vswitchVlanIngressIfIndex"), (0, "ZXR10-VSWITCH-MIB", "zxr10vswitchVlanIngressExtVlanid"))
if mibBuilder.loadTexts: zxr10vsiwtchVlanEntry.setStatus('current')
zxr10vswitchVlanIngressExtVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanIngressExtVlanid.setStatus('current')
zxr10vswitchVlanIngressIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanIngressIfIndex.setStatus('current')
zxr10vswitchVlanIngressIntVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanIngressIntVlanid.setStatus('current')
zxr10vswitchVlanEgressExtVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 4), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanEgressExtVlanid.setStatus('current')
zxr10vswitchVlanEgressIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 5), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanEgressIfIndex.setStatus('current')
zxr10vswitchVlanEgressIntVlanid = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanEgressIntVlanid.setStatus('current')
zxr10vswitchVlanVlanidRange = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 7), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanVlanidRange.setStatus('current')
zxr10vswitchVlandDirection = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 8), VsiwtchVlanDirection()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlandDirection.setStatus('current')
zxr10vswitchVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 9), EntryStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanRowStatus.setStatus('current')
zxr10vswitchVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 3, 1, 10), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: zxr10vswitchVlanDesc.setStatus('current')
zxr10vswitchVlanTableLastchange = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 101, 4, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: zxr10vswitchVlanTableLastchange.setStatus('current')
mibBuilder.exportSymbols("ZXR10-VSWITCH-MIB", zxr10vswitchVlanTable=zxr10vswitchVlanTable, zxr10vswitchVlandDirection=zxr10vswitchVlandDirection, VsiwtchTransMode=VsiwtchTransMode, zxr10vsiwtchIfIndex=zxr10vsiwtchIfIndex, zxr10vswitchIfTableLastchange=zxr10vswitchIfTableLastchange, zxr10vswitchVlanEgressExtVlanid=zxr10vswitchVlanEgressExtVlanid, zxr10vswitchIfStatus=zxr10vswitchIfStatus, zxr10vswitchIfDesc=zxr10vswitchIfDesc, DisplayString=DisplayString, zxr10vswitchIfTransType=zxr10vswitchIfTransType, zte=zte, zxr10vswitchVlanEgressIntVlanid=zxr10vswitchVlanEgressIntVlanid, zxr10vswitch=zxr10vswitch, zxr10vswitchVlanIngressIntVlanid=zxr10vswitchVlanIngressIntVlanid, zxr10vswitchVlanDesc=zxr10vswitchVlanDesc, zxr10vswitchVlanTableLastchange=zxr10vswitchVlanTableLastchange, zxr10vswitchVlanRowStatus=zxr10vswitchVlanRowStatus, zxr10vswitchVlanVlanidRange=zxr10vswitchVlanVlanidRange, VsiwtchVlanDirection=VsiwtchVlanDirection, zxr10protocol=zxr10protocol, zxr10vswitchVlanEgressIfIndex=zxr10vswitchVlanEgressIfIndex, zxr10vswitchIfType=zxr10vswitchIfType, zxr10vswitchIfEntry=zxr10vswitchIfEntry, zxr10vswitchIfAddr=zxr10vswitchIfAddr, zxr10vswitchIfTable=zxr10vswitchIfTable, zxr10=zxr10, PYSNMP_MODULE_ID=zxr10vswitch, zxr10vswitchVlanIngressExtVlanid=zxr10vswitchVlanIngressExtVlanid, zxr10vswitchVlanIngressIfIndex=zxr10vswitchVlanIngressIfIndex, zxr10vsiwtchVlanEntry=zxr10vsiwtchVlanEntry)
| 107.220779 | 1,405 | 0.782461 | 847 | 8,256 | 7.624557 | 0.179457 | 0.01053 | 0.012078 | 0.016104 | 0.359864 | 0.296996 | 0.225612 | 0.225612 | 0.165996 | 0.158098 | 0 | 0.102916 | 0.082001 | 8,256 | 76 | 1,406 | 108.631579 | 0.749175 | 0.039729 | 0 | 0 | 0 | 0 | 0.123122 | 0.013386 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.015152 | 0.106061 | 0 | 0.212121 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
7bf9744f230737437e3d306790047ff082697ee6 | 622 | py | Python | tovp/contributions/admin.py | nrsimha/tovp | 311bc957c95c294811d737f5df30b0a218d35610 | [
"MIT"
] | null | null | null | tovp/contributions/admin.py | nrsimha/tovp | 311bc957c95c294811d737f5df30b0a218d35610 | [
"MIT"
] | null | null | null | tovp/contributions/admin.py | nrsimha/tovp | 311bc957c95c294811d737f5df30b0a218d35610 | [
"MIT"
] | null | null | null | from django.contrib import admin
from reversion_compare.admin import CompareVersionAdmin
from .models import Source, Pledge, BulkPayment, Contribution
class PledgeModelAdmin(CompareVersionAdmin):
class Meta:
model = Pledge
class BulkPaymentModelAdmin(CompareVersionAdmin):
class Meta:
model = BulkPayment
class ContributionModelAdmin(CompareVersionAdmin):
class Meta:
model = Contribution
admin.site.register(Source)
admin.site.register(BulkPayment, BulkPaymentModelAdmin)
admin.site.register(Pledge, PledgeModelAdmin)
admin.site.register(Contribution, ContributionModelAdmin)
| 23.923077 | 61 | 0.794212 | 58 | 622 | 8.5 | 0.362069 | 0.073022 | 0.137931 | 0.200811 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.141479 | 622 | 25 | 62 | 24.88 | 0.923221 | 0 | 0 | 0.1875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.1875 | 0 | 0.5625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
7bfb544a00bc85df01aab929cc506b66ae46b320 | 3,329 | py | Python | pyzscaler/zpa/certificates.py | LetMeR00t/pyZscaler | 6b8027a4f76fdc1f95321558251a91d954218d9f | [
"MIT"
] | 16 | 2021-07-09T00:20:31.000Z | 2022-02-17T19:29:26.000Z | pyzscaler/zpa/certificates.py | jacobgarder/pyZscaler | 77cf2ff9d64b49b932ec251a35041bfc0abf1223 | [
"MIT"
] | 62 | 2021-07-21T03:42:09.000Z | 2022-03-18T09:08:20.000Z | pyzscaler/zpa/certificates.py | jacobgarder/pyZscaler | 77cf2ff9d64b49b932ec251a35041bfc0abf1223 | [
"MIT"
] | 8 | 2021-09-11T08:14:53.000Z | 2022-03-25T20:14:41.000Z | from box import Box, BoxList
from restfly.endpoint import APIEndpoint, APISession
from pyzscaler.utils import Iterator
class CertificatesAPI(APIEndpoint):
def __init__(self, api: APISession):
super().__init__(api)
self.v2_url = api.v2_url
def list_browser_access(self, **kwargs) -> BoxList:
"""
Returns a list of all Browser Access certificates.
Args:
**kwargs: Optional keyword args.
Keyword Args:
**max_items (int, optional):
The maximum number of items to request before stopping iteration.
**max_pages (int, optional):
The maximum number of pages to request before stopping iteration.
**pagesize (int, optional):
Specifies the page size. The default size is 20, but the maximum size is 500.
**search (str, optional):
The search string used to match against features and fields.
Returns:
:obj:`BoxList`: List of all Browser Access certificates.
Examples:
>>> for cert in zpa.certificates.list_browser_access():
... print(cert)
"""
return BoxList(Iterator(self._api, f"{self.v2_url}/clientlessCertificate/issued", **kwargs))
def get_browser_access(self, certificate_id: str) -> Box:
"""
Returns information on a specified Browser Access certificate.
Args:
certificate_id (str):
The unique identifier for the Browser Access certificate.
Returns:
:obj:`Box`:
The Browser Access certificate resource record.
Examples:
>>> ba_certificate = zpa.certificates.get_browser_access('99999')
"""
return self._get(f"clientlessCertificate/{certificate_id}")
def get_enrolment(self, certificate_id: str) -> Box:
"""
Returns information on the specified enrollment certificate.
Args:
certificate_id (str): The unique id of the enrollment certificate.
Returns:
:obj:`Box`: The enrollment certificate resource record.
Examples:
enrolment_cert = zpa.certificates.get_enrolment('99999999')
"""
return self._get(f"enrollmentCert/{certificate_id}")
def list_enrolment(self, **kwargs) -> BoxList:
"""
Returns a list of all configured enrollment certificates.
Args:
**kwargs: Optional keyword args.
Keyword Args:
**max_items (int, optional):
The maximum number of items to request before stopping iteration.
**max_pages (int, optional):
The maximum number of pages to request before stopping iteration.
**pagesize (int, optional):
Specifies the page size. The default size is 20, but the maximum size is 500.
**search (str, optional):
The search string used to match against features and fields.
Returns:
:obj:`BoxList`: List of all enrollment certificates.
Examples:
>>> for cert in zpa.certificates.list_enrolment():
... print(cert)
"""
return BoxList(Iterator(self._api, f"{self.v2_url}/enrollmentCert", **kwargs))
| 33.29 | 100 | 0.604986 | 358 | 3,329 | 5.513966 | 0.251397 | 0.059271 | 0.018237 | 0.042553 | 0.632219 | 0.604863 | 0.591692 | 0.551165 | 0.424519 | 0.424519 | 0 | 0.01176 | 0.310303 | 3,329 | 99 | 101 | 33.626263 | 0.847997 | 0.606188 | 0 | 0 | 0 | 0 | 0.164303 | 0.164303 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0.2 | 0 | 0.866667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
7bfe2b4ece43c01b44ad963a5150e9f4010b6c20 | 1,271 | py | Python | api/accounts/urls.py | BerniWittmann/beachanmeldung | 9014dea5c31ea9e26f18d753d8d836741865c38e | [
"Unlicense",
"MIT"
] | null | null | null | api/accounts/urls.py | BerniWittmann/beachanmeldung | 9014dea5c31ea9e26f18d753d8d836741865c38e | [
"Unlicense",
"MIT"
] | 5 | 2020-06-05T17:31:08.000Z | 2022-03-11T23:16:12.000Z | api/accounts/urls.py | BerniWittmann/beachanmeldung | 9014dea5c31ea9e26f18d753d8d836741865c38e | [
"Unlicense",
"MIT"
] | null | null | null | from django.conf.urls import url
from authemail.views import PasswordResetVerify, PasswordChange
from .views import (CustomLogin, CustomLogout, CustomPasswordResetVerified,
CustomUserMe, CustomPasswordReset, CustomSignupVerify,
ResendVerification, CustomSignup)
urlpatterns = [
url(r'^signup/$', CustomSignup.as_view(), name='authemail-signup'),
url(r'^signup/verify/$', CustomSignupVerify.as_view(),
name='authemail-signup-verify'),
url(r'^login/$', CustomLogin.as_view(), name='authemail-login'),
url(r'^logout/$', CustomLogout.as_view(), name='authemail-logout'),
url(r'^password/reset/$', CustomPasswordReset.as_view(),
name='authemail-password-reset'),
url(r'^password/reset/verify/$', PasswordResetVerify.as_view(),
name='authemail-password-reset-verify'),
url(r'^password/reset/verified/$', CustomPasswordResetVerified.as_view(),
name='authemail-password-reset-verified'),
url(r'^password/change/$', PasswordChange.as_view(),
name='authemail-password-change'),
url(r'^users/me/$', CustomUserMe.as_view(), name='authemail-me'),
url(r'^resend_verification/$', ResendVerification.as_view(),
name='authemail-resend-verification'),
]
| 41 | 77 | 0.691581 | 131 | 1,271 | 6.625954 | 0.267176 | 0.046083 | 0.115207 | 0.218894 | 0.199309 | 0.110599 | 0 | 0 | 0 | 0 | 0 | 0 | 0.148702 | 1,271 | 30 | 78 | 42.366667 | 0.802218 | 0 | 0 | 0 | 0 | 0 | 0.302124 | 0.186467 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.478261 | 0.130435 | 0 | 0.130435 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
d007e202cb2310fcc201b71dd74d07329b841c59 | 387 | py | Python | tests/services/test_violLog.py | nagasudhirpulla/violation_msg_app | df4107c81b1343cb67573c9e1b96f271acfb0402 | [
"MIT"
] | null | null | null | tests/services/test_violLog.py | nagasudhirpulla/violation_msg_app | df4107c81b1343cb67573c9e1b96f271acfb0402 | [
"MIT"
] | 1 | 2021-11-03T10:22:53.000Z | 2021-11-06T05:41:01.000Z | tests/services/test_violLog.py | nagasudhirpulla/violation_msg_app | df4107c81b1343cb67573c9e1b96f271acfb0402 | [
"MIT"
] | null | null | null | import unittest
from src.config.appConfig import loadAppConfig
from src.services.violLog import saveViolLog
class TestGetReasonId(unittest.TestCase):
def test_run(self) -> None:
"""tests the function that gets the reason Id
"""
violLogFilePath = loadAppConfig()["violDataFilePath"]
res = saveViolLog({}, violLogFilePath)
self.assertTrue(res) | 32.25 | 61 | 0.70801 | 40 | 387 | 6.825 | 0.725 | 0.051282 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.20155 | 387 | 12 | 62 | 32.25 | 0.883495 | 0.108527 | 0 | 0 | 0 | 0 | 0.048338 | 0 | 0 | 0 | 0 | 0 | 0.125 | 1 | 0.125 | false | 0 | 0.375 | 0 | 0.625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
d0187bbe664120aff82e4e874760d0b63ddc512a | 304 | py | Python | SimorghDjango/customer_subsystem/urls.py | erfannoury/Simorgh | b7a5b6e6144117a373ab31a4660b65f224267b38 | [
"MIT"
] | 1 | 2015-02-03T14:10:00.000Z | 2015-02-03T14:10:00.000Z | SimorghDjango/customer_subsystem/urls.py | erfannoury/Simorgh | b7a5b6e6144117a373ab31a4660b65f224267b38 | [
"MIT"
] | 1 | 2015-02-05T11:22:21.000Z | 2015-02-07T16:37:06.000Z | SimorghDjango/customer_subsystem/urls.py | erfannoury/Simorgh | b7a5b6e6144117a373ab31a4660b65f224267b38 | [
"MIT"
] | null | null | null | from django.conf.urls import patterns, url
from django.conf import settings
from customer_subsystem import views
urlpatterns = patterns('',
url(r'^$', views.index, name = "index"),
url(r'^search/$', views.search, name = "search"),
)
| 30.4 | 72 | 0.555921 | 32 | 304 | 5.25 | 0.5 | 0.119048 | 0.166667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.322368 | 304 | 9 | 73 | 33.777778 | 0.815534 | 0 | 0 | 0 | 0 | 0 | 0.072607 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.428571 | 0 | 0.428571 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
d021d45c0a57f7a9d1ced88c2c20471acd74e73a | 1,035 | py | Python | psx/_dump_/48/_dump_ida_/overlay_a/set_vars.py | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 15 | 2018-06-28T01:11:25.000Z | 2021-09-27T15:57:18.000Z | psx/_dump_/48/_dump_ida_/overlay_a/set_vars.py | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-29T04:08:23.000Z | 2019-10-17T13:57:22.000Z | psx/_dump_/48/_dump_ida_/overlay_a/set_vars.py | maoa3/scalpel | 2e7381b516cded28996d290438acc618d00b2aa7 | [
"Unlicense"
] | 7 | 2018-06-28T01:11:34.000Z | 2020-05-23T09:21:48.000Z | del_items(0x80122A40)
SetType(0x80122A40, "struct Creds CreditsTitle[6]")
del_items(0x80122BE8)
SetType(0x80122BE8, "struct Creds CreditsSubTitle[28]")
del_items(0x80123084)
SetType(0x80123084, "struct Creds CreditsText[35]")
del_items(0x8012319C)
SetType(0x8012319C, "int CreditsTable[224]")
del_items(0x801243BC)
SetType(0x801243BC, "struct DIRENTRY card_dir[16][2]")
del_items(0x801248BC)
SetType(0x801248BC, "struct file_header card_header[16][2]")
del_items(0x801242E0)
SetType(0x801242E0, "struct sjis sjis_table[37]")
del_items(0x801297BC)
SetType(0x801297BC, "unsigned char save_buffer[106496]")
del_items(0x80129724)
SetType(0x80129724, "struct FeTable McLoadGameMenu")
del_items(0x80129704)
SetType(0x80129704, "char *CharFileList[5]")
del_items(0x80129718)
SetType(0x80129718, "char *Classes[3]")
del_items(0x80129740)
SetType(0x80129740, "struct FeTable McLoadCharMenu")
del_items(0x8012975C)
SetType(0x8012975C, "struct FeTable McLoadCard1Menu")
del_items(0x80129778)
SetType(0x80129778, "struct FeTable McLoadCard2Menu")
| 35.689655 | 60 | 0.815459 | 126 | 1,035 | 6.547619 | 0.412698 | 0.135758 | 0.014545 | 0.026667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.262397 | 0.064734 | 1,035 | 28 | 61 | 36.964286 | 0.589876 | 0 | 0 | 0 | 0 | 0 | 0.377778 | 0 | 0 | 0 | 0.270531 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d0289169636b78a07f310565db90c9a8ef265b60 | 5,998 | py | Python | cs15211/IslandPerimeter.py | JulyKikuAkita/PythonPrac | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | [
"Apache-2.0"
] | 1 | 2021-07-05T01:53:30.000Z | 2021-07-05T01:53:30.000Z | cs15211/IslandPerimeter.py | JulyKikuAkita/PythonPrac | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | [
"Apache-2.0"
] | null | null | null | cs15211/IslandPerimeter.py | JulyKikuAkita/PythonPrac | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | [
"Apache-2.0"
] | 1 | 2018-01-08T07:14:08.000Z | 2018-01-08T07:14:08.000Z | __source__ = 'https://leetcode.com/problems/island-perimeter/'
# Time: O(n)
# Space: O(1)
#
# Description: Leetcode # 463. Island Perimeter
# Though: what if theres' a lake?
# Lake: [[0,1,0,0],[1,0,1,0],[0,1,0,0],[1,1,0,0]]
# No Lake: [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
# -> both works
# You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
# Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water,
# and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes"
# (water inside that isn't connected to the water around the island). One cell is a square with side length 1.
# The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
#
# Example:
#
# [[0,1,0,0],
# [1,1,1,0],
# [0,1,0,0],
# [1,1,0,0]]
#
# Answer: 16
# Explanation: The perimeter is the 16 yellow stripes in the image below:
#
# Companies
# Google
# Related Topics
# Hash Table
#
import unittest
import operator
class Solution(object):
# Since there are no lakes, every pair of neighbour cells with different values is part of the perimeter
# (more precisely, the edge between them is).
# So just count the differing pairs, both horizontally and vertically
# (for the latter I simply transpose the grid).
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
return sum(sum(map(operator.ne, [0] + row, row + [0]))
for row in grid + map(list, zip(*grid)))
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
print Solution().containsDuplicate([12344555,12344555])
if __name__ == '__main__':
unittest.main()
Java = '''
Thought:
# Brute force, but do we need to do flood fill?
# 114ms 62.73%
class Solution {
public int islandPerimeter(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int row = grid.length;
int col = grid[0].length;
int sum = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j] == 1) {
int k = 0;
if (i > 0 && grid[i - 1][j] == 1) k++;
if (j > 0 && grid[i][j - 1] == 1) k++;
if (i + 1 < row && grid[i + 1][j] == 1) k++;
if (j + 1 < col && grid[i][j + 1] == 1) k++;
sum += (4 - k);
}
}
}
return sum;
}
}
# Improve, do not re-visit
add 4 for each land and remove 2 for each neighbor
Thought: loop over the matrix and count the number of islands;
if the current dot is an island, count if it has any right neighbour or down neighbour;
the result is islands * 4 - neighbours * 2
# 78ms 45.56%
class Solution {
public int islandPerimeter(int[][] grid) {
int islands = 0, neighbors = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == 1) {
islands++;
if ( i < grid.length - 1 && grid[i+1][j] == 1) neighbors++;
if (j < grid[i].length - 1 && grid[i][j + 1] == 1) neighbors++;
}
}
}
return islands * 4 - neighbors * 2;
}
}
# 53ms 98.72%
class Solution {
public int islandPerimeter(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
res += 4;
if (i > 0 && grid[i - 1][j] == 1) res -= 2;
if (j > 0 && grid[i][j-1] == 1) res -= 2;
}
}
}
return res;
}
}
# DFS:
# 132ms 18.36%
class Solution {
public int islandPerimeter(int[][] grid) {
if (grid == null) return 0;
for (int i = 0 ; i < grid.length ; i++){
for (int j = 0 ; j < grid[0].length ; j++){
if (grid[i][j] == 1) {
return getPerimeter(grid,i,j); // if not lake,
// count += getPerimeter(grid,i,j); // and return count at the end if with lake
}
}
}
return 0;
}
public int getPerimeter(int[][] grid, int i, int j){
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0) {return 1;}
if (grid[i][j] == -1) return 0;
int count = 0;
grid[i][j] = -1;
count += getPerimeter(grid, i-1, j);
count += getPerimeter(grid, i, j-1);
count += getPerimeter(grid, i, j+1);
count += getPerimeter(grid, i+1, j);
return count;
}
}
# 124ms 32.91%
class Solution {
// the idea is traverse the whole grid, automatically +=4 every time we see a 1,
// check this point's surroundings, if the surrounding is not of of boundary and it
// is a 1, means, also a land, then -= 1
private static final int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int islandPerimeter(int[][] grid) {
int res = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] == 1){
res += 4;
for(int[] dir : dirs){
int x = dir[0] + i;
int y = dir[1] + j;
if(x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || grid[x][y] == 0) continue;
res -= 1;
}
}
}
}
return res;
}
}
'''
| 32.775956 | 114 | 0.493164 | 845 | 5,998 | 3.485207 | 0.265089 | 0.040747 | 0.032598 | 0.0309 | 0.296774 | 0.278778 | 0.237012 | 0.216638 | 0.195925 | 0.195925 | 0 | 0.056159 | 0.355785 | 5,998 | 182 | 115 | 32.956044 | 0.706004 | 0.199233 | 0 | 0.234375 | 0 | 0.09375 | 0.893336 | 0.034277 | 0 | 0 | 0 | 0 | 0.007813 | 0 | null | null | 0 | 0.015625 | null | null | 0.007813 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d02bde8f0c7d3bace5760baa46013d89f9796a63 | 637 | py | Python | generateSite.py | guilhermeoki/botpad | 141e2092267438306cb2ece5a2dbaf559f551cf4 | [
"MIT"
] | null | null | null | generateSite.py | guilhermeoki/botpad | 141e2092267438306cb2ece5a2dbaf559f551cf4 | [
"MIT"
] | null | null | null | generateSite.py | guilhermeoki/botpad | 141e2092267438306cb2ece5a2dbaf559f551cf4 | [
"MIT"
] | null | null | null | import random
import string
import hashlib
class Page:
def create_password(self):
password = "".join(random.SystemRandom().choice(string.ascii_uppercase + string.digits + string.ascii_lowercase) for _ in range(random.randint(50,100)))
return password
def generate_hash(self):
pw = self.create_password()
h = hashlib.sha512(pw).hexdigest()
return h
def create_page(self):
hash_message = self.generate_hash()
self.site = 'http://dontpad.com/'+hash_message+"/control"
return self.site
if __name__ == '__main__':
p = Page()
print p.create_page() | 28.954545 | 160 | 0.653061 | 78 | 637 | 5.089744 | 0.525641 | 0.04534 | 0.080605 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.016327 | 0.230769 | 637 | 22 | 161 | 28.954545 | 0.793878 | 0 | 0 | 0 | 0 | 0 | 0.054859 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.222222 | 0.166667 | null | null | 0.055556 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
d02cc0665931fd092264257874566c608a52931a | 487 | py | Python | 框架/FastAPI/main.py | wanZzz6/Modules-Learn | 7bb92327372ec369e23b2ef307302a91a9b86a5d | [
"MIT"
] | 13 | 2020-03-07T04:03:36.000Z | 2022-02-28T10:42:32.000Z | 框架/FastAPI/main.py | wanZzz6/Modules-Learn | 7bb92327372ec369e23b2ef307302a91a9b86a5d | [
"MIT"
] | null | null | null | 框架/FastAPI/main.py | wanZzz6/Modules-Learn | 7bb92327372ec369e23b2ef307302a91a9b86a5d | [
"MIT"
] | 2 | 2020-03-07T04:03:45.000Z | 2020-04-07T15:35:58.000Z | # coding: utf-8
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class User(BaseModel):
id: int
name: str
friends: list
@app.get("/")
def index():
return {"admin": "welcome to FastAPI"}
@app.get("/users/{user_id}")
def read_user(user_id: int, name: str = None):
return {"user_id": user_id, "name": name}
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
return {"user_name": user.name, "user_id": user_id}
| 18.037037 | 55 | 0.655031 | 74 | 487 | 4.162162 | 0.391892 | 0.155844 | 0.058442 | 0.077922 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.0025 | 0.178645 | 487 | 26 | 56 | 18.730769 | 0.7675 | 0.026694 | 0 | 0 | 0 | 0 | 0.175847 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.1875 | false | 0 | 0.125 | 0.1875 | 0.75 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
d02cd28867d46f358fcc144d4e2cf3d655041447 | 1,660 | py | Python | test/samples/gtk/gtkcombobox.py | ABEMBARKA/monoUI | 5fda266ad2db8f89580a40b525973d86cd8de939 | [
"MIT"
] | 1 | 2019-08-13T15:22:12.000Z | 2019-08-13T15:22:12.000Z | test/samples/gtk/gtkcombobox.py | ABEMBARKA/monoUI | 5fda266ad2db8f89580a40b525973d86cd8de939 | [
"MIT"
] | null | null | null | test/samples/gtk/gtkcombobox.py | ABEMBARKA/monoUI | 5fda266ad2db8f89580a40b525973d86cd8de939 | [
"MIT"
] | 1 | 2019-08-13T15:22:17.000Z | 2019-08-13T15:22:17.000Z | #!/usr/bin/env python
# example gtkcombobox.py
import pygtk
pygtk.require('2.0')
import gtk
import gobject
class ComboBox:
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_title("Combo Box")
self.window.connect("delete_event", self.delete_event)
self.window.set_border_width(12)
# create a horizontal box (VBox) to organize widgets
# we will pack two buttons in this box.
self.vbox = gtk.VBox(False, 0)
store = gtk.ListStore(gobject.TYPE_STRING)
combo = gtk.ComboBox(store)
cell = gtk.CellRendererText()
combo.pack_start(cell, True)
combo.add_attribute(cell, 'text', 0)
combo.insert_text(0, "Apple")
combo.insert_text(1, "Banana")
combo.insert_text(2, "Cherry")
combo.insert_text(3, "Durian")
combo.insert_text(4, "Fig")
combo.insert_text(5, "Grapefruit")
combo.insert_text(6, "Jakfruit")
combo.insert_text(7, "Kiwi")
combo.insert_text(8, "Lemon")
combo.insert_text(9, "Mango")
combo.insert_text(10, "Orange")
combo.insert_text(11, "Papaya")
self.button = gtk.Button("ButtoN")
self.vbox.pack_start(self.button, True, True, 0)
self.vbox.pack_start(combo, True, True, 0)
self.window.add(self.vbox)
self.button.show()
self.vbox.show()
combo.show()
self.window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
ComboBox()
main()
| 27.213115 | 62 | 0.613855 | 217 | 1,660 | 4.525346 | 0.414747 | 0.13442 | 0.183299 | 0.034623 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018639 | 0.256627 | 1,660 | 60 | 63 | 27.666667 | 0.777147 | 0.079518 | 0 | 0 | 0 | 0 | 0.073491 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.066667 | null | null | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d0373c1cc3d8625adf95c7e72d29205720642412 | 4,992 | py | Python | backend/tomato/migrations/migration_0001.py | dswd/ToMaTo | 355fd3a8c7f95dc72c62383b3edfa8f6c0396bf4 | [
"BSD-4-Clause-UC"
] | 2 | 2016-11-10T06:12:05.000Z | 2016-11-10T06:12:10.000Z | backend/tomato/migrations/migration_0001.py | dswd/ToMaTo | 355fd3a8c7f95dc72c62383b3edfa8f6c0396bf4 | [
"BSD-4-Clause-UC"
] | 2 | 2015-01-19T16:00:24.000Z | 2015-01-20T11:33:56.000Z | backend/tomato/migrations/migration_0001.py | dswd/ToMaTo | 355fd3a8c7f95dc72c62383b3edfa8f6c0396bf4 | [
"BSD-4-Clause-UC"
] | 1 | 2016-11-10T06:12:15.000Z | 2016-11-10T06:12:15.000Z | from mongoengine import *
import string, random, crypt, time
from mongoengine.errors import NotUniqueError
class Usage(EmbeddedDocument):
memory = FloatField(default=0.0) #unit: bytes
diskspace = FloatField(default=0.0) #unit: bytes
traffic = FloatField(default=0.0) #unit: bytes
cputime = FloatField(default=0.0) #unit: cpu seconds
class UsageRecord(EmbeddedDocument):
begin = FloatField(required=True)
end = FloatField(required=True)
measurements = IntField(default=0)
usage = EmbeddedDocumentField(Usage, required=True)
meta = {
'collection': 'usage_record',
'ordering': ['type', 'end'],
'indexes': [
('type', 'end')
]
}
class UsageStatistics(Document):
by5minutes = ListField(EmbeddedDocumentField(UsageRecord), db_field='5minutes')
byHour = ListField(EmbeddedDocumentField(UsageRecord), db_field='hour')
byDay = ListField(EmbeddedDocumentField(UsageRecord), db_field='day')
byMonth = ListField(EmbeddedDocumentField(UsageRecord), db_field='month')
byYear = ListField(EmbeddedDocumentField(UsageRecord), db_field='year')
meta = {
'collection': 'usage_statistics',
}
class Organization(Document):
name = StringField(unique=True, required=True)
totalUsage = ReferenceField(UsageStatistics, db_field='total_usage', required=True, reverse_delete_rule=DENY)
label = StringField(required=True)
homepageUrl = URLField(db_field='homepage_url')
imageUrl = URLField(db_field='image_url')
description = StringField()
meta = {
'ordering': ['name'],
'indexes': [
'name'
]
}
class Quota(EmbeddedDocument):
monthly = EmbeddedDocumentField(Usage, required=True)
used = EmbeddedDocumentField(Usage, required=True)
usedTime = FloatField(db_field='used_time', required=True)
continousFactor = FloatField(db_field='continous_factor')
class User(Document):
name = StringField(required=True, unique_with='origin')
origin = StringField(required=True)
organization = ReferenceField(Organization, required=True, reverse_delete_rule=DENY)
password = StringField(required=True)
passwordTime = FloatField(db_field='password_time', required=True)
lastLogin = FloatField(db_field='last_login', required=True)
totalUsage = ReferenceField(UsageStatistics, db_field='total_usage', required=True, reverse_delete_rule=DENY)
quota = EmbeddedDocumentField(Quota, required=True)
realname = StringField()
email = EmailField()
flags = ListField(StringField())
clientData = DictField(db_field='client_data')
meta = {
'ordering': ['name'],
'indexes': [
'lastLogin', 'passwordTime', 'flags', 'organization', ('name', 'origin')
]
}
def storePassword(self, password):
saltchars = string.ascii_letters + string.digits + './'
salt = "$1$"
salt += ''.join([ random.choice(saltchars) for _ in range(8) ])
self.password = crypt.crypt(password, salt)
self.password_time = time.time()
self.save()
return self
DEFAULTS = {
"kvmqm": {"ram": 512, "cpus": 1, "diskspace": 10240},
"openvz": {"ram": 512, "cpus": 1, "diskspace": 10240},
"repy": {"ram": 50, "cpus": 0.25},
}
class Profile(Document):
tech = StringField(required=True)
name = StringField(required=True, unique_with='tech')
preference = IntField(default=0, required=True)
label = StringField()
description = StringField()
restricted = BooleanField(default=False)
ram = IntField(min_value=0)
cpus = FloatField(min_value=0)
diskspace = IntField(min_value=0)
meta = {
'ordering': ['tech', '+preference', 'name'],
'indexes': [
('tech', 'preference'), ('tech', 'name')
]
}
class Network(Document):
kind = StringField(required=True, unique=True)
preference = IntField(default=0, required=True)
restricted = BooleanField(default=False)
label = StringField()
description = StringField()
big_icon = BooleanField(default=False)
show_as_common = BooleanField(default=False)
meta = {
'ordering': ['-preference', 'kind'],
'indexes': [
('kind', 'preference')
]
}
def migrate():
try:
org = Organization(name="others", label="Others", totalUsage=UsageStatistics().save()).save()
except NotUniqueError:
org = Organization.objects.get(name="others")
try:
User(name="admin", origin="", organization=org, password="", passwordTime=time.time(),
lastLogin=time.time(), totalUsage=UsageStatistics().save(), email="mail@example.com",
quota=Quota(monthly=Usage(cputime= 5.0 *(60*60*24*30), memory=10e9, diskspace=100e9, traffic=5.0e6 /8.0*(60*60*24*30)), used=Usage(), usedTime=time.time(), continousFactor=1.0),
realname="Admin", flags=["global_admin", "global_host_manager", "debug", "nomails"]).save().storePassword("changeme")
except NotUniqueError:
pass
for tech, defaults in DEFAULTS.items():
try:
Profile(tech=tech, name="normal", label="Normal", preference=10, ram=defaults['ram'], cpus=defaults['cpus'], diskspace=defaults.get('diskspace', 0)).save()
except NotUniqueError:
pass
try:
Network(kind="internet", preference=10, label="Internet", big_icon=True, show_as_common=True).save()
except NotUniqueError:
pass | 33.503356 | 180 | 0.723958 | 564 | 4,992 | 6.322695 | 0.294326 | 0.074033 | 0.045149 | 0.060292 | 0.224341 | 0.145541 | 0.056646 | 0.056646 | 0.056646 | 0.056646 | 0 | 0.017743 | 0.119391 | 4,992 | 149 | 181 | 33.503356 | 0.793449 | 0.010016 | 0 | 0.269231 | 0 | 0 | 0.121685 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.015385 | false | 0.084615 | 0.023077 | 0 | 0.546154 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
d03da8b9b1caaad90879dfc43136c509eda1d3f4 | 1,270 | py | Python | viper/icon_viper/actions/list_available_modules/schema.py | xhennessy-r7/insightconnect-plugins | 59268051313d67735b5dd3a30222eccb92aca8e9 | [
"MIT"
] | null | null | null | viper/icon_viper/actions/list_available_modules/schema.py | xhennessy-r7/insightconnect-plugins | 59268051313d67735b5dd3a30222eccb92aca8e9 | [
"MIT"
] | null | null | null | viper/icon_viper/actions/list_available_modules/schema.py | xhennessy-r7/insightconnect-plugins | 59268051313d67735b5dd3a30222eccb92aca8e9 | [
"MIT"
] | null | null | null | # GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "List available modules"
class Input:
pass
class Output:
MODULES = "modules"
class ListAvailableModulesInput(komand.Input):
schema = json.loads("""
{}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
class ListAvailableModulesOutput(komand.Output):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"modules": {
"type": "array",
"title": "Available Modules",
"items": {
"$ref": "#/definitions/Module"
},
"order": 1
}
},
"required": [
"modules"
],
"definitions": {
"Module": {
"type": "object",
"title": "Module",
"properties": {
"description": {
"type": "string",
"title": "Module Description",
"description": "Description of module",
"order": 2
},
"name": {
"type": "string",
"title": "Module Title",
"description": "Title of module",
"order": 1
}
}
}
}
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
| 18.405797 | 57 | 0.522047 | 108 | 1,270 | 5.916667 | 0.398148 | 0.050078 | 0.046948 | 0.050078 | 0.134585 | 0.134585 | 0.134585 | 0.134585 | 0.134585 | 0.134585 | 0 | 0.003452 | 0.315748 | 1,270 | 68 | 58 | 18.676471 | 0.731876 | 0.029134 | 0 | 0.285714 | 1 | 0 | 0.628757 | 0.017872 | 0 | 0 | 0 | 0 | 0 | 1 | 0.035714 | false | 0.017857 | 0.035714 | 0 | 0.232143 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d053a35eebc8809d28a8c4295616adee5dc1ec33 | 175 | py | Python | disassembler/formats/helpers/__init__.py | jchristman/PyDA | 25a1091bfff369736e534424ddbdc426ba32a3a0 | [
"BSD-3-Clause"
] | 12 | 2015-11-24T22:43:14.000Z | 2021-03-24T05:01:43.000Z | disassembler/formats/helpers/__init__.py | jchristman/PyDA | 25a1091bfff369736e534424ddbdc426ba32a3a0 | [
"BSD-3-Clause"
] | 1 | 2015-04-22T17:26:31.000Z | 2015-04-22T17:48:38.000Z | disassembler/formats/helpers/__init__.py | jchristman/PyDA | 25a1091bfff369736e534424ddbdc426ba32a3a0 | [
"BSD-3-Clause"
] | 9 | 2015-03-05T17:43:47.000Z | 2021-03-19T14:29:49.000Z | import os,glob
filenames = [os.path.splitext(os.path.basename(f))[0] for f in glob.glob(os.path.dirname(__file__)+"/*.py")]
filenames.remove('__init__')
__all__ = filenames | 43.75 | 109 | 0.725714 | 27 | 175 | 4.259259 | 0.62963 | 0.156522 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00625 | 0.085714 | 175 | 4 | 110 | 43.75 | 0.7125 | 0 | 0 | 0 | 0 | 0 | 0.075145 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d058b9fb39f701ac74001f7c045adae2f75cc99d | 684 | py | Python | leetcode/14.LongestCommonPrefix/soln.py | saisankargochhayat/algo_quest | a24f9a22c019ab31d56bd5a7ca5ba790d54ce5dc | [
"Apache-2.0"
] | 3 | 2017-02-15T20:55:04.000Z | 2018-09-26T18:48:24.000Z | leetcode/14.LongestCommonPrefix/soln.py | saisankargochhayat/algo_quest | a24f9a22c019ab31d56bd5a7ca5ba790d54ce5dc | [
"Apache-2.0"
] | 4 | 2017-10-07T18:59:20.000Z | 2019-10-08T05:43:25.000Z | leetcode/14.LongestCommonPrefix/soln.py | saisankargochhayat/algo_quest | a24f9a22c019ab31d56bd5a7ca5ba790d54ce5dc | [
"Apache-2.0"
] | 1 | 2017-10-08T06:52:21.000Z | 2017-10-08T06:52:21.000Z | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
res = []
common = [res.append(list(set(a))[0]) for a in itertools.takewhile(lambda x: len(set(x)) == 1, [x for x in zip(*strs)])]
return "".join(res)
# Enumeration soln
# def longestCommonPrefix(self, strs):
# """
# :type strs: List[str]
# :rtype: str
# """
# if not strs:
# return ""
# shortest = min(strs,key=len)
# for i, ch in enumerate(shortest):
# for other in strs:
# if other[i] != ch:
# return shortest[:i]
# return shortest
| 29.73913 | 128 | 0.479532 | 77 | 684 | 4.25974 | 0.493506 | 0.128049 | 0.158537 | 0.182927 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004706 | 0.378655 | 684 | 22 | 129 | 31.090909 | 0.767059 | 0.466374 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0 | 0 | 0.6 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
d05cab55ee67590f412e777583344cdaf4c5da5e | 18,881 | py | Python | open_spiel/python/games/dynamic_routing_data.py | mcx/open_spiel | 062cbfc07621343e7d77209cb421ba690328142b | [
"Apache-2.0"
] | null | null | null | open_spiel/python/games/dynamic_routing_data.py | mcx/open_spiel | 062cbfc07621343e7d77209cb421ba690328142b | [
"Apache-2.0"
] | null | null | null | open_spiel/python/games/dynamic_routing_data.py | mcx/open_spiel | 062cbfc07621343e7d77209cb421ba690328142b | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
"""Default data for dynamic routing game."""
from open_spiel.python.games import dynamic_routing_utils
# The line network is a very simple network (O -> A -> D) with the goal of
# testing the routing game. There is no possible action and all cars will go
# from node O (being at node O means being on the link bef_O->O) to node D
# (being at node D means being on the link D->aft_D).
LINE_NETWORK = dynamic_routing_utils.Network({
"bef_O": "O",
"O": ["A"],
"A": ["D"],
"D": ["aft_D"],
"aft_D": []
})
LINE_NETWORK_VEHICLES_DEMAND = [
dynamic_routing_utils.Vehicle("bef_O->O", "D->aft_D") for _ in range(2)
]
LINE_NETWORK_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand("bef_O->O", "D->aft_D", 0,
100)
]
# The Braess network comes from the Braess paradox: Braess, D., 1968. "Uber ein
# Paradoxon aus der Verkehrsplanung". Unternehmensforschung 12, 258-268.
BRAESS_NUM_PLAYER = 5
BRAESS_NETWORK = dynamic_routing_utils.Network(
{
"O": "A",
"A": ["B", "C"],
"B": ["C", "D"],
"C": ["D"],
"D": ["E"],
"E": []
},
node_position={
"O": (0, 0),
"A": (1, 0),
"B": (2, 1),
"C": (2, -1),
"D": (3, 0),
"E": (4, 0)
},
bpr_a_coefficient={
"O->A": 0,
"A->B": 1.0,
"A->C": 0,
"B->C": 0,
"B->D": 0,
"C->D": 1.0,
"D->E": 0
},
bpr_b_coefficient={
"O->A": 1.0,
"A->B": 1.0,
"A->C": 1.0,
"B->C": 1.0,
"B->D": 1.0,
"C->D": 1.0,
"D->E": 1.0
},
capacity={
"O->A": BRAESS_NUM_PLAYER,
"A->B": BRAESS_NUM_PLAYER,
"A->C": BRAESS_NUM_PLAYER,
"B->C": BRAESS_NUM_PLAYER,
"B->D": BRAESS_NUM_PLAYER,
"C->D": BRAESS_NUM_PLAYER,
"D->E": BRAESS_NUM_PLAYER
},
free_flow_travel_time={
"O->A": 0,
"A->B": 1.0,
"A->C": 2.0,
"B->C": 0.25,
"B->D": 2.0,
"C->D": 1.0,
"D->E": 0
})
BRAESS_NETWORK_VEHICLES_DEMAND = [
dynamic_routing_utils.Vehicle("O->A", "D->E")
for _ in range(BRAESS_NUM_PLAYER)
]
BRAESS_NETWORK_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand("O->A", "D->E", 0,
BRAESS_NUM_PLAYER)
]
# The Sioux Falls data comes from "An Efficient Approach to Solving the Road
# Network Equilibrium Traffic Assignment Problem" by L. J. LeBlanc and E. K.
# Morlok (http://doi.org/10.1016/0041-1647(75)90030-1). We scale uniformly the
# data to decrease the number of time steps needed to cross the network. The
# demand and congestion functions data has been copied and pasted from the
# paper. The node position has been created from the paper's figure with a
# simple scale.
__SIOUX_FALLS_ADJACENCY = {
"1": ["2", "3"],
"2": ["1", "6"],
"3": ["1", "4", "12"],
"4": ["3", "5", "11"],
"5": ["4", "6", "9"],
"6": ["2", "5", "8"],
"7": ["8", "18"],
"8": ["6", "7", "9", "16"],
"9": ["5", "8", "10"],
"10": ["9", "11", "15", "16", "17"],
"11": ["4", "10", "12", "14"],
"12": ["3", "11", "13"],
"13": ["12", "24"],
"14": ["11", "15", "23"],
"15": ["10", "14", "19", "22"],
"16": ["8", "10", "17", "18"],
"17": ["10", "16", "19"],
"18": ["7", "16", "20"],
"19": ["15", "17", "20"],
"20": ["18", "19", "21", "22"],
"21": ["20", "22", "24"],
"22": ["15", "20", "21", "23"],
"23": ["14", "22", "24"],
"24": ["13", "21", "23"]
}
__SIOUX_FALLS_FREE_FLOW_TRAVEL_TIME = {
"1->2": 6, "1->3": 4, "2->1": 6, "2->6": 5, "3->1": 4, "3->4": 4,
"3->12": 4, "4->3": 4, "4->5": 2, "4->11": 6, "5->4": 2, "5->6": 4,
"5->9": 5, "6->2": 5, "6->5": 4, "6->8": 2, "7->8": 3, "7->18": 2,
"8->6": 2, "8->7": 3, "8->9": 10, "8->16": 5, "9->5": 5, "9->8": 10,
"9->10": 3, "10->9": 3, "10->11": 5, "10->15": 6, "10->16": 4, "10->17": 8,
"11->4": 6, "11->10": 5, "11->12": 6, "11->14": 4, "12->3": 4, "12->11": 6,
"12->13": 3, "13->12": 3, "13->24": 4, "14->11": 4, "14->15": 5,
"14->23": 4, "15->10": 6, "15->14": 5, "15->19": 3, "15->22": 3, "16->8": 5,
"16->10": 4, "16->17": 2, "16->18": 3, "17->10": 8, "17->16": 2,
"17->19": 2, "18->7": 2, "18->16": 3, "18->20": 4, "19->15": 3, "19->17": 2,
"19->20": 4, "20->18": 4, "20->19": 4, "20->21": 6, "20->22": 5,
"21->20": 6, "21->22": 2, "21->24": 3, "22->15": 3, "22->20": 5,
"22->21": 2, "22->23": 4, "23->14": 4, "23->22": 4, "23->24": 2,
"24->13": 4, "24->21": 3, "24->23": 2
}
__SIOUX_FALLS_BPR_A_COEFF = {
"1->2": 2 * 1e-18,
"1->3": 2 * 1e-18,
"2->1": 2 * 1e-18,
"2->6": 1240 * 1e-18,
"3->1": 2 * 1e-18,
"3->4": 6 * 1e-18,
"3->12": 2 * 1e-18,
"4->3": 6 * 1e-18,
"4->5": 3 * 1e-18,
"4->11": 1550 * 1e-18,
"5->4": 3 * 1e-18,
"5->6": 1000 * 1e-18,
"5->9": 75 * 1e-18,
"6->2": 1240 * 1e-18,
"6->5": 1000 * 1e-18,
"6->8": 520 * 1e-18,
"7->8": 119 * 1e-18,
"7->18": 1 * 1e-18,
"8->6": 520 * 1e-18,
"8->7": 119 * 1e-18,
"8->9": 2306 * 1e-18,
"8->16": 1156 * 1e-18,
"9->5": 75 * 1e-18,
"9->8": 2306 * 1e-18,
"9->10": 11 * 1e-18,
"10->9": 11 * 1e-18,
"10->11": 75 * 1e-18,
"10->15": 26 * 1e-18,
"10->16": 1080 * 1e-18,
"10->17": 1929 * 1e-18,
"11->4": 1550 * 1e-18,
"11->10": 75 * 1e-18,
"11->12": 1550 * 1e-18,
"11->14": 1061 * 1e-18,
"12->3": 2 * 1e-18,
"12->11": 1550 * 1e-18,
"12->13": 1 * 1e-18,
"13->12": 1 * 1e-18,
"13->24": 893 * 1e-18,
"14->11": 1061 * 1e-18,
"14->15": 1085 * 1e-18,
"14->23": 1020 * 1e-18,
"15->10": 26 * 1e-18,
"15->14": 1085 * 1e-18,
"15->19": 10 * 1e-18,
"15->22": 53 * 1e-18,
"16->8": 1156 * 1e-18,
"16->10": 1080 * 1e-18,
"16->17": 401 * 1e-18,
"16->18": 3 * 1e-18,
"17->10": 1929 * 1e-18,
"17->16": 401 * 1e-18,
"17->19": 553 * 1e-18,
"18->7": 1 * 1e-18,
"18->16": 3 * 1e-18,
"18->20": 2 * 1e-18,
"19->15": 10 * 1e-18,
"19->17": 553 * 1e-18,
"19->20": 957 * 1e-18,
"20->18": 2 * 1e-18,
"20->19": 957 * 1e-18,
"20->21": 1373 * 1e-18,
"20->22": 1130 * 1e-18,
"21->20": 1373 * 1e-18,
"21->22": 401 * 1e-18,
"21->24": 789 * 1e-18,
"22->15": 53 * 1e-18,
"22->20": 1130 * 1e-18,
"22->21": 401 * 1e-18,
"22->23": 960 * 1e-18,
"23->14": 1020 * 1e-18,
"23->22": 960 * 1e-18,
"23->24": 451 * 1e-18,
"24->13": 893 * 1e-18,
"24->21": 789 * 1e-18,
"24->23": 451 * 1e-18,
}
__SIOUX_FALLS_NODES = {
"1": (0, 9), "2": (5, 9), "3": (0, 8), "4": (1, 8), "5": (3, 8),
"6": (5, 8), "7": (7, 6), "8": (5, 6), "9": (3, 6), "10": (3, 5),
"11": (1, 5), "12": (0, 5), "13": (0, 0), "14": (1, 2), "15": (3, 2),
"16": (5, 5), "17": (5, 4), "18": (7, 5), "19": (5, 2), "20": (5, 0),
"21": (3, 0), "22": (3, 1), "23": (1, 1), "24": (1, 0)
}
__SIOUX_FALLS_DEMAND_AUX = [
("2", "1", 1), ("3", "1", 1), ("4", "1", 5), ("5", "1", 2),
("6", "1", 3), ("7", "1", 5), ("8", "1", 8), ("9", "1", 5),
("10", "1", 13), ("11", "1", 5), ("12", "1", 2), ("13", "1", 5),
("14", "1", 3), ("15", "1", 5), ("16", "1", 5), ("17", "1", 4),
("18", "1", 1), ("19", "1", 3), ("20", "1", 3), ("21", "1", 1),
("22", "1", 4), ("23", "1", 3), ("24", "1", 1), ("1", "2", 1),
("3", "2", 1), ("4", "2", 2), ("5", "2", 1), ("6", "2", 4),
("7", "2", 2), ("8", "2", 4), ("9", "2", 2), ("10", "2", 6),
("11", "2", 2), ("12", "2", 1), ("13", "2", 3), ("14", "2", 1),
("15", "2", 1), ("16", "2", 4), ("17", "2", 2), ("19", "2", 1),
("20", "2", 1), ("22", "2", 1), ("1", "3", 1), ("2", "3", 1),
("4", "3", 2), ("5", "3", 1), ("6", "3", 3), ("7", "3", 1),
("8", "3", 2), ("9", "3", 1), ("10", "3", 3), ("11", "3", 3),
("12", "3", 2), ("13", "3", 1), ("14", "3", 1), ("15", "3", 1),
("16", "3", 2), ("17", "3", 1), ("22", "3", 1), ("23", "3", 1),
("1", "4", 5), ("2", "4", 2), ("3", "4", 2), ("5", "4", 5),
("6", "4", 4), ("7", "4", 4), ("8", "4", 7), ("9", "4", 7),
("10", "4", 12), ("11", "4", 14), ("12", "4", 6), ("13", "4", 6),
("14", "4", 5), ("15", "4", 5), ("16", "4", 8), ("17", "4", 5),
("18", "4", 1), ("19", "4", 2), ("20", "4", 3), ("21", "4", 2),
("22", "4", 4), ("23", "4", 5), ("24", "4", 2), ("1", "5", 2),
("2", "5", 1), ("3", "5", 1), ("4", "5", 5), ("6", "5", 2),
("7", "5", 2), ("8", "5", 5), ("9", "5", 8), ("10", "5", 10),
("11", "5", 5), ("12", "5", 2), ("13", "5", 2), ("14", "5", 1),
("15", "5", 2), ("16", "5", 5), ("17", "5", 2), ("19", "5", 1),
("20", "5", 1), ("21", "5", 1), ("22", "5", 2), ("23", "5", 1),
("1", "6", 3), ("2", "6", 4), ("3", "6", 3), ("4", "6", 4),
("5", "6", 2), ("7", "6", 4), ("8", "6", 8), ("9", "6", 4),
("10", "6", 8), ("11", "6", 4), ("12", "6", 2), ("13", "6", 2),
("14", "6", 1), ("15", "6", 2), ("16", "6", 9), ("17", "6", 5),
("18", "6", 1), ("19", "6", 2), ("20", "6", 3), ("21", "6", 1),
("22", "6", 2), ("23", "6", 1), ("24", "6", 1), ("1", "7", 5),
("2", "7", 2), ("3", "7", 1), ("4", "7", 4), ("5", "7", 2),
("6", "7", 4), ("8", "7", 10), ("9", "7", 6), ("10", "7", 19),
("11", "7", 5), ("12", "7", 7), ("13", "7", 4), ("14", "7", 2),
("15", "7", 5), ("16", "7", 14), ("17", "7", 10), ("18", "7", 2),
("19", "7", 4), ("20", "7", 5), ("21", "7", 2), ("22", "7", 5),
("23", "7", 2), ("24", "7", 1), ("1", "8", 8), ("2", "8", 4),
("3", "8", 2), ("4", "8", 7), ("5", "8", 5), ("6", "8", 8),
("7", "8", 10), ("9", "8", 8), ("10", "8", 16), ("11", "8", 8),
("12", "8", 6), ("13", "8", 6), ("14", "8", 4), ("15", "8", 6),
("16", "8", 22), ("17", "8", 14), ("18", "8", 3), ("19", "8", 7),
("20", "8", 9), ("21", "8", 4), ("22", "8", 5), ("23", "8", 3),
("24", "8", 2), ("1", "9", 5), ("2", "9", 2), ("3", "9", 1),
("4", "9", 7), ("5", "9", 8), ("6", "9", 4), ("7", "9", 6),
("8", "9", 8), ("10", "9", 28), ("11", "9", 14), ("12", "9", 6),
("13", "9", 6), ("14", "9", 6), ("15", "9", 9), ("16", "9", 14),
("17", "9", 9), ("18", "9", 2), ("19", "9", 4), ("20", "9", 6),
("21", "9", 3), ("22", "9", 7), ("23", "9", 5), ("24", "9", 2),
("1", "10", 13), ("2", "10", 6), ("3", "10", 3), ("4", "10", 12),
("5", "10", 10), ("6", "10", 8), ("7", "10", 19), ("8", "10", 16),
("9", "10", 28), ("11", "10", 40), ("12", "10", 20), ("13", "10", 19),
("14", "10", 21), ("15", "10", 40), ("16", "10", 44), ("17", "10", 39),
("18", "10", 7), ("19", "10", 18), ("20", "10", 25), ("21", "10", 12),
("22", "10", 26), ("23", "10", 18), ("24", "10", 8), ("1", "11", 5),
("2", "11", 2), ("3", "11", 3), ("4", "11", 15), ("5", "11", 5),
("6", "11", 4), ("7", "11", 5), ("8", "11", 8), ("9", "11", 14),
("10", "11", 39), ("12", "11", 14), ("13", "11", 10), ("14", "11", 16),
("15", "11", 14), ("16", "11", 14), ("17", "11", 10), ("18", "11", 1),
("19", "11", 4), ("20", "11", 6), ("21", "11", 4), ("22", "11", 11),
("23", "11", 13), ("24", "11", 6), ("1", "12", 2), ("2", "12", 1),
("3", "12", 2), ("4", "12", 6), ("5", "12", 2), ("6", "12", 2),
("7", "12", 7), ("8", "12", 6), ("9", "12", 6), ("10", "12", 20),
("11", "12", 14), ("13", "12", 13), ("14", "12", 7), ("15", "12", 7),
("16", "12", 7), ("17", "12", 6), ("18", "12", 2), ("19", "12", 3),
("20", "12", 4), ("21", "12", 3), ("22", "12", 7), ("23", "12", 7),
("24", "12", 5), ("1", "13", 5), ("2", "13", 3), ("3", "13", 1),
("4", "13", 6), ("5", "13", 2), ("6", "13", 2), ("7", "13", 4),
("8", "13", 6), ("9", "13", 6), ("10", "13", 19), ("11", "13", 10),
("12", "13", 13), ("14", "13", 6), ("15", "13", 7), ("16", "13", 6),
("17", "13", 5), ("18", "13", 1), ("19", "13", 3), ("20", "13", 6),
("21", "13", 6), ("22", "13", 13), ("23", "13", 8), ("24", "13", 8),
("1", "14", 3), ("2", "14", 1), ("3", "14", 1), ("4", "14", 5),
("5", "14", 1), ("6", "14", 1), ("7", "14", 2), ("8", "14", 4),
("9", "14", 6), ("10", "14", 21), ("11", "14", 16), ("12", "14", 7),
("13", "14", 6), ("15", "14", 13), ("16", "14", 7), ("17", "14", 7),
("18", "14", 1), ("19", "14", 3), ("20", "14", 5), ("21", "14", 4),
("22", "14", 12), ("23", "14", 11), ("24", "14", 4), ("1", "15", 5),
("2", "15", 1), ("3", "15", 1), ("4", "15", 5), ("5", "15", 2),
("6", "15", 2), ("7", "15", 5), ("8", "15", 6), ("9", "15", 10),
("10", "15", 40), ("11", "15", 14), ("12", "15", 7), ("13", "15", 7),
("14", "15", 13), ("16", "15", 12), ("17", "15", 15), ("18", "15", 2),
("19", "15", 8), ("20", "15", 11), ("21", "15", 8), ("22", "15", 26),
("23", "15", 10), ("24", "15", 4), ("1", "16", 5), ("2", "16", 4),
("3", "16", 2), ("4", "16", 8), ("5", "16", 5), ("6", "16", 9),
("7", "16", 14), ("8", "16", 22), ("9", "16", 14), ("10", "16", 44),
("11", "16", 14), ("12", "16", 7), ("13", "16", 6), ("14", "16", 7),
("15", "16", 12), ("17", "16", 28), ("18", "16", 5), ("19", "16", 13),
("20", "16", 16), ("21", "16", 6), ("22", "16", 12), ("23", "16", 5),
("24", "16", 3), ("1", "17", 4), ("2", "17", 2), ("3", "17", 1),
("4", "17", 5), ("5", "17", 2), ("6", "17", 5), ("7", "17", 10),
("8", "17", 14), ("9", "17", 9), ("10", "17", 39), ("11", "17", 10),
("12", "17", 6), ("13", "17", 5), ("14", "17", 7), ("15", "17", 15),
("16", "17", 28), ("18", "17", 6), ("19", "17", 17), ("20", "17", 17),
("21", "17", 6), ("22", "17", 17), ("23", "17", 6), ("24", "17", 3),
("1", "18", 1), ("4", "18", 1), ("6", "18", 1), ("7", "18", 2),
("8", "18", 3), ("9", "18", 2), ("10", "18", 7), ("11", "18", 2),
("12", "18", 2), ("13", "18", 1), ("14", "18", 1), ("15", "18", 2),
("16", "18", 5), ("17", "18", 6), ("19", "18", 3), ("20", "18", 4),
("21", "18", 1), ("22", "18", 3), ("23", "18", 1), ("1", "19", 3),
("2", "19", 1), ("4", "19", 2), ("5", "19", 1), ("6", "19", 2),
("7", "19", 4), ("8", "19", 7), ("9", "19", 4), ("10", "19", 18),
("11", "19", 4), ("12", "19", 3), ("13", "19", 3), ("14", "19", 3),
("15", "19", 8), ("16", "19", 13), ("17", "19", 17), ("18", "19", 3),
("20", "19", 12), ("21", "19", 4), ("22", "19", 12), ("23", "19", 3),
("24", "19", 1), ("1", "20", 3), ("2", "20", 1), ("4", "20", 3),
("5", "20", 1), ("6", "20", 3), ("7", "20", 5), ("8", "20", 9),
("9", "20", 6), ("10", "20", 25), ("11", "20", 6), ("12", "20", 5),
("13", "20", 6), ("14", "20", 5), ("15", "20", 11), ("16", "20", 16),
("17", "20", 17), ("18", "20", 4), ("19", "20", 12), ("21", "20", 12),
("22", "20", 24), ("23", "20", 7), ("24", "20", 4), ("1", "21", 1),
("4", "21", 2), ("5", "21", 1), ("6", "21", 1), ("7", "21", 2),
("8", "21", 4), ("9", "21", 3), ("10", "21", 12), ("11", "21", 4),
("12", "21", 3), ("13", "21", 6), ("14", "21", 4), ("15", "21", 8),
("16", "21", 6), ("17", "21", 6), ("18", "21", 1), ("19", "21", 4),
("20", "21", 12), ("22", "21", 18), ("23", "21", 7), ("24", "21", 5),
("1", "22", 4), ("2", "22", 1), ("3", "22", 1), ("4", "22", 4),
("5", "22", 2), ("6", "22", 2), ("7", "22", 5), ("8", "22", 5),
("9", "22", 7), ("10", "22", 26), ("11", "22", 11), ("12", "22", 7),
("13", "22", 13), ("14", "22", 12), ("15", "22", 26), ("16", "22", 12),
("17", "22", 17), ("18", "22", 3), ("19", "22", 12), ("20", "22", 24),
("21", "22", 18), ("23", "22", 21), ("24", "22", 11), ("1", "23", 3),
("3", "23", 1), ("4", "23", 5), ("5", "23", 1), ("6", "23", 1),
("7", "23", 2), ("8", "23", 3), ("9", "23", 5), ("10", "23", 18),
("11", "23", 13), ("12", "23", 7), ("13", "23", 8), ("14", "23", 11),
("15", "23", 10), ("16", "23", 5), ("17", "23", 6), ("18", "23", 1),
("19", "23", 3), ("20", "23", 7), ("21", "23", 7), ("22", "23", 21),
("24", "23", 7), ("1", "24", 1), ("4", "24", 2), ("6", "24", 1),
("7", "24", 1), ("8", "24", 2), ("9", "24", 2), ("10", "24", 8),
("11", "24", 6), ("12", "24", 5), ("13", "24", 7), ("14", "24", 4),
("15", "24", 4), ("16", "24", 3), ("17", "24", 3), ("19", "24", 1),
("20", "24", 4), ("21", "24", 5), ("22", "24", 11), ("23", "24", 7)
]
def create_sioux_falls_network():
"""Returns Sioux Falls network object (Network).
Adds the origin and destination link to the adjacency list
__SIOUX_FALLS_ADJACENCY, to the BPR coefficients
__SIOUX_FALLS_FREE_FLOW_TRAVEL_TIME and __SIOUX_FALLS_BPR_A_COEFF and to the
node positions __SIOUX_FALLS_NODES and returns the network.
The BPR (Burean of Public Roads) coefficients are the coefficients used to
compute the travel time as a function of the volume on each link.
"""
adjacency = {}
free_flow_travel_time = __SIOUX_FALLS_FREE_FLOW_TRAVEL_TIME.copy()
bpr_a_coeff = __SIOUX_FALLS_BPR_A_COEFF.copy()
node_position = {}
for k, nodes in __SIOUX_FALLS_ADJACENCY.items():
adjacency[k] = nodes + [f"aft_{k}"]
adjacency[f"bef_{k}"] = [k]
adjacency[f"aft_{k}"] = []
free_flow_travel_time[f"bef_{k}->{k}"] = 0
free_flow_travel_time[f"{k}->aft_{k}"] = 0
bpr_a_coeff[f"bef_{k}->{k}"] = 0
bpr_a_coeff[f"{k}->aft_{k}"] = 0
for node, coord in __SIOUX_FALLS_NODES.items():
node_position[node] = coord
node_position[f"bef_{node}"] = coord
node_position[f"aft_{node}"] = coord
return dynamic_routing_utils.Network(
adjacency,
node_position=node_position,
bpr_a_coefficient=bpr_a_coeff,
bpr_b_coefficient={k: 4 for k in bpr_a_coeff},
capacity={k: 1 for k in bpr_a_coeff},
free_flow_travel_time=free_flow_travel_time)
SIOUX_FALLS_NETWORK = create_sioux_falls_network()
SIOUX_FALLS_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand(
f"bef_{origin}->{origin}", f"{dest}->aft_{dest}", 0, count * 1e2)
for (origin, dest, count) in __SIOUX_FALLS_DEMAND_AUX]
SIOUX_FALLS_DUMMY_OD_DEMAND = [
dynamic_routing_utils.OriginDestinationDemand("bef_19->19", "1->aft_1", 0,
70 * 1e2),
dynamic_routing_utils.OriginDestinationDemand("bef_1->1", "19->aft_19", 0,
70 * 1e2)
]
| 43.706019 | 80 | 0.381971 | 3,196 | 18,881 | 2.188986 | 0.079474 | 0.043453 | 0.029874 | 0.023156 | 0.137078 | 0.082762 | 0.044597 | 0.00486 | 0.002573 | 0 | 0 | 0.263615 | 0.243366 | 18,881 | 431 | 81 | 43.807425 | 0.226095 | 0.101901 | 0 | 0.032172 | 0 | 0 | 0.183485 | 0.001301 | 0 | 0 | 0 | 0 | 0 | 1 | 0.002681 | false | 0 | 0.002681 | 0 | 0.008043 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d0803d9236e955e980b86c815f6ee3650fa2cf37 | 979 | py | Python | backend/app/models/comment.py | wufangjie/My-First-Web-App | 43fe8e24879a0aa4d0ba697616706e9ed837ab44 | [
"MIT"
] | null | null | null | backend/app/models/comment.py | wufangjie/My-First-Web-App | 43fe8e24879a0aa4d0ba697616706e9ed837ab44 | [
"MIT"
] | null | null | null | backend/app/models/comment.py | wufangjie/My-First-Web-App | 43fe8e24879a0aa4d0ba697616706e9ed837ab44 | [
"MIT"
] | null | null | null | from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy import Column, String, Integer, DateTime
from .base import Base, TINYINT
class Comments(Base):
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
blog_id = Column(Integer, nullable=False, index=True)
user_id = Column(Integer, nullable=False, comment="评论用户", index=True)
content = Column(String(140), nullable=False, comment="评论内容")
add_time = Column(DateTime, nullable=False, comment="评论时间")
re = Column(Integer, comment="回复谁, 0 表示 blog's owner", default=0)
# ForeignKey("user.id"), # 因为有 0 存在, 所以不能设置 foreign key
state = Column(TINYINT, comment="是否删除 {0: 正常, 1: 删除}", default=0)
# blog_id = relationship("Blog", back_populates="comments")
# user_id = relationship("User", back_populates="comments") # same name is ok?
# # TODO: 本表之间的 relationship
# NOTE: 表名 comment 的话会和关键字冲突, 不能用:
# [SQL: INSERT INTO comment (blog_id
| 40.791667 | 82 | 0.713994 | 132 | 979 | 5.227273 | 0.477273 | 0.075362 | 0.065217 | 0.066667 | 0.081159 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010949 | 0.160368 | 979 | 23 | 83 | 42.565217 | 0.828467 | 0.286006 | 0 | 0 | 0 | 0 | 0.076923 | 0 | 0 | 0 | 0 | 0.043478 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
d0b6ba583cfdd347fb1f781976c6dcbaa54528ba | 265 | py | Python | deepspeed/amp/tests/gpt2_mp_solo.py | YLJALDC/DeepSpeed | 3362dac38e6c6bff369d3562b1549dc86fa1c633 | [
"MIT"
] | 1 | 2021-05-13T19:49:15.000Z | 2021-05-13T19:49:15.000Z | deepspeed/amp/tests/gpt2_mp_solo.py | YLJALDC/DeepSpeed | 3362dac38e6c6bff369d3562b1549dc86fa1c633 | [
"MIT"
] | null | null | null | deepspeed/amp/tests/gpt2_mp_solo.py | YLJALDC/DeepSpeed | 3362dac38e6c6bff369d3562b1549dc86fa1c633 | [
"MIT"
] | null | null | null | from deepspeed.amp import query_amp_topo
orca_cluster = "../orca_resource_1.yml"
gpt2_model_config = {"name": "gpt2", "sequence_length": 1024, "hidden_size": 768, "num_layers": 12, "vocab_size": 50512}
ret = query_amp_topo(orca_cluster, gpt2_model_config, 50)
| 26.5 | 120 | 0.750943 | 40 | 265 | 4.575 | 0.7 | 0.087432 | 0.131148 | 0.174863 | 0.251366 | 0 | 0 | 0 | 0 | 0 | 0 | 0.084746 | 0.109434 | 265 | 9 | 121 | 29.444444 | 0.690678 | 0 | 0 | 0 | 0 | 0 | 0.290076 | 0.083969 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d0b7de45617977b0a98ef90fa57df9740c7f21ca | 3,551 | py | Python | bin/test/test_parse_design.py | trev-f/SRAlign | f41d1172faee05b054b24d369a1dc8a41a33f9f0 | [
"MIT"
] | null | null | null | bin/test/test_parse_design.py | trev-f/SRAlign | f41d1172faee05b054b24d369a1dc8a41a33f9f0 | [
"MIT"
] | 14 | 2022-03-12T02:27:50.000Z | 2022-03-22T17:25:11.000Z | bin/test/test_parse_design.py | trev-f/SRAtac | b6e3f3ec91cdc1811a861f515be29871b38eecf3 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
"""
tests for parse_design.py
"""
import os
import re
from subprocess import getstatusoutput
prg = '../parse_design.py'
# --------------------------------------------------
def test_exists():
"""exists"""
assert os.path.isfile(prg)
# --------------------------------------------------
def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert re.match("usage", out, re.IGNORECASE)
# --------------------------------------------------
def test_missing_header():
"""no header"""
rv, out = getstatusoutput(f'{prg} PE_design_noHeader.csv')
assert rv == 1
expected = f"ERROR: Samplesheet -> Missing or invalid header.\n\tLINE: HSL-1,wt_control,1,data/HSL-1_R1.fastq.gz,data/HSL-1_R2.fastq.gz"
assert out.strip() == expected
# --------------------------------------------------
def test_check_read_types():
"""mixed read types"""
rv, out = getstatusoutput(f'{prg} SE_design_mixTypes.csv')
assert rv == 1
expected = f"ERROR: Samplesheet -> Mixed read types.\n\tLINE: HSL-3,wt_DMSO,1,data/HSL-3_R1.fastq.gz,data/HSL-3_R2.fastq.gz\n\tHSL-4,wt_DMSO,2,data/HSL-4_R1.fastq.gz,data/HSL-4_R2.fastq.gz"
assert out.strip() == expected
# --------------------------------------------------
def test_single_end():
"""single end"""
rv, out = getstatusoutput(f'{prg} SE_design_good.csv')
# check status
assert rv == 0
assert out == ''
# check output file
expected = (
'lib_ID,sample_rep,fq1\n'
'HSL-1,wt_control_rep1,data/HSL-1_R1.fastq.gz\n'
'HSL-2,wt_control_rep2,data/HSL-2_R1.fastq.gz\n'
'HSL-3,wt_DMSO_rep1,data/HSL-3_R1.fastq.gz\n'
'HSL-4,wt_DMSO_rep2,data/HSL-4_R1.fastq.gz'
)
out_file = 'SE_design_good_parsed.csv'
out_text = open(out_file).read().rstrip()
assert out_text == expected
# cleanup
if os.path.isfile(out_file):
os.remove(out_file)
# --------------------------------------------------
def test_paired_end():
"""paired end"""
rv, out = getstatusoutput(f'{prg} PE_design_good.csv')
# check status
assert rv == 0
assert out == ''
# check output file
expected = (
'lib_ID,sample_rep,fq1,fq2\n'
'HSL-1,wt_control_rep1,data/HSL-1_R1.fastq.gz,data/HSL-1_R2.fastq.gz\n'
'HSL-2,wt_control_rep2,data/HSL-2_R1.fastq.gz,data/HSL-2_R2.fastq.gz\n'
'HSL-3,wt_DMSO_rep1,data/HSL-3_R1.fastq.gz,data/HSL-3_R2.fastq.gz\n'
'HSL-4,wt_DMSO_rep2,data/HSL-4_R1.fastq.gz,data/HSL-4_R2.fastq.gz'
)
out_file = 'PE_design_good_parsed.csv'
out_text = open(out_file).read().rstrip()
assert out_text == expected
# cleanup
if os.path.isfile(out_file):
os.remove(out_file)
# --------------------------------------------------
def test_bam():
"""bam"""
rv, out = getstatusoutput(f'{prg} bam_design_good.csv')
# check status
assert rv == 0
assert out == ''
# check output file
expected = (
'lib_ID,sample_rep,bam,tool_IDs\n'
'HSL-1,wt_control_rep1,data/HSL-1.bam,bt2_sSR\n'
'HSL-2,wt_control_rep2,data/HSL-2.bam,bt2_sSR\n'
'HSL-3,wt_DMSO_rep1,data/HSL-3.bam,bwM\n'
'HSL-4,wt_DMSO_rep2,data/HSL-4.bam,'
)
out_file = 'bam_design_good_parsed.csv'
out_text = open(out_file).read().rstrip()
assert out_text == expected
# cleanup
if os.path.isfile(out_file):
os.remove(out_file)
| 27.527132 | 193 | 0.568572 | 518 | 3,551 | 3.694981 | 0.183398 | 0.08046 | 0.051724 | 0.047544 | 0.755486 | 0.716301 | 0.713166 | 0.65256 | 0.613898 | 0.532393 | 0 | 0.028552 | 0.191214 | 3,551 | 129 | 194 | 27.527132 | 0.637883 | 0.165306 | 0 | 0.376812 | 0 | 0.086957 | 0.425327 | 0.34446 | 0 | 0 | 0 | 0 | 0.231884 | 1 | 0.101449 | false | 0 | 0.043478 | 0 | 0.144928 | 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 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d0db84bd7ecaf35ceccfcfb4a988c5d821f27b18 | 205 | py | Python | exercicios/ex012.py | DeyvisonR/curso_python | 983b634d39f542369628ae48c7449ea75fd1ebbd | [
"MIT"
] | null | null | null | exercicios/ex012.py | DeyvisonR/curso_python | 983b634d39f542369628ae48c7449ea75fd1ebbd | [
"MIT"
] | null | null | null | exercicios/ex012.py | DeyvisonR/curso_python | 983b634d39f542369628ae48c7449ea75fd1ebbd | [
"MIT"
] | null | null | null | preço = float(input('digite o preço do produto: '))
desconto = preço - (preço * 5 / 100)
print('o produto que custava R${:.2f}, na promoção com desconto de 5% vai custar R${:.2f}'.format(preço, desconto))
| 51.25 | 115 | 0.678049 | 33 | 205 | 4.212121 | 0.666667 | 0.043165 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.040462 | 0.156098 | 205 | 3 | 116 | 68.333333 | 0.763006 | 0 | 0 | 0 | 0 | 0.333333 | 0.531707 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.333333 | 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 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d0f0e40995faa05e93c5dd507627e214b4ecd7af | 982 | py | Python | coinmessage/__init__.py | coinmessage/coinmessage | d09d6f1e8378c24d14b7eda863b4b729f2dbfa6b | [
"MIT"
] | 10 | 2015-06-24T07:15:05.000Z | 2019-02-10T11:39:42.000Z | coinmessage/__init__.py | coinmessage/coinmessage | d09d6f1e8378c24d14b7eda863b4b729f2dbfa6b | [
"MIT"
] | null | null | null | coinmessage/__init__.py | coinmessage/coinmessage | d09d6f1e8378c24d14b7eda863b4b729f2dbfa6b | [
"MIT"
] | null | null | null | import hashlib
from base64 import b64encode, b64decode
from pycoin.encoding import sec_to_public_pair, wif_to_secret_exponent
from encrypt import PubKey, PrivKey, BasePoint
from services import get_public_key_from_address, get_private_key_from_address
def encrypt_message(address, message):
"""Encrypts a message to an address.
"""
hex_public_key = get_public_key_from_address(address)
x, y = sec_to_public_pair(hex_public_key.decode('hex'))
public_key = PubKey(BasePoint.curve(), x, y)
encrypted = b64encode(public_key.encrypt(message))
return encrypted
def decrypt_message(public_key, encrypted_message):
"""Decrypts the message given a public key and an encrypted message.
User needs to control the private key via bitcoind.
"""
wif = get_private_key_from_address(public_key)
secret_exponent = wif_to_secret_exponent(wif)
private_key = PrivKey(secret_exponent)
return private_key.decrypt(b64decode(encrypted_message))
| 36.37037 | 78 | 0.781059 | 138 | 982 | 5.23913 | 0.333333 | 0.112033 | 0.077455 | 0.041494 | 0.130014 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011962 | 0.148676 | 982 | 26 | 79 | 37.769231 | 0.852871 | 0.153768 | 0 | 0 | 0 | 0 | 0.003722 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.3125 | 0 | 0.5625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
d0f45a1b17a3800f920b520b799f9d2b0fc21898 | 75 | py | Python | XICRA_pip/XICRA/config/__init__.py | MartaLoBalastegui/XICRA | 74a7e74379c7e1b3fc1360d2c609994e884ee37a | [
"MIT"
] | 3 | 2021-05-16T21:13:22.000Z | 2022-01-23T08:47:48.000Z | XICRA_pip/XICRA/config/__init__.py | MartaLoBalastegui/XICRA | 74a7e74379c7e1b3fc1360d2c609994e884ee37a | [
"MIT"
] | 16 | 2021-03-11T10:51:25.000Z | 2022-03-12T01:02:00.000Z | XICRA_pip/XICRA/config/__init__.py | MartaLoBalastegui/XICRA | 74a7e74379c7e1b3fc1360d2c609994e884ee37a | [
"MIT"
] | 3 | 2021-03-05T10:07:38.000Z | 2022-01-23T08:48:06.000Z | __all__ = [
'extern_progs',
'set_config'
]
from XICRA.config import *
| 9.375 | 26 | 0.666667 | 9 | 75 | 4.888889 | 0.888889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | 75 | 7 | 27 | 10.714286 | 0.733333 | 0 | 0 | 0 | 0 | 0 | 0.297297 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.2 | 0 | 0.2 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
d0f6cc4f0267695dad0d012a0d7fdc8fe77cca28 | 1,492 | py | Python | user_test.py | batyrotich/Password-Locker | 61e75ebf7dfdf7153961c81c2f165a9d389beb64 | [
"MIT"
] | null | null | null | user_test.py | batyrotich/Password-Locker | 61e75ebf7dfdf7153961c81c2f165a9d389beb64 | [
"MIT"
] | null | null | null | user_test.py | batyrotich/Password-Locker | 61e75ebf7dfdf7153961c81c2f165a9d389beb64 | [
"MIT"
] | null | null | null | import unittest
from user import User
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for users class behaviour
'''
def setUp(self):
'''
setup method to run before each test case
'''
self.new_user = User("eddah", "1234")
def tearDown(self):
'''
tearDown method that does clean up after each test case has run.
'''
User.user_list = []
def test__init(self):
'''
test_init test case to test if the object is initialized properly
'''
self.assertEqual(self.new_user.name, "eddah")
self.assertEqual(self.new_user.password, "1234")
def test_save_user(self):
'''
save_user method saves user objects to user_list
'''
self.new_user.save_user()
self.assertEqual(len(User.user_list), 1)
def test_save_multiple_user(self):
'''
test_save_multiple_user to sheck if we can save multiple users
'''
self.new_user.save_user()
test_user = User("Test", "password")
test_user.save_user()
self.assertEqual(len(User.user_list), 2)
def test_delete_user(self):
'''
method to remove saved users
'''
self.new_user.save_user()
test_user = User("Test", "password") #new user
test_user.save_user()
self.new_user.delete_user() # Deleting a user object
self.assertEqual(len(User.user_list), 1)
if __name__ == '__main__':
unittest.main()
| 27.62963 | 72 | 0.621984 | 197 | 1,492 | 4.48731 | 0.299492 | 0.063348 | 0.087104 | 0.050905 | 0.33371 | 0.239819 | 0.239819 | 0.20362 | 0.20362 | 0.108597 | 0 | 0.010082 | 0.268767 | 1,492 | 53 | 73 | 28.150943 | 0.800183 | 0.273458 | 0 | 0.346154 | 0 | 0 | 0.05291 | 0 | 0 | 0 | 0 | 0 | 0.192308 | 1 | 0.230769 | false | 0.115385 | 0.076923 | 0 | 0.346154 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
d0f73b828f951afd0927765b0f7bd95a1b3cea2b | 363 | py | Python | rctk/widgets/date.py | rctk/rctk | dc8640e75179c8560ca0cd64e709fefef58d5d2a | [
"BSD-2-Clause"
] | 2 | 2015-05-08T20:55:06.000Z | 2015-06-23T23:04:27.000Z | rctk/widgets/date.py | rctk/rctk | dc8640e75179c8560ca0cd64e709fefef58d5d2a | [
"BSD-2-Clause"
] | null | null | null | rctk/widgets/date.py | rctk/rctk | dc8640e75179c8560ca0cd64e709fefef58d5d2a | [
"BSD-2-Clause"
] | null | null | null | from rctk.widgets.control import Control, Attribute
from rctk.task import Task
from rctk.event import Changable
class Date(Control, Changable):
name = "date"
value = Attribute("", Attribute.STRING)
def create(self):
## XXX this should become a "real" property!
self.tk.create_control(self, pickerconfig={'dateFormat':'yy-mm-dd'})
| 24.2 | 76 | 0.69697 | 47 | 363 | 5.361702 | 0.638298 | 0.095238 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.187328 | 363 | 14 | 77 | 25.928571 | 0.854237 | 0.112948 | 0 | 0 | 0 | 0 | 0.069182 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.375 | 0 | 0.875 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
d0fa809db440fbc17f024b30963290d3642ed9cf | 1,129 | py | Python | ir-sensor/run-san.py | mucelee/rpi_sensys | a7b5b0859ceb8d0b4b9df09289b62901bef9033d | [
"MIT"
] | null | null | null | ir-sensor/run-san.py | mucelee/rpi_sensys | a7b5b0859ceb8d0b4b9df09289b62901bef9033d | [
"MIT"
] | null | null | null | ir-sensor/run-san.py | mucelee/rpi_sensys | a7b5b0859ceb8d0b4b9df09289b62901bef9033d | [
"MIT"
] | null | null | null | from os import environ
import time
from Utilities.configParser import Config
from SAN.sensorAgentNode import SensorAgentNode
from SAN.contextBrokerHandler import ContextBrokerHandler
from irSensor import IrSensor
CONFIG_FILE = "fiware_config.ini"
parsedConfigFile = Config(CONFIG_FILE)
if __name__ == '__main__':
# Optionally set verbose logging of json data
ContextBrokerHandler.verboseLogging = False
# Create an instance of the Fiware OCB handler
ocbHandler = ContextBrokerHandler(parsedConfigFile.getFiwareServerAddress())
# Create SAN instance
sensorAgentNode = SensorAgentNode()
# Create sensor
irSensor = IrSensor()
sensorAgentNode.add_sensor(irSensor)
# Attach SAN to OCB handler
ocbHandler.attach_entity(sensorAgentNode)
# Register entities with OCB server
ocbHandler.register_entities()
# Keep running until user Ctrl+C's
try:
while True:
pass
except KeyboardInterrupt:
pass
print "Done"
# Delete entities after shutting down
ocbHandler.unregister_entities()
| 27.536585 | 81 | 0.715678 | 113 | 1,129 | 7.017699 | 0.575221 | 0.017654 | 0.050441 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.234721 | 1,129 | 40 | 82 | 28.225 | 0.917824 | 0.222321 | 0 | 0.086957 | 0 | 0 | 0.034982 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.086957 | 0.26087 | null | null | 0.043478 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
19043fd12765a0052a6b353f17e8adcb97c0c782 | 864 | py | Python | snippets.py | qm64/python | 3b796944095c362de72c005f2ae78a246d87ca11 | [
"MIT"
] | null | null | null | snippets.py | qm64/python | 3b796944095c362de72c005f2ae78a246d87ca11 | [
"MIT"
] | null | null | null | snippets.py | qm64/python | 3b796944095c362de72c005f2ae78a246d87ca11 | [
"MIT"
] | null | null | null | # Python snippets
#################################
class MetaClass(type):
"""Return a class object with the __class__ attribute equal to the class object.
This allows interesting things within the class, such as __class__.__name__,
which are otherwise not available.
This class is used as a metaclass by including it in the class definition:
class SomeClass(object, metaclass=MetaClass):
Then within the class, attributes of the class can be accessed, such as
__class__.__name__. This is different from type(self).__name__,
as the latter gives the class of self, which may not be the same as the
surrounding class definition, due to inheritance.
"""
def __new__(mcs, name, bases, attrs):
attrs['__class__'] = name
return type.__new__(mcs, name, bases, attrs)
#################################
| 36 | 84 | 0.662037 | 113 | 864 | 4.743363 | 0.486726 | 0.104478 | 0.052239 | 0.05597 | 0.074627 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.204861 | 864 | 23 | 85 | 37.565217 | 0.780204 | 0.685185 | 0 | 0 | 0 | 0 | 0.055215 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0 | 0 | 0.75 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
1908160a04b802c1afa327aa7158c1f5c32df960 | 420 | py | Python | leetcode/2000_reverse_prefix_of_word.py | jacquerie/leetcode | a05e6b832eb0e0740aaff7b2eb3109038ad404bf | [
"MIT"
] | 3 | 2018-05-10T09:56:49.000Z | 2020-11-07T18:09:42.000Z | leetcode/2000_reverse_prefix_of_word.py | jacquerie/leetcode | a05e6b832eb0e0740aaff7b2eb3109038ad404bf | [
"MIT"
] | null | null | null | leetcode/2000_reverse_prefix_of_word.py | jacquerie/leetcode | a05e6b832eb0e0740aaff7b2eb3109038ad404bf | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
return ''.join(reversed(word[:word.find(ch) + 1])) + word[word.find(ch) + 1:]
if __name__ == '__main__':
solution = Solution()
assert 'dcbaefd' == solution.reversePrefix('abcdefd', 'd')
assert 'zxyxxe' == solution.reversePrefix('xyxzxe', 'z')
assert 'abcd' == solution.reversePrefix('abcd', 'z')
| 30 | 85 | 0.614286 | 49 | 420 | 5.102041 | 0.55102 | 0.252 | 0.096 | 0.112 | 0.12 | 0 | 0 | 0 | 0 | 0 | 0 | 0.008746 | 0.183333 | 420 | 13 | 86 | 32.307692 | 0.720117 | 0.05 | 0 | 0 | 0 | 0 | 0.11335 | 0 | 0 | 0 | 0 | 0 | 0.375 | 1 | 0.125 | false | 0 | 0 | 0.125 | 0.375 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
ef7091eb1f8300af0f6d864e7f979597acc4bedb | 3,830 | py | Python | pymcworld/gamerules.py | gullyn/pymcworld | c6546d0a0b9d46a5350cdb29b7b18fe9a0083caa | [
"MIT"
] | 1 | 2021-05-11T22:48:11.000Z | 2021-05-11T22:48:11.000Z | pymcworld/gamerules.py | gullyn/pymcworld | c6546d0a0b9d46a5350cdb29b7b18fe9a0083caa | [
"MIT"
] | 1 | 2021-05-11T22:49:50.000Z | 2021-05-12T12:08:45.000Z | pymcworld/gamerules.py | gullyn/pymcworld | c6546d0a0b9d46a5350cdb29b7b18fe9a0083caa | [
"MIT"
] | null | null | null | class GameRules:
"""
A list of gamerules used by the world.
Contains all gamerules for Java edition as of 1.16.5.
"""
def __init__(self):
"""
Creates the rules of the class.
"""
self.rules = []
self.create_game_rules()
def create_game_rules(self):
"""
Saves every gamerule to the self.rules array.
"""
self.rules.extend([
{
"name": "announceAdvancements",
"value": "true",
"type": "bool"
},
{
"name": "commandBlockOutput",
"value": "true",
"type": "bool"
},
{
"name": "disableElytraMovementCheck",
"value": "false",
"type": "bool"
},
{
"name": "disableRaids",
"value": "false",
"type": "bool"
},
{
"name": "doDaylightCycle",
"value": "true",
"type": "bool"
},
{
"name": "doEntityDrops",
"value": "true",
"type": "bool"
},
{
"name": "doFireTick",
"value": "true",
"type": "bool"
},
{
"name": "doInsomnia",
"value": "true",
"type": "bool"
},
{
"name": "doImmediateRespawn",
"value": "false",
"type": "bool"
},
{
"name": "doLimitedCrafting",
"value": "false",
"type": "bool"
},
{
"name": "doMobLoot",
"value": "true",
"type": "bool"
},
{
"name": "doMobSpawning",
"value": "true",
"type": "bool"
},
{
"name": "doPatrolSpawning",
"value": "true",
"type": "bool"
},
{
"name": "doTileDrops",
"value": "true",
"type": "bool"
},
{
"name": "doTraderSpawning",
"value": "true",
"type": "bool"
},
{
"name": "doWeatherCycle",
"value": "true",
"type": "bool"
},
{
"name": "drowningDamage",
"value": "true",
"type": "bool"
},
{
"name": "fallDamage",
"value": "true",
"type": "bool"
},
{
"name": "fireDamage",
"value": "true",
"type": "bool"
},
{
"name": "forgiveDeadPlayers",
"value": "true",
"type": "bool"
},
{
"name": "freezeDamage",
"value": "true",
"type": "bool"
},
{
"name": "keepInventory",
"value": "false",
"type": "bool"
},
{
"name": "logAdminCommands",
"value": "true",
"type": "bool"
},
{
"name": "maxCommandChainLength",
"value": "65536",
"type": "int"
},
{
"name": "maxEntityCramming",
"value": "24",
"type": "int"
},
{
"name": "mobGriefing",
"value": "true",
"type": "bool"
},
{
"name": "naturalRegeneration",
"value": "true",
"type": "bool"
},
{
"name": "playersSleepingPercentage",
"value": "100",
"type": "int"
},
{
"name": "randomTickSpeed",
"value": "3",
"type": "int"
},
{
"name": "reducedDebugInfo",
"value": "false",
"type": "bool"
},
{
"name": "sendCommandFeedback",
"value": "true",
"type": "bool"
},
{
"name": "showDeathMessages",
"value": "true",
"type": "bool"
},
{
"name": "spawnRadius",
"value": "10",
"type": "int"
},
{
"name": "spectatorsGenerateChunks",
"value": "true",
"type": "bool"
},
{
"name": "universalAnger",
"value": "false",
"type": "bool"
}
])
def set_rule(self, name, value):
"""
Sets a rule. The value must be the type (bool, int) of the gamerule.
:param name: the name of the rule
:param value: the value to set the rule to
"""
for rule in self.rules:
if rule["name"] == name:
if rule["type"] == "bool" and not isinstance(value, bool):
raise ValueError("Given value is not of correct type")
elif not isinstance(value, int):
raise ValueError("Given value is not of correct type")
rule["value"] = str(value).lower()
return True
raise ValueError(f"Game rule {name} could not be found")
| 17.409091 | 70 | 0.493473 | 356 | 3,830 | 5.283708 | 0.283708 | 0.136098 | 0.185008 | 0.207868 | 0.372674 | 0.04572 | 0.04572 | 0.04572 | 0.04572 | 0 | 0 | 0.006289 | 0.294256 | 3,830 | 219 | 71 | 17.488584 | 0.689604 | 0.082768 | 0 | 0.348958 | 0 | 0 | 0.40127 | 0.027714 | 0 | 0 | 0 | 0 | 0 | 1 | 0.015625 | false | 0 | 0 | 0 | 0.026042 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ef7c3d0e0ad75d3643ad4a322ceff64fe0be0f42 | 260 | py | Python | sort/mysteryAlgorithm.py | udohsolomon/LearnAlgorithms | 36f8e2af4efe65a6b9627b400da77931ef5a6a26 | [
"MIT"
] | null | null | null | sort/mysteryAlgorithm.py | udohsolomon/LearnAlgorithms | 36f8e2af4efe65a6b9627b400da77931ef5a6a26 | [
"MIT"
] | null | null | null | sort/mysteryAlgorithm.py | udohsolomon/LearnAlgorithms | 36f8e2af4efe65a6b9627b400da77931ef5a6a26 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
def mysteryAlgorithm(lst):
for i in range(1,len(lst)):
while i > 0 and lst[i-1] > lst[i]:
lst[i], lst[i-1] = lst[i-1], lst[i]
i -= 1
return lst
print(mysteryAlgorithm([6, 4, 3, 8, 5])) | 28.888889 | 47 | 0.5 | 44 | 260 | 2.954545 | 0.522727 | 0.184615 | 0.115385 | 0.184615 | 0.176923 | 0 | 0 | 0 | 0 | 0 | 0 | 0.067797 | 0.319231 | 260 | 9 | 48 | 28.888889 | 0.666667 | 0.080769 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0 | 0 | 0.285714 | 0.142857 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ef819a8408a30e2d3cd5a4c10a7d7eb838b27e47 | 352 | py | Python | katas/kyu_7/simple_template.py | the-zebulan/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | 40 | 2016-03-09T12:26:20.000Z | 2022-03-23T08:44:51.000Z | katas/kyu_7/simple_template.py | akalynych/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | null | null | null | katas/kyu_7/simple_template.py | akalynych/CodeWars | 1eafd1247d60955a5dfb63e4882e8ce86019f43a | [
"MIT"
] | 36 | 2016-11-07T19:59:58.000Z | 2022-03-31T11:18:27.000Z | from re import compile, finditer
REGEX = compile(r'\{\{([a-zA-Z]+)\}\}')
REPLS = ('{{', '{'), ('}}', '}')
def create_template(s):
def my_template(**kwargs):
keys = {a.group(1): '' for a in finditer(REGEX, s)}
keys.update(kwargs)
return reduce(lambda a, kv: a.replace(*kv), REPLS, s).format(**keys)
return my_template
| 27.076923 | 76 | 0.565341 | 48 | 352 | 4.083333 | 0.604167 | 0.132653 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003571 | 0.204545 | 352 | 12 | 77 | 29.333333 | 0.696429 | 0 | 0 | 0 | 0 | 0 | 0.071023 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.111111 | 0 | 0.555556 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
ef8bc0cee75de8968d0e62e51eaa6a769c4a7d0e | 1,175 | py | Python | python/setup.py | jderoo/megaind-rpi | 4e0a24a292b572481005bc5953d3a158dceb9fc9 | [
"MIT"
] | 7 | 2020-12-14T04:09:29.000Z | 2022-03-18T23:45:51.000Z | python/setup.py | jderoo/megaind-rpi | 4e0a24a292b572481005bc5953d3a158dceb9fc9 | [
"MIT"
] | 15 | 2020-11-21T22:51:46.000Z | 2022-01-24T07:26:07.000Z | python/setup.py | jderoo/megaind-rpi | 4e0a24a292b572481005bc5953d3a158dceb9fc9 | [
"MIT"
] | 7 | 2021-02-25T04:10:50.000Z | 2022-03-23T13:54:32.000Z | #from distutils.core import setup
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name = 'megaind',
packages=setuptools.find_packages(),
version = '1.0.4',
license='MIT',
description = 'Library to control Sequent Microsystems Industrial Automation Card',
author = 'Sequent Microsystems',
author_email = 'olcitu@gmail.com',
url = 'https://sequentmicrosystems.com',
keywords = ['industrial', 'raspberry', 'power', '4-20mA', '0-10V', 'optoisolated'],
install_requires=[
"smbus",
],
classifiers=[
'Development Status :: 4 - Beta', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package
'Intended Audience :: Developers',
'Topic :: Software Development :: Build Tools',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
)
| 36.71875 | 146 | 0.631489 | 129 | 1,175 | 5.72093 | 0.651163 | 0.154472 | 0.203252 | 0.176152 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.026115 | 0.217872 | 1,175 | 31 | 147 | 37.903226 | 0.776931 | 0.113191 | 0 | 0.068966 | 0 | 0 | 0.567889 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.034483 | 0 | 0.034483 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
efb33b41faee662ae66767badcbc13c0d4fae901 | 1,666 | py | Python | finite_games/normal_form/algorithms.py | rtloftin/strategically_efficient_rl | 85a702b9361211d345a58cc60696e4e851d48ec4 | [
"MIT"
] | 7 | 2021-08-02T14:28:33.000Z | 2021-12-27T03:30:47.000Z | finite_games/normal_form/algorithms.py | rtloftin/strategically_efficient_rl | 85a702b9361211d345a58cc60696e4e851d48ec4 | [
"MIT"
] | 3 | 2021-08-02T17:35:52.000Z | 2022-02-10T04:42:17.000Z | finite_games/normal_form/algorithms.py | rtloftin/strategically_efficient_rl | 85a702b9361211d345a58cc60696e4e851d48ec4 | [
"MIT"
] | 2 | 2021-08-02T17:30:05.000Z | 2021-09-13T12:16:29.000Z | import numpy as np
from normal_form.solvers import build_solver
from normal_form.sparring_exp3 import SparringExp3
from normal_form.sparring_rmax import SparringRMax
from normal_form.explore_exploit import ExploreExploit
from normal_form.sparring_ppo import SparringPPO
from normal_form.nash_v import NashV
class Expert:
def __init__(self, N, M, T, config):
self._game = np.zeros((N, M,))
# Get solver
solver = config.get("solver", "linear_programming")
solver_config = config.get("solver_config", {})
self._solver = build_solver(solver, solver_config)
def sample(self, G):
self._game = G.G.copy()
def strategies(self):
row_strategies, column_strategies, _ = self._solver(self._game, 1.0 - self._game)
return row_strategies, column_strategies
def __repr__(self):
return "expert"
class UniformRandom:
def __init__(self, N, M, T, config):
self._row_strategy = np.ones(N, dtype=float) / N
self._column_strategy = np.ones(M, dtype=float) / M
def sample(self, G):
pass
def strategies(self):
return self._row_strategy, self._column_strategy
def __repr__(self):
return "random"
ALGORITHMS = {
"random": UniformRandom,
"expert": Expert,
"exp3": SparringExp3,
"rmax": SparringRMax, # TODO: Need to check implementation
"explore_exploit": ExploreExploit,
"ppo": SparringPPO,
"nash_v": NashV,
}
def build_algorithm(alg, N, M, T, config={}):
if alg not in ALGORITHMS:
raise ValueError(f"Leanring algorithm '{alg}' is not defined")
return ALGORITHMS[alg](N, M, T, config)
| 26.444444 | 89 | 0.67587 | 214 | 1,666 | 5.004673 | 0.331776 | 0.056022 | 0.078431 | 0.033613 | 0.067227 | 0.044818 | 0.044818 | 0.044818 | 0 | 0 | 0 | 0.004612 | 0.219088 | 1,666 | 62 | 90 | 26.870968 | 0.818601 | 0.027011 | 0 | 0.186047 | 0 | 0 | 0.082818 | 0 | 0 | 0 | 0 | 0.016129 | 0 | 1 | 0.209302 | false | 0.023256 | 0.162791 | 0.069767 | 0.534884 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
efb87ed31ac6b6fbafa917d0c0b05c9f206b6e1d | 11,496 | py | Python | cirq/qutrit/controlled_ternary_gate.py | epiqc/qutrits | fe24c420ac81ee0134af88f4d7102b71c15200fb | [
"Apache-2.0"
] | 16 | 2019-05-28T14:32:43.000Z | 2022-02-10T08:49:53.000Z | cirq/qutrit/controlled_ternary_gate.py | GerrardFalcon/qutrits | fe24c420ac81ee0134af88f4d7102b71c15200fb | [
"Apache-2.0"
] | 3 | 2021-03-24T19:25:19.000Z | 2021-03-24T19:25:36.000Z | cirq/qutrit/controlled_ternary_gate.py | GerrardFalcon/qutrits | fe24c420ac81ee0134af88f4d7102b71c15200fb | [
"Apache-2.0"
] | 8 | 2019-05-28T15:57:31.000Z | 2022-01-05T12:14:57.000Z |
import itertools
from cirq import ops
from cirq.qutrit import raw_types
from cirq.qutrit import common_gates
import math, numpy as np
class ControlledTernaryGate(raw_types.TernaryLogicGate,
ops.CompositeGate,
ops.ReversibleEffect,
ops.TextDiagrammable):
def __init__(self, base_gate, control_values):
""" Args:
control_values: E.g. [(2,), (1,), (0,1)] for a three
control gate that triggers if the first qutrit is 2, the
second is 1 and the third is either 0 or 1.
"""
self.base_gate = base_gate
self.control_values = control_values
def validate_trits(self, trits):
pass
def applied_to_trits(self, trits):
pass
def default_decompose(self, qutrits):
# qutrits are control, target or control, control, target
assert len(self.control_values) in [1, 2]
assert len(qutrits) == len(self.control_values) + 1
if len(self.control_values) == 1:
if self.control_values == ((2,),) and self.base_gate == common_gates.F01:
yield C2F01()(*qutrits)
elif self.control_values == ((1,),) and self.base_gate == common_gates.PlusOne:
yield C1PlusOne()(*qutrits)
elif self.control_values == ((1,),) and self.base_gate == common_gates.MinusOne:
yield C1MinusOne()(*qutrits)
else:
assert False, "control_values: %s, base_gate: %s" % (self.control_values, self.base_gate)
elif len(self.control_values) == 2:
if self.control_values == ((1,), (1,)) and self.base_gate == common_gates.PlusOne:
yield C1C1PlusOne()(*qutrits)
elif self.control_values == ((1,), (1,)) and self.base_gate == common_gates.MinusOne:
yield C1C1MinusOne()(*qutrits)
elif self.control_values == ((2,), (2,)) and self.base_gate == common_gates.PlusOne:
yield C2C2PlusOne()(*qutrits)
elif self.control_values == ((2,), (2,)) and self.base_gate == common_gates.MinusOne:
yield C2C2MinusOne()(*qutrits)
else:
assert False, "control_values: %s, base_gate: %s" % (self.control_values, self.base_gate)
else:
assert False, 'more than two controls'
@staticmethod
def all_controlled_gates(base_gate, base_name, max_controls=1,
control_types=((0,), (1,), (2,), (0,1), (0,2), (1,2))):
gates = {}
for control_num in range(1, max_controls+1):
for controls in itertools.product(control_types,
repeat=control_num):
gate_pre = ''.join('C'+''.join(map(str, (c for c in control)))
for control in controls)
gate_name = gate_pre + base_name
gate = ControlledTernaryGate(base_gate, controls)
gates[gate_name] = gate
return gates
def inverse(self):
return ControlledTernaryGate(self.base_gate.inverse(),
self.control_values)
def _control_symbols(self):
return tuple(','.join(map(str, vals))
for vals in self.control_values)
def text_diagram_info(self, args):
base_info = self.base_gate.text_diagram_info(args)
c_syms = self._control_symbols()
return ops.TextDiagramInfo(c_syms+base_info.wire_symbols,
exponent=base_info.exponent,
connected=True)
def validate_trits(self, trits):
super().validate_trits(trits)
self.base_gate.validate_trits(trits[len(self.control_values):])
def applied_to_trits(self, trits):
len_trits = len(trits)
controls = trits[:len(self.control_values)]
control_active = all(
trit in matches
for trit, matches in zip(controls, self.control_values)
)
if control_active:
changed_trits = self.base_gate.applied_to_trits(
trits[len(self.control_values):])
trits[len(self.control_values):] = changed_trits
return trits
class C1C1PlusOne(raw_types.TernaryLogicGate,
ops.CompositeGate):
def default_decompose(self, qutrits):
yield Ry12(-math.pi/4)(qutrits[2])
yield C1F12()(qutrits[1], qutrits[2])
yield Ry12(-math.pi/4)(qutrits[2])
yield C1F12()(qutrits[0], qutrits[2])
yield Ry12(math.pi/4)(qutrits[2])
yield C1F12()(qutrits[1], qutrits[2])
yield Ry12Pi4Ry01Pi4()(qutrits[2])
yield C1F01()(qutrits[1], qutrits[2])
yield Ry01(math.pi/4)(qutrits[2])
yield C1F01()(qutrits[0], qutrits[2])
yield Ry01(-math.pi/4)(qutrits[2])
yield C1F01()(qutrits[1], qutrits[2])
yield Ry01(-math.pi/4)(qutrits[2])
class C2C2PlusOne(raw_types.TernaryLogicGate,
ops.CompositeGate):
def default_decompose(self, qutrits):
yield Ry12(-math.pi/4)(qutrits[2])
yield C2F12()(qutrits[1], qutrits[2])
yield Ry12(-math.pi/4)(qutrits[2])
yield C2F12()(qutrits[0], qutrits[2])
yield Ry12(math.pi/4)(qutrits[2])
yield C2F12()(qutrits[1], qutrits[2])
yield Ry12Pi4Ry01Pi4()(qutrits[2])
yield C2F01()(qutrits[1], qutrits[2])
yield Ry01(math.pi/4)(qutrits[2])
yield C2F01()(qutrits[0], qutrits[2])
yield Ry01(-math.pi/4)(qutrits[2])
yield C2F01()(qutrits[1], qutrits[2])
yield Ry01(-math.pi/4)(qutrits[2])
class C1C1MinusOne(raw_types.TernaryLogicGate,
ops.CompositeGate):
def default_decompose(self, qutrits):
yield Ry01(math.pi/4)(qutrits[2])
yield C1F01()(qutrits[1], qutrits[2])
yield Ry01(math.pi/4)(qutrits[2])
yield C1F01()(qutrits[0], qutrits[2])
yield Ry01(-math.pi/4)(qutrits[2])
yield C1F01()(qutrits[1], qutrits[2])
yield Ry01MinusPi4Ry12MinusPi4()(qutrits[2])
yield C1F12()(qutrits[1], qutrits[2])
yield Ry12(-math.pi/4)(qutrits[2])
yield C1F12()(qutrits[0], qutrits[2])
yield Ry12(math.pi/4)(qutrits[2])
yield C1F12()(qutrits[1], qutrits[2])
yield Ry12(math.pi/4)(qutrits[2])
class C2C2MinusOne(raw_types.TernaryLogicGate,
ops.CompositeGate):
def default_decompose(self, qutrits):
yield Ry01(math.pi/4)(qutrits[2])
yield C2F01()(qutrits[1], qutrits[2])
yield Ry01(math.pi/4)(qutrits[2])
yield C2F01()(qutrits[0], qutrits[2])
yield Ry01(-math.pi/4)(qutrits[2])
yield C2F01()(qutrits[1], qutrits[2])
yield Ry01MinusPi4Ry12MinusPi4()(qutrits[2])
yield C2F12()(qutrits[1], qutrits[2])
yield Ry12(-math.pi/4)(qutrits[2])
yield C2F12()(qutrits[0], qutrits[2])
yield Ry12(math.pi/4)(qutrits[2])
yield C2F12()(qutrits[1], qutrits[2])
yield Ry12(math.pi/4)(qutrits[2])
class Ry01(raw_types.TernaryLogicGate):
def __init__(self, theta):
self.theta = theta
def _unitary_(self):
theta = self.theta
return np.array([[math.cos(theta/2.0), -math.sin(theta/2.0), 0],
[math.sin(theta/2.0), math.cos(theta/2.0), 0],
[0, 0, 1]])
class Ry12(raw_types.TernaryLogicGate):
def __init__(self, theta):
self.theta = theta
def _unitary_(self):
theta = self.theta
return np.array([[1, 0, 0],
[0, math.cos(theta/2.0), -math.sin(theta/2.0)],
[0, math.sin(theta/2.0), math.cos(theta/2.0)]])
class Ry01MinusPi4Ry12MinusPi4(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.dot(Ry12(-math.pi/4)._unitary_(), Ry01(-math.pi/4)._unitary_())
class Ry12Pi4Ry01Pi4(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.dot(Ry01(math.pi/4)._unitary_(), Ry12(math.pi/4)._unitary_())
class C1F01(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]])
class C2F01(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]])
class C1F12(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]])
class C2F12(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 0]])
class C1PlusOne(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]])
class C1MinusOne(raw_types.TernaryLogicGate):
def _unitary_(self):
return np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]])
| 41.652174 | 105 | 0.488866 | 1,561 | 11,496 | 3.499039 | 0.081999 | 0.142805 | 0.185646 | 0.210912 | 0.704138 | 0.656536 | 0.623947 | 0.618272 | 0.613695 | 0.572684 | 0 | 0.11614 | 0.358125 | 11,496 | 275 | 106 | 41.803636 | 0.624068 | 0.018789 | 0 | 0.600858 | 0 | 0 | 0.008025 | 0 | 0 | 0 | 0 | 0 | 0.021459 | 1 | 0.111588 | false | 0.008584 | 0.021459 | 0.042918 | 0.261803 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
efc60c291e40c63da4d093b0bbfd9da8b93f85b0 | 635 | py | Python | products/admin.py | atakansite/ecommerce | 9dbde349ab7b0166eaf85679ccf64543350142d8 | [
"MIT"
] | null | null | null | products/admin.py | atakansite/ecommerce | 9dbde349ab7b0166eaf85679ccf64543350142d8 | [
"MIT"
] | null | null | null | products/admin.py | atakansite/ecommerce | 9dbde349ab7b0166eaf85679ccf64543350142d8 | [
"MIT"
] | null | null | null | from django.contrib import admin
from django.contrib import admin
from products.models import Products
from products.models import MainCategory
from products.models import SubCategory
class ProductsAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
class MainCategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
class SubCategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
# Register your models here.
admin.site.register(Products, ProductsAdmin)
admin.site.register(MainCategory, MainCategoryAdmin)
admin.site.register(SubCategory, SubCategoryAdmin) | 26.458333 | 52 | 0.785827 | 68 | 635 | 7.294118 | 0.323529 | 0.072581 | 0.108871 | 0.145161 | 0.395161 | 0.395161 | 0.189516 | 0 | 0 | 0 | 0 | 0 | 0.108661 | 635 | 24 | 53 | 26.458333 | 0.876325 | 0.040945 | 0 | 0.357143 | 0 | 0 | 0.044408 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.357143 | 0 | 0.785714 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
efdc1f85a95b8cd6ee202298c2c12dc1a0294bf2 | 354 | py | Python | krgram/tl/api/functions/users.py | krow89/krgram | 52257d143be44b3c038c9458837f2df4b1640fa7 | [
"MIT"
] | null | null | null | krgram/tl/api/functions/users.py | krow89/krgram | 52257d143be44b3c038c9458837f2df4b1640fa7 | [
"MIT"
] | null | null | null | krgram/tl/api/functions/users.py | krow89/krgram | 52257d143be44b3c038c9458837f2df4b1640fa7 | [
"MIT"
] | null | null | null | from krgram.tl.api.types.globals import InputUser
from krgram.tl.types import *
class getUsers(TLFunction):
ID = 0xd91a548
def get_structure(self):
return ("id", Vector()),
TLRegister.register(getUsers)
class getFullUser(TLFunction):
ID = 0xca30a5b1
def get_structure(self):
return ("id", InputUser()),
TLRegister.register(getFullUser)
| 15.391304 | 49 | 0.742938 | 43 | 354 | 6.069767 | 0.534884 | 0.076628 | 0.091954 | 0.145594 | 0.206897 | 0.206897 | 0 | 0 | 0 | 0 | 0 | 0.035948 | 0.135593 | 354 | 22 | 50 | 16.090909 | 0.816993 | 0 | 0 | 0.166667 | 0 | 0 | 0.011299 | 0 | 0 | 0 | 0.053672 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.166667 | 0.166667 | 0.833333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
efe45ee2db3f2926ed33207b9e85f3b6880a9b92 | 5,591 | py | Python | tests/models.py | tysonholub/RestResponse | a4b312b96b3931e6304cec26b80aa51298727e74 | [
"MIT"
] | 1 | 2019-06-25T15:13:41.000Z | 2019-06-25T15:13:41.000Z | tests/models.py | tysonholub/RestResponse | a4b312b96b3931e6304cec26b80aa51298727e74 | [
"MIT"
] | null | null | null | tests/models.py | tysonholub/RestResponse | a4b312b96b3931e6304cec26b80aa51298727e74 | [
"MIT"
] | null | null | null | from RestResponse import ApiModel, ApiCollection
from RestResponse.orm.sqlalchemy import RESTResponse
from tests import test_db
class DBModel(test_db.Model):
id = test_db.Column(test_db.Integer, primary_key=True)
data = test_db.Column(RESTResponse(), nullable=True)
none_prop_test = test_db.Column(test_db.String, nullable=True)
def __init__(self, data=None):
data = data or {}
self.data = data
class Model(ApiModel):
def __init__(self, data=None):
self._data = data
@property
def _foo(self):
return self._get_string(self._data._foo)
@_foo.setter
def _foo(self, _foo):
self._data._foo = self._set_string(_foo)
@property
def id(self):
return self._get_int(self._data.id)
@id.setter
def id(self, id):
self._data.id = self._set_int(id)
@property
def id_doesnt_raise(self):
return self._get_int(self._data.id_doesnt_raise)
@id_doesnt_raise.setter
def id_doesnt_raise(self, id):
self._data.id_doesnt_raise = self._format_int(id, raises_value_error=False)
@property
def string(self):
return self._get_string(self._data.string)
@string.setter
def string(self, string):
self._data.string = self._set_string(string)
@property
def string_doesnt_raise(self):
return self._get_string(self._data.string_doesnt_raise)
@string_doesnt_raise.setter
def string_doesnt_raise(self, string):
self._data.string_doesnt_raise = self._format_string(string, raises_value_error=False)
@property
def floating_point(self):
return self._get_float(self._data.floating_point)
@floating_point.setter
def floating_point(self, floating_point):
self._data.floating_point = self._set_float(floating_point)
@property
def floating_point_doesnt_raise(self):
return self._get_float(self._data.floating_point_doesnt_raise)
@floating_point_doesnt_raise.setter
def floating_point_doesnt_raise(self, floating_point):
self._data.floating_point_doesnt_raise = self._format_float(floating_point, raises_value_error=False)
@property
def date_time(self):
return self._get_datetime(self._data.date_time)
@date_time.setter
def date_time(self, date_time):
self._data.date_time = self._set_datetime(date_time)
@property
def date_time_doesnt_raise(self):
return self._get_datetime(self._data.date_time_doesnt_raise)
@date_time_doesnt_raise.setter
def date_time_doesnt_raise(self, date_time):
self._data.date_time_doesnt_raise = self._format_datetime(date_time, raises_value_error=False)
@property
def date(self):
return self._get_date(self._data.date)
@date.setter
def date(self, date):
self._data.date = self._set_date(date)
@property
def date_doesnt_raise(self):
return self._get_date(self._data.date_doesnt_raise)
@date_doesnt_raise.setter
def date_doesnt_raise(self, date):
self._data.date_doesnt_raise = self._format_date(date, raises_value_error=False)
@property
def func(self):
return self._data.func
@func.setter
def func(self, func):
self._data.func = func
@property
def binary(self):
return self._data.binary
@binary.setter
def binary(self, binary):
self._data.binary = binary
@property
def int_collection(self):
if not self._data.int_collection:
self._data.int_collection = ApiCollection(self._set_int)
return self._data.int_collection
@int_collection.setter
def int_collection(self, int_collection):
self._data.int_collection = ApiCollection(self._set_int, int_collection)
@property
def int_collection_doesnt_raise(self):
if not self._data.int_collection_doesnt_raise:
self._data.int_collection_doesnt_raise = ApiCollection(self._format_int, raises_value_error=False)
return self._data.int_collection_doesnt_raise
@int_collection_doesnt_raise.setter
def int_collection_doesnt_raise(self, int_collection):
self._data.int_collection_doesnt_raise = ApiCollection(
self._format_int, int_collection, raises_value_error=False
)
@property
def ref(self):
if not self._data.ref:
self._data.ref = Ref()
return Ref(self._data.ref)
@ref.setter
def ref(self, ref):
self._data.ref = Ref(ref)
@property
def ref_collection(self):
if not self._data.ref_collection:
self._data.ref_collection = ApiCollection(Ref)
return self._data.ref_collection
@ref_collection.setter
def ref_collection(self, ref_collection):
self._data.ref_collection = ApiCollection(Ref, ref_collection)
class Ref(ApiModel):
def __init__(self, data=None):
self._data = data
@property
def id(self):
return self._get_int(self._data.id)
@id.setter
def id(self, id):
self._data.id = self._set_int(id)
@property
def string(self):
return self._get_string(self._data.string)
@string.setter
def string(self, string):
self._data.string = self._set_string(string)
class OverridesModel(ApiModel):
def __init__(self, data=None):
self.__opts__['_overrides'] = ['_foo']
self._data = data
@property
def _foo(self):
return self._get_string(self._data._foo)
@_foo.setter
def _foo(self, _foo):
self._data._foo = self._set_string(_foo)
| 27.955 | 110 | 0.690216 | 743 | 5,591 | 4.798116 | 0.076716 | 0.125666 | 0.075736 | 0.06676 | 0.69425 | 0.60561 | 0.458065 | 0.373072 | 0.307714 | 0.260589 | 0 | 0 | 0.215704 | 5,591 | 199 | 111 | 28.095477 | 0.812999 | 0 | 0 | 0.38 | 0 | 0 | 0.002504 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.293333 | false | 0 | 0.02 | 0.106667 | 0.493333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
efe61ab76b7b978727880878915f1966cbd5de01 | 6,162 | py | Python | ContactMechanics/Substrates.py | ComputationalMechanics/ContactMechanics | c734edeae83f5b3369fd9a2bd1c4fc7d00e382f3 | [
"MIT"
] | 7 | 2020-06-03T20:01:42.000Z | 2021-03-03T09:24:37.000Z | ContactMechanics/Substrates.py | ComputationalMechanics/ContactMechanics | c734edeae83f5b3369fd9a2bd1c4fc7d00e382f3 | [
"MIT"
] | 19 | 2020-06-02T13:02:18.000Z | 2021-03-19T09:48:12.000Z | ContactMechanics/Substrates.py | ComputationalMechanics/ContactMechanics | c734edeae83f5b3369fd9a2bd1c4fc7d00e382f3 | [
"MIT"
] | 1 | 2021-09-10T22:20:41.000Z | 2021-09-10T22:20:41.000Z | #
# Copyright 2015, 2019-2020 Lars Pastewka
# 2018-2019 Antoine Sanner
# 2015-2016 Till Junge
#
# ### MIT license
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
"""
Base class for continuum mechanics models of halfspaces
"""
import abc
class Substrate(object, metaclass=abc.ABCMeta):
""" Generic baseclass from which all substate classes derive
"""
_periodic = None
class Error(Exception):
# pylint: disable=missing-docstring
pass
name = 'generic_halfspace'
def spawn_child(self, dummy):
""" does nothing for most substrates.
"""
raise self.Error(
"Only substrates with free boundaries can do this")
@classmethod
def is_periodic(cls):
"non-periodic substrates can use some optimisations"
if cls._periodic is not None:
return cls._periodic
raise cls.Error(
("periodicity of Substrate type '{}' ('{}') is not defined"
"").format(cls.name, cls.__name__))
@property
@abc.abstractmethod
def nb_domain_grid_pts(self):
"""
"""
pass
@property
@abc.abstractmethod
def nb_subdomain_grid_pts(self):
"""
When working in Parallel one processor holds only Part of the Data
:return:
"""
pass
@property
@abc.abstractmethod
def subdomain_locations(self):
"""
When working in Parallel one processor holds only Part of the Data
:return:
"""
pass
@property
@abc.abstractmethod
def communicator(self):
"""Return the MPI communicator"""
pass
# @property
# @abc.abstractmethod
# def dim(self, ):
# "return the substrate's physical dimension"
# pass
def check(self, force=None):
"""
Checks wether force is still in the value range handled correctly.
In this case all forces are ok.
Parameters
----------
force
Returns
-------
"""
pass
class ElasticSubstrate(Substrate, metaclass=abc.ABCMeta):
""" Generic baseclass for elastic substrates
"""
name = 'generic_elastic_halfspace'
# Since an elastic substrate essentially defines a Potential, a similar
# internal structure is chosen
def __init__(self):
self.energy = None
self.force = None
self.force_k = None
def __repr__(self):
dims = 'x', 'y', 'z'
size_str = ', '.join('{}: {}({})'.format(dim, size, nb_grid_pts) for
dim, size, nb_grid_pts in zip(dims, self.size,
self.nb_grid_pts))
return "{0.dim}-dimensional halfspace '{0.name}', " \
"physical_sizes(nb_grid_pts) in {1}, E' = {0.young}" \
.format(self, size_str)
def compute(self, disp, pot=True, forces=False):
"""
computes and stores the elastic energy and/or surface forces
the as function of the surface displacement. Note that forces, not
surface pressures are expected. This is contrary to most formulations
in the literature, but convenient in the code (consistency with the
softWall interaction potentials). This choice may come back to bite me.
Parameters:
gap -- array containing the point-wise gap values
pot -- (default True) whether the energy should be evaluated
forces -- (default False) whether the forces should be evaluated
"""
self.energy, self.force = self.evaluate(
disp, pot, forces)
def compute_k(self, disp_k, pot=True, forces=False):
"""
computes and stores the elastic energy and/or surface forces
the as function of the surface displacement in Fourier Space.
Note that forces, not surface pressures are expected.
This is contrary to most formulations
in the literature, but convenient in the code (consistency with the
softWall interaction potentials). This choice may come back to bite me.
Parameters:
gap -- array containing the point-wise gap values
pot -- (default True) whether the energy should be evaluated
forces -- (default False) whether the forces should be evaluated
"""
self.energy, self.force_k = self.evaluate_k(
disp_k, pot, forces)
def evaluate(self, disp, pot=True, forces=False):
"""
computes and returns the elastic energy and/or surface forces
as function of the surface displacement. See docstring for 'compute'
for more details
Parameters:
gap -- array containing the point-wise gap values
pot -- (default True) whether the energy should be evaluated
forces -- (default False) whether the forces should be evaluated
"""
raise NotImplementedError()
class PlasticSubstrate(Substrate):
""" Generic baseclass for plastic substrates
"""
# pylint: disable=too-few-public-methods
name = 'generic_plastic_halfspace'
| 33.308108 | 79 | 0.638754 | 752 | 6,162 | 5.172872 | 0.363032 | 0.022622 | 0.026221 | 0.03599 | 0.404627 | 0.353728 | 0.344987 | 0.336247 | 0.324679 | 0.324679 | 0 | 0.007246 | 0.28335 | 6,162 | 184 | 80 | 33.48913 | 0.873641 | 0.564103 | 0 | 0.237288 | 0 | 0 | 0.14487 | 0.033906 | 0 | 0 | 0 | 0 | 0 | 1 | 0.20339 | false | 0.101695 | 0.016949 | 0 | 0.389831 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
effd91a6a374971283dacb08b1786b0d49944d0c | 4,323 | py | Python | tests/test_currency_tax.py | tek-shinobi/tekmoney | 88a51795ae20be00855bfae2cd1b4b0485b0fb01 | [
"MIT"
] | 1 | 2020-02-28T22:33:08.000Z | 2020-02-28T22:33:08.000Z | tests/test_currency_tax.py | tek-shinobi/tekmoney | 88a51795ae20be00855bfae2cd1b4b0485b0fb01 | [
"MIT"
] | 3 | 2020-03-24T18:13:23.000Z | 2021-02-02T22:36:13.000Z | tests/test_currency_tax.py | tek-shinobi/tekmoney | 88a51795ae20be00855bfae2cd1b4b0485b0fb01 | [
"MIT"
] | null | null | null | import pytest
from tekmoney.currency import Currency
from tekmoney.currency_tax import CurrencyWithTax
from tekmoney.utils import tek_sum
def test_init():
currency = CurrencyWithTax(net=Currency(1, "USD"), gross=Currency(1, "USD"))
assert (currency.net == Currency(1, "USD")) and (
currency.gross == Currency(1, "USD")
)
with pytest.raises(ValueError):
CurrencyWithTax(net=Currency(1, "USD"), gross=Currency(1, "GBP"))
with pytest.raises(TypeError):
CurrencyWithTax(1, 1)
def test_str():
currency = CurrencyWithTax(net=Currency(1, "USD"), gross=Currency(1, "USD"))
assert str(currency) == "CurrencyWithTax(net=1 USD, gross=1 USD)"
def test_add():
currency1 = CurrencyWithTax(Currency(10, "USD"), Currency(15, "USD"))
currency2 = CurrencyWithTax(Currency(20, "USD"), Currency(30, "USD"))
assert currency2 + currency1 == CurrencyWithTax(
Currency(30, "USD"), Currency(45, "USD")
)
currency3 = currency1 + Currency(5, "USD")
assert currency3.net == Currency(15, "USD")
assert currency3.gross == Currency(20, "USD")
with pytest.raises(ValueError):
currency1 + CurrencyWithTax(Currency(10, "GBP"), Currency(10, "GBP"))
with pytest.raises(TypeError):
currency1 + 1
def test_sub():
currency1 = CurrencyWithTax(Currency(10, "USD"), Currency(15, "USD"))
currency2 = CurrencyWithTax(Currency(30, "USD"), Currency(45, "USD"))
assert currency2 - currency1 == CurrencyWithTax(
Currency(20, "USD"), Currency(30, "USD")
)
currency3 = currency1 - Currency(5, "USD")
assert currency3.net == Currency(5, "USD")
assert currency3.gross == Currency(10, "USD")
with pytest.raises(ValueError):
currency1 - CurrencyWithTax(Currency(10, "GBP"), Currency(10, "GBP"))
with pytest.raises(TypeError):
currency1 - 1
def test_mult():
currency1 = CurrencyWithTax(Currency(10, "EUR"), Currency(20, "EUR"))
assert currency1 * 2 == CurrencyWithTax(Currency(20, "EUR"), Currency(40, "EUR"))
assert 2 * currency1 == currency1 * 2
with pytest.raises(TypeError):
currency1 * currency1
def test_div():
currency1 = CurrencyWithTax(Currency(10, "EUR"), Currency(20, "EUR"))
assert currency1 / 2 == CurrencyWithTax(Currency(5, "EUR"), Currency(10, "EUR"))
with pytest.raises(TypeError):
currency1 / currency1
def test_comparison():
currency = CurrencyWithTax(Currency(10, "EUR"), Currency(15, "EUR"))
assert currency == CurrencyWithTax(Currency(10, "EUR"), Currency(15, "EUR"))
assert currency != CurrencyWithTax(Currency(20, "EUR"), Currency(30, "EUR"))
assert currency != CurrencyWithTax(Currency(10, "GBP"), Currency(15, "GBP"))
assert currency != Currency(10, "EUR")
assert currency < CurrencyWithTax(Currency(20, "EUR"), Currency(30, "EUR"))
assert currency <= CurrencyWithTax(Currency(10, "EUR"), Currency(15, "EUR"))
assert currency <= CurrencyWithTax(Currency(20, "EUR"), Currency(30, "EUR"))
assert currency > CurrencyWithTax(Currency(1, "EUR"), Currency(1, "EUR"))
assert currency >= CurrencyWithTax(Currency(10, "EUR"), Currency(15, "EUR"))
assert currency >= CurrencyWithTax(Currency(1, "EUR"), Currency(1, "EUR"))
assert not currency <= CurrencyWithTax(Currency(1, "EUR"), Currency(1, "EUR"))
assert not currency >= CurrencyWithTax(Currency(20, "EUR"), Currency(30, "EUR"))
with pytest.raises(ValueError):
currency < CurrencyWithTax(Currency(10, "GBP"), Currency(15, "GBP"))
with pytest.raises(TypeError):
currency >= Currency(1, "EUR")
with pytest.raises(TypeError):
currency < Currency(20, "EUR")
def test_quantize():
price = CurrencyWithTax(Currency("1.001", "EUR"), Currency("1.001", "EUR"))
assert price.quantize() == (
CurrencyWithTax(Currency("1.00", "EUR"), Currency("1.00", "EUR"))
)
def test_currency():
price = CurrencyWithTax(Currency(1, "PLN"), Currency(1, "PLN"))
assert price.currency == "PLN"
def test_tax():
price = CurrencyWithTax(Currency(10, "USD"), Currency(15, "USD"))
assert price.tax == Currency(5, "USD")
def test_tek_sum():
assert tek_sum([Currency(5, "USD"), Currency(10, "USD")]) == Currency(15, "USD")
with pytest.raises(TypeError):
tek_sum([])
| 38.598214 | 85 | 0.65672 | 498 | 4,323 | 5.668675 | 0.096386 | 0.236273 | 0.115126 | 0.102019 | 0.751683 | 0.702444 | 0.647184 | 0.592986 | 0.512575 | 0.512575 | 0 | 0.050871 | 0.17696 | 4,323 | 111 | 86 | 38.945946 | 0.742552 | 0 | 0 | 0.204545 | 0 | 0 | 0.068702 | 0.004858 | 0 | 0 | 0 | 0 | 0.306818 | 1 | 0.125 | false | 0 | 0.045455 | 0 | 0.170455 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
efff50fca31f11e3944dc99e32a17c13c96bde67 | 739 | py | Python | Beginner/2750.py | LorranSutter/URI-Online-Judge | aef885b9a7caa83484cf172e29eea8ec92fc3627 | [
"MIT"
] | null | null | null | Beginner/2750.py | LorranSutter/URI-Online-Judge | aef885b9a7caa83484cf172e29eea8ec92fc3627 | [
"MIT"
] | null | null | null | Beginner/2750.py | LorranSutter/URI-Online-Judge | aef885b9a7caa83484cf172e29eea8ec92fc3627 | [
"MIT"
] | null | null | null | line = '-'*39
bases = '|' + ' ' + 'decimal' + ' ' + '|' + ' ' + 'octal' + ' ' + '|' + ' ' + 'Hexadecimal' + ' ' + '|'
blankNum1 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*4 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
blankNum2 = '|' + ' '*6 + '{0}' + ' '*4 + '|' + ' '*3 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
blankNum3 = '|' + ' '*5 + '{0}' + ' '*4 + '|' + ' '*3 + '{1}' + ' '*4 + '|' + ' '*7 + '{2}' + ' '*7 + '|'
print(line)
print(bases)
print(line)
for k in range(8):
print(blankNum1.format(k, oct(k)[2:], hex(k)[2:]))
for k in range(8,10):
print(blankNum2.format(k, oct(k)[2:], hex(k)[2:].upper()))
for k in range(10,16):
print(blankNum3.format(k, oct(k)[2:], hex(k)[2:].upper()))
print(line)
| 38.894737 | 109 | 0.364005 | 93 | 739 | 2.892473 | 0.311828 | 0.04461 | 0.033457 | 0.04461 | 0.394052 | 0.286245 | 0.286245 | 0.286245 | 0.163569 | 0 | 0 | 0.087814 | 0.244926 | 739 | 18 | 110 | 41.055556 | 0.394265 | 0 | 0 | 0.2 | 0 | 0 | 0.131258 | 0 | 0.266667 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.466667 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
4bd7eb8491ac04fe77ed957d22f9a5d89cb2ee85 | 124 | py | Python | PythonGUI/HelloWorldp2.py | minna001/Learning_Python | f91cd9f719fdb3fdd5f2f2262532dad2a37a5518 | [
"MIT"
] | null | null | null | PythonGUI/HelloWorldp2.py | minna001/Learning_Python | f91cd9f719fdb3fdd5f2f2262532dad2a37a5518 | [
"MIT"
] | null | null | null | PythonGUI/HelloWorldp2.py | minna001/Learning_Python | f91cd9f719fdb3fdd5f2f2262532dad2a37a5518 | [
"MIT"
] | null | null | null | from guizero import App, Text
app = App(title="Hello World")
message = Text(app,text="Welcome to the app")
app.display()
| 15.5 | 45 | 0.709677 | 20 | 124 | 4.4 | 0.65 | 0.159091 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.153226 | 124 | 7 | 46 | 17.714286 | 0.838095 | 0 | 0 | 0 | 0 | 0 | 0.237705 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4bd9707e1d966531a0c7e5c506a7010e5f340b21 | 2,634 | py | Python | fitness/time.py | anaandresarroyo/GarminDataAnalyserOld | 6f215e59903395b2fccfd54f0d083cee563d39e0 | [
"MIT"
] | null | null | null | fitness/time.py | anaandresarroyo/GarminDataAnalyserOld | 6f215e59903395b2fccfd54f0d083cee563d39e0 | [
"MIT"
] | null | null | null | fitness/time.py | anaandresarroyo/GarminDataAnalyserOld | 6f215e59903395b2fccfd54f0d083cee563d39e0 | [
"MIT"
] | null | null | null | import numpy as np
import pandas as pd
def calculate_elapsed_time(timestamp, units_t='sec', mode='start', fixed_timestamp=None):
"""Calculate the elapsed time from a timestamp pandas Series.
Arguments:
timestamp : timestamp pandas Series
Timestamp values
units_d: string
Units of the calculated time, e.g. 'sec' (default), 'min', or 'h'
mode : string
If 'start' calculate the elapsed time between all points of the array and the first point.
If 'previous' calculate the elapsed time between all points of the array the previous point.
If 'fixed' calculate the elapsed time between all points of the array the fixed_timestamp.
fixed_timestamp : one timestamp value
Fixed timestamp value to be used as a reference to calculate the elapsed time.
Output:
elapsed_time: float pandas Series
Contains the calculated elapsed time in units of units_t
"""
# The Garmin Forerunner 35 takes data every 1 second
origin_time = np.empty(timestamp.shape, dtype=type(timestamp))
if mode == 'start':
origin_time[:] = timestamp[0]
elif mode == 'previous':
origin_time[0] = timestamp[0]
for i, time in enumerate(timestamp[0:-1]):
origin_time[i + 1] = time
# TODO: change to origin_time.append(time)
elif mode == 'fixed':
origin_time[:] = fixed_timestamp
else:
raise ValueError('Unable to recognise the mode.')
# TODO: whey does origin_time have to be converted to datetime?
timedelta = timestamp - pd.to_datetime(origin_time)
elapsed_time = timedelta.astype('timedelta64[s]') # in seconds
if units_t == 's':
pass
elif units_t == 'sec':
pass
elif units_t == 'min':
# Convert seconds to minutes
elapsed_time = elapsed_time / 60
elif units_t == 'h':
# Convert seconds to hours
elapsed_time = elapsed_time / 60 / 60
else:
raise ValueError('Unable to recognise the units for the time.')
return elapsed_time
def select_times(StartTimeDoubleSpinBox, EndTimeDoubleSpinBox, df):
# TODO: use pandas time indexing
start_time = StartTimeDoubleSpinBox.value()
end_time = EndTimeDoubleSpinBox.value()
mask_start = df['elapsed time'] >= start_time
mask_end = df['elapsed time'] <= end_time
return df.loc[mask_start & mask_end]
def auto_crop_records(df):
"""
Crops the records dataframe.
:param df: pandas dataframe
:return: cropped_df: pandas dataframe
"""
# TODO: write this function
cropped_df = df.copy()
return cropped_df
| 33.769231 | 100 | 0.668185 | 349 | 2,634 | 4.919771 | 0.332378 | 0.102504 | 0.055329 | 0.066977 | 0.162493 | 0.134537 | 0.134537 | 0.089109 | 0.089109 | 0.089109 | 0 | 0.008599 | 0.249431 | 2,634 | 77 | 101 | 34.207792 | 0.859889 | 0.421033 | 0 | 0.111111 | 0 | 0 | 0.10084 | 0 | 0 | 0 | 0 | 0.025974 | 0 | 1 | 0.083333 | false | 0.055556 | 0.055556 | 0 | 0.222222 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
4be2b82c7026e1cb6b85847fdb56af84ffdf9902 | 15,733 | py | Python | smedl/structures/monitor.py | PRECISE/SMEDL | b0096d11fe4aa9febcf2f01346e2e28c6db13a32 | [
"MIT"
] | null | null | null | smedl/structures/monitor.py | PRECISE/SMEDL | b0096d11fe4aa9febcf2f01346e2e28c6db13a32 | [
"MIT"
] | null | null | null | smedl/structures/monitor.py | PRECISE/SMEDL | b0096d11fe4aa9febcf2f01346e2e28c6db13a32 | [
"MIT"
] | null | null | null | # Copyright (c) 2021 The Trustees of the University of Pennsylvania
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Structures and types for SMEDL monitors (.smedl files)
"""
import types
from . import expr
from smedl.parser.exceptions import (NameCollision, ElseCollision,
NameNotDefined)
class StateVariable(object):
"""Stores the information for a single state variable in a SMEDL spec"""
def __init__(self, name, type_, initial_value=None):
self._name = name
self._type = type_ # SMEDL type
if initial_value is not None:
self._initial_value = initial_value
else:
if self._type == expr.SmedlType.INT:
self._initial_value = "0"
elif self._type == expr.SmedlType.FLOAT:
self._initial_value = "0.0"
elif self._type == expr.SmedlType.CHAR:
self._initial_value = "'\\0'"
elif self._type == expr.SmedlType.STRING:
self._initial_value = '""'
elif self._type == expr.SmedlType.POINTER:
self._initial_value = "NULL"
elif self._type == expr.SmedlType.OPAQUE:
self._initial_value = '(SMEDLOpaque) {NULL, 0}'
@property
def name(self):
return self._name
@property
def type(self):
return self._type
@property
def initial_value(self):
return self._initial_value
class Action(object):
"""A base class for all the action types that may appear in the list of
actions for a transition step."""
def __init__(self, action_type):
"""Initialize the action
Parameters:
action_type - A string describing the type of action for use with Jinja
"""
self._action_type = action_type
@property
def action_type(self):
return self._action_type
class AssignmentAction(Action):
"""An action representing assigning an expression to a state variable"""
def __init__(self, var, expr):
"""Initialize the assignment.
Parameters:
var - The name of the state variable to assign to
expr - An expr.Expression to be assigned to it
"""
super().__init__('assignment')
self._var = var
self._expr = expr
@property
def var(self):
return self._var
@property
def expr(self):
return self._expr
class IncrementAction(Action):
"""An action representing incrementing a state variable"""
def __init__(self, var):
"""Initialize the increment using the provided state variable name."""
super().__init__('increment')
self._var = var
@property
def var(self):
return self._var
class DecrementAction(Action):
"""An action representing decrementing a state variable"""
def __init__(self, var):
"""Initialize the decrement using the provided state variable name."""
super().__init__('decrement')
self._var = var
@property
def var(self):
return self._var
class RaiseAction(Action):
"""An action representing raising an event"""
def __init__(self, event, params):
"""Initialize the raise action.
Parameters:
event - The name of the event to be raised
params - Parameters of the event as an iterable of expr.Expression
"""
super().__init__('raise')
self._event = event
self._params = tuple(params)
@property
def event(self):
return self._event
@property
def params(self):
return self._params
class CallAction(Action):
"""An action representing a call to a helper function."""
def __init__(self, function, params):
"""Initialize the function call action.
Parameters:
function - The name of the helper function to call
params - Parameters of the call as an iterable of expr.Expression
"""
super().__init__('call')
self._function = function
self._params = tuple(params)
@property
def function(self):
return self._function
@property
def params(self):
return self._params
class Scenario(object):
"""Stores the information for a single scenario in a SMEDL spec"""
def __init__(self, name):
self._name = name
# List of state names: The first state in the list is the initial state
self._states = []
# Implicit states are created when a scenario has a transition that
# goes directly into another transition, e.g.:
#
# state_a -> event1() -> event2() -> state_b
#
# This would create an implicit state between event1 and event2.
# Implicit states are given numbers sequentially, so we need to keep
# track of how many exist so far.
#
# In the generated code, implicit states get names like "_state0"
self._implicit_states = 0
# Final state: A state name from self._states or None
self._final_state = None
# Steps: Single steps from a transition.
# Keys are 2-tuples (state, event name) representing the state the step
# leads from and the event it is for. State is either a string if it
# is a named state or an integer if it is an implicit state.
# Values are lists of 3-tuples (condition, dest state, list of actions)
# where condition is an Expression (that should evaluate to an INT,
# FLOAT, or CHAR), dest state is a string or int as above, and list
# of actions is precisely a list of Action.
self._steps = dict()
# Else transitions: Keys are 2-tuples (state, event name) and
# values are 2-tuples (dest state, list of Actions)
self._elses = dict()
@property
def name(self):
return self._name
@property
def states(self):
return self._states
@property
def implicit_states(self):
return self._implicit_states
@property
def final_state(self):
return self._final_state
@property
def all_states(self):
"""Get a list of all states, explicit and implicit"""
return self.states + list(range(self.implicit_states))
@property
def steps(self):
return types.MappingProxyType(self._steps)
@property
def elses(self):
return types.MappingProxyType(self._elses)
def get_implicit_state(self):
"""Get the next unused implicit state number"""
state = self._implicit_states
self._implicit_states += 1
return state
def _add_state(self, name):
"""Add a state to the scenario, if a string and not already present.
The first state added becomes the initial state."""
if isinstance(name, str) and name not in self._states:
self._states.append(name)
def _add_else(self, from_state, event, to_state, actions):
"""Add else actions to a particular state-event pair"""
if to_state is not None:
key = (from_state, event)
if key in self._elses:
raise ElseCollision("An else is already defined for {}/{}"
.format(from_state, event))
self._elses[key] = (to_state, actions)
def add_step(self, from_state, event, condition, to_state, actions,
else_state=None, else_actions=None):
"""Add a step to the scenario
Parameters:
from_state - Name of state (or number of implicit state) this step is
from. If state does not exist yet, it will be added. Note that the
first from state of the first step added will become the starting
state for the scenario!
event - Name of event this step is for.
condition - An Expression representing the condition for this step, or
None if no condition
to_state - Name of state (or number of implicit state) this step is to
actions - A list of Action
else_state - Name of the "else state" or None if not provided. This may
only be provided for each from_state/event pair *once* or an
ElseCollision is raised
else_actions - A list of Action to occur when transitioning to the else
state
"""
# Add the from, to, and else states if necessary
self._add_state(from_state)
self._add_state(to_state)
self._add_state(else_state)
# If condition is None, convert to a true Expression (1)
if condition is None:
condition = expr.Literal('1', expr.SmedlType.INT)
# Otherwise, ensure it is not a string or opaque
else:
condition.condition_type_check()
# Add a new entry to the steps dict
key = (from_state, event)
value = (condition, to_state, actions)
try:
self._steps[key].append(value)
except KeyError:
self._steps[key] = [value]
# Add the else
self._add_else(from_state, event, else_state, else_actions)
def add_final_state(self, state):
"""Check if the given state exists and if so, store it as the final
state for this scenario"""
if state not in self._states:
raise NameNotDefined("Final state {} for scenario {} does not "
"exist".format(state, self._name))
self._final_state = state
def handles_event(self, event):
"""Check if this scenario has any transitions for the specified event.
Return True or False.
Parameters:
event - The name of the event to check for
"""
for key in self._steps.keys():
if key[1] == event:
return True
return False
class MonitorSpec(object):
"""A monitor specification from a .smedl file"""
def __init__(self, name, path):
"""Instantiate a new MonitorSpec to hold the data from a .smedl file"""
# Name of the monitor.
self._name = name
# Path where the monitor resides (used to try and locate helpers during
# generation)
self._path = path
# List of helper header files, with the enclosing "" or <>
self._helpers = []
# State vars: keys are names, values are StateVariables
self._state_vars = dict()
# Imported, internal, and exported events: keys are names, values are
# tuples of SmedlType representing their parameters
self._imported_events = dict()
self._internal_events = dict()
self._exported_events = dict()
# List of Scenarios containing the state machines themselves
self._scenarios = []
@property
def name(self):
return self._name
@property
def path(self):
return self._path
@property
def helpers(self):
return self._helpers
@property
def state_vars(self):
return types.MappingProxyType(self._state_vars)
@property
def imported_events(self):
return types.MappingProxyType(self._imported_events)
@property
def internal_events(self):
return types.MappingProxyType(self._internal_events)
@property
def exported_events(self):
return types.MappingProxyType(self._exported_events)
@property
def scenarios(self):
return self._scenarios
def add_helper(self, helper):
"""Add a header file for helper functions. helper is a string
containing the text to come after #include, e.g. '<helper.h>' or
'"helper.h"'"""
self._helpers.append(helper)
def add_state_var(self, name, type_, initial_value=None):
"""Add a state variable to the monitor after checking for duplicate
declaration. If an initial value isn't provided, a default will be
used."""
if name in self._state_vars:
raise NameCollision("State variable {} already defined".format(
name))
self._state_vars[name] = StateVariable(name, type_, initial_value)
def add_event(self, type_, name, param_list):
"""Add an event to the monitor. The type must be a string that's either
"imported", "internal", or "exported". The name is a string and the
param_list is an iterable of SmedlType."""
if (name in self._imported_events
or name in self._internal_events
or name in self._exported_events):
raise NameCollision("Event {} already defined".format(name))
if type_ == "imported":
self._imported_events[name] = tuple(param_list)
elif type_ == "internal":
self._internal_events[name] = tuple(param_list)
elif type_ == "exported":
self._exported_events[name] = tuple(param_list)
else:
raise ValueError("Unexpected event type {}".format(type_))
def add_scenario(self, scenario):
"""Add a Scenario to the monitor. If a scenario with the same name is
already present, raise NameCollision."""
# Check for name collisions
for s in self._scenarios:
if s.name == scenario.name:
raise NameCollision("A scenario with name {} already exists"
.format(scenario.name))
self.scenarios.append(scenario)
def get_event(self, name):
"""Retrieve the list of SmedlType representing an events parameters,
whether it be an imported, internal, or exported event. Return None
if the name is not a valid event."""
if name in self._imported_events:
return self._imported_events[name]
elif name in self._internal_events:
return self._internal_events[name]
elif name in self._exported_events:
return self._exported_events[name]
else:
return None
def needs_handler(self, event):
"""Return True if any scenario handles the given event, False
otherwise."""
for scenario in self._scenarios:
if scenario.handles_event(event):
return True
return False
def get_final_states(self):
"""Return a dict mapping scenario names to final state names, for any
scenario with a final state"""
results = dict()
for scenario in self._scenarios:
if scenario.final_state is not None:
results[scenario.name] = scenario.final_state
return results
def __repr__(self):
# TODO Proably do this by adding __repr__ to components and calling
# those
pass
| 35.040089 | 79 | 0.631729 | 1,998 | 15,733 | 4.83033 | 0.172172 | 0.030774 | 0.029013 | 0.013056 | 0.210445 | 0.159154 | 0.121749 | 0.088281 | 0.050565 | 0.019687 | 0 | 0.002065 | 0.292061 | 15,733 | 448 | 80 | 35.118304 | 0.864428 | 0.404437 | 0 | 0.275424 | 0 | 0 | 0.034243 | 0 | 0 | 0 | 0 | 0.002232 | 0 | 1 | 0.211864 | false | 0.004237 | 0.04661 | 0.110169 | 0.45339 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
4bef5c25af17acdbb4c078d37f8ca1b669255ba2 | 349 | py | Python | Python/Algorithms/selection_sort.py | SalazarLucas/Algorithms-and-DataStructures | ba99badb592264bd6a289b561aaa246982c88a3a | [
"MIT"
] | null | null | null | Python/Algorithms/selection_sort.py | SalazarLucas/Algorithms-and-DataStructures | ba99badb592264bd6a289b561aaa246982c88a3a | [
"MIT"
] | null | null | null | Python/Algorithms/selection_sort.py | SalazarLucas/Algorithms-and-DataStructures | ba99badb592264bd6a289b561aaa246982c88a3a | [
"MIT"
] | null | null | null | def selection_sort(arr):
for num in range(0, len(arr)):
min_position = num
for i in range(num, len(arr)):
if arr[i] < arr[min_position]:
min_position = i
temp = arr[num]
arr[num] = arr[min_position]
arr[min_position] = temp
arr = [6, 3, 8, 5, 2, 7, 4, 1]
print(f'Unordered: {arr}')
selection_sort(arr)
print(f'Ordered: {arr}') | 19.388889 | 33 | 0.633238 | 62 | 349 | 3.451613 | 0.435484 | 0.257009 | 0.261682 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.032028 | 0.194842 | 349 | 18 | 34 | 19.388889 | 0.729537 | 0 | 0 | 0 | 0 | 0 | 0.085714 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0 | 0 | 0.076923 | 0.153846 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4bf7c697bd02fdf5d911f36ef2daf8bf65f3a2c8 | 270 | py | Python | python/flipAndInvertImage.py | caleberi/LeetCode | fa170244648f73e76d316a6d7fc0e813adccaa82 | [
"MIT"
] | 1 | 2021-08-10T20:00:24.000Z | 2021-08-10T20:00:24.000Z | python/flipAndInvertImage.py | caleberi/LeetCode | fa170244648f73e76d316a6d7fc0e813adccaa82 | [
"MIT"
] | null | null | null | python/flipAndInvertImage.py | caleberi/LeetCode | fa170244648f73e76d316a6d7fc0e813adccaa82 | [
"MIT"
] | 3 | 2021-06-11T11:56:39.000Z | 2021-08-10T08:50:49.000Z | class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
for idx in range(len(image)):
image[idx] = list(reversed(image[idx]))
image[idx] = [1 if b == 0 else 0 for b in image[idx]]
return image
| 38.571429 | 76 | 0.581481 | 39 | 270 | 4.025641 | 0.512821 | 0.203822 | 0.140127 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.015306 | 0.274074 | 270 | 6 | 77 | 45 | 0.785714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ef03da3e85031b5a65d63dcdb2acce7fea95fb1f | 86 | py | Python | human_detector/config.py | damien1994/human_detector | 2ffe6d510dafd812d799d603159119e4cfc1f0ae | [
"MIT"
] | null | null | null | human_detector/config.py | damien1994/human_detector | 2ffe6d510dafd812d799d603159119e4cfc1f0ae | [
"MIT"
] | null | null | null | human_detector/config.py | damien1994/human_detector | 2ffe6d510dafd812d799d603159119e4cfc1f0ae | [
"MIT"
] | null | null | null | WINSTRIDE = (8, 8)
PADDING = (8, 8)
SCALE = 1.15
MIN_NEIGHBORS = 5
OVERLAP_NMS = 0.9
| 12.285714 | 18 | 0.639535 | 16 | 86 | 3.3125 | 0.8125 | 0.075472 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.147059 | 0.209302 | 86 | 6 | 19 | 14.333333 | 0.632353 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ef06237f0050b3b0b01c5913b0e49bffaff760f3 | 402 | py | Python | foxylib/tools/arithmetic/tests/test_arithmetic_tool.py | foxytrixy-com/foxylib | 94b8c5b9f8b12423393c68f7d9f910258840ed18 | [
"BSD-3-Clause"
] | null | null | null | foxylib/tools/arithmetic/tests/test_arithmetic_tool.py | foxytrixy-com/foxylib | 94b8c5b9f8b12423393c68f7d9f910258840ed18 | [
"BSD-3-Clause"
] | 3 | 2019-12-12T05:17:44.000Z | 2022-03-11T23:40:50.000Z | foxylib/tools/arithmetic/tests/test_arithmetic_tool.py | foxytrixy-com/foxylib | 94b8c5b9f8b12423393c68f7d9f910258840ed18 | [
"BSD-3-Clause"
] | 2 | 2019-10-16T17:39:34.000Z | 2020-02-10T06:32:08.000Z | import logging
from unittest import TestCase
from foxylib.tools.arithmetic.arithmetic_tool import ArithmeticTool
from foxylib.tools.log.foxylib_logger import FoxylibLogger
class TestArithmeticTool(TestCase):
@classmethod
def setUpClass(cls):
FoxylibLogger.attach_stderr2loggers(logging.DEBUG)
def test_01(self):
self.assertEqual(ArithmeticTool.divide_and_ceil(10, 3), 4) | 28.714286 | 67 | 0.791045 | 47 | 402 | 6.638298 | 0.680851 | 0.070513 | 0.102564 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.020231 | 0.139303 | 402 | 14 | 68 | 28.714286 | 0.881503 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 1 | 0.2 | false | 0 | 0.4 | 0 | 0.7 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
ef08591c547bb462dde64e18026a8d99ee911a2e | 101 | py | Python | Homework/Hw4/Solution/problem2.py | jmsevillam/Herramientas-Computacionales-UniAndes | 957338873bd6a17201dfd4629c7edd5760e2271d | [
"MIT"
] | null | null | null | Homework/Hw4/Solution/problem2.py | jmsevillam/Herramientas-Computacionales-UniAndes | 957338873bd6a17201dfd4629c7edd5760e2271d | [
"MIT"
] | null | null | null | Homework/Hw4/Solution/problem2.py | jmsevillam/Herramientas-Computacionales-UniAndes | 957338873bd6a17201dfd4629c7edd5760e2271d | [
"MIT"
] | 5 | 2019-05-27T13:35:51.000Z | 2020-09-30T15:19:39.000Z | def fac(n):
if n==1 or n==0:
return 1
else:
return n*fac(n-1)
print(fac(10))
| 14.428571 | 25 | 0.475248 | 20 | 101 | 2.4 | 0.55 | 0.166667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.092308 | 0.356436 | 101 | 6 | 26 | 16.833333 | 0.646154 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0 | 0 | 0.5 | 0.166667 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ef294280f46d8bfef031ac143455f12af4e4de96 | 89 | py | Python | speech/speech_test.py | naren-m/home_assistant | a20d64b79d97cbb2c9bae197c0900515ed8bfbfc | [
"MIT"
] | null | null | null | speech/speech_test.py | naren-m/home_assistant | a20d64b79d97cbb2c9bae197c0900515ed8bfbfc | [
"MIT"
] | null | null | null | speech/speech_test.py | naren-m/home_assistant | a20d64b79d97cbb2c9bae197c0900515ed8bfbfc | [
"MIT"
] | null | null | null | import speech
sentence = 'Time to leave for office'
su = speech.Speak()
su.say(sentence) | 17.8 | 37 | 0.741573 | 14 | 89 | 4.714286 | 0.785714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.146067 | 89 | 5 | 38 | 17.8 | 0.868421 | 0 | 0 | 0 | 0 | 0 | 0.266667 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ef2f461c0793116a0bd71aeea1d1c1880032dd8e | 711 | py | Python | garbage_router/data_io.py | Kenny2github/OEC-2022 | 816dd961a26c9f2a631bc0cb5e2ae683951ff680 | [
"Apache-2.0"
] | null | null | null | garbage_router/data_io.py | Kenny2github/OEC-2022 | 816dd961a26c9f2a631bc0cb5e2ae683951ff680 | [
"Apache-2.0"
] | null | null | null | garbage_router/data_io.py | Kenny2github/OEC-2022 | 816dd961a26c9f2a631bc0cb5e2ae683951ff680 | [
"Apache-2.0"
] | null | null | null | from __future__ import annotations
from functools import cache
from csv import reader, writer
from typing import TypedDict
from .enums import NodeType
from .waste import Waste
from .cmdargs import args
from .node import Node
class ReadData(TypedDict):
nodes: list[Node]
waste: list[Waste]
@cache
def read_data(path: str) -> list[Node]:
nodes: list[Node] = []
with open(path) as infile:
for row in reader(infile):
nodes.append(Node.from_csv_row(row))
return nodes
def write_data(path: list[Node]):
with open(args().output, 'w', newline='') as outfile:
csv_writer = writer(outfile)
for node in path:
csv_writer.writerow(node.to_csv_row()) | 27.346154 | 57 | 0.68917 | 101 | 711 | 4.732673 | 0.415842 | 0.066946 | 0.054393 | 0.066946 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.212377 | 711 | 26 | 58 | 27.346154 | 0.853571 | 0 | 0 | 0 | 0 | 0 | 0.001404 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.086957 | false | 0 | 0.347826 | 0 | 0.608696 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
ef34fd3227876a65c806f328bb854ee367521876 | 1,269 | py | Python | common/exceptions.py | caltechlibrary/documentarist | 055ad42f623c7affb584a6004e1bdba73d6312ac | [
"BSD-3-Clause"
] | 10 | 2020-04-27T19:12:14.000Z | 2022-02-11T07:06:17.000Z | common/exceptions.py | caltechlibrary/documentarist | 055ad42f623c7affb584a6004e1bdba73d6312ac | [
"BSD-3-Clause"
] | null | null | null | common/exceptions.py | caltechlibrary/documentarist | 055ad42f623c7affb584a6004e1bdba73d6312ac | [
"BSD-3-Clause"
] | 2 | 2020-04-27T19:12:21.000Z | 2021-03-15T10:47:16.000Z | '''
exceptions.py: exceptions defined by textform
Authors
-------
Michael Hucka <mhucka@caltech.edu> -- Caltech Library
Copyright
---------
Copyright (c) 2020 by the California Institute of Technology. This code is
open-source software released under a 3-clause BSD license. Please see the
file "LICENSE" for more information.
'''
# Base class.
# .............................................................................
# The base class makes it possible to use a single test to distinguish between
# exceptions generated by Documentarist code and exceptions generated by
# something else.
class DocumentaristException(Exception):
'''Base class for Documentarist exceptions.'''
pass
# Exception classes.
# .............................................................................
class CannotProceed(DocumentaristException):
'''A recognizable condition caused an early exit from the program.'''
pass
class UserCancelled(DocumentaristException):
'''The user elected to cancel/quit the program.'''
pass
class CorruptedContent(DocumentaristException):
'''Content corruption has been detected.'''
pass
class InternalError(DocumentaristException):
'''Unrecoverable problem involving textform itself.'''
pass
| 27 | 79 | 0.652482 | 127 | 1,269 | 6.519685 | 0.661417 | 0.032609 | 0.050725 | 0.045894 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004621 | 0.14736 | 1,269 | 46 | 80 | 27.586957 | 0.760628 | 0.722616 | 0 | 0.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0.5 | 0 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
ef3b6a7e66b54ce7fd460d473244685fc5f41533 | 838 | py | Python | tests/coverage/api/test_delete_quote.py | vyahello/quotes | 6b724ccff4091e0190f975599d80b42181e38a7c | [
"MIT"
] | 3 | 2020-03-31T22:16:04.000Z | 2021-03-26T20:04:17.000Z | tests/coverage/api/test_delete_quote.py | vyahello/quotes | 6b724ccff4091e0190f975599d80b42181e38a7c | [
"MIT"
] | 8 | 2020-03-30T15:04:55.000Z | 2021-07-25T09:05:37.000Z | tests/coverage/api/test_delete_quote.py | vyahello/quotes | 6b724ccff4091e0190f975599d80b42181e38a7c | [
"MIT"
] | null | null | null | import pytest
from tests.markers import api
from urequest.response import Response
from urequest.session import Session
from urequest.url import HttpsUrl
pytestmark = api
@pytest.fixture(scope="module")
def delete_quote_page(session: Session) -> Response:
yield session.get(
HttpsUrl(host="quote-quote.herokuapp.com", path="delete/2")
)
@pytest.fixture(scope="module")
def delete_quote_content(delete_quote_page: Response) -> str:
yield str(delete_quote_page)
def test_new_quote_status(delete_quote_page: Response) -> None:
assert delete_quote_page.is_ok()
def test_title(delete_quote_content: str) -> None:
assert "Delete Quote" in delete_quote_content
def test_navigation(delete_quote_content: str) -> None:
assert "Delete" in delete_quote_content
assert "Go Back" in delete_quote_content
| 25.393939 | 67 | 0.768496 | 117 | 838 | 5.264957 | 0.34188 | 0.214286 | 0.175325 | 0.097403 | 0.243506 | 0.243506 | 0.243506 | 0 | 0 | 0 | 0 | 0.001389 | 0.140811 | 838 | 32 | 68 | 26.1875 | 0.854167 | 0 | 0 | 0.095238 | 0 | 0 | 0.083532 | 0.029833 | 0 | 0 | 0 | 0 | 0.190476 | 1 | 0.238095 | false | 0 | 0.238095 | 0 | 0.47619 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
ef3e5ae9607c66688157ff34024ca3a23594c8b2 | 1,425 | py | Python | nbtutor/ipython/factories/kvp_heap_object_factory.py | vincentxavier/nbtutor | c1da217c44a84bd13b190c72eb0ef1ba66bbc90a | [
"BSD-3-Clause"
] | 423 | 2016-11-24T12:51:16.000Z | 2022-03-09T13:11:16.000Z | nbtutor/ipython/factories/kvp_heap_object_factory.py | vincentxavier/nbtutor | c1da217c44a84bd13b190c72eb0ef1ba66bbc90a | [
"BSD-3-Clause"
] | 52 | 2016-11-20T12:40:46.000Z | 2022-03-31T17:48:43.000Z | nbtutor/ipython/factories/kvp_heap_object_factory.py | vincentxavier/nbtutor | c1da217c44a84bd13b190c72eb0ef1ba66bbc90a | [
"BSD-3-Clause"
] | 41 | 2017-01-18T15:11:01.000Z | 2022-03-09T13:07:35.000Z | from typing import Any, Collection, Dict, Union, Optional
from ..models.heap_object import HeapObject, RenderOptions
from ..models.options import Options
from ..models.unique_identifier import UniqueIdentifier
from .base_heap_object_factory import HeapObjectFactory
class KvpHeapObjectFactory(HeapObjectFactory):
def __init__(self, obj: Dict, options: Options = None) -> None:
super().__init__(obj, options)
self._items = obj.items()
self._object_id = self.get_object_id(obj)
self._max_len = (self.options.max_size or len(self._items)) if self.options is not None else len(obj)
self._render_options: Optional[RenderOptions] = None
if (len(self._items) > self._max_len):
self._render_options = RenderOptions(True)
self._object = {k: v for (k, v) in list(self._items)[:self._max_len]}
def get_id(self) -> str:
return self._object_id
def get_value(self) -> str:
return self.get_type()
def get_objects_to_reduce(self) -> Union[None, Collection[Any]]:
return self._object.values()
def create(self) -> HeapObject:
heap_obj = HeapObject(self.get_id(), self.get_type(), self.get_value(), 'kvp', self._render_options)
heap_obj.immutable = False
heap_obj.references = {k: UniqueIdentifier(HeapObjectFactory.get_object_id(v)) for k, v in self._object.items()}
return heap_obj
| 36.538462 | 120 | 0.692632 | 189 | 1,425 | 4.936508 | 0.312169 | 0.053591 | 0.032154 | 0.030011 | 0.057878 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.197193 | 1,425 | 38 | 121 | 37.5 | 0.815559 | 0 | 0 | 0 | 0 | 0 | 0.002105 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.192308 | false | 0 | 0.192308 | 0.115385 | 0.576923 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
ef40c531e99b4c1edff6bf2dfe45c5053356c0c5 | 1,440 | py | Python | aws_data_tools/models/sns.py | timoguin/aws-data-tools-py | f986daea360d3ffdb49a60c28d150254bb76b251 | [
"MIT"
] | 4 | 2021-06-10T05:41:39.000Z | 2021-12-17T14:51:45.000Z | aws_data_tools/models/sns.py | timoguin/aws-data-tools-py | f986daea360d3ffdb49a60c28d150254bb76b251 | [
"MIT"
] | 3 | 2021-12-10T20:55:06.000Z | 2022-01-28T00:27:18.000Z | aws_data_tools/models/sns.py | timoguin/aws-data-tools-py | f986daea360d3ffdb49a60c28d150254bb76b251 | [
"MIT"
] | null | null | null | from dataclasses import dataclass
import logging
from typing import Optional
from .base import ModelBase
from ..utils.validators import is_valid_json
logging.getLogger(__name__).addHandler(logging.NullHandler())
@dataclass
class SnsMessageData(ModelBase):
"""Represents the data from an SNS message that is under the "Sns" field"""
message: str
message_id: str
signature: str
signature_version: str
signing_cert_url: str
subject: str
timestamp: str
topic_arn: str
type: str
unsubscribe_url: str
# TODO: Unsure if there are additional attributes if the message comes from an SNS
# FIFO topic
@dataclass
class SnsMessage(ModelBase):
"""Schema for an SNS message"""
message: str
message_id: str
subject: str
timestamp: str
topic_arn: str
type: str
unsubscribe_url: str
signature: Optional[str]
signature_version: Optional[str]
signing_cert_url: Optional[str]
# TODO: Unsure if there are additional attributes if the message comes from an SNS
# FIFO topic
@property
def is_body_json(self) -> bool:
"""Check if the message body is a JSON string"""
return is_valid_json(self.message)
@dataclass
class LambdaSnsMessage(ModelBase):
"""Represents the SNS message format when using Lambda subscriptions"""
event_source: str
event_version: str
event_subscription_arn: str
sns: SnsMessage
| 22.857143 | 86 | 0.7125 | 187 | 1,440 | 5.347594 | 0.385027 | 0.02 | 0.027 | 0.038 | 0.314 | 0.273 | 0.273 | 0.273 | 0.273 | 0.273 | 0 | 0 | 0.220833 | 1,440 | 62 | 87 | 23.225806 | 0.891266 | 0.270139 | 0 | 0.435897 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.016129 | 0 | 1 | 0.025641 | false | 0 | 0.128205 | 0 | 0.871795 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
322ee538f22f989d2d12063a0bb1a1f11c94db98 | 364 | py | Python | misc/format_override_test.py | ilil01/qdt | 2921fb121f8c6e8cd29bd82fc4b591cb92abab78 | [
"BSD-3-Clause"
] | 29 | 2017-12-22T17:25:56.000Z | 2022-03-03T08:27:01.000Z | misc/format_override_test.py | ilil01/qdt | 2921fb121f8c6e8cd29bd82fc4b591cb92abab78 | [
"BSD-3-Clause"
] | 33 | 2019-11-26T17:21:14.000Z | 2021-08-23T03:28:12.000Z | misc/format_override_test.py | ilil01/qdt | 2921fb121f8c6e8cd29bd82fc4b591cb92abab78 | [
"BSD-3-Clause"
] | 7 | 2017-12-22T17:14:59.000Z | 2022-01-30T19:52:03.000Z | class MyStr(str):
def __format__(self, *args, **kwargs):
print("my format")
return str.__format__(self, *args, **kwargs)
def __mod__(self, *args, **kwargs):
print("mod")
return str.__mod__(self, *args, **kwargs)
if __name__ == "__main__":
ms = MyStr("- %s - {} -")
print(ms.format("test"))
print(ms % "test")
| 24.266667 | 52 | 0.554945 | 43 | 364 | 4.139535 | 0.418605 | 0.179775 | 0.314607 | 0.224719 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | 364 | 14 | 53 | 26 | 0.652015 | 0 | 0 | 0 | 0 | 0 | 0.107143 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.181818 | false | 0 | 0 | 0 | 0.454545 | 0.363636 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3232c7c09602170284133247fa7468f996bb6621 | 89 | py | Python | Basic-OpenCV/programOne.py | hasibul-islam-nirob/OpenCV | 432c601edac1fda3eba615b2dd9bc56901598de6 | [
"Apache-2.0"
] | null | null | null | Basic-OpenCV/programOne.py | hasibul-islam-nirob/OpenCV | 432c601edac1fda3eba615b2dd9bc56901598de6 | [
"Apache-2.0"
] | null | null | null | Basic-OpenCV/programOne.py | hasibul-islam-nirob/OpenCV | 432c601edac1fda3eba615b2dd9bc56901598de6 | [
"Apache-2.0"
] | null | null | null |
import cv2
img = cv2.imread("img/nirob.jpg");
cv2.imshow('output',img);
cv2.waitKey(0); | 14.833333 | 34 | 0.685393 | 15 | 89 | 4.066667 | 0.666667 | 0.196721 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.061728 | 0.089888 | 89 | 6 | 35 | 14.833333 | 0.691358 | 0 | 0 | 0 | 0 | 0 | 0.213483 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3235367709df1298c65c7404d5cf5a0cffb61f61 | 583 | py | Python | python-projects/dictio.py | dropandfly23/pythons | 6982b74f30bb965cfe949bfbff1030506acd5638 | [
"MIT"
] | 1 | 2020-06-15T08:23:55.000Z | 2020-06-15T08:23:55.000Z | python-projects/dictio.py | dropandfly23/pythons | 6982b74f30bb965cfe949bfbff1030506acd5638 | [
"MIT"
] | null | null | null | python-projects/dictio.py | dropandfly23/pythons | 6982b74f30bb965cfe949bfbff1030506acd5638 | [
"MIT"
] | null | null | null | # Program: Gmail Dictionary Attack v2
# Author: dropnfly23
# Purpose: Brute force smtp.gmail.com using a dictionary attack over TLS.
import smtplib
smtpserver = smtplib.SMTP("smtp.gmail.com", 587,timeout=None)
smtpserver.ehlo()
smtpserver.starttls()
user = 'mygmail@gmail.com'
passwfile = raw_input("Enter the password file name: ")
passwfile = open("./dico.txt", "r")
for password in passwfile:
try:
smtpserver.login(user, password)
print "[+] Password Found: %s" % password
break;
except smtplib.SMTPAuthenticationError:
print "[!] Password Incorrect: %s" % password | 26.5 | 73 | 0.735849 | 74 | 583 | 5.783784 | 0.662162 | 0.056075 | 0.056075 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011952 | 0.138937 | 583 | 22 | 74 | 26.5 | 0.840637 | 0.216124 | 0 | 0 | 0 | 0 | 0.264317 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.428571 | 0.071429 | null | null | 0.142857 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
323c15a70ba7159df03dbc195edb24d14f1883dd | 1,120 | py | Python | Chapter6/double_tree_and_tree_notes.py | qimanchen/Algorithm_Python | 72eabb5fcc9fafb17172879c1250d3c9553e583d | [
"Apache-2.0"
] | null | null | null | Chapter6/double_tree_and_tree_notes.py | qimanchen/Algorithm_Python | 72eabb5fcc9fafb17172879c1250d3c9553e583d | [
"Apache-2.0"
] | null | null | null | Chapter6/double_tree_and_tree_notes.py | qimanchen/Algorithm_Python | 72eabb5fcc9fafb17172879c1250d3c9553e583d | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
树:是由结点与节点之间的链接关系组成
树的特征:
1、存在唯一的起始点,树根
2、树根外的其他结点都有且只有一个前驱结点;但每个结点可以有0-n个后继
树可以有多个尾结点
3、树根可以到达任意结点(有限跳)
4、任意两个不同结点向下出发,无交叉
二叉树:
树中每个结点最多关联到两个后继结点
后继结点明确分左右
左右子树必须明确说明
几个基本概念:(都是对于二叉树而言)
空树:不包含任何结点
单点树:只包含一个结点
父结点和子节点是相对而言的
边:父到子,具有方向性
兄弟结点:具有相同的父结点的结点
树叶:没有子节点的二叉树
分支结点
度数:一个结点的子结点的个数
路径边的条数 -- 路径的长度
到自身,长度为0
路径唯一性
从树根到树中任一结点的路径长度 --- 结点的层数
二叉树的高度(深度) -- 树中结点最大层数
二叉树的性质:
1、在非空二叉树第i层中至多有2^i个结点(i >=0)
2、高度为h的二叉树至多有2^(h+1)-1个结点 (h>=0)
3、对于任何非空二叉树,如果叶结点的个数为n0,度数为2的结点个数为n2
n0 = n2 + 1
满二叉树;
所有分支结点的度数都为2
性质; 满二叉树里的叶结点比分支结点多一个
扩充二叉树:
将非满二叉树扩充成满 -- 外部结点:内部结点
完全二叉树:
最后一层排不满,且空位都在右边(如果有空位的话)
n个结点的完全二叉树高度 h =[log_2(n)], 即为不大于它的最大整数
notes: 从上到下,从左到右编号,0开始,对任意结点i都有
1、0 -- 根结点
2、i>0, 父结点编号int((i-1)/2)
3、2*i + 1 < n, 左子结点序号为 2*i + 1, 否则它没有子节点
4、2*i + 2 < n ,右子结点序号为 2*i + 2, 否则没有子结点
(i-1)/2
i i+1
2*i +1 2*i + 2
总结:
""" | 15.135135 | 44 | 0.563393 | 141 | 1,120 | 4.468085 | 0.680851 | 0.025397 | 0.019048 | 0.019048 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.064136 | 0.317857 | 1,120 | 74 | 45 | 15.135135 | 0.760471 | 2.209821 | 0 | null | 0 | null | 0 | 0 | null | 0 | 0 | 0 | null | 1 | null | true | 0 | 0 | null | null | null | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
3244b69bae1cd368807a0c3eb2896cda7275ddef | 732 | py | Python | src/dbversions/__init__.py | chof747/dbversions | e5635b1bf23d2e6f0730d9822a1226b9ff737c2a | [
"BSD-3-Clause"
] | null | null | null | src/dbversions/__init__.py | chof747/dbversions | e5635b1bf23d2e6f0730d9822a1226b9ff737c2a | [
"BSD-3-Clause"
] | null | null | null | src/dbversions/__init__.py | chof747/dbversions | e5635b1bf23d2e6f0730d9822a1226b9ff737c2a | [
"BSD-3-Clause"
] | null | null | null | from git import Commit
import os,sys
import logging
import six
def astring(s):
if isinstance(s, six.text_type):
converted = s.encode('ascii', 'ignore')
if not isinstance(converted, bytes):
s = converted
elif isinstance(s, Commit):
s = s.hexsha
return s
def getResourcePath(resource):
return os.path.join(os.path.dirname(sys.modules['dbversions'].__file__),
resource)
VERBOSITY = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
from .config import Config
from .db import DbDump
from .gitanalyzer import GitAnalyzer
from .DBConfig import DBConfig
def parseEnvironments(option):
envs = option.split(',')
return envs | 24.4 | 77 | 0.662568 | 89 | 732 | 5.393258 | 0.516854 | 0.045833 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.240437 | 732 | 30 | 78 | 24.4 | 0.863309 | 0 | 0 | 0 | 0 | 0 | 0.030014 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.130435 | false | 0 | 0.347826 | 0.043478 | 0.608696 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
324a3cb5ff6311790bd6708c21e4294649d115c0 | 3,471 | py | Python | nlpml/destination.py | johann-petrak/nlp-ml | 86e1e86b8b2fa915cacd2ca8a39635ce982d9f4e | [
"Apache-2.0"
] | null | null | null | nlpml/destination.py | johann-petrak/nlp-ml | 86e1e86b8b2fa915cacd2ca8a39635ce982d9f4e | [
"Apache-2.0"
] | null | null | null | nlpml/destination.py | johann-petrak/nlp-ml | 86e1e86b8b2fa915cacd2ca8a39635ce982d9f4e | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
'''
Base class and example implementations for serial destinations. Anything that implements
write and optionally close can be used too.
A destination can get just the item or a tuple with id and item, depending on how the processor
was configured before running.
NOTE: the set_data method was added for situations where the destination is an in-memory object but
the destination instance is running in a different process. In that situation the code taking care of the processes
can get the data from the other process and set it in the original instance.
However, the processors in processor.py run the destination writer in the same process where it came from, so this
should be fine.
'''
from abc import ABC, abstractmethod
import json
class SerialDestination(ABC):
"""
Base class for all implementations of something that needs serial writing.
"""
def __init__(self):
self.data = None
@abstractmethod
def write(self, item):
"""
Write the next item to the destination.
:param item: the data to write
:return:
"""
pass
def close(self):
"""
Close the destination if necessary, otherwise do nothing.
:return:
"""
pass
def get_data(self):
"""
Returns the data from the destination if this is an in-memory destination.
For other kinds of destination, this could return None or whatever makes sense.
:return:
"""
return self.data
def set_data(self, data):
"""
This can be used to set the data in the original instance if a copy of the instance was used
in a different process to create the data.
:param data: the data to set
:return:
"""
self.data = data
def size(self):
"""
Returns the number of items written to that destination.
:return: number of items
"""
class SdJsonLinesFile(SerialDestination):
"""
A destination which writes each item as json to a line in a destination file.
"""
def __init__(self, file):
"""
Destination for writing items to a line of JSON each in a file.
:param file: the file to write to.
"""
self.file = file
self.fh = open(file, "wt", encoding="utf8")
self.n = 0
def write(self, item):
self.fh.write(json.dumps(item))
self.n += 1
self.fh.write("\n")
def size(self):
return self.n
class SdList(SerialDestination):
"""
A destination for lists
"""
def __init__(self, thelist):
if not isinstance(thelist, list):
raise Exception("Must be a list")
self.data = thelist
def write(self, item):
import sys
self.data.append(item)
def size(self):
return len(self.n)
class SdMap(SerialDestination):
"""
A destination for maps/dictionaries. For these, the destination needs to receive the tuple (id, item) from
the processor!
"""
def __init__(self, themap):
if not isinstance(themap, map):
raise Exception("Must be a map")
self.data = themap
def write(self, item):
if not isinstance(item, tuple) or not len(item) == 2:
raise Exception("write must get a tuple (id, item) instead of item!")
self.data[item[0]] = item[1]
def size(self):
return len(self.data)
| 27.330709 | 115 | 0.626909 | 473 | 3,471 | 4.560254 | 0.315011 | 0.03338 | 0.020399 | 0.029671 | 0.041725 | 0.022253 | 0 | 0 | 0 | 0 | 0 | 0.002445 | 0.292999 | 3,471 | 126 | 116 | 27.547619 | 0.876528 | 0.480841 | 0 | 0.212766 | 0 | 0 | 0.056291 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.319149 | false | 0.042553 | 0.06383 | 0.06383 | 0.553191 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
325d3ce6f61963efc80156f76ef791404a402514 | 404 | py | Python | tests/endpoints/test_non_settled_partners.py | s0b0lev/raiden-client-python | 4eecdda10650f081e4449449949067af6356d542 | [
"MIT"
] | 3 | 2019-08-01T12:47:16.000Z | 2020-07-05T15:28:53.000Z | tests/endpoints/test_non_settled_partners.py | s0b0lev/raiden-client-python | 4eecdda10650f081e4449449949067af6356d542 | [
"MIT"
] | 17 | 2019-08-01T07:51:58.000Z | 2020-05-29T09:48:37.000Z | tests/endpoints/test_non_settled_partners.py | s0b0lev/raiden-client-python | 4eecdda10650f081e4449449949067af6356d542 | [
"MIT"
] | null | null | null | from raiden_client.endpoints.non_settled_partners import NonSettledPartners
def test_non_settled_partners_request() -> None:
request = NonSettledPartners(token_address="0x145737846791E749f96344135Ce211BE8C510a17")
assert request.endpoint == f"/tokens/{request.token_address}/partners"
assert request.method == "get"
assert request.name == "non-settled"
assert not request.payload()
| 40.4 | 92 | 0.787129 | 43 | 404 | 7.186047 | 0.581395 | 0.097087 | 0.116505 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.092697 | 0.118812 | 404 | 9 | 93 | 44.888889 | 0.775281 | 0 | 0 | 0 | 0 | 0 | 0.237624 | 0.20297 | 0 | 0 | 0.10396 | 0 | 0.571429 | 1 | 0.142857 | false | 0 | 0.142857 | 0 | 0.285714 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
325d838ceb8cbc28e388a9ecaa2531906cef876c | 3,958 | py | Python | slave/app/view_manager/routes.py | darksigma/traceless | eed3a35e90b8bbbf272e1f324e1c28de7afe08da | [
"MIT"
] | 1 | 2015-06-19T14:27:52.000Z | 2015-06-19T14:27:52.000Z | slave/app/view_manager/routes.py | pratheeknagaraj/securechat | eed3a35e90b8bbbf272e1f324e1c28de7afe08da | [
"MIT"
] | null | null | null | slave/app/view_manager/routes.py | pratheeknagaraj/securechat | eed3a35e90b8bbbf272e1f324e1c28de7afe08da | [
"MIT"
] | 1 | 2016-04-09T19:25:11.000Z | 2016-04-09T19:25:11.000Z | from . import view_manager
from flask import jsonify, request, abort
from flask import current_app as app
import os
from .. import traceless_crypto
import requests
import json
@view_manager.route('/', methods = ['POST'])
def hello_world():
print "hello world"
return "hello world"
@view_manager.route('/send_ping', methods=['POST'])
def send_ping():
with app.jinja_env.globals['server_view_manager_lock']:
try:
headers = {'content-type': 'application/json'}
args = {
'slave_url' : app.jinja_env.globals['server_me_url'],
'view_num' : app.jinja_env.globals['server_view_number'],
'rsa_n' : app.jinja_env.globals['server_rsa'].n,
'rsa_d' : app.jinja_env.globals['server_rsa'].d,
'rsa_e' : app.jinja_env.globals['server_rsa'].e
}
response = requests.post(app.jinja_env.globals['server_master_url'] + "/process_ping", headers=headers, data=json.dumps(args))
r = json.loads(response.text)
shard = get_shard(r['views'])
if shard is not None:
if shard in app.jinja_env.globals['server_views']:
print app.jinja_env.globals['server_views']
needForward = r['views'][shard]['B'] != '' \
and r['views'][shard]['P'] == app.jinja_env.globals['server_me_url'] \
and r['views'][shard]['B'] != app.jinja_env.globals['server_views'][shard]['B']
if needForward:
try:
finished = False
while not finished:
# print "TRYING TO FORWARD!"
args = {
'messages_table' : app.jinja_env.globals['server_messages_table']
}
headers = {'content-type': 'application/json'}
response = requests.post(r['views'][shard]['B'] + "/process_forward", headers=headers, data=json.dumps(args))
r2 = json.loads(response.text)
finished = r2['success']
# if r2['success'] == False:
# return jsonify({'success' : False}), 200
except requests.exceptions.RequestException as e:
print e
return jsonify({'success' : False}), 200
app.jinja_env.globals['shard'] = shard
app.jinja_env.globals['server_view_number'] = r['views'][app.jinja_env.globals['shard']]['N']
app.jinja_env.globals['server_views'] = r['views']
return jsonify({'success' : True,
'server_views' : r['views']}), 200
except requests.exceptions.RequestException as e:
print e
return jsonify({'success' : False}), 200
@view_manager.route('/process_forward', methods=['POST'])
def process_forward():
with app.jinja_env.globals['server_view_manager_lock']:
if app.jinja_env.globals['server_views'][app.jinja_env.globals['shard']]['B'] != app.jinja_env.globals['server_me_url']:
return jsonify({'success' : False}), 200
for slot in request.json['messages_table']:
app.jinja_env.globals['server_messages_table'][slot] = request.json['messages_table'][slot]
print app.jinja_env.globals['server_messages_table']
return jsonify({'success' : True}), 200
def get_shard(views):
shard = [x for x in views if views[x]['P'] == app.jinja_env.globals['server_me_url'] or views[x]['B'] == app.jinja_env.globals['server_me_url']]
if len(shard) == 0:
return None
else:
shard = shard[0]
return shard
| 49.475 | 148 | 0.535371 | 435 | 3,958 | 4.678161 | 0.204598 | 0.094349 | 0.12973 | 0.212285 | 0.551843 | 0.47027 | 0.312039 | 0.228993 | 0.170025 | 0.078624 | 0 | 0.008722 | 0.333754 | 3,958 | 79 | 149 | 50.101266 | 0.762988 | 0.02476 | 0 | 0.214286 | 0 | 0 | 0.170384 | 0.028786 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.1 | null | null | 0.071429 | 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 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
32604f97c69d2d4ce203af50f85a019aa0643b35 | 752 | py | Python | vendor/packages/sqlalchemy/sqla_nose.py | jgmize/kitsune | 8f23727a9c7fcdd05afc86886f0134fb08d9a2f0 | [
"BSD-3-Clause"
] | 2 | 2019-08-19T17:08:47.000Z | 2019-10-05T11:37:02.000Z | vendor/packages/sqlalchemy/sqla_nose.py | jgmize/kitsune | 8f23727a9c7fcdd05afc86886f0134fb08d9a2f0 | [
"BSD-3-Clause"
] | null | null | null | vendor/packages/sqlalchemy/sqla_nose.py | jgmize/kitsune | 8f23727a9c7fcdd05afc86886f0134fb08d9a2f0 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
"""
nose runner script.
Only use this script if setuptools is not available, i.e. such as
on Python 3K. Otherwise consult README.unittests for the
recommended methods of running tests.
"""
try:
import sqlalchemy
except ImportError:
from os import path
import sys
sys.path.append(path.join(path.dirname(__file__), 'lib'))
import nose
from sqlalchemy.test.noseplugin import NoseSQLAlchemy
from sqlalchemy.util import py3k
if __name__ == '__main__':
if py3k:
# this version breaks verbose output,
# but is the only API that nose3 currently supports
nose.main(plugins=[NoseSQLAlchemy()])
else:
# this is the "correct" API
nose.main(addplugins=[NoseSQLAlchemy()])
| 25.066667 | 65 | 0.704787 | 100 | 752 | 5.18 | 0.67 | 0.054054 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006723 | 0.208777 | 752 | 29 | 66 | 25.931034 | 0.863866 | 0.420213 | 0 | 0 | 0 | 0 | 0.025943 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
32704cdbe0b63460015dc3b639dacc659dd1ec52 | 2,858 | py | Python | app/model/user_repository.py | marcosricardoss/flask-restful-skeleton | 59792c25189d2b3ee7a09d5167ced7835ce1819b | [
"Unlicense",
"MIT"
] | 10 | 2019-06-26T02:14:44.000Z | 2022-03-29T12:55:21.000Z | app/model/user_repository.py | marcosricardoss/flask-docker-boilerplate | 5f0fead79e2c38e7231d8570ce64389620940a20 | [
"MIT"
] | 3 | 2019-12-26T17:28:44.000Z | 2020-03-10T19:35:07.000Z | app/model/user_repository.py | marcosricardoss/flask-docker-boilerplate | 5f0fead79e2c38e7231d8570ce64389620940a20 | [
"MIT"
] | 4 | 2020-04-23T06:30:18.000Z | 2021-12-07T18:07:39.000Z | """It contains UserRepository class."""
from werkzeug.security import generate_password_hash, check_password_hash
from .models import User
from .repository import Repository
class UserRepository(Repository):
"""It Contains specific method related to de User
model to do operation in the dabase.
"""
def __init__(self):
Repository.__init__(self, User)
def get_by_username(self, username: str) -> User:
"""Retrive a users from database by its username.
Parameters:
username (str): The username of the user.
Returns:
User: User model object.
"""
return self.session.query(User).filter_by(username=username).first()
def save(self, user: User) -> None:
"""Saves a user in the database.
Parameters:
model (User): A user model object.
"""
user.password = generate_password_hash(user.password)
self.session.add(user)
self.session.commit()
def update(self, user: User) -> None:
"""Update a existent user in the database.
Parameters:
model (object): A user model object.
"""
user.password = generate_password_hash(user.password)
self.session.commit()
def authenticate(self, username: str, password: str) -> bool:
"""checks user authenticity by username and password.
Parameters:
username (str): The username of the user.
password (str): The password of the user.
Returns:
bool: A boolean indicating the user authenticity.
"""
user = self.get_by_username(username)
if user and check_password_hash(user.password, password):
return user
return False
def is_invalid(self, user: User) -> list:
"""Checks if a given model object is valid.
Parameters:
user (User): The User model object.
editing (bool): Indicates whether the validation is for an editing.
Returns:
list: A list containing the fields errors.
"""
invalid = list()
if not user.username:
invalid.append({"username": "must be filled"})
if not user.password:
invalid.append({"password": "must be filled"})
if user.password and len(user.password) < 3:
invalid.append({"password": "minimum length of 3 characters"})
# verify if there is another user with the same username
user_checking = self.get_by_username(user.username)
if user_checking:
if (not user.id) or (user.id != user_checking.id):
invalid.append({"username": "is already in use."})
# remove from the session if it is not valid
if invalid:
user.remove_session()
return invalid
| 28.29703 | 79 | 0.608467 | 338 | 2,858 | 5.056213 | 0.289941 | 0.063195 | 0.035108 | 0.04213 | 0.16852 | 0.16852 | 0.131071 | 0.131071 | 0.08309 | 0.08309 | 0 | 0.001001 | 0.30056 | 2,858 | 100 | 80 | 28.58 | 0.853927 | 0.341847 | 0 | 0.114286 | 1 | 0 | 0.065654 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.171429 | false | 0.257143 | 0.085714 | 0 | 0.4 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.