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
8300a51e4d9835364398b0d1dde5890755098af7
466
py
Python
cube/util.py
Bhaskers-Blu-Org1/skills-for-planning
98575d963e63d2c84075df9500c74c14f8a8553b
[ "ECL-2.0", "Apache-2.0" ]
2
2020-07-08T09:58:13.000Z
2021-03-19T05:40:29.000Z
cube/util.py
Bhaskers-Blu-Org1/skills-for-planning
98575d963e63d2c84075df9500c74c14f8a8553b
[ "ECL-2.0", "Apache-2.0" ]
6
2021-03-19T03:13:37.000Z
2022-03-11T23:57:41.000Z
cube/util.py
IBM/skills-for-planning
98575d963e63d2c84075df9500c74c14f8a8553b
[ "ECL-2.0", "Apache-2.0" ]
4
2019-08-30T15:12:07.000Z
2020-06-29T14:50:22.000Z
class ansi: pass ansi.red = '\x1b[41m' ansi.orange = '\x1b[48;5;130m' ansi.green = '\x1b[42m' ansi.yellow = '\x1b[43m' ansi.blue = '\x1b[44m' ansi.magenta = '\x1b[45m' ansi.cyan = '\x1b[46m' ansi.white = '\x1b[47m' ansi.reset = '\x1b[49m' fill = { 'O': ansi.orange+' '+ansi.reset, 'G': ansi.green+' '+ansi.reset, 'Y': ansi.yellow+' '+ansi.reset, 'R': ansi.red+' '+ansi.reset, 'B': ansi.cyan+' '+ansi.reset, 'W': ansi.white+' '+ansi.reset, }
23.3
36
0.577253
72
466
3.736111
0.430556
0.234201
0
0
0
0
0
0
0
0
0
0.079692
0.165236
466
19
37
24.526316
0.611825
0
0
0
0
0
0.193133
0
0
0
0
0
0
1
0
false
0.055556
0
0
0.055556
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
1
0
0
0
0
0
2
8306d7cca7e0742313870051160f6f50cf9d11a8
1,608
py
Python
test.py
jin0g/soundset
6167638323eac5c475102c72c836f51b8442f54e
[ "MIT" ]
null
null
null
test.py
jin0g/soundset
6167638323eac5c475102c72c836f51b8442f54e
[ "MIT" ]
null
null
null
test.py
jin0g/soundset
6167638323eac5c475102c72c836f51b8442f54e
[ "MIT" ]
null
null
null
import soundset # create random score for C3~C5note == 130.8~523.3hz #-> score object s1 = soundset.score.random(length=32,tempo=120,beat=16,chord=3,pitch=3,register=25,random_state=None) # create score piano roll #-> 2-dim binaly numpy array, size of (length, 128) roll = s1.to_roll(ignore_out_of_range=False) assert roll.dtype==int, 'it is binaly array but dtype is int' assert roll.shape==(32,128), 'shape is to (32,128)' assert roll.min()==0 and roll.max()==1, 'binaly array' assert all( roll.sum(axis=1)==3 ), 'each line has 3 notes' roll = s1.to_roll(ignore_out_of_range=True) assert roll.shape == (32,25), 'the roll shape is to (32,25) when ignore_out_of_range is True' # synthesize score #-> 1 or 2-dim float on [-1,1] numpy array, size of (length):mono or (length, 2):stereo wave = s1.to_wave(instrument=0,stereo=True,rate=44100) # inst0=piano assert wave.dtype==float assert wave.shape==(44100*32*4/16*60/120, 2) assert -1<=wave.min() and wave.max()<=1 # synthesize score with system soundfont wave = s1.to_wave(instrument=40) # synthesize violin with default font # refaences ## score ## you can generate specific score with pianoroll # s2 = soundset.score.generate(roll=roll) # the size must be (length, 128) ## (in future) you can generate score from midi file # s2 = soundset.score.load(filename='midi/file/name.midi') ## (in future) you can save score as midi file # s2.save(filename='midifilename.midi') ## synthesize ## (in future) wave is Periodic function which period is 2 pi, and range is [-1,1] # s2.to_wave(wave=np.sin) print('') print('all tests pass.') print('done.')
31.529412
101
0.718284
280
1,608
4.071429
0.410714
0.014035
0.028947
0.042105
0.126316
0.049123
0.049123
0.049123
0
0
0
0.068296
0.13495
1,608
50
102
32.16
0.751258
0.477612
0
0
0
0
0.208128
0
0
0
0
0
0.470588
1
0
false
0.058824
0.058824
0
0.058824
0.176471
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
1
0
0
0
0
0
2
830c4fb6acc6e91ec81caadf39038409b30f4920
1,809
py
Python
oo/pessoa.py
gabriel-igorq/pythonbirds
b782103cbb7c141205b0bad5ec2488b2723d34f5
[ "MIT" ]
null
null
null
oo/pessoa.py
gabriel-igorq/pythonbirds
b782103cbb7c141205b0bad5ec2488b2723d34f5
[ "MIT" ]
null
null
null
oo/pessoa.py
gabriel-igorq/pythonbirds
b782103cbb7c141205b0bad5ec2488b2723d34f5
[ "MIT" ]
null
null
null
class Pessoa: # Atributos de classe/default olhos = 2 def __init__(self, *filhos, nome = None, idade = 26): # Atributos de instancia self.nome = nome self.idade = idade self.filhos = list(filhos) # Método da instância def cumprimentar(self): return f'Olá, meu nome é {self.nome}' # Método da classe(usando decorator) @staticmethod def metodo_estatico(): return 42 # Usado para acessar dados da própria classe @classmethod def nome_e_atributos_de_classe(cls): return f'{cls} - olhos {cls.olhos}' class Homem(Pessoa): def cumprimentar(self): cumprimentar_da_classe = super().cumprimentar() return f'{cumprimentar_da_classe}. Aperto de mão' class Mutante(Pessoa): olhos = 3 if __name__ == '__main__': biel = Mutante(nome='Gabriel') rogerin = Homem(biel, nome='Rogério') print(Pessoa.cumprimentar(rogerin)) print(id(rogerin)) print(rogerin.cumprimentar()) print(rogerin.nome) print(rogerin.idade) for filho in rogerin.filhos: print(filho.nome) rogerin.sobrenome = 'Costa' del rogerin.filhos rogerin.olhos = 1 del rogerin.olhos print(rogerin.__dict__) print(biel.__dict__) print(Pessoa.olhos) print(rogerin.olhos) print(biel.olhos) print(id(Pessoa.olhos), id(rogerin.olhos), id(biel.olhos)) print(Pessoa.metodo_estatico(), rogerin.metodo_estatico()) print(Pessoa.nome_e_atributos_de_classe(), rogerin.nome_e_atributos_de_classe()) pessoa = Pessoa('Anonimo') print(isinstance(pessoa, Pessoa)) print(isinstance(pessoa, Homem)) print(isinstance(biel, Homem)) print(isinstance(biel, Pessoa)) print(biel.olhos) print(rogerin.cumprimentar()) print(biel.cumprimentar())
28.714286
84
0.667219
220
1,809
5.309091
0.3
0.061644
0.058219
0.041096
0.056507
0
0
0
0
0
0
0.004947
0.2178
1,809
63
85
28.714286
0.820495
0.081813
0
0.12
0
0
0.075483
0.015097
0
0
0
0.015873
0
1
0.1
false
0
0
0.06
0.28
0.42
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
0
1
0
2
830c662f316cd3c904e5e3ac03da64f58992c82e
3,195
py
Python
ai/STA/Strategy/passes_with_decisions.py
RoboCupULaval/StrategyAI
ccddde144f2c0a67113d2e5ffe7c75ed9d4a3d19
[ "MIT" ]
13
2018-03-14T10:20:10.000Z
2021-12-10T05:36:47.000Z
ai/STA/Strategy/passes_with_decisions.py
RoboCupULaval/StrategyIA
ccddde144f2c0a67113d2e5ffe7c75ed9d4a3d19
[ "MIT" ]
200
2016-04-29T23:13:01.000Z
2018-03-13T14:36:39.000Z
ai/STA/Strategy/passes_with_decisions.py
RoboCupULaval/StrategyIA
ccddde144f2c0a67113d2e5ffe7c75ed9d4a3d19
[ "MIT" ]
45
2015-07-04T18:57:39.000Z
2018-01-11T16:11:13.000Z
# Under MIT License, see LICENSE.txt from functools import partial from Util.role import Role from ai.Algorithm.evaluation_module import best_passing_option from ai.STA.Strategy.strategy import Strategy from ai.STA.Tactic.go_kick import GoKick from ai.STA.Tactic.goalkeeper import GoalKeeper from ai.STA.Tactic.pass_to_player import PassToPlayer from ai.STA.Tactic.tactic_constants import Flags # TODO: This strategy is quite limited, only a two player move (FIRST_ATTACK and GOALER) class PassesWithDecisions(Strategy): def __init__(self, p_game_state): super().__init__(p_game_state) their_goal = self.game_state.field.their_goal_pose node_pass_to_second_attack = self.create_node(Role.FIRST_ATTACK, PassToPlayer(self.game_state, self.assigned_roles[Role.FIRST_ATTACK], args=[self.assigned_roles[Role.SECOND_ATTACK].id])) node_pass_to_middle = self.create_node(Role.FIRST_ATTACK, PassToPlayer(self.game_state, self.assigned_roles[Role.FIRST_ATTACK], args=[self.assigned_roles[Role.MIDDLE].id])) node_go_kick = self.create_node(Role.FIRST_ATTACK, GoKick(self.game_state, self.assigned_roles[Role.FIRST_ATTACK], their_goal)) second_attack_is_best_receiver = partial(self.is_best_receiver, Role.SECOND_ATTACK) middle_is_best_receiver = partial(self.is_best_receiver, Role.MIDDLE) current_tactic_succeeded = partial(self.current_tactic_succeed, Role.FIRST_ATTACK) node_pass_to_second_attack.connect_to(node_pass_to_middle, when=second_attack_is_best_receiver) node_pass_to_second_attack.connect_to(node_go_kick, when=middle_is_best_receiver) node_pass_to_second_attack.connect_to(node_pass_to_second_attack, when=current_tactic_succeeded) node_pass_to_middle.connect_to(node_pass_to_second_attack, when=current_tactic_succeeded) node_go_kick.connect_to(node_pass_to_second_attack, when=current_tactic_succeeded) self.create_node(Role.GOALKEEPER, GoalKeeper(self.game_state, self.assigned_roles[Role.GOALKEEPER])) @classmethod def required_roles(cls): return [Role.GOALKEEPER, Role.FIRST_ATTACK, Role.SECOND_ATTACK, Role.MIDDLE] def current_tactic_succeed(self, role): if self.roles_graph[role].current_tactic_name == 'PassToPlayer': return self.roles_graph[role].current_tactic.status_flag == Flags.SUCCESS else: return False def is_best_receiver(self, role): if self.current_tactic_succeed(role): if best_passing_option(self.assigned_roles[Role.FIRST_ATTACK].id) == self.assigned_roles[role].id: return True return False
47.686567
118
0.646009
381
3,195
5.03937
0.220472
0.075
0.052083
0.0875
0.477604
0.424479
0.360417
0.342708
0.342708
0.274479
0
0
0.286385
3,195
66
119
48.409091
0.842105
0.037872
0
0.145833
0
0
0.003908
0
0
0
0
0.015152
0
1
0.083333
false
0.291667
0.166667
0.020833
0.375
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
831b11a8e6e1918037179c01b51fe771e6728e2a
4,271
py
Python
netcat/the_long_lost.py
benhunter/py-stuff
a04f94851370e08a65792a53a6207f3146eb130b
[ "MIT" ]
3
2017-05-22T03:14:21.000Z
2019-05-24T11:44:15.000Z
netcat/the_long_lost.py
benhunter/py-stuff
a04f94851370e08a65792a53a6207f3146eb130b
[ "MIT" ]
null
null
null
netcat/the_long_lost.py
benhunter/py-stuff
a04f94851370e08a65792a53a6207f3146eb130b
[ "MIT" ]
null
null
null
# hackers.gg - Web - The Long Lost import requests from bs4 import BeautifulSoup base_url = "http://hackers.gg:8006" url2 = "http://hackers.gg:8006/stage2.php" ''' var p455 = '%77%68%30%30%2c%30%62%66%75%35%63%34%37%31%30%6e%21'; function check() { var 1npu7 = prompt('Gimme that pass: '); if (1npu7 == unescape(p455)) { alert('thats the one!'); } else { alert('nope'); } } ''' password1 = '%77%68%30%30%2c%30%62%66%75%35%63%34%37%31%30%6e%21' # print(d.decode('string-escape')) # not working? code is from python 2 password1 = "wh00,0bfu5c4710n!" r = requests.post(url2, data={'auth': password1}) print(r.content) # stage2.php # We found this hash: f25a2fc72690b780b2a14e140ef6a9e0--> url3 = "http://hackers.gg:8006/stage2login.php" r = requests.post(url3) print(r.content) print('\nstage3.php') url4 = "http://hackers.gg:8006/dir1/dir2/stage3.php" r = requests.post(url4, data={'uname2': 'itzel', 'pass2': 'iloveyou'}) print(r) print(r.content) print(r.headers) soup = BeautifulSoup(r.content) soup.prettify() print(soup) ''' result: <!DOCTYPE html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <title>Static Code Analysis</title> </head> <body> <p>Hey, I have this PHP that should read the contents of a file. I think it's secure, can you check?</p> <p>Input how you'd read the contents of hackers.gg:8006/index.php</p> <code>$filetext = file_get_contents($_POST['filename'].'.php');</code><br/><br/> <form action="/dir1/dir2/stage3.php" method="post"> <input name="uname2" type="hidden" value="Itzel"/> <input name="pass2" type="hidden" value="iloveyou"/> <input name="exploit" type="text"/> <input name="submitexploit" type="submit" value="Submit"/> </form> </body> </html> ''' print('\nstage3.php - exploit') url4 = "http://hackers.gg:8006/dir1/dir2/stage3.php" r = requests.post(url4, data={'uname2': 'Itzel', 'pass2': 'iloveyou', 'filename': 'index'}) print(r) print(r.content) print(r.headers) soup = BeautifulSoup(r.content) soup.prettify() print(soup) print('\nstage3.php - exploit try 2') url4 = "http://hackers.gg:8006/dir1/dir2/stage3.php" r = requests.post(url4, data={'uname2': 'Itzel', 'pass2': 'iloveyou', 'exploit': '/../../index', 'submitexploit': 'Submit'}) print(r) print(r.headers) print(r.content) soup = BeautifulSoup(r.content) soup.prettify() print(soup) print('\nstage3.php - exploit try 3') url4 = "http://hackers.gg:8006/dir1/dir2/stage3.php" # r = requests.post(url4, data={'uname2': 'Itzel', 'pass2': 'iloveyou', 'exploit':"index.php'); phpinfo(); print('", 'filename':"index.php'); phpinfo(); print('"}) r = requests.post(url4, data={'uname2': 'Itzel', 'pass2': 'iloveyou', 'exploit': "index.php'); phpinfo(); print('"}) print(r) print(r.content) print(r.headers) soup = BeautifulSoup(r.content) soup.prettify() print(soup) print('\nStage 4: /tgbyhnujmedc.php') url_stage4 = base_url + '/tgbyhnujmedc.php' print(url_stage4) r = requests.get(url_stage4) print(r) print(r.headers) print(r.content) soup = BeautifulSoup(r.content, 'html.parser') soup.prettify() print(soup) # /images directory # http://hackers.gg:8006/images/loungepass.txt ''' louge pass is "OMGTHEWORLDISENDING" You need to set a cookie "pass" to "OMGTHEWORLDISENDING" to access ''' # http://hackers.gg:8006/robots.txt # /MitigatorsLounge.php url_stage5 = base_url + '/MitigatorsLounge.php' print(url_stage5) r = requests.get(url_stage5, cookies={'pass': 'OMGTHEWORLDISENDING'}) print(r) print(r.headers) print(r.content) soup = BeautifulSoup(r.content, 'html.parser') soup.prettify() print(soup) # final.php url_stage6 = base_url + '/final.php' print(url_stage6) r = requests.get(url_stage6, cookies={'pass': 'OMGTHEWORLDISENDING'}) print(r) print(r.headers) print(r.content) soup = BeautifulSoup(r.content, 'html.parser') soup.prettify() print(soup) url_stage7 = base_url + '/finalauth.php' print(url_stage7) r = requests.post(url_stage7, cookies={'pass': 'OMGTHEWORLDISENDING'}, data={'submit': 'Submit', 'month': 'December'}) print(r) print(r.headers) print(r.content) soup = BeautifulSoup(r.content, 'html.parser') soup.prettify() print(soup)
28.473333
163
0.673144
602
4,271
4.742525
0.269103
0.056743
0.045534
0.05359
0.451839
0.451839
0.451839
0.451839
0.451839
0.451839
0
0.05665
0.132053
4,271
149
164
28.66443
0.713515
0.107937
0
0.635294
0
0.011765
0.32
0.027429
0
0
0
0
0
1
0
false
0.117647
0.023529
0
0.023529
0.517647
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
1
0
2
831cdd64935b4bc8528028bfcc1033157010f201
2,724
py
Python
ai2business/kpi_collector/test/test_finance_collector.py
Anselmoo/ai2business
98af02afe5317e6a6271528e062f00118396645f
[ "Apache-2.0" ]
null
null
null
ai2business/kpi_collector/test/test_finance_collector.py
Anselmoo/ai2business
98af02afe5317e6a6271528e062f00118396645f
[ "Apache-2.0" ]
24
2020-12-03T07:47:42.000Z
2020-12-19T16:38:01.000Z
ai2business/kpi_collector/test/test_finance_collector.py
Anselmoo/ai2business
98af02afe5317e6a6271528e062f00118396645f
[ "Apache-2.0" ]
null
null
null
"""Test-Enviroment for finance_collector.py""" import pandas as pd from ai2business.kpi_collector import finance_collector as fnc ticker = fnc.FinanceCollector() builder = fnc.DesignerFinanceCollector(["SPY", "AAPL", "MSFT"]) ticker.builder = builder def test_find_chart_history(): ticker.find_chart_histogram() assert type(builder.return_dataframe) == type(pd.DataFrame()) def test_find_isin_code(): ticker.find_isin_code() assert type(builder.return_dict) == type(dict()) def test_find_major_holders_dict(): ticker.find_major_holders() assert type(builder.return_dict) == type(dict()) def test_find_institutional_holders(): ticker.find_institutional_holders() assert type(builder.return_dict) == type(dict()) def test_find_mutualfund_holders(): ticker.find_mutualfund_holders() assert type(builder.return_dict) == type(dict()) def test_find_dividends(): ticker.find_dividends() assert type(builder.return_dict) == type(dict()) def test_find_splits(): ticker.find_splits() assert type(builder.return_dict) == type(dict()) def test_find_actions(): ticker.find_actions() assert type(builder.return_dict) == type(dict()) def test_find_info(): ticker.find_info() assert type(builder.return_dict) == type(dict()) def test_find_calendar(): ticker.find_calendar() assert type(builder.return_dict) == type(dict()) def test_find_recommendation(): ticker.find_recommendations() assert type(builder.return_dict) == type(dict()) def test_find_earnings(): ticker.find_earnings() assert type(builder.return_dict) == type(dict()) def test_find_quarterly_earnings(): ticker.find_quarterly_earnings() assert type(builder.return_dict) == type(dict()) def test_find_financials(): ticker.find_financials() assert type(builder.return_dict) == type(dict()) def test_find_quarterly_financials(): ticker.find_quarterly_financials() assert type(builder.return_dict) == type(dict()) def test_find_balancesheet(): ticker.find_balancesheet() assert type(builder.return_dict) == type(dict()) def test_find_quarterly_balancesheet(): ticker.find_quarterly_balancesheet() assert type(builder.return_dict) == type(dict()) def test_find_cashflow(): ticker.find_cashflow() assert type(builder.return_dict) == type(dict()) def test_find_quarterly_cashflow(): ticker.find_quarterly_cashflow() assert type(builder.return_dict) == type(dict()) def test_find_sustainability(): ticker.find_sustainability() assert type(builder.return_dict) == type(dict()) def test_find_options(): ticker.find_options() assert type(builder.return_dict) == type(dict())
23.894737
65
0.732746
345
2,724
5.478261
0.147826
0.077778
0.122222
0.255556
0.551323
0.551323
0.551323
0.532804
0.532804
0.532804
0
0.000427
0.140602
2,724
113
66
24.106195
0.80692
0.014684
0
0.294118
0
0
0.004108
0
0
0
0
0
0.308824
1
0.308824
false
0
0.029412
0
0.338235
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
831fed5f645d227dd8a7adcb51449e33b9c83b11
287
py
Python
CSGO Data Analysis/CSGODataAnalysis/test.py
PatrickKoss/BettingPrediction
8082bb89d00d28ade774a445a1645dc07ac86127
[ "MIT" ]
null
null
null
CSGO Data Analysis/CSGODataAnalysis/test.py
PatrickKoss/BettingPrediction
8082bb89d00d28ade774a445a1645dc07ac86127
[ "MIT" ]
null
null
null
CSGO Data Analysis/CSGODataAnalysis/test.py
PatrickKoss/BettingPrediction
8082bb89d00d28ade774a445a1645dc07ac86127
[ "MIT" ]
null
null
null
from datetime import datetime import requests import pandas as pd import os date = datetime.strptime("1-5-2020", "%d-%m-%Y") print(datetime.fromtimestamp(1451442397)) print(datetime.timestamp(date)) # r = requests.get("https://api.opendota.com/api/proMatches") # print(len(r.json()))
22.076923
61
0.738676
42
287
5.047619
0.690476
0.132075
0
0
0
0
0
0
0
0
0
0.061538
0.094077
287
12
62
23.916667
0.753846
0.278746
0
0
0
0
0.078431
0
0
0
0
0
0
1
0
false
0
0.571429
0
0.571429
0.285714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
832bb0378622f0c3603216be8460c6c24c68b8fa
854
py
Python
mne_features/mock_numba.py
agramfort/mne-features
f86f5b8918cf76499a860bb45dbb309ca7f0655a
[ "BSD-3-Clause" ]
null
null
null
mne_features/mock_numba.py
agramfort/mne-features
f86f5b8918cf76499a860bb45dbb309ca7f0655a
[ "BSD-3-Clause" ]
2
2020-07-21T15:11:23.000Z
2020-07-23T07:45:07.000Z
mne_features/mock_numba.py
agramfort/mne-features
f86f5b8918cf76499a860bb45dbb309ca7f0655a
[ "BSD-3-Clause" ]
null
null
null
# Function to mock numba and let the code work on any system from warnings import warn try: import numba as nb except ImportError as _: warn('Numba not found. Your code will be slower.') class Bunch(dict): """Dictionnary-like object that exposes its keys as attributes.""" def __init__(self, **kwargs): # noqa: D102 dict.__init__(self, kwargs) self.__dict__ = self class MockType(object): def __getitem__(self, slice): return self def __call__(self, *args, **kwargs): return nb = Bunch() nb.int32 = MockType() nb.int64 = MockType() nb.float32 = MockType() nb.float64 = MockType() nb.optional = MockType() def jit(*args, **kwargs): def identity(ob): return ob return identity nb.jit = jit
23.081081
74
0.593677
104
854
4.673077
0.557692
0.082305
0.057613
0
0
0
0
0
0
0
0
0.018613
0.307963
854
36
75
23.722222
0.803723
0.153396
0
0
0
0
0.058659
0
0
0
0
0
0
1
0.2
false
0
0.12
0.12
0.56
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
832ef366de9345b97ef036feb02cc106b2fb36ed
250
py
Python
examples/testh2o.py
delcacho/DataSciencePlatform
c19ac4c1aba54bafc0fed05cc534bb447ab3b631
[ "BSD-3-Clause" ]
null
null
null
examples/testh2o.py
delcacho/DataSciencePlatform
c19ac4c1aba54bafc0fed05cc534bb447ab3b631
[ "BSD-3-Clause" ]
null
null
null
examples/testh2o.py
delcacho/DataSciencePlatform
c19ac4c1aba54bafc0fed05cc534bb447ab3b631
[ "BSD-3-Clause" ]
null
null
null
from pyspark.sql import SparkSession spark = SparkSession.builder.master("local").getOrCreate() from pysparkling import * import h2o h2oConf = H2OConf(spark).set('spark.ui.enabled', 'false') hc = H2OContext.getOrCreate(spark, conf=h2oConf) print(hc)
31.25
58
0.78
32
250
6.09375
0.65625
0
0
0
0
0
0
0
0
0
0
0.02193
0.088
250
7
59
35.714286
0.833333
0
0
0
0
0
0.104
0
0
0
0
0
0
1
0
false
0
0.428571
0
0.428571
0.142857
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
8334ea11efee4e4de12a17540882d69aeb5be16d
252
py
Python
constants.py
Ozeuth/geometric-textures
1284f26253d8a432d5aca0e3ea1a2321a6d9ab06
[ "MIT" ]
39
2020-08-17T21:50:08.000Z
2022-03-31T07:03:10.000Z
constants.py
Ozeuth/geometric-textures
1284f26253d8a432d5aca0e3ea1a2321a6d9ab06
[ "MIT" ]
1
2021-04-15T21:45:53.000Z
2021-04-15T21:45:53.000Z
constants.py
Ozeuth/geometric-textures
1284f26253d8a432d5aca0e3ea1a2321a6d9ab06
[ "MIT" ]
5
2020-12-12T00:37:05.000Z
2021-11-10T12:39:18.000Z
import os EPSILON = 1e-6 DEBUG = False PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__)) DATA_ROOT = f'{PROJECT_ROOT}/dataset' RAW_MESHES = f'{DATA_ROOT}/raw' CACHE_ROOT = f'{DATA_ROOT}/cache' CHECKPOINTS_ROOT = f'{PROJECT_ROOT}/checkpoints'
25.2
58
0.761905
40
252
4.475
0.5
0.184358
0.134078
0.178771
0
0
0
0
0
0
0
0.008772
0.095238
252
9
59
28
0.776316
0
0
0
0
0
0.31746
0.190476
0
0
0
0
0
1
0
false
0
0.125
0
0.125
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
83568904e4df6aceea09591897cf4af5254832bf
1,644
py
Python
simlady/test_cigar.py
shinichinamba/simlady
5a0392e8aed9e3183258468afb92fbef6f0c4fe3
[ "MIT" ]
2
2020-09-24T14:27:23.000Z
2020-09-28T01:47:44.000Z
simlady/test_cigar.py
shinichinamba/simlady
5a0392e8aed9e3183258468afb92fbef6f0c4fe3
[ "MIT" ]
null
null
null
simlady/test_cigar.py
shinichinamba/simlady
5a0392e8aed9e3183258468afb92fbef6f0c4fe3
[ "MIT" ]
null
null
null
from simlady.simlady import calculate_cigar_operations_lady MATCH, DELETION, INSERTION, SUBST = (7, 2, 1, 8) # PySam CIGAR Operation Codes def test_all_matches(): result = calculate_cigar_operations_lady(100, [], [], []) assert result == [(MATCH, 100)] def test_all_inserts(): result = calculate_cigar_operations_lady(10, list(range(10)), [], []) assert result == [(INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1),(INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1)] def test_all_deletion(): # 100 deletions in a row result in 100 new bases that match if the other lists are empty result = calculate_cigar_operations_lady(100, [0]*100, [], []) assert result == [(INSERTION, 100), (MATCH, 100)] def test_all_substitution(): result = calculate_cigar_operations_lady(100, [], [], list(range(100))) assert result == [(SUBST, 100)] def test_every_second_deletion(): result = calculate_cigar_operations_lady(10, [], list(range(9)), []) assert result == [(DELETION, 9), (MATCH, 1)] def test_1(): result = calculate_cigar_operations_lady(10, [4,5,6], [0,1,2,3], [6]) assert result == [(DELETION, 4), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (MATCH, 1), (INSERTION, 1), (SUBST, 1), (MATCH, 3)] def test_2(): result = calculate_cigar_operations_lady(10, [2,2,5,5], [1,2], []) assert result == [(MATCH, 1), (DELETION, 1), (INSERTION, 2), (DELETION, 1), (MATCH, 2), (INSERTION, 2), (MATCH, 5)]
39.142857
300
0.638078
228
1,644
4.438596
0.223684
0.083004
0.177866
0.189723
0.504941
0.469368
0.288538
0.288538
0.199605
0.199605
0
0.074616
0.168491
1,644
41
301
40.097561
0.665691
0.069343
0
0
0
0
0
0
0
0
0
0
0.304348
1
0.304348
false
0
0.043478
0
0.347826
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
8357219d1e965c8ec1f502318b60387f2611c712
193
py
Python
learning_files/arithmetic.py
MineJockey/python-basics
bd0370413362c69e55fc81366d8c995875f9308a
[ "MIT" ]
null
null
null
learning_files/arithmetic.py
MineJockey/python-basics
bd0370413362c69e55fc81366d8c995875f9308a
[ "MIT" ]
null
null
null
learning_files/arithmetic.py
MineJockey/python-basics
bd0370413362c69e55fc81366d8c995875f9308a
[ "MIT" ]
null
null
null
# Arithmetic # +, -, *, /, %, all work with numbers and variables holding numbers # +=, -=, *=, /=, i.e x += 1 is the same as x = x + 1 x = 1 + 1 # assign 1 + 1 to x y = 0 y += x # add x to y
27.571429
68
0.502591
36
193
2.694444
0.583333
0.061856
0
0
0
0
0
0
0
0
0
0.051852
0.300518
193
6
69
32.166667
0.666667
0.818653
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
55c72150479643dd44ea44eed6af2a7920cb9cd6
877
py
Python
medium/python/c0089_166_fraction-to-recurring-decimal/00_leetcode_0089.py
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
medium/python/c0089_166_fraction-to-recurring-decimal/00_leetcode_0089.py
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
medium/python/c0089_166_fraction-to-recurring-decimal/00_leetcode_0089.py
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
3
2018-02-09T02:46:48.000Z
2021-02-20T08:32:03.000Z
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #166. Fraction to Recurring Decimal #Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. #If the fractional part is repeating, enclose the repeating part in parentheses. #For example, #Given numerator = 1, denominator = 2, return "0.5". #Given numerator = 2, denominator = 1, return "2". #Given numerator = 2, denominator = 3, return "0.(6)". # Credits: #Special thanks to @Shangrila for adding this problem and creating all test cases. #class Solution(object): # def fractionToDecimal(self, numerator, denominator): # """ # :type numerator: int # :type denominator: int # :rtype: str # """ # Time Is Money
38.130435
115
0.721779
113
877
5.60177
0.610619
0.066351
0.041074
0.082149
0
0
0
0
0
0
0
0.019691
0.189282
877
23
116
38.130435
0.870605
0.950969
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
55cb0a2a60aa786fc9f39549ee2fd66b3ca7e956
2,359
py
Python
kids_math/gifs.py
crvernon/kids_math
7975d87de9a4fe951ae345bb6ef9167bca236d4e
[ "MIT" ]
null
null
null
kids_math/gifs.py
crvernon/kids_math
7975d87de9a4fe951ae345bb6ef9167bca236d4e
[ "MIT" ]
null
null
null
kids_math/gifs.py
crvernon/kids_math
7975d87de9a4fe951ae345bb6ef9167bca236d4e
[ "MIT" ]
null
null
null
import pkg_resources from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" from IPython import display class PeterRabbitGif: # Source: https://tenor.com/view/smile-wink-peter-rabbit-peter-rabbit-gifs-gif-11787571 WINKING = pkg_resources.resource_filename('kids_math', 'img/peter_rabbit_winking.gif') # Source: https://tenor.com/view/no-nope-dont-beg-peter-rabbit-gif-11782011 NOPE = pkg_resources.resource_filename('kids_math', 'img/peter_rabbit_no.gif') @staticmethod def display_gif(gif): """Display GIF in a Jupyter, CoLab, or IPython Notebook""" with open(gif, 'rb') as f: return display.Image(data=f.read(), format='png') def wink(self): """Display Peter Rabbit winking GIF""" return self.display_gif(PeterRabbitGif.WINKING) def nope(self): """Display Peter Rabbit saying no GIF""" return self.display_gif(PeterRabbitGif.NOPE) class FrozenGif: # Source: https://tenor.com/view/disney-princess-its-me-frozen-elsa-gif-15403239 ELSA_WALKING = pkg_resources.resource_filename('kids_math', 'img/frozen_walking.gif') # Source: https://media.tenor.com/images/69d62f9ebd55c45d08ab6af501cbfa47/tenor.gif OLAF_HEART = pkg_resources.resource_filename('kids_math', 'img/frozen_olaf_heart.gif') @staticmethod def display_gif(gif): """Display GIF in a Jupyter, CoLab, or IPython Notebook""" with open(gif, 'rb') as f: return display.Image(data=f.read(), format='png') def walking(self): """Display Peter Rabbit winking GIF""" return self.display_gif(FrozenGif.ELSA_WALKING) def olaf_heart(self): """Display Peter Rabbit saying no GIF""" return self.display_gif(FrozenGif.OLAF_HEART) class RapunzelGif: # Source: https://media.giphy.com/media/14rbfgZ6aTgwAo/giphy.gif SWINGING = pkg_resources.resource_filename('kids_math', 'img/rapunzel_swinging.gif') @staticmethod def display_gif(gif): """Display GIF in a Jupyter, CoLab, or IPython Notebook""" with open(gif, 'rb') as f: return display.Image(data=f.read(), format='png') def swinging(self): """Display Peter Rabbit winking GIF""" return self.display_gif(RapunzelGif.SWINGING)
29.123457
92
0.690123
301
2,359
5.27907
0.255814
0.069226
0.062933
0.088106
0.623033
0.57961
0.550661
0.526117
0.469478
0.406545
0
0.023013
0.189487
2,359
80
93
29.4875
0.808054
0.303942
0
0.352941
0
0
0.116468
0.077019
0
0
0
0
0
1
0.235294
false
0
0.088235
0
0.794118
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
55cf7134b90b7833deb1ff568833b4f7f47cf724
153
py
Python
src/parser/test.py
satojk/fishnet
c963d3108d7aba3cc18c7a8b6214bcde3297ac65
[ "MIT" ]
null
null
null
src/parser/test.py
satojk/fishnet
c963d3108d7aba3cc18c7a8b6214bcde3297ac65
[ "MIT" ]
null
null
null
src/parser/test.py
satojk/fishnet
c963d3108d7aba3cc18c7a8b6214bcde3297ac65
[ "MIT" ]
null
null
null
import reader with open("./scraper/samples/example_game.pgn") as my_file: data = my_file.read() game1 = reader.Game(data) print(game1.ai_player())
19.125
59
0.72549
24
153
4.458333
0.75
0.11215
0
0
0
0
0
0
0
0
0
0.014925
0.124183
153
7
60
21.857143
0.783582
0
0
0
0
0
0.222222
0.222222
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0.2
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
55d684f73270e0f6c5a4e11a5eaa6ba745a20baf
1,068
py
Python
Mobiles/migrations/0005_auto_20210524_2056.py
roqcodes/RoundUpCart
444aad70ff5d8b0646b6ee58f1e7df25358a7c3c
[ "MIT-0", "MIT" ]
1
2021-06-16T14:15:35.000Z
2021-06-16T14:15:35.000Z
Mobiles/migrations/0005_auto_20210524_2056.py
roqcodes/RoundUpCart
444aad70ff5d8b0646b6ee58f1e7df25358a7c3c
[ "MIT-0", "MIT" ]
null
null
null
Mobiles/migrations/0005_auto_20210524_2056.py
roqcodes/RoundUpCart
444aad70ff5d8b0646b6ee58f1e7df25358a7c3c
[ "MIT-0", "MIT" ]
null
null
null
# Generated by Django 3.2.3 on 2021-05-24 15:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Mobiles', '0004_payment_email'), ] operations = [ migrations.AddField( model_name='payment', name='address', field=models.CharField(default='user_adress', max_length=255), ), migrations.AddField( model_name='payment', name='city', field=models.CharField(default='user_city', max_length=255), ), migrations.AddField( model_name='payment', name='state', field=models.CharField(default='user_state', max_length=255), ), migrations.AddField( model_name='payment', name='zip', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='payment', name='name', field=models.CharField(default='user', max_length=255), ), ]
27.384615
74
0.555243
103
1,068
5.621359
0.407767
0.07772
0.138169
0.172712
0.53886
0.324698
0.259067
0.259067
0.259067
0
0
0.044138
0.321161
1,068
38
75
28.105263
0.754483
0.042135
0
0.4375
1
0
0.114594
0
0
0
0
0
0
1
0
false
0
0.03125
0
0.125
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
55df3f9a4453735497316a76187a62544eeca635
368
py
Python
server_config.py
rvillegasm/evergreen-production-backend
312ebb1578e2935251d92edd4cecc714cf8a3d3e
[ "MIT" ]
null
null
null
server_config.py
rvillegasm/evergreen-production-backend
312ebb1578e2935251d92edd4cecc714cf8a3d3e
[ "MIT" ]
null
null
null
server_config.py
rvillegasm/evergreen-production-backend
312ebb1578e2935251d92edd4cecc714cf8a3d3e
[ "MIT" ]
null
null
null
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS app = Flask(__name__) CORS(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://admin:pinguinos@evergreen-database-1.cjk96vzdjzzq.us-east-1.rds.amazonaws.com:3306/evergreen_database_1' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app)
36.8
168
0.82337
51
368
5.705882
0.529412
0.092784
0.130584
0
0
0
0
0
0
0
0
0.026316
0.070652
368
10
169
36.8
0.824561
0
0
0
0
0.125
0.485095
0.485095
0
0
0
0
0
1
0
false
0
0.375
0
0.375
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
1
0
0
0
0
2
55e1d53e5ecfd493888331b53f041f7d206c7905
419
py
Python
plugins/url_plugins/paloaltonetworks.py
mz-techops/banhammer
02476db3d2bb617dbe50827687065fbea7553caf
[ "BSD-3-Clause" ]
3
2018-03-09T23:29:25.000Z
2020-11-25T15:34:13.000Z
plugins/url_plugins/paloaltonetworks.py
whyallyn/banhammer
59fc81b15d9950a7a40279a9d1df8101c58df569
[ "BSD-3-Clause" ]
3
2018-05-08T01:10:43.000Z
2021-03-19T21:56:36.000Z
plugins/url_plugins/paloaltonetworks.py
whyallyn/banhammer
59fc81b15d9950a7a40279a9d1df8101c58df569
[ "BSD-3-Clause" ]
2
2018-05-10T15:07:24.000Z
2018-06-20T16:24:00.000Z
"""Define all Palo Alto Networks actions.""" from plugins.interfaces import Url class PaloAltoNetworks(Url): """Palo Alto Networks URL object.""" def __init__(self, url, reason): self.url = url self.reason = reason def add_to_ebl(self): """Add to BanHammer's External Block List for PAN firewalls.""" # no need to do anything as EBL's are hosted on BanHammer pass
27.933333
71
0.651551
58
419
4.603448
0.655172
0.059925
0.11985
0
0
0
0
0
0
0
0
0
0.252983
419
14
72
29.928571
0.853035
0.439141
0
0
0
0
0
0
0
0
0
0
0
1
0.285714
false
0.142857
0.142857
0
0.571429
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
55e57b14f9dabcdaedc49fb41948ba90db2f564d
8,345
py
Python
torchbenchmark/score/generate_score_config.py
xuzhao9/benchmark
ebf5ead0cf4a514e5898d370f4d208f0d46648b9
[ "BSD-3-Clause" ]
384
2017-05-26T17:45:48.000Z
2022-03-24T13:41:04.000Z
torchbenchmark/score/generate_score_config.py
xuzhao9/benchmark
ebf5ead0cf4a514e5898d370f4d208f0d46648b9
[ "BSD-3-Clause" ]
473
2017-06-11T02:36:40.000Z
2022-03-31T22:57:34.000Z
torchbenchmark/score/generate_score_config.py
xuzhao9/benchmark
ebf5ead0cf4a514e5898d370f4d208f0d46648b9
[ "BSD-3-Clause" ]
108
2017-05-27T03:01:52.000Z
2022-03-21T11:36:00.000Z
""" Generate a fully specified benchmark configuration file, given a lightweight specification and a complete source of benchmark data. Specification File ------------------ Score hierarchy input intended to be as easy to construct as possible, relying on automatic inference of unspecified weights, benchmark configs, and normalization factors given a particular instance of benchmark data. Structure: Root _ - category | required: - domain | 3 layers of organizational structure - task _| - benchmark name - keyword match for root name in benchmark, omit children unless used _ - train/eval | optional: - device | provide specific weights or - compiler/runtime _| exclude particular configs by omission Rules for describing the weight hierarchy - everything is a dict, since at any level you could specify a weight - if a weight is not specified, it is computed automatically with respect its direct siblings. - if specific benchmark configurations are omitted under a benchmark name, all configurations present in the normalization data json are weighted equally Normalization Data ------------------ Used to 'fill in the gaps' in the human written specification. - particular configurations (train/eval, device, compiler/runtime) present in this data are used to compute benchmark weights - measurements from this data are used as normalization factors in score computation such that new data is scored relative to this data. #### TODO #### - handle multiple normalization files, one for models, one for synthetic, etc - make explicit configuration choice for throughput vs runtime metrics - assert same machine used for all normalization files and freeze that in """ import argparse import json import yaml from collections import defaultdict def generate_bench_cfg(spec, norm, target): cfg = { 'target': target, 'benchmarks': {}, } benchmark_names = [b['name'] for b in norm['benchmarks']] benchmark_norms = {b['name']: b['stats']['mean'] for b in norm['benchmarks']} assert len(spec['hierarchy']) > 0, "Must specify at least one category" category_weight = 1.0 / len(spec['hierarchy']) for category in spec['hierarchy']: category_spec = spec['hierarchy'][category] assert isinstance(category_spec, dict), f"Category {category} in spec must be non-empty" assert 'weight' not in category_spec, "TODO implement manual category weights" domain_weight = 1.0 / len(category_spec) for domain in category_spec: tasks = category_spec[domain] assert isinstance(tasks, dict), f"Domain {category}:{domain} in spec must be non-empty" assert 'weight' not in tasks, "TODO implement manual domain weights" task_weight = 1.0 / len(tasks) for task in tasks: benchmarks = tasks[task] assert isinstance(benchmarks, dict), f"Task {category}:{domain}:{task} in spec must be non-empty" assert 'weight' not in benchmarks, "TODO implement manual task weights" benchmark_weight = 1.0 / len(benchmarks) for benchmark in benchmarks: assert benchmarks[benchmark] is None, "TODO handle benchmark as dict of config specs" # assert 'weight' not in benchmarks[benchmark], "TODO implement manual benchmark weights" found_benchmarks = [name for name in benchmark_names if benchmark in name] assert len(found_benchmarks) > 0, f"No normalization data found for {benchmark}" config_weight = 1.0 / len(found_benchmarks) for b in found_benchmarks: weight = domain_weight * task_weight * benchmark_weight * config_weight cfg['benchmarks'][b] = { 'weight': weight, 'norm': benchmark_norms[b], } return cfg # Support generate a config from benchmark data that runs partial of the spec def generate_bench_cfg_partial(spec, norm, target): benchmark_names = [b['name'] for b in norm['benchmarks']] rec_defaultdict = lambda: defaultdict(rec_defaultdict) partial_spec = rec_defaultdict() def gen_partial_spec(category, domain, task, benchmark): found_benchmarks = [name for name in benchmark_names if benchmark in name] if len(found_benchmarks) > 0: partial_spec['hierarchy'][category][domain][task][benchmark] = None def visit_each_benchmark(spec, func): for category in spec['hierarchy']: category_spec = spec['hierarchy'][category] for domain in category_spec: tasks = category_spec[domain] for task in tasks: benchmarks = tasks[task] for benchmark in benchmarks: func(category, domain, task, benchmark) visit_each_benchmark(spec, gen_partial_spec) return generate_bench_cfg(partial_spec, norm, target) def check(spec): assert len(spec['hierarchy']) > 0, "Must specify at least one category" for category in spec['hierarchy']: category_spec = spec['hierarchy'][category] assert isinstance(category_spec, dict), f"Category {category} in spec must be non-empty" assert 'weight' not in category_spec, "TODO implement manual category weights" for domain in category_spec: tasks = category_spec[domain] assert isinstance(tasks, dict), f"Domain {category}:{domain} in spec must be non-empty" assert 'weight' not in tasks, "TODO implement manual domain weights" for task in tasks: benchmarks = tasks[task] assert isinstance(benchmarks, dict), f"Task {category}:{domain}:{task} in spec must be non-empty" assert 'weight' not in benchmarks, "TODO implement manual task weights" for benchmark in benchmarks: assert benchmarks[benchmark] is None, "TODO handle benchmark as dict of config specs" # assert 'weight' not in benchmarks[benchmark], "TODO implement manual benchmark weights" if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--specification", required=True, help="yaml file describing weight hierarchy") parser.add_argument("--normalization_data", required=True, help="pytest-benchmark json file used for generating normalization " "values and filling in unspecified benchmark configurations") parser.add_argument("--output_file", required=True, help="generated complete benchmark configuration") parser.add_argument("--target_score", default=1000, help="target score value given these normalizations and specifications") parser.add_argument("--partial", action='store_true', help="generates partial config if the benchmark only runs part of the spec." "normally, the spec is supposed to define the set of benchmarks that's expected to exist," "and then the provided json data is expected to provide the norm values to match the spec." "To simplify debugging, and not for normal score runs, we allow a convenience for producing" "a score configuration that matches whatever json data is provided.") args = parser.parse_args() with open(args.specification) as spec_file: spec = yaml.full_load(spec_file) with open(args.normalization_data) as norm_file: norm = json.load(norm_file) with open(args.output_file, 'w') as out_file: check(spec) if args.partial: bench_cfg = generate_bench_cfg_partial(spec, norm, args.target_score) else: bench_cfg = generate_bench_cfg(spec, norm, args.target_score) yaml.dump(bench_cfg, out_file)
46.620112
116
0.641102
985
8,345
5.328934
0.232487
0.032006
0.022862
0.02591
0.385788
0.364069
0.358163
0.337779
0.337779
0.314155
0
0.003173
0.282445
8,345
178
117
46.882022
0.873413
0.266866
0
0.390476
1
0
0.277014
0.008513
0
0
0
0.011236
0.161905
1
0.047619
false
0
0.038095
0
0.104762
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
1
0
0
0
0
0
0
0
0
0
0
2
55eeeb81464e686bec1e979b7ad8d2f319dd875d
309
py
Python
tests/dataracebench/omprace_scripts/run_omprace.py
rutgers-apl/omp-racer
a8a32e186950997b8eee7864f766819129a5ee06
[ "BSD-2-Clause" ]
2
2020-09-17T15:18:49.000Z
2021-03-06T10:21:23.000Z
tests/dataracebench/omprace_scripts/run_omprace.py
rutgers-apl/omp-racer
a8a32e186950997b8eee7864f766819129a5ee06
[ "BSD-2-Clause" ]
1
2020-09-08T18:36:24.000Z
2020-09-17T15:18:27.000Z
tests/dataracebench/omprace_scripts/run_omprace.py
rutgers-apl/omp-racer
a8a32e186950997b8eee7864f766819129a5ee06
[ "BSD-2-Clause" ]
1
2021-01-19T15:28:15.000Z
2021-01-19T15:28:15.000Z
#!/usr/bin/python import sys, string, os, popen2, shutil, platform, subprocess, pprint, time import util, commands from math import sqrt import csv folder = [] cmd= [ "python run_all.py", if __name__ == "__main__": #files = os.listdir("./") util.run_command(cmd ,verbose=True)
19.3125
74
0.644013
40
309
4.725
0.8
0
0
0
0
0
0
0
0
0
0
0.004149
0.220065
309
16
75
19.3125
0.780083
0
0
0
0
0
0.093284
0
0
0
0
0
0
0
null
null
0
0.444444
null
null
0.111111
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
55fee79d566b6516a2508da606e338244d825d1a
8,992
py
Python
spc/backends/mars_mips.py
adamnew123456/spc
8809d1817f66cf8266f145aa0c2474b32dc1087a
[ "MIT" ]
1
2017-10-15T19:55:48.000Z
2017-10-15T19:55:48.000Z
spc/backends/mars_mips.py
adamnew123456/spc
8809d1817f66cf8266f145aa0c2474b32dc1087a
[ "MIT" ]
null
null
null
spc/backends/mars_mips.py
adamnew123456/spc
8809d1817f66cf8266f145aa0c2474b32dc1087a
[ "MIT" ]
null
null
null
""" MARS compiler backend - responsible for taking program events emitted by the driver and converting them into code. """ import logging from ..backend_utils import FunctionStack from .common32 import Common32Backend from .. import types from ..util import mangle_label LOGGER = logging.getLogger('spc.mars_mips') class MarsFunctionStack(FunctionStack): """ Specializes the default function stack for the MARS code generator. """ # # Stack layout: # # | ... | # | param_2 | # | param_1 |__/-- $fp # | old_fp |__/-- -4($fp) # | old_ra |__/-- -8($fp) # | local_1 | # | local_2 | # | ... | # def _starting_locals_offset(self): return -8 def _starting_param_offset(self): return 0 def _expand_stack(self, size): self.backend._write_instr(' addi $sp, $sp, -{}', size) def _shrink_stack(self, size): self.backend._write_instr(' addi $sp, $sp, {}', size) class MarsTemplates: """ Template code which is plugged into the generic 32-bit backend, which generates MARS code. """ frame_reg = '$fp' return_reg = '$v0' # Right now, the common32 backend only ever asks for two of these, so # this is acceptable tmp_regs = ['$t0', '$t1'] platform_os = 'mars' platform_arch = 'mips' comment_fmt = '# {}' def __init__(self): self.backend = None def make_func_stack(self): return MarsFunctionStack(self.backend) def _write_instr(self, *args, **kwargs): """ Convenience method to avoid writing out 'backend' """ self.backend._write_instr(*args, **kwargs) def emit_label(self, label): self._write_instr('{}:', label) def emit_data_segment(self): self._write_instr('.data') def emit_stack_string(self, base_addr, escaped_bytes): for idx, byte in enumerate(escaped_bytes): self._write_instr(' li $t0, {}', byte) self._write_instr(' sb $t0, {}($fp)', base_addr + idx) def emit_static_string(self, unescaped_bytes): self._write_instr(' .asciiz "{}"', unescaped_bytes) def emit_static_space(self, size): self._write_instr(' .space {}', size) def emit_text_segment(self): self._write_instr('.text') def emit_prog_header(self): self._write_instr(' jal _main_stub') self._write_instr(' li $v0, 10') self._write_instr(' syscall') def emit_prog_footer(self, main_label): self._write_instr('_main_stub:') self._write_instr(' j {}', main_label) def emit_export(self, name, type_of): if isinstance(type_of, types.FunctionDecl): self._write_instr('.globl {}', mangle_label(name)) else: if name in self.backend.ctx_arrays: size = self.backend.ctx_arrays[name] else: size = self.backend._type_size(name) self._write_instr('.extern {}, {}', mangle_label(name), size) def emit_func_header(self, name): self._write_instr(' sw $fp, -4($sp)') self._write_instr(' sw $ra, -8($sp)') self._write_instr(' addi $fp, $sp, 0') self._write_instr(' addi $sp, $sp, -8') def emit_func_footer(self): self._write_instr(' addi $sp, $sp, 8') self._write_instr(' lw $fp, -4($sp)') self._write_instr(' lw $ra, -8($sp)') self._write_instr(' jr $ra') def emit_asm(self, name, code): for instr in code.splitlines(): self._write_instr('{}', instr) def emit_move_word(self, move_reg, src_reg, src_offset, dest_reg, dest_offset): self._write_instr(' lw {}, {}({})', move_reg, src_offset, src_reg) self._write_instr(' sw {}, {}({})', move_reg, dest_offset, dest_reg) def emit_move_byte(self, move_reg, src_reg, src_offset, dest_reg, dest_offset): self._write_instr(' lb {}, {}({})', move_reg, src_offset, src_reg) self._write_instr(' sb {}, {}({})', move_reg, dest_offset, dest_reg) def emit_load_int(self, reg, value): self._write_instr(' li {}, {}', reg, value) def emit_load_byte(self, reg, value): self._write_instr(' lb {}, {}', reg, value) def emit_load_static_addr(self, reg, name): self._write_instr(' la {}, {}', reg, mangle_label(name)) def emit_load_stack_addr(self, reg, offset): self._write_instr(' addi {}, $fp, {}', reg, offset) def emit_load_stack_word(self, reg, offset): self._write_instr(' lw {}, {}($fp)', reg, offset) def emit_save_stack_word(self, reg, offset): self._write_instr(' sw {}, {}($fp)', reg, offset) def emit_load_stack_byte(self, reg, offset): self._write_instr(' lb {}, {}($fp)', reg, offset) def emit_save_stack_byte(self, reg, offset): self._write_instr(' sb {}, {}($fp)', reg, offset) def emit_int_to_byte(self, reg): self._write_instr(' sll {0}, {0}, 24', reg) self._write_instr(' sra {0}, {0}, 24', reg) def emit_byte_to_int(self, reg): pass def emit_array_offset(self, reg, array_offset, index_offset, elem_size): self._write_instr(' lw $t0, {}($fp)', array_offset) self._write_instr(' lw $t1, {}($fp)', index_offset) self._write_instr(' li $t2, {}', elem_size) self._write_instr(' mult $t1, $t2') self._write_instr(' mflo $t1') self._write_instr(' add {}, $t0, $t1', reg) def emit_left_array_offset(self, reg, array_offset, index_offset, elem_size): self._write_instr(' lw $t0, {}($fp)', array_offset) self._write_instr(' lw $t1, {}($fp)', index_offset) self._write_instr(' li $t2, {}', elem_size) self._write_instr(' mult $t1, $t2') self._write_instr(' mflo $t1') self._write_instr(' sub {}, $t0, $t1', reg) def emit_struct_offset(self, reg, total_offset): self._write_instr(' addi {0}, {0}, {1}', reg, total_offset) def emit_add(self, dest_reg, rhs_reg): self._write_instr(' add {0}, {0}, {1}', dest_reg, rhs_reg) def emit_sub(self, dest_reg, rhs_reg): self._write_instr(' sub {0}, {0}, {1}', dest_reg, rhs_reg) def emit_mul(self, dest_reg, rhs_reg): self._write_instr(' mult {}, {}', dest_reg, rhs_reg) self._write_instr(' mflo {}', dest_reg) def emit_div(self, dest_reg, rhs_reg): self._write_instr(' div {}, {}', dest_reg, rhs_reg) self._write_instr(' mflo {}', dest_reg) def emit_mod(self, dest_reg, rhs_reg): self._write_instr(' div {}, {}', dest_reg, rhs_reg) self._write_instr(' mfhi {}', dest_reg) def emit_less(self, dest_reg, rhs_reg): self._write_instr(' slt {0}, {0}, {1}', dest_reg, rhs_reg) def emit_greater(self, dest_reg, rhs_reg): self._write_instr(' sgt {0}, {0}, {1}', dest_reg, rhs_reg) def emit_lesseq(self, dest_reg, rhs_reg): self._write_instr(' sle {0}, {0}, {1}', dest_reg, rhs_reg) def emit_greateq(self, dest_reg, rhs_reg): self._write_instr(' sge {0}, {0}, {1}', dest_reg, rhs_reg) def emit_eq(self, dest_reg, rhs_reg): self._write_instr(' seq {0}, {0}, {1}', dest_reg, rhs_reg) def emit_noteq(self, dest_reg, rhs_reg): self._write_instr(' sne {0}, {0}, {1}', dest_reg, rhs_reg) def emit_bit_and(self, dest_reg, rhs_reg): self._write_instr(' and {0}, {0}, {1}', dest_reg, rhs_reg) def emit_bit_or(self, dest_reg, rhs_reg): self._write_instr(' or {0}, {0}, {1}', dest_reg, rhs_reg) def emit_shiftleft(self, dest_reg, rhs_reg): self._write_instr(' sllv {0}, {0}, {1}', dest_reg, rhs_reg) def emit_shiftright_arith(self, dest_reg, rhs_reg): self._write_instr(' srav {0}, {0}, {1}', dest_reg, rhs_reg) def emit_shiftright_log(self, dest_reg, rhs_reg): self._write_instr(' slav {0}, {0}, {1}', dest_reg, rhs_reg) def emit_bit_not(self, reg): self._write_instr(' not {}, {}', reg, reg) def emit_branch_if_zero(self, reg, label): self._write_instr(' beq {}, $0, {}', reg, label) def emit_branch_if_nonzero(self, reg, label): self._write_instr(' bne {}, $0, {}', reg, label) def emit_not(self, reg): self._write_instr(' seq {0}, {0}, $0', reg) def emit_indirect_call(self, reg): self._write_instr(' jalr {}', reg) def emit_jump(self, label): self._write_instr(' j {}', label) def get_backend(output, filename, is_library): """ Returns the backend represented by this module. """ return Common32Backend(MarsTemplates(), output, filename, is_library)
34.060606
81
0.585409
1,206
8,992
4.021559
0.180763
0.162887
0.216495
0.085773
0.533196
0.456082
0.40701
0.374227
0.242268
0.189485
0
0.015691
0.2629
8,992
263
82
34.190114
0.716053
0.06895
0
0.11976
0
0
0.156057
0
0
0
0
0
0
1
0.341317
false
0.005988
0.02994
0.017964
0.443114
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
360e40d685aef148649d810554c29b67296e0100
2,733
py
Python
ducktest/subtypes.py
markuswissinger/ducktestpy
4e9f75edc2bd953f670639a4a4ce9ad10a6a3577
[ "Apache-2.0" ]
4
2016-07-18T08:46:11.000Z
2017-08-12T14:24:49.000Z
ducktest/subtypes.py
markuswissinger/ducktestpy
4e9f75edc2bd953f670639a4a4ce9ad10a6a3577
[ "Apache-2.0" ]
null
null
null
ducktest/subtypes.py
markuswissinger/ducktestpy
4e9f75edc2bd953f670639a4a4ce9ad10a6a3577
[ "Apache-2.0" ]
null
null
null
""" Copyright 2016 Markus Wissinger. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from ducktest.base import PlainTypeWrapper, ContainerTypeWrapper, MappingTypeWrapper is_subtype_functions = [] def is_subtype(a, b): """a is subtype of b""" return any((function(a, b) for function in is_subtype_functions)) def both_are_instances(a, b, wrapper_class): return isinstance(a, wrapper_class) and isinstance(b, wrapper_class) def is_plain_subtype(a, b): return both_are_instances(a, b, PlainTypeWrapper) and issubclass(a.own_type, b.own_type) def is_subtype_of_any(a, b_iterable): return any((is_subtype(a, b) for b in b_iterable)) def is_container_subtype(a, b): return both_are_instances(a, b, ContainerTypeWrapper) and issubclass(a.own_type, b.own_type) and \ all((is_subtype_of_any(a_contained, b.contained_types) for a_contained in a.contained_types)) def key_sets(mapping_type_wrapper): return (mapped[0] for mapped in mapping_type_wrapper.mapped_types) def value_sets(mapping_type_wrapper): return (mapped[1] for mapped in mapping_type_wrapper.mapped_types) def each_is_subtype_of_some_in(key_set_a, key_set_b): return all((is_subtype_of_any(a_key, key_set_b) for a_key in key_set_a)) def all_compatible(a_sets, b_sets): return_value = True for a_set in a_sets: return_value = False for b_set in b_sets: if not each_is_subtype_of_some_in(a_set, b_set): return False return_value = True return return_value def is_mapping_subtype(a, b): return both_are_instances(a, b, MappingTypeWrapper) \ and issubclass(a.own_type, b.own_type) \ and all_compatible(key_sets(a), key_sets(b)) \ and all_compatible(value_sets(a), value_sets(b)) is_subtype_functions.extend([ is_plain_subtype, is_container_subtype, is_mapping_subtype, ]) def remove_subtypes(some_types): result = set([]) for a in some_types: should_add = True for b in some_types: if a is b: continue if is_subtype(a, b): should_add = False if should_add: result.add(a) return result
29.074468
104
0.713502
424
2,733
4.337264
0.266509
0.058728
0.029364
0.036977
0.250136
0.232191
0.154432
0.154432
0.138662
0.038064
0
0.004625
0.208928
2,733
93
105
29.387097
0.845976
0.218075
0
0.04
0
0
0
0
0
0
0
0
0
1
0.22
false
0
0.02
0.16
0.48
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
360eeacde89fd463b52d60f7b4df62c9bbada394
9,718
py
Python
mealpy/bio_based/SMA.py
rishavpramanik/mealpy
d4a4d5810f15837764e4ee61517350fef3dc92b3
[ "MIT" ]
null
null
null
mealpy/bio_based/SMA.py
rishavpramanik/mealpy
d4a4d5810f15837764e4ee61517350fef3dc92b3
[ "MIT" ]
null
null
null
mealpy/bio_based/SMA.py
rishavpramanik/mealpy
d4a4d5810f15837764e4ee61517350fef3dc92b3
[ "MIT" ]
null
null
null
#!/usr/bin/env python # Created by "Thieu" at 20:22, 12/06/2020 ----------% # Email: nguyenthieu2102@gmail.com % # Github: https://github.com/thieu1995 % # --------------------------------------------------% import numpy as np from copy import deepcopy from mealpy.optimizer import Optimizer class BaseSMA(Optimizer): """ My changed version of: Slime Mould Algorithm (SMA) Notes ~~~~~ + Selected 2 unique and random solution to create new solution (not to create variable) --> remove third loop in original version + Check bound and update fitness after each individual move instead of after the whole population move in the original version + This version not only faster but also better than the original version Hyper-parameters should fine tuned in approximate range to get faster convergence toward the global optimum: + p_t (float): [0.01, 0.1], probability threshold (z in the paper) Examples ~~~~~~~~ >>> import numpy as np >>> from mealpy.bio_based.SMA import BaseSMA >>> >>> def fitness_function(solution): >>> return np.sum(solution**2) >>> >>> problem_dict1 = { >>> "fit_func": fitness_function, >>> "lb": [-10, -15, -4, -2, -8], >>> "ub": [10, 15, 12, 8, 20], >>> "minmax": "min", >>> } >>> >>> epoch = 1000 >>> pop_size = 50 >>> p_t = 0.03 >>> model = BaseSMA(problem_dict1, epoch, pop_size, p_t) >>> best_position, best_fitness = model.solve() >>> print(f"Solution: {best_position}, Fitness: {best_fitness}") """ ID_WEI = 2 def __init__(self, problem, epoch=10000, pop_size=100, p_t=0.03, **kwargs): """ Args: problem (dict): The problem dictionary epoch (int): maximum number of iterations, default = 10000 pop_size (int): number of population size, default = 100 p_t (float): probability threshold (z in the paper), default = 0.03 """ super().__init__(problem, kwargs) self.epoch = self.validator.check_int("epoch", epoch, [1, 100000]) self.pop_size = self.validator.check_int("pop_size", pop_size, [10, 10000]) self.p_t = self.validator.check_float("p_t", p_t, (0, 1.0)) self.nfe_per_epoch = self.pop_size self.sort_flag = True def create_solution(self, lb=None, ub=None): """ Args: lb: list of lower bound values ub: list of upper bound values Returns: list: [position, target, weight] """ position = self.generate_position(lb, ub) position = self.amend_position(position, lb, ub) target = self.get_target_wrapper(position) weight = np.zeros(len(lb)) return [position, target, weight] def evolve(self, epoch): """ The main operations (equations) of algorithm. Inherit from Optimizer class Args: epoch (int): The current iteration """ # plus eps to avoid denominator zero s = self.g_best[self.ID_TAR][self.ID_FIT] - self.pop[-1][self.ID_TAR][self.ID_FIT] + self.EPSILON # calculate the fitness weight of each slime mold for i in range(0, self.pop_size): # Eq.(2.5) if i <= int(self.pop_size / 2): self.pop[i][self.ID_WEI] = 1 + np.random.uniform(0, 1, self.problem.n_dims) * \ np.log10((self.g_best[self.ID_TAR][self.ID_FIT] - self.pop[i][self.ID_TAR][self.ID_FIT]) / s + 1) else: self.pop[i][self.ID_WEI] = 1 - np.random.uniform(0, 1, self.problem.n_dims) * \ np.log10((self.g_best[self.ID_TAR][self.ID_FIT] - self.pop[i][self.ID_TAR][self.ID_FIT]) / s + 1) a = np.arctanh(-((epoch + 1) / (self.epoch+1)) + 1) # Eq.(2.4) b = 1 - (epoch + 1) / (self.epoch+1) pop_new = [] for idx in range(0, self.pop_size): # Update the Position of search agent if np.random.uniform() < self.p_t: # Eq.(2.7) pos_new = self.generate_position(self.problem.lb, self.problem.ub) else: p = np.tanh(np.abs(self.pop[idx][self.ID_TAR][self.ID_FIT] - self.g_best[self.ID_TAR][self.ID_FIT])) # Eq.(2.2) vb = np.random.uniform(-a, a, self.problem.n_dims) # Eq.(2.3) vc = np.random.uniform(-b, b, self.problem.n_dims) # two positions randomly selected from population, apply for the whole problem size instead of 1 variable id_a, id_b = np.random.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) pos_1 = self.g_best[self.ID_POS] + vb * (self.pop[idx][self.ID_WEI] * self.pop[id_a][self.ID_POS] - self.pop[id_b][self.ID_POS]) pos_2 = vc * self.pop[idx][self.ID_POS] pos_new = np.where(np.random.uniform(0, 1, self.problem.n_dims) < p, pos_1, pos_2) # Check bound and re-calculate fitness after each individual move pos_new = self.amend_position(pos_new, self.problem.lb, self.problem.ub) pop_new.append([pos_new, None, np.zeros(self.problem.n_dims)]) self.pop = self.update_target_wrapper_population(pop_new) class OriginalSMA(BaseSMA): """ The original version of: Slime Mould Algorithm (SMA) Links: 1. https://doi.org/10.1016/j.future.2020.03.055 2. https://www.researchgate.net/publication/340431861_Slime_mould_algorithm_A_new_method_for_stochastic_optimization Hyper-parameters should fine tuned in approximate range to get faster convergence toward the global optimum: + p_t (float): [0.01, 0.1], probability threshold (z in the paper) Examples ~~~~~~~~ >>> import numpy as np >>> from mealpy.bio_based.SMA import OriginalSMA >>> >>> def fitness_function(solution): >>> return np.sum(solution**2) >>> >>> problem_dict1 = { >>> "fit_func": fitness_function, >>> "lb": [-10, -15, -4, -2, -8], >>> "ub": [10, 15, 12, 8, 20], >>> "minmax": "min", >>> } >>> >>> epoch = 1000 >>> pop_size = 50 >>> p_t = 0.03 >>> model = OriginalSMA(problem_dict1, epoch, pop_size, p_t) >>> best_position, best_fitness = model.solve() >>> print(f"Solution: {best_position}, Fitness: {best_fitness}") References ~~~~~~~~~~ [1] Li, S., Chen, H., Wang, M., Heidari, A.A. and Mirjalili, S., 2020. Slime mould algorithm: A new method for stochastic optimization. Future Generation Computer Systems, 111, pp.300-323. """ ID_WEI = 2 def __init__(self, problem, epoch=10000, pop_size=100, p_t=0.03, **kwargs): """ Args: problem (dict): The problem dictionary epoch (int): maximum number of iterations, default = 1000 pop_size (int): number of population size, default = 100 p_t (float): probability threshold (z in the paper), default = 0.03 """ super().__init__(problem, epoch, pop_size, p_t, **kwargs) def evolve(self, epoch): """ The main operations (equations) of algorithm. Inherit from Optimizer class Args: epoch (int): The current iteration """ # plus eps to avoid denominator zero s = self.g_best[self.ID_TAR][self.ID_FIT] - self.pop[-1][self.ID_TAR][self.ID_FIT] + self.EPSILON # calculate the fitness weight of each slime mold for i in range(0, self.pop_size): # Eq.(2.5) if i <= int(self.pop_size / 2): self.pop[i][self.ID_WEI] = 1 + np.random.uniform(0, 1, self.problem.n_dims) * \ np.log10((self.g_best[self.ID_TAR][self.ID_FIT] - self.pop[i][self.ID_TAR][self.ID_FIT]) / s + 1) else: self.pop[i][self.ID_WEI] = 1 - np.random.uniform(0, 1, self.problem.n_dims) * \ np.log10((self.g_best[self.ID_TAR][self.ID_FIT] - self.pop[i][self.ID_TAR][self.ID_FIT]) / s + 1) a = np.arctanh(-((epoch + 1) / (self.epoch+1)) + 1) # Eq.(2.4) b = 1 - (epoch + 1) / (self.epoch+1) pop_new = [] for idx in range(0, self.pop_size): # Update the Position of search agent current_agent = deepcopy(self.pop[idx]) if np.random.uniform() < self.p_t: # Eq.(2.7) current_agent[self.ID_POS] = np.random.uniform(self.problem.lb, self.problem.ub) else: p = np.tanh(np.abs(current_agent[self.ID_TAR][self.ID_FIT] - self.g_best[self.ID_TAR][self.ID_FIT])) # Eq.(2.2) vb = np.random.uniform(-a, a, self.problem.n_dims) # Eq.(2.3) vc = np.random.uniform(-b, b, self.problem.n_dims) for j in range(0, self.problem.n_dims): # two positions randomly selected from population id_a, id_b = np.random.choice(list(set(range(0, self.pop_size)) - {idx}), 2, replace=False) if np.random.uniform() < p: # Eq.(2.1) current_agent[self.ID_POS][j] = self.g_best[self.ID_POS][j] + \ vb[j] * (current_agent[self.ID_WEI][j] * self.pop[id_a][self.ID_POS][j] - self.pop[id_b][self.ID_POS][j]) else: current_agent[self.ID_POS][j] = vc[j] * current_agent[self.ID_POS][j] pos_new = self.amend_position(current_agent[self.ID_POS], self.problem.lb, self.problem.ub) pop_new.append([pos_new, None, np.zeros(self.problem.n_dims)]) self.pop = self.update_target_wrapper_population(pop_new)
43.578475
144
0.579337
1,377
9,718
3.936819
0.179375
0.05534
0.026563
0.038369
0.746172
0.701162
0.670909
0.65689
0.65689
0.63088
0
0.037797
0.273101
9,718
222
145
43.774775
0.729615
0.406771
0
0.576923
0
0
0.003056
0
0
0
0
0
0
1
0.064103
false
0
0.038462
0
0.166667
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
361769a2e1fd406066a71a8bb8b75d2718df639b
468
py
Python
src/aussie_bot/modules/rules.py
Berg53/aussieIRCbot
54b684147c3032588c0b9dad22e07c556aafeae4
[ "MIT" ]
1
2019-01-14T22:48:45.000Z
2019-01-14T22:48:45.000Z
src/aussie_bot/modules/rules.py
Berg53/aussieIRCbot
54b684147c3032588c0b9dad22e07c556aafeae4
[ "MIT" ]
5
2019-01-04T07:39:25.000Z
2021-03-31T19:11:27.000Z
src/aussie_bot/modules/rules.py
Berg53/aussieIRCbot
54b684147c3032588c0b9dad22e07c556aafeae4
[ "MIT" ]
1
2019-02-27T05:53:29.000Z
2019-02-27T05:53:29.000Z
def handler(connection, event): if event.arguments and event.arguments[0].startswith("!r"): connection.privmsg(event.target, "\x02\x034 Rule one: \x035 No Banninating!") connection.privmsg(event.target, "\x02\x034 Rule two: \x035 See rule one") connection.privmsg( event.target, "\x02\x034 Rule three: \x035 It's against the rules to enforce em" ) def get_handlers(): return (("pubmsg", handler),)
36
87
0.632479
59
468
5
0.576271
0.172881
0.223729
0.284746
0.39661
0.39661
0.39661
0
0
0
0
0.070028
0.237179
468
12
88
39
0.756303
0
0
0
0
0
0.331197
0
0
0
0
0
0
1
0.2
false
0
0
0.1
0.3
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
36231df177833f0be5a1f61f4410d48a5f978cea
2,391
py
Python
pysan/multi/attributes.py
pysan-dev/pysan
60ca77ebac1749dadc91e6331f6da4b4c814e503
[ "Apache-2.0" ]
4
2020-05-18T20:19:25.000Z
2021-09-12T09:47:00.000Z
pysan/multi/attributes.py
pysan-dev/pysan
60ca77ebac1749dadc91e6331f6da4b4c814e503
[ "Apache-2.0" ]
10
2020-05-19T12:10:03.000Z
2020-11-19T11:17:05.000Z
pysan/multi/attributes.py
pysan-dev/pysan
60ca77ebac1749dadc91e6331f6da4b4c814e503
[ "Apache-2.0" ]
null
null
null
# AUTOGENERATED! DO NOT EDIT! File to edit: 21_multi_attributes.ipynb (unless otherwise specified). __all__ = ['are_recurrent', 'get_summary_statistic', 'get_routine_scores', 'get_synchrony', 'get_sequence_frequencies'] # Cell def are_recurrent(sequences): "Returns true if any of the sequences in a given collection are recurrant, false otherwise." for sequence in sequences: if pysan_core.is_recurrent(sequence): return True return False # Cell def get_summary_statistic(sequence, function): "Computes a summary statistic (e.g. entropy, complexity, or turbulence) for each sequence in a collection, returning the results as a list." pass # Cell def get_routine_scores(sequences, duration): "Returns a list containing the routine scores for each sequence in a collection using :meth:`get_routine() <pysan.core.get_routine>`." pass # Cell def get_synchrony(sequences): "Computes the normalised synchrony between a two or more sequences. Synchrony here refers to positions with identical elements, e.g. two identical sequences have a synchrony of 1, two completely different sequences have a synchrony of 0. The value is normalised by dividing by the number of positions compared. This computation is defined in Cornwell's 2015 book on social sequence analysis, page 230." shortest_sequence = min([len(s) for s in sequences]) same_elements = [] for position in range(shortest_sequence): elements_at_this_position = [] for sequence in sequences: elements_at_this_position.append(sequence[position]) same_elements.append(elements_at_this_position.count(elements_at_this_position[0]) == len(elements_at_this_position)) return same_elements.count(True) / shortest_sequence # Cell def get_sequence_frequencies(sequences): "Computes the frequencies of different sequences in a collection, returning a dictionary of their string representations and counts." # converting to strings makes comparison easy sequences_as_strings = [str(s) for s in sequences] sequence_frequencies = {} for sequence in set(sequences_as_strings): sequence_frequencies[sequence] = sequences_as_strings.count(sequence) sequence_frequencies = {k: v for k, v in sorted(sequence_frequencies.items(), key=lambda item: item[1], reverse=True)} return sequence_frequencies
41.947368
406
0.757842
325
2,391
5.396923
0.381538
0.075827
0.039909
0.062714
0.078677
0.031927
0
0
0
0
0
0.006566
0.171895
2,391
57
407
41.947368
0.879293
0.444584
0
0.129032
1
0.096774
0.44184
0.032011
0
0
0
0
0
1
0.16129
false
0.064516
0
0
0.290323
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
3623ccbc63862d0b34cd8a147df66d7ecee8408e
1,881
py
Python
backend/db/entities/mixin/tunjangan_kinerja.py
R-N/sistem_gaji_vue_thrift
9ba800b4d8e7849e2c6c4016cb32633caab087be
[ "MIT" ]
null
null
null
backend/db/entities/mixin/tunjangan_kinerja.py
R-N/sistem_gaji_vue_thrift
9ba800b4d8e7849e2c6c4016cb32633caab087be
[ "MIT" ]
null
null
null
backend/db/entities/mixin/tunjangan_kinerja.py
R-N/sistem_gaji_vue_thrift
9ba800b4d8e7849e2c6c4016cb32633caab087be
[ "MIT" ]
null
null
null
from sqlalchemy import Column, Integer, String, ForeignKeyConstraint from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declared_attr from .general import pop_periode class MxTunjanganKinerja: __tablename__ = 'tunjangan_kinerja' @declared_attr def job_level_id(cls): return Column(Integer, primary_key=True) @declared_attr def kinerja(cls): return Column(String(1), primary_key=True) # PK job_level_id & kinerja @declared_attr def nilai(cls): return Column(Integer, nullable=False) @declared_attr def job_level(cls): return relationship("DbJobLevel", back_populates="tunjangan_kinerja", uselist=False) @declared_attr def kinerja_rel(cls): return relationship("DbKinerja", uselist=False) @declared_attr def __table_args__(cls): return ( ForeignKeyConstraint( pop_periode(cls, ["periode", "job_level_id"]), pop_periode(cls, ["job_level.periode", "job_level.id"]), deferrable=True ), ForeignKeyConstraint( pop_periode(cls, ["periode", "kinerja"]), pop_periode(cls, ["kinerja.periode", "kinerja.kode"]), deferrable=True ), ) ''' def mx_init( self, job_level_id, kinerja, nilai ): self.job_level_id = job_level_id self.kinerja = kinerja self.nilai = nilai ''' def mx_reconstruct(self): pass def mx_repr(self): return "id=%r, job_level_id=%r, kinerja=%r, nilai=%r)>" % (self.id, self.job_level_id, self.kinerja, self.nilai) def mx_init_repr(self): return { 'job_level_id': self.job_level_id, 'kinerja': self.kinerja, 'nilai': self.nilai }
26.871429
120
0.606061
207
1,881
5.241546
0.251208
0.095853
0.101382
0.051613
0.250691
0
0
0
0
0
0
0.00075
0.291334
1,881
69
121
27.26087
0.813203
0.013291
0
0.266667
0
0
0.128252
0
0
0
0
0
0
1
0.2
false
0.022222
0.088889
0.177778
0.511111
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
36457e6d822b243c12ce99c513a9ac5929c0b3b7
557
py
Python
wwag/filters.py
zhoutong/wwag
41afb58589781e5c168f76f918cf00a93b35a78c
[ "MIT" ]
null
null
null
wwag/filters.py
zhoutong/wwag
41afb58589781e5c168f76f918cf00a93b35a78c
[ "MIT" ]
null
null
null
wwag/filters.py
zhoutong/wwag
41afb58589781e5c168f76f918cf00a93b35a78c
[ "MIT" ]
null
null
null
from wwag import app @app.template_filter('date') def date_filter(s): return s.strftime("%d %B %Y") @app.template_filter('youtube_thumbnail_url') def youtube_thumbnail_url_filter(s): return "http://img.youtube.com/vi/" + s.split("/")[-1] + "/default.jpg" @app.template_filter('price') def price_filter(s): if s == None: return "Free" else: return "$%s" % s @app.template_filter('viewer_type') def viewer_type_filter(s): if s == "R": return "Regular" elif s == "P": return "Premium" elif s == "C": return "CrowdFunding"
21.423077
73
0.653501
83
557
4.216867
0.46988
0.125714
0.194286
0.057143
0
0
0
0
0
0
0
0.002155
0.166966
557
25
74
22.28
0.752155
0
0
0
0
0
0.222621
0.037702
0
0
0
0
0
1
0.190476
false
0
0.047619
0.095238
0.571429
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
366001cb286d022791f574db88cfcae8ca66d5fa
418
py
Python
logux/apps.py
sobolevn/django-1
6a1a469a938f787be670548a842da6b4b239e931
[ "MIT" ]
17
2020-04-04T12:09:12.000Z
2021-09-29T10:35:31.000Z
logux/apps.py
sobolevn/django-1
6a1a469a938f787be670548a842da6b4b239e931
[ "MIT" ]
46
2020-04-04T11:56:30.000Z
2021-04-12T08:47:16.000Z
logux/apps.py
sobolevn/django-1
6a1a469a938f787be670548a842da6b4b239e931
[ "MIT" ]
2
2020-07-13T10:04:53.000Z
2020-08-10T08:26:29.000Z
from django.apps import AppConfig from logux import settings from logux.utils import autodiscover class LoguxConfig(AppConfig): """ Logux app conf """ name = 'logux' verbose_name = 'Logux' def ready(self): # check if all required settings is defined settings.get_config() # import all logux_actions.py and logux_subscriptions.py from consumer modules autodiscover()
24.588235
86
0.696172
51
418
5.627451
0.627451
0.062718
0
0
0
0
0
0
0
0
0
0
0.23445
418
16
87
26.125
0.896875
0.322967
0
0
0
0
0.036364
0
0
0
0
0
0
1
0.111111
false
0
0.333333
0
0.777778
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
3673fb2320ff6c18cfd7d5a506d4b0d19b4de6c8
940
py
Python
robovat/utils/time_utils.py
leobxpan/robovat
0d360c34c677cf018c4daab0b8e758943ae1d2c1
[ "MIT" ]
62
2020-04-08T11:26:24.000Z
2021-09-06T02:45:53.000Z
robovat/utils/time_utils.py
leobxpan/robovat
0d360c34c677cf018c4daab0b8e758943ae1d2c1
[ "MIT" ]
7
2020-04-12T13:10:10.000Z
2022-03-12T00:15:03.000Z
robovat/utils/time_utils.py
leobxpan/robovat
0d360c34c677cf018c4daab0b8e758943ae1d2c1
[ "MIT" ]
17
2020-04-12T17:37:01.000Z
2021-09-07T01:51:46.000Z
"""Utilities for timing. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import datetime import signal import time class TimeoutException(Exception): """Exception for timeout. """ pass class Timeout(): """Timeout class using ALARM signal. """ def __init__(self, sec): self.sec = sec def __enter__(self): signal.signal(signal.SIGALRM, self.raise_timeout_exception) signal.alarm(self.sec) def __exit__(self, *args): signal.alarm(0) # disable alarm def raise_timeout_exception(self, *args): raise TimeoutException() def get_timestamp_as_string(): """Get the current timestamp as a string. Returns: The timestamp as a string of the format YYYYMMDD_hhmmss_ffffff. """ t = time.time() return datetime.datetime.fromtimestamp(t).strftime('%Y%m%d_%H%M%S_%f')
20.888889
74
0.676596
116
940
5.163793
0.465517
0.050083
0.080134
0.0601
0
0
0
0
0
0
0
0.00137
0.223404
940
44
75
21.363636
0.819178
0.234043
0
0
0
0
0.023358
0
0
0
0
0
0
1
0.238095
false
0.047619
0.285714
0
0.666667
0.047619
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
3674d65c7800d8dfeab0f387283c9318113da355
683
py
Python
test_polyfit.py
oscarliu666/partia-flood-warning-system
51b9e35266ab9f45f5b32593b93f0c90a3ec55b0
[ "MIT" ]
null
null
null
test_polyfit.py
oscarliu666/partia-flood-warning-system
51b9e35266ab9f45f5b32593b93f0c90a3ec55b0
[ "MIT" ]
null
null
null
test_polyfit.py
oscarliu666/partia-flood-warning-system
51b9e35266ab9f45f5b32593b93f0c90a3ec55b0
[ "MIT" ]
null
null
null
from floodsystem.flood import stations_highest_rel_level from floodsystem.utils import sorted_by_key from floodsystem.stationdata import build_station_list from floodsystem.stationdata import update_water_levels from floodsystem.datafetcher import fetch_measure_levels from floodsystem.station import MonitoringStation from floodsystem.analysis import polyfit import datetime import numpy as np def run(): stations = build_station_list() update_water_levels(stations) key =stations[1].measure_id dt = 2 dates, levels = fetch_measure_levels(key,dt=datetime.timedelta(days=dt)) poly,shift = polyfit(dates,levels,4) print(poly) print(shift) run()
26.269231
76
0.800878
91
683
5.813187
0.461538
0.198488
0.098299
0.120983
0
0
0
0
0
0
0
0.005093
0.137628
683
25
77
27.32
0.893039
0
0
0
0
0
0
0
0
0
0
0
0
1
0.052632
false
0
0.473684
0
0.526316
0.105263
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
3675e30007d78b9cb83da2b30178ec83652317d9
4,679
py
Python
src/methodfinder/methodfinder-test.py
billsix/methodfinder
7446ae0ecc9c1129f6f75294d7fd5a9090a4af2f
[ "MIT" ]
20
2019-06-28T02:09:21.000Z
2020-08-05T17:07:58.000Z
src/methodfinder/methodfinder-test.py
billsix/methodfinder
7446ae0ecc9c1129f6f75294d7fd5a9090a4af2f
[ "MIT" ]
1
2019-09-10T20:09:43.000Z
2019-09-11T04:18:44.000Z
src/methodfinder/methodfinder-test.py
billsix/methodfinder
7446ae0ecc9c1129f6f75294d7fd5a9090a4af2f
[ "MIT" ]
null
null
null
# Copyright (c) 2019 William Emerison Six # # 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 methodfinder import itertools import doctest import unittest import numpy class TestMethodFinder(unittest.TestCase): def test_in(self): self.assertListEqual( methodfinder._find([[1, 2, 6, 7], 6], expected_value=True), [ '6 in [1, 2, 6, 7]\n# to use the "in" syntax with your own type, override __contains__' ], ) def test_join(self): self.assertListEqual( methodfinder._find([" ", ["foo", "bar"]], expected_value="foo bar"), ["' '.join(['foo', 'bar'])"], ) def test_permutations(self): self.assertListEqual( methodfinder._find([itertools, [1, 2]], expected_value=[[1, 2], [2, 1]]), ["itertools.permutations([1, 2])"], ) def test_zip(self): self.assertListEqual( methodfinder._find([[1, 2], [3, 4]], expected_value=[[1, 3], [2, 4]]), ["zip([1, 2], [3, 4])"], ) def test_zip2(self): self.assertListEqual( methodfinder._find( [itertools, [1, 2], [3, 4]], expected_value=[[1, 3], [2, 4]] ), ["itertools.zip_longest([1, 2], [3, 4])"], ) def test_len(self): self.assertListEqual( methodfinder._find([[]], expected_value=0), ["len([])", "sum([])"] ) def test_any(self): self.assertListEqual( methodfinder._find([[]], expected_value=False), ["any([])", "bool([])", "callable([])"], ) def test_str(self): self.assertListEqual( methodfinder._find([3], expected_value="3"), ["ascii(3)", "format(3)", "repr(3)", "str(3)"], ) def test_add(self): self.assertListEqual( methodfinder._find([-1, 3], expected_value=2), ["-1%3", "-1+3", "3+-1"] ) def test_divide(self): self.assertListEqual(methodfinder._find([3, 2], expected_value=1.5), ["3/2"]) def test_doublenegative(self): self.assertListEqual( methodfinder._find([-1], expected_value=1), ["-(-1)", "-1.bit_length()", "-1.denominator", "abs(-1)"], ) def test_add2(self): self.assertListEqual( methodfinder._find([1, 2], expected_value=3), ["1+2", "1^2", "1|2", "2+1", "2^1", "2|1"], ) def test_one_one_one(self): self.assertListEqual( methodfinder._find([1, 1], expected_value=1), [ "1&1", "1**1", "1*1", "1.denominator", "1.numerator", "1.real", "1//1", "1|1", "max(1, 1)", "min(1, 1)", "pow(1, 1)", "round(1, 1)", ], ) def test_hasattr(self): self.assertListEqual( methodfinder._find([[1, 2], "__iter__"], expected_value=True), ["hasattr([1, 2], '__iter__')"], ) def test_doctest(self): failureCount, testCount = doctest.testmod(methodfinder) self.assertEqual(0, failureCount) def test_numpy(self): import numpy as np self.assertListEqual( methodfinder._find( [3, np], expected_value=np.array( [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] ), ), ["numpy.eye(3)", "numpy.identity(3)"], ) if __name__ == "__main__": unittest.main()
32.268966
103
0.546698
552
4,679
4.507246
0.311594
0.013666
0.186897
0.211013
0.309887
0.27492
0.173633
0.063505
0.024116
0.024116
0
0.043345
0.304766
4,679
144
104
32.493056
0.721488
0.226544
0
0.201923
0
0.009615
0.142262
0.014171
0
0
0
0
0.153846
1
0.153846
false
0
0.057692
0
0.221154
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
36790c3a437310efdad890903e46691778226b8d
5,767
py
Python
sdk/python/pulumi_aws_native/globalaccelerator/_inputs.py
AaronFriel/pulumi-aws-native
5621690373ac44accdbd20b11bae3be1baf022d1
[ "Apache-2.0" ]
29
2021-09-30T19:32:07.000Z
2022-03-22T21:06:08.000Z
sdk/python/pulumi_aws_native/globalaccelerator/_inputs.py
AaronFriel/pulumi-aws-native
5621690373ac44accdbd20b11bae3be1baf022d1
[ "Apache-2.0" ]
232
2021-09-30T19:26:26.000Z
2022-03-31T23:22:06.000Z
sdk/python/pulumi_aws_native/globalaccelerator/_inputs.py
AaronFriel/pulumi-aws-native
5621690373ac44accdbd20b11bae3be1baf022d1
[ "Apache-2.0" ]
4
2021-11-10T19:42:01.000Z
2022-02-05T10:15:49.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from ._enums import * __all__ = [ 'AcceleratorTagArgs', 'EndpointGroupEndpointConfigurationArgs', 'EndpointGroupPortOverrideArgs', 'ListenerPortRangeArgs', ] @pulumi.input_type class AcceleratorTagArgs: def __init__(__self__, *, key: pulumi.Input[str], value: pulumi.Input[str]): """ Tag is a key-value pair associated with accelerator. :param pulumi.Input[str] key: Key of the tag. Value can be 1 to 127 characters. :param pulumi.Input[str] value: Value for the tag. Value can be 1 to 255 characters. """ pulumi.set(__self__, "key", key) pulumi.set(__self__, "value", value) @property @pulumi.getter def key(self) -> pulumi.Input[str]: """ Key of the tag. Value can be 1 to 127 characters. """ return pulumi.get(self, "key") @key.setter def key(self, value: pulumi.Input[str]): pulumi.set(self, "key", value) @property @pulumi.getter def value(self) -> pulumi.Input[str]: """ Value for the tag. Value can be 1 to 255 characters. """ return pulumi.get(self, "value") @value.setter def value(self, value: pulumi.Input[str]): pulumi.set(self, "value", value) @pulumi.input_type class EndpointGroupEndpointConfigurationArgs: def __init__(__self__, *, endpoint_id: pulumi.Input[str], client_ip_preservation_enabled: Optional[pulumi.Input[bool]] = None, weight: Optional[pulumi.Input[int]] = None): """ The configuration for a given endpoint :param pulumi.Input[str] endpoint_id: Id of the endpoint. For Network/Application Load Balancer this value is the ARN. For EIP, this value is the allocation ID. For EC2 instances, this is the EC2 instance ID :param pulumi.Input[bool] client_ip_preservation_enabled: true if client ip should be preserved :param pulumi.Input[int] weight: The weight for the endpoint. """ pulumi.set(__self__, "endpoint_id", endpoint_id) if client_ip_preservation_enabled is not None: pulumi.set(__self__, "client_ip_preservation_enabled", client_ip_preservation_enabled) if weight is not None: pulumi.set(__self__, "weight", weight) @property @pulumi.getter(name="endpointId") def endpoint_id(self) -> pulumi.Input[str]: """ Id of the endpoint. For Network/Application Load Balancer this value is the ARN. For EIP, this value is the allocation ID. For EC2 instances, this is the EC2 instance ID """ return pulumi.get(self, "endpoint_id") @endpoint_id.setter def endpoint_id(self, value: pulumi.Input[str]): pulumi.set(self, "endpoint_id", value) @property @pulumi.getter(name="clientIPPreservationEnabled") def client_ip_preservation_enabled(self) -> Optional[pulumi.Input[bool]]: """ true if client ip should be preserved """ return pulumi.get(self, "client_ip_preservation_enabled") @client_ip_preservation_enabled.setter def client_ip_preservation_enabled(self, value: Optional[pulumi.Input[bool]]): pulumi.set(self, "client_ip_preservation_enabled", value) @property @pulumi.getter def weight(self) -> Optional[pulumi.Input[int]]: """ The weight for the endpoint. """ return pulumi.get(self, "weight") @weight.setter def weight(self, value: Optional[pulumi.Input[int]]): pulumi.set(self, "weight", value) @pulumi.input_type class EndpointGroupPortOverrideArgs: def __init__(__self__, *, endpoint_port: pulumi.Input[int], listener_port: pulumi.Input[int]): """ listener to endpoint port mapping. """ pulumi.set(__self__, "endpoint_port", endpoint_port) pulumi.set(__self__, "listener_port", listener_port) @property @pulumi.getter(name="endpointPort") def endpoint_port(self) -> pulumi.Input[int]: return pulumi.get(self, "endpoint_port") @endpoint_port.setter def endpoint_port(self, value: pulumi.Input[int]): pulumi.set(self, "endpoint_port", value) @property @pulumi.getter(name="listenerPort") def listener_port(self) -> pulumi.Input[int]: return pulumi.get(self, "listener_port") @listener_port.setter def listener_port(self, value: pulumi.Input[int]): pulumi.set(self, "listener_port", value) @pulumi.input_type class ListenerPortRangeArgs: def __init__(__self__, *, from_port: pulumi.Input[int], to_port: pulumi.Input[int]): """ A port range to support for connections from clients to your accelerator. """ pulumi.set(__self__, "from_port", from_port) pulumi.set(__self__, "to_port", to_port) @property @pulumi.getter(name="fromPort") def from_port(self) -> pulumi.Input[int]: return pulumi.get(self, "from_port") @from_port.setter def from_port(self, value: pulumi.Input[int]): pulumi.set(self, "from_port", value) @property @pulumi.getter(name="toPort") def to_port(self) -> pulumi.Input[int]: return pulumi.get(self, "to_port") @to_port.setter def to_port(self, value: pulumi.Input[int]): pulumi.set(self, "to_port", value)
33.52907
217
0.648171
708
5,767
5.069209
0.162429
0.110337
0.065199
0.07523
0.564224
0.354695
0.301198
0.27027
0.240178
0.117582
0
0.004793
0.240333
5,767
171
218
33.725146
0.814426
0.214843
0
0.186916
1
0
0.110384
0.047942
0
0
0
0
0
1
0.205607
false
0
0.056075
0.037383
0.383178
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
3682b2cba02c610618de72113328abd2deb7c194
190
py
Python
utility_scripts/lib/__init__.py
fmarchenko/utility_scripts
02ebe00a9ed74342faca4d5972b449aae2b1af80
[ "MIT" ]
null
null
null
utility_scripts/lib/__init__.py
fmarchenko/utility_scripts
02ebe00a9ed74342faca4d5972b449aae2b1af80
[ "MIT" ]
null
null
null
utility_scripts/lib/__init__.py
fmarchenko/utility_scripts
02ebe00a9ed74342faca4d5972b449aae2b1af80
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function __author__ = "Fedor Marchenko" __email__ = "mfs90@mail.ru" __date__ = "Jul 11, 2016"
19
55
0.715789
25
190
4.72
1
0
0
0
0
0
0
0
0
0
0
0.055215
0.142105
190
9
56
21.111111
0.668712
0.221053
0
0
0
0
0.275862
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.25
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
368ce558e88ef90f423d7454857d8095aa58ff73
2,509
py
Python
savu/plugins/alignment/sinogram_alignment_tools.py
elainehoml/Savu
e4772704606f71d6803d832084e10faa585e7358
[ "Apache-2.0" ]
39
2015-03-30T14:03:42.000Z
2022-03-16T16:50:33.000Z
savu/plugins/alignment/sinogram_alignment_tools.py
elainehoml/Savu
e4772704606f71d6803d832084e10faa585e7358
[ "Apache-2.0" ]
670
2015-02-11T11:08:09.000Z
2022-03-21T09:27:57.000Z
savu/plugins/alignment/sinogram_alignment_tools.py
elainehoml/Savu
e4772704606f71d6803d832084e10faa585e7358
[ "Apache-2.0" ]
54
2015-02-13T14:09:52.000Z
2022-01-24T13:57:09.000Z
from savu.plugins.plugin_tools import PluginTools class SinogramAlignmentTools(PluginTools): """The centre of mass of each row is determined and then a sine function fit through these to determine the centre of rotation. The residual between each centre of mass and the sine function is then used to align each row. """ def define_parameters(self): """ threshold: visibility: basic dtype: [None,str] description: e.g. a.b will set all values above a to b. default: None p0: visibility: basic dtype: list[float,float,float] description: Initial guess for the parameters of scipy.optimize.curve_fit. default: [1, 1, 1] type: visibility: intermediate dtype: str description: Either centre_of_mass or shift, with the latter requiring ProjectionVerticalAlignment prior to this plugin. default: centre_of_mass options: [centre_of_mass, shift] """ def citation(self): u""" The Tomographic filtering performed in this processing chain is derived from this work. bibtex: @article{price2015chemical, title={Chemical imaging of single catalyst particles with scanning $\mu$-XANES-CT and $\mu$-XRF-CT}, author={Price, SWT and Ignatyev, K and Geraki, K and Basham, M and Filik, J and Vo, NT and Witte, PT and Beale, AM and Mosselmans, JFW}, journal={Physical Chemistry Chemical Physics}, volume={17}, number={1}, pages={521--529}, year={2015}, publisher={Royal Society of Chemistry}} endnote: %0 Journal Article %T Chemical imaging of single catalyst particles with scanning \u03BC-XANES-CT and \u03BC-XRF-CT %A Price, SWT %A Ignatyev, K %A Geraki, K %A Basham, M %A Filik, J %A Vo, NT %A Witte, PT %A Beale, AM %A Mosselmans, JFW %J Physical Chemistry Chemical Physics %V 17 %N 1 %P 521-529 %D 2015 %I Royal Society of Chemistry doi: "10.1039/c4cp04488f" """
36.897059
152
0.53328
281
2,509
4.729537
0.512456
0.036117
0.045147
0.034612
0.078254
0.078254
0.078254
0.078254
0
0
0
0.033887
0.400159
2,509
67
153
37.447761
0.849169
0.74731
0
0
0
0
0
0
0
0
0
0
0
1
0.4
false
0
0.2
0
0.8
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
369b6ab61b597630bd7b6f6ae01097611a84e857
865
py
Python
tests/core/actions/cancel_task/test_cancel_task_request.py
Himon-SYNCRAFT/taskplus
9e6293840941d0cb4fd7bac0f8ff66f8e72cc62b
[ "BSD-3-Clause" ]
null
null
null
tests/core/actions/cancel_task/test_cancel_task_request.py
Himon-SYNCRAFT/taskplus
9e6293840941d0cb4fd7bac0f8ff66f8e72cc62b
[ "BSD-3-Clause" ]
null
null
null
tests/core/actions/cancel_task/test_cancel_task_request.py
Himon-SYNCRAFT/taskplus
9e6293840941d0cb4fd7bac0f8ff66f8e72cc62b
[ "BSD-3-Clause" ]
null
null
null
from taskplus.core.actions import CancelTaskRequest def test_cancel_task_request(): task_id = 1 request = CancelTaskRequest(task_id) assert request.task_id == task_id assert request.is_valid() def test_cancel_task_without_id(): task_id = None request = CancelTaskRequest(task_id) assert request.task_id == task_id assert not request.is_valid() assert len(request.errors) == 1 error = request.errors[0] assert error.parameter == 'task_id' assert error.message == 'is required' def test_cancel_task_bad_request(): task_id = 'abc' request = CancelTaskRequest(task_id) assert request.task_id == task_id assert not request.is_valid() assert len(request.errors) == 1 error = request.errors[0] assert error.parameter == 'task_id' assert error.message == 'expected int, got str(abc)'
25.441176
56
0.705202
117
865
4.974359
0.273504
0.14433
0.164948
0.130584
0.668385
0.668385
0.668385
0.668385
0.668385
0.668385
0
0.007205
0.197688
865
33
57
26.212121
0.831412
0
0
0.583333
0
0
0.062428
0
0
0
0
0
0.5
1
0.125
false
0
0.041667
0
0.166667
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
2
369ca4abecd80c410f0709178a0a10c15491164f
214
py
Python
test_eval_actions.py
vineetm/Focused-Attention-Improves-Document-Grounded-Generation
7b3a2711709fa3ef6911c81542f85b90d06827ff
[ "MIT" ]
null
null
null
test_eval_actions.py
vineetm/Focused-Attention-Improves-Document-Grounded-Generation
7b3a2711709fa3ef6911c81542f85b90d06827ff
[ "MIT" ]
null
null
null
test_eval_actions.py
vineetm/Focused-Attention-Improves-Document-Grounded-Generation
7b3a2711709fa3ef6911c81542f85b90d06827ff
[ "MIT" ]
null
null
null
from eval_actions import ActionsEvaluator evaluator = ActionsEvaluator() gold = "[send link] fhfhf [okay] fjfjfjfjf" pred = "[send link] [send link] fhfhf fjfjfjfjf" print(evaluator.compute_tp_fp_fn(gold, pred))
26.75
48
0.771028
28
214
5.75
0.642857
0.149068
0.161491
0
0
0
0
0
0
0
0
0
0.121495
214
8
49
26.75
0.856383
0
0
0
0
0
0.339535
0
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0.2
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
36b0119c30eaac5defe37ffd50c4a9c46b2030e7
2,073
py
Python
base/logg.py
forestsheep/middleman
34d54f9ffd9d7bcd775a8dcce4f00dd6c5bb1acd
[ "MIT" ]
null
null
null
base/logg.py
forestsheep/middleman
34d54f9ffd9d7bcd775a8dcce4f00dd6c5bb1acd
[ "MIT" ]
null
null
null
base/logg.py
forestsheep/middleman
34d54f9ffd9d7bcd775a8dcce4f00dd6c5bb1acd
[ "MIT" ]
null
null
null
# coding:UTF-8 import inspect import json import logging.config import os def init(): if not os.path.exists('log'): os.makedirs('log') config = json.load(open('conf/logger.config')) logging.config.dictConfig(config) info('log init successful.') pass def info_response(msg): logger = logging.getLogger('mylogger') logger.info(msg) pass def info(msg): logger = logging.getLogger('mylogger') stack = inspect.stack() infodict = dict() infodict['method'] = stack[1][3] infodict['file'] = stack[1][1] infodict['line'] = stack[1][2] infodict['source code'] = stack[1][4] infodict['message'] = msg logger.info(json.dumps(infodict)) pass def error(msg): logger = logging.getLogger('mylogger') stack = inspect.stack() infodict = dict() infodict['method'] = stack[1][3] infodict['file'] = stack[1][1] infodict['line'] = stack[1][2] infodict['source code'] = stack[1][4] infodict['message'] = msg logger.error(json.dumps(infodict)) pass def debug(msg): logger = logging.getLogger('mylogger') stack = inspect.stack() infodict = dict() infodict['method'] = stack[1][3] infodict['file'] = stack[1][1] infodict['line'] = stack[1][2] infodict['source code'] = stack[1][4] infodict['message'] = msg logger.debug(json.dumps(infodict)) pass def warn(msg): logger = logging.getLogger('mylogger') stack = inspect.stack() infodict = dict() infodict['method'] = stack[1][3] infodict['file'] = stack[1][1] infodict['line'] = stack[1][2] infodict['source code'] = stack[1][4] infodict['message'] = msg logger.warn(json.dumps(infodict)) pass def critical(msg): logger = logging.getLogger('mylogger') stack = inspect.stack() infodict = dict() infodict['method'] = stack[1][3] infodict['file'] = stack[1][1] infodict['line'] = stack[1][2] infodict['source code'] = stack[1][4] infodict['message'] = msg logger.critical(json.dumps(infodict)) pass
23.556818
50
0.615533
261
2,073
4.885057
0.180077
0.094118
0.075294
0.117647
0.767843
0.666667
0.666667
0.666667
0.666667
0.666667
0
0.024985
0.208394
2,073
87
51
23.827586
0.751981
0.005789
0
0.685714
0
0
0.122509
0
0
0
0
0
0
1
0.1
false
0.1
0.057143
0
0.157143
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
36b96b780f548a8ff3aa04b02e5efa61961d181f
939
py
Python
py_stringmatching/tokenizer/tokenizer.py
kvpradap/conda-pysm-appveyor
1dd8e54e8e105780420b25f3f2498977ae5c2f25
[ "MIT", "BSD-3-Clause" ]
115
2016-04-20T06:59:28.000Z
2022-02-12T03:32:59.000Z
py_stringmatching/tokenizer/tokenizer.py
kvpradap/conda-pysm-appveyor
1dd8e54e8e105780420b25f3f2498977ae5c2f25
[ "MIT", "BSD-3-Clause" ]
59
2016-04-20T06:56:11.000Z
2022-01-25T08:16:58.000Z
py_stringmatching/tokenizer/tokenizer.py
kvpradap/conda-pysm-appveyor
1dd8e54e8e105780420b25f3f2498977ae5c2f25
[ "MIT", "BSD-3-Clause" ]
17
2016-04-20T06:59:46.000Z
2022-01-18T17:45:48.000Z
class Tokenizer(object): """The root class for tokenizers. Args: return_set (boolean): A flag to indicate whether to return a set of tokens instead of a bag of tokens (defaults to False). Attributes: return_set (boolean): An attribute to store the flag return_set. """ def __init__(self, return_set=False): self.return_set = return_set def get_return_set(self): """Gets the value of the return_set flag. Returns: The boolean value of the return_set flag. """ return self.return_set def set_return_set(self, return_set): """Sets the value of the return_set flag. Args: return_set (boolean): a flag to indicate whether to return a set of tokens instead of a bag of tokens. """ self.return_set = return_set return True
30.290323
114
0.588924
124
939
4.282258
0.282258
0.271186
0.122411
0.090395
0.536723
0.453861
0.410546
0.312618
0.312618
0.312618
0
0
0.347178
939
30
115
31.3
0.866232
0.58573
0
0.25
0
0
0
0
0
0
0
0
0
1
0.375
false
0
0
0
0.75
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
36c7b788412752423bb4c238c398d217c8d23f65
23,268
py
Python
tests/test_bip39.py
spletnik/bip_utils
d0fa0290e31a8a69fd5644ceb09e096deb515dfd
[ "MIT" ]
null
null
null
tests/test_bip39.py
spletnik/bip_utils
d0fa0290e31a8a69fd5644ceb09e096deb515dfd
[ "MIT" ]
null
null
null
tests/test_bip39.py
spletnik/bip_utils
d0fa0290e31a8a69fd5644ceb09e096deb515dfd
[ "MIT" ]
null
null
null
# Copyright (c) 2021 Emanuele Bellocchia # # 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. # Imports import binascii import unittest from bip_utils import ( Bip39ChecksumError, Bip39WordsNum, Bip39EntropyBitLen, Bip39Languages, Bip39EntropyGenerator, Bip39MnemonicGenerator, Bip39MnemonicValidator, Bip39SeedGenerator ) from bip_utils.bip39 import Bip39Utils # Tests from BIP39 page # https://github.com/trezor/python-mnemonic/blob/master/vectors.json TEST_VECT = [ # # Basic 12-words # { "entropy": b"00000000000000000000000000000000", "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "seed": b"c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04", }, { "entropy": b"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "mnemonic": "legal winner thank year wave sausage worth useful legal winner thank yellow", "seed": b"2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607", }, { "entropy": b"80808080808080808080808080808080", "mnemonic": "letter advice cage absurd amount doctor acoustic avoid letter advice cage above", "seed": b"d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f12eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8", }, { "entropy": b"ffffffffffffffffffffffffffffffff", "mnemonic": "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong", "seed": b"ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a13332572917f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069", }, # # Basic 18-words # { "entropy": b"000000000000000000000000000000000000000000000000", "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon agent", "seed": b"035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa", }, { "entropy": b"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "mnemonic": "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal will", "seed": b"f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c392d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd", }, { "entropy": b"808080808080808080808080808080808080808080808080", "mnemonic": "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter always", "seed": b"107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913ffb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65", }, { "entropy": b"ffffffffffffffffffffffffffffffffffffffffffffffff", "mnemonic": "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo when", "seed": b"0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528", }, # # Basic 24-words # { "entropy": b"0000000000000000000000000000000000000000000000000000000000000000", "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon art", "seed": b"bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8", }, { "entropy": b"7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f", "mnemonic": "legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth useful legal winner thank year wave sausage worth title", "seed": b"bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146ad717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87", }, { "entropy": b"8080808080808080808080808080808080808080808080808080808080808080", "mnemonic": "letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic avoid letter advice cage absurd amount doctor acoustic bless", "seed": b"c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61af0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f", }, { "entropy": b"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "mnemonic": "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo vote", "seed": b"dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad", }, # # Various # { "entropy": b"9e885d952ad362caeb4efe34a8e91bd2", "mnemonic": "ozone drill grab fiber curtain grace pudding thank cruise elder eight picnic", "seed": b"274ddc525802f7c828d8ef7ddbcdc5304e87ac3535913611fbbfa986d0c9e5476c91689f9c8a54fd55bd38606aa6a8595ad213d4c9c9f9aca3fb217069a41028", }, { "entropy": b"6610b25967cdcca9d59875f5cb50b0ea75433311869e930b", "mnemonic": "gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog", "seed": b"628c3827a8823298ee685db84f55caa34b5cc195a778e52d45f59bcf75aba68e4d7590e101dc414bc1bbd5737666fbbef35d1f1903953b66624f910feef245ac", }, { "entropy": b"68a79eaca2324873eacc50cb9c6eca8cc68ea5d936f98787c60c7ebc74e6ce7c", "mnemonic": "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay length", "seed": b"64c87cde7e12ecf6704ab95bb1408bef047c22db4cc7491c4271d170a1b213d20b385bc1588d9c7b38f1b39d415665b8a9030c9ec653d75e65f847d8fc1fc440", }, { "entropy": b"c0ba5a8e914111210f2bd131f3d5e08d", "mnemonic": "scheme spot photo card baby mountain device kick cradle pact join borrow", "seed": b"ea725895aaae8d4c1cf682c1bfd2d358d52ed9f0f0591131b559e2724bb234fca05aa9c02c57407e04ee9dc3b454aa63fbff483a8b11de949624b9f1831a9612", }, { "entropy": b"6d9be1ee6ebd27a258115aad99b7317b9c8d28b6d76431c3", "mnemonic": "horn tenant knee talent sponsor spell gate clip pulse soap slush warm silver nephew swap uncle crack brave", "seed": b"fd579828af3da1d32544ce4db5c73d53fc8acc4ddb1e3b251a31179cdb71e853c56d2fcb11aed39898ce6c34b10b5382772db8796e52837b54468aeb312cfc3d", }, { "entropy": b"9f6a2878b2520799a44ef18bc7df394e7061a224d2c33cd015b157d746869863", "mnemonic": "panda eyebrow bullet gorilla call smoke muffin taste mesh discover soft ostrich alcohol speed nation flash devote level hobby quick inner drive ghost inside", "seed": b"72be8e052fc4919d2adf28d5306b5474b0069df35b02303de8c1729c9538dbb6fc2d731d5f832193cd9fb6aeecbc469594a70e3dd50811b5067f3b88b28c3e8d", }, { "entropy": b"23db8160a31d3e0dca3688ed941adbf3", "mnemonic": "cat swing flag economy stadium alone churn speed unique patch report train", "seed": b"deb5f45449e615feff5640f2e49f933ff51895de3b4381832b3139941c57b59205a42480c52175b6efcffaa58a2503887c1e8b363a707256bdd2b587b46541f5", }, { "entropy": b"8197a4a47f0425faeaa69deebc05ca29c0a5b5cc76ceacc0", "mnemonic": "light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud access", "seed": b"4cbdff1ca2db800fd61cae72a57475fdc6bab03e441fd63f96dabd1f183ef5b782925f00105f318309a7e9c3ea6967c7801e46c8a58082674c860a37b93eda02", }, { "entropy": b"066dca1a2bb7e8a1db2832148ce9933eea0f3ac9548d793112d9a95c9407efad", "mnemonic": "all hour make first leader extend hole alien behind guard gospel lava path output census museum junior mass reopen famous sing advance salt reform", "seed": b"26e975ec644423f4a4c4f4215ef09b4bd7ef924e85d1d17c4cf3f136c2863cf6df0a475045652c57eb5fb41513ca2a2d67722b77e954b4b3fc11f7590449191d", }, { "entropy": b"f30f8c1da665478f49b001d94c5fc452", "mnemonic": "vessel ladder alter error federal sibling chat ability sun glass valve picture", "seed": b"2aaa9242daafcee6aa9d7269f17d4efe271e1b9a529178d7dc139cd18747090bf9d60295d0ce74309a78852a9caadf0af48aae1c6253839624076224374bc63f", }, { "entropy": b"c10ec20dc3cd9f652c7fac2f1230f7a3c828389a14392f05", "mnemonic": "scissors invite lock maple supreme raw rapid void congress muscle digital elegant little brisk hair mango congress clump", "seed": b"7b4a10be9d98e6cba265566db7f136718e1398c71cb581e1b2f464cac1ceedf4f3e274dc270003c670ad8d02c4558b2f8e39edea2775c9e232c7cb798b069e88", }, { "entropy": b"f585c11aec520db57dd353c69554b21a89b20fb0650966fa0a9d6f74fd989d8f", "mnemonic": "void come effort suffer camp survey warrior heavy shoot primary clutch crush open amazing screen patrol group space point ten exist slush involve unfold", "seed": b"01f5bced59dec48e362f2c45b5de68b9fd6c92c6634f44d6d40aab69056506f0e35524a518034ddc1192e1dacd32c1ed3eaa3c3b131c88ed8e7e54c49a5d0998", }, # # Different languages (generated and checked with other tools) # # Italian { "entropy": b"1f3816778bbb384fa7dab64f593ec7df", "mnemonic": "bosco sarto perplesso baccano ribadire cassone piacere frassino favoloso seme replica sagoma", "seed": b"332e7e798088280ae79534de319252f6f8ed357ee7dc1c2aa674cb46546184f25367c9cd1bedbf6a10b8ba2306a33dc13828c8629967e1bd26a952545b769969", "lang": Bip39Languages.ITALIAN, }, { "entropy": b"e12e14deab85bcbafc561e44d50f96d71357aa08b1251a8abe392fa1e560465d", "mnemonic": "svolta lentezza davvero freccetta gatto gergo unitario scambiare eluso pretesto tesserato ramingo cuculo solvente bussola campale bava foro odierno giurato bisturi recinto barca rinnovo", "seed": b"79558674b80227b7ec92567744cbbf91fd97ec26bf266d1b3defd2304ffce4ad4e11acc072ecf5e820cb8211f399ac2584e15e3ee8b580e7abe8171b451f8a81", "lang": Bip39Languages.ITALIAN, }, # French { "entropy": b"c4cf0ca40669a21673d3419b9bce0489", "mnemonic": "pupitre hangar capable anaphore mérite ambigu revivre fixer miette sodium inexact asticot", "seed": b"73bc4755506335d59cc7ffd493465a16e09a0cce83dcde8b0d2a96b171ec1e05ceea2886f63936b7229ccb90c464ca58ebc2b024ec0d5505fe7b0d1ec2bdf419", "lang": Bip39Languages.FRENCH, }, { "entropy": b"639b3b85d452eaa61ddeeebb7699792483c9b75d0020311d0002e2b13bf0ed01", "mnemonic": "fatigue semaine souvenir obliger chausson encoche guitare sismique plateau peigne éviter donjon cuisine sésame gouffre acompte cigare tarif aborder querelle astre venimeux patience cascade", "seed": b"02440d6ea198766fe10c7e5a532fcbe231024bb09ad3dd4665dcbd3427911228e6f1ebce9e21b26172e0a4cd172a37bdc41cdc26c9f6dd97e91c0cdfc5e0fa11", "lang": Bip39Languages.FRENCH, }, # Spanish { "entropy": b"72754293ddabb5286e683ab657636637", "mnemonic": "inerte panal órbita proa proa mover potro ajeno pleno prisión sodio humilde", "seed": b"fb88d495839e5a0a9f03048349e016cd0d2f1add2625da9911b5679c0927ebe364470c0675af47c46ccf94dc2e243d62c00e1c5687144177f37cf30ec356fb7d", "lang": Bip39Languages.SPANISH, }, { "entropy": b"0a7a0e7056dd570d3031f11c1f77b6be79d65794263344e11e1e3c11c7fd1886", "mnemonic": "alto sagrado nota peatón señal maldad radical curar barco visor trauma legión nueve carro esquí reloj disco alfiler mando júpiter báscula yeso gastar rígido", "seed": b"b1f69660a6defbee34a85dce645858da424e5c481f9b61ec9758fbd5d986ca95eb790f0fd0878356c7f79d3b85ca030d45e85fe680987429f27b8d2fde3e41a6", "lang": Bip39Languages.SPANISH, }, # Portuguese { "entropy": b"502f2e4fdebd715a7b04f3fd28069e50", "mnemonic": "dominado guaxinim lotado piscar sadio olaria tinteiro mexer voador cortejo neural moita", "seed": b"7fa6942c80ac82e1fbbd8bfcd1d71a9a3a7fdd8c76a6631c8bc1adf84af75364267ec7e63e8b2e922e4f8a89041f0293490374b0999921385503148eeb8df8cd", "lang": Bip39Languages.PORTUGUESE, }, { "entropy": b"e1257e7d2c2d5d13f69ba62693e7c4efd4e4084f2747af3a6a5e6c316ce24e62", "mnemonic": "soprano cacau milhar enquanto rugido juiz secar girino bocado milenar trilogia socorro discreta aclamar coluna teclado orar robalo manada saltar arroba garimpo clareza esgrima", "seed": b"06bcf33e49ba7055bf2c405e2921b76ecc9348998612fb383ab294c87d0791bdfc6451091ff29642bdb2cdffa90cf478e731223f42ca5f9c06777ea6a7c25e33", "lang": Bip39Languages.PORTUGUESE, }, # Czech { "entropy": b"0cc43525e0289632d208c4b45b0d912c", "mnemonic": "branka dorost klam slanina omezit cuketa kazeta cizost rozchod tvaroh majetek kyvadlo", "seed": b"6f34c0375358ff4188cf884e8dbb3b45738afe9fd7389b700f3bad4781c6e36db657f748d5a10abb8d30f36a0f067401453eb75cb8e9758394b53d74448b7932", "lang": Bip39Languages.CZECH, }, { "entropy": b"13c1b202721c14e9390b093dec53ce898028be41a8be10d83178b2139d331731", "mnemonic": "chichot bronz obvinit vidle slina naposled vidle lomcovat invalida lstivost zamezit chalupa astma lihovina bazilika cinkot bzukot slon letokruh mahagon hrnek plevel lehce facka", "seed": b"b1c4419f57696d40e6a764490ba62a1eb3722c5aa3636a168700a624fff6420ba10277d4c0d8a0989126af30bd939cce8acd7bd305f9d6757377fd8fbdae446a", "lang": Bip39Languages.CZECH, }, # Chinese (simplified) { "entropy": b"4af203a39228787182365db8625ef85c", "mnemonic": "犯 宝 亭 术 圈 斯 度 鸭 允 但 荒 兼", "seed": b"873a8af2f9a181e6006f5b47b76d90668edd217271276dcc42e09aeed410f9c3037861e8f45d7fd977dd47b27ff59cb99f69464af34db0696979b2cab60f6641", "lang": Bip39Languages.CHINESE_SIMPLIFIED, }, { "entropy": b"c728f71b2169073ff18c0a7cc13b7dcc026ed301afd0f0b359ae9db27e41d45d", "mnemonic": "竞 爱 洛 李 闻 冰 瓷 敢 归 高 胀 嘴 切 伯 后 嫂 浩 臣 乐 京 场 光 跑 碧", "seed": b"e31b8769b7e95b703f18d51f0dbb02d160f66d0736e9c450491402b3f86a02947ad1cc26695dfa96146ab0f709ba0df581d52289fbdca8b0e0df94e9ef33e9d6", "lang": Bip39Languages.CHINESE_SIMPLIFIED, }, # Chinese (traditional) { "entropy": b"3546f07366d9451fff7e90ec48a48ad6", "mnemonic": "酸 劃 別 冒 耕 頓 餓 輔 烷 另 東 幸", "seed": b"d863e03468ee820d51bb2d3965c4ec6788343811a3de88b962aa924ac3c8e329204d865540757e9b5884bc1f8c99c2a266992e764cb4cadb6ef6f55dfa86a7b4", "lang": Bip39Languages.CHINESE_TRADITIONAL, }, { "entropy": b"5c44ac4fcb2bf886df37a5391dac7b08bd19610c700580663462146b7557b14f", "mnemonic": "衛 權 變 煉 簽 輪 歸 纜 查 撒 西 正 錫 獎 連 了 腦 驗 入 萬 仲 窮 迷 漂", "seed": b"d817a3dcf7365911d7eb7a28f3cd6c833462100cbfc4f3db3b54beb03ed13170bb7f990f2589c8ab0fb4aaf5a561a4544556f5260a0ecedf252c4c42861f11a0", "lang": Bip39Languages.CHINESE_TRADITIONAL, }, # Korean { "entropy": b"7cf050d2a257004f26decf7d100c1ffd", "mnemonic": "신규 아시아 동화책 민주 솔직히 넥타이 요금 출입 신념 실험 거품 환영", "seed": b"64e91f1ca49a1463905da6ec21a00b44c24f6fc3b6ce9ec18a1f277f6f17f01ecd70c29ac20751f50eea954d62e74616178cf10a18dd3d5aa767fcad2cd15f9a", "lang": Bip39Languages.KOREAN, }, { "entropy": b"2e59cfc5e2466699703543185fdad758bf0095146d8616eeb53fb935b977c7d9", "mnemonic": "담임 짜증 한여름 주말 서적 백색 제출 이틀 국가 흑인 재산 작업 한꺼번에 방면 보름 자존심 구름 스스로 변명 수업 비용 점수 기념 대합실", "seed": b"6f76a73fb8d7124e5b893fa752df2fa9f1cca7178524f9f8ca2f7c2674c6967eb5772f8b7645b45d9a0ecff2ff039582b31614e32603e395c6b33b3736c1cc7e", "lang": Bip39Languages.KOREAN, }, ] # Tests passphrase TEST_PASSPHRASE = "TREZOR" # Tests for valid entropy bit lengths TEST_VECT_ENTROPY_BITLEN_VALID = [ Bip39EntropyBitLen.BIT_LEN_128, Bip39EntropyBitLen.BIT_LEN_160, Bip39EntropyBitLen.BIT_LEN_192, Bip39EntropyBitLen.BIT_LEN_224, Bip39EntropyBitLen.BIT_LEN_256, ] # Tests for invalid entropy bit lengths TEST_VECT_ENTROPY_BITLEN_INVALID = [ 127, 129, 159, 161, 191, 193, 223, 225, 255, 257, ] # Tests for valid words number TEST_VECT_WORDS_NUM_VALID = [ Bip39WordsNum.WORDS_NUM_12, Bip39WordsNum.WORDS_NUM_15, Bip39WordsNum.WORDS_NUM_18, Bip39WordsNum.WORDS_NUM_21, Bip39WordsNum.WORDS_NUM_24, ] # Tests for invalid words number TEST_VECT_WORDS_NUM_INVALID = [ 11, 13, 17, 19, 20, 22, 23, 25, ] # Tests for invalid mnemonics TEST_VECT_MNEMONIC_INVALID = [ # Wrong length { "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon", "exception": ValueError, }, # Wrong checksum { "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon any", "exception": Bip39ChecksumError, }, # Not existent word { "mnemonic": "abandon abandon abandon notexistent abandon abandon abandon abandon abandon abandon abandon about", "exception": ValueError, }, # Wrong language { "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "lang": Bip39Languages.ITALIAN, "exception": ValueError, }, ] # # Tests # class Bip39Tests(unittest.TestCase): # Run all tests in test vector def test_vector(self): for test in TEST_VECT: lang = test["lang"] if "lang" in test else Bip39Languages.ENGLISH # Test mnemonic generator mnemonic = Bip39MnemonicGenerator(lang).FromEntropy(binascii.unhexlify(test["entropy"])) self.assertEqual(test["mnemonic"], mnemonic) # Test mnemonic validator using string (language specified) bip39_mnemonic_validator = Bip39MnemonicValidator(mnemonic, lang) entropy = bip39_mnemonic_validator.GetEntropy() self.assertEqual(test["entropy"], binascii.hexlify(entropy)) self.assertTrue(bip39_mnemonic_validator.IsValid()) # Test mnemonic validator using list (automatic language detection) bip39_mnemonic_validator = Bip39MnemonicValidator(Bip39Utils.MnemonicToList(mnemonic)) entropy = bip39_mnemonic_validator.GetEntropy() self.assertEqual(test["entropy"], binascii.hexlify(entropy)) self.assertTrue(bip39_mnemonic_validator.IsValid()) # Test seed generator using string seed = Bip39SeedGenerator(mnemonic, lang).Generate(TEST_PASSPHRASE) self.assertEqual(test["seed"], binascii.hexlify(seed)) # Test seed generator using list seed = Bip39SeedGenerator(Bip39Utils.MnemonicToList(mnemonic), lang).Generate(TEST_PASSPHRASE) self.assertEqual(test["seed"], binascii.hexlify(seed)) # Test entropy generator and construction from valid entropy bit lengths def test_entropy_valid_bitlen(self): for test_bit_len in TEST_VECT_ENTROPY_BITLEN_VALID: # Test generator entropy = Bip39EntropyGenerator(test_bit_len).Generate() self.assertEqual(len(entropy), test_bit_len // 8) # Generate mnemonic mnemonic = Bip39MnemonicGenerator().FromEntropy(entropy) # Compute the expected mnemonic length mnemonic_len = (test_bit_len + (test_bit_len // 32)) // 11 # Test generated mnemonic length self.assertEqual(len(Bip39Utils.MnemonicToList(mnemonic)), mnemonic_len) # Test entropy generator and construction from invalid entropy bit lengths def test_entropy_invalid_bitlen(self): for test_bit_len in TEST_VECT_ENTROPY_BITLEN_INVALID: self.assertRaises(ValueError, Bip39EntropyGenerator, test_bit_len) # Build a dummy entropy with that bit length # Subtract 8 because, otherwise, dividing by 8 could result in a correct byte length dummy_ent = b"\x00" * ((test_bit_len - 8) // 8) # Construct from it self.assertRaises(ValueError, Bip39MnemonicGenerator().FromEntropy, dummy_ent) # Test construction from valid words number def test_from_valid_words_num(self): for test_words_num in TEST_VECT_WORDS_NUM_VALID: mnemonic = Bip39MnemonicGenerator().FromWordsNumber(test_words_num) self.assertEqual(len(Bip39Utils.MnemonicToList(mnemonic)), test_words_num) # Test construction from invalid words number def test_from_invalid_words_num(self): for test_words_num in TEST_VECT_WORDS_NUM_INVALID: self.assertRaises(ValueError, Bip39MnemonicGenerator().FromWordsNumber, test_words_num) # Tests invalid mnemonic def test_invalid_mnemonic(self): for test in TEST_VECT_MNEMONIC_INVALID: lang = test["lang"] if "lang" in test else Bip39Languages.ENGLISH self.assertFalse(Bip39MnemonicValidator(test["mnemonic"], lang).IsValid()) self.assertRaises(test["exception"], Bip39MnemonicValidator(test["mnemonic"], lang).Validate) self.assertRaises(test["exception"], Bip39MnemonicValidator(test["mnemonic"], lang).GetEntropy) self.assertRaises(test["exception"], Bip39SeedGenerator, test["mnemonic"], lang) # Tests invalid parameters def test_invalid_params(self): self.assertRaises(TypeError, Bip39MnemonicGenerator, 0) self.assertRaises(TypeError, Bip39MnemonicValidator, "", 0) self.assertRaises(TypeError, Bip39MnemonicValidator, 123) self.assertRaises(TypeError, Bip39SeedGenerator, 123)
52.761905
213
0.754513
1,925
23,268
8.983896
0.438961
0.06962
0.094715
0.113334
0.175032
0.158494
0.139297
0.134902
0.124031
0.124031
0
0.245178
0.17999
23,268
440
214
52.881818
0.668134
0.101857
0
0.09697
0
0.048485
0.616907
0.338136
0
0
0
0
0.063636
1
0.021212
false
0.009091
0.012121
0
0.036364
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
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
36d6f6617d88166e39534db093750184b69e750b
1,977
py
Python
coords/pos_xy.py
mlabru/coords
8a00d42effa827768f708764c9c8263745ca9b15
[ "CC0-1.0" ]
null
null
null
coords/pos_xy.py
mlabru/coords
8a00d42effa827768f708764c9c8263745ca9b15
[ "CC0-1.0" ]
null
null
null
coords/pos_xy.py
mlabru/coords
8a00d42effa827768f708764c9c8263745ca9b15
[ "CC0-1.0" ]
null
null
null
# -*- coding: utf-8 -*- """ pos_xy. DOCUMENT ME! 2015.nov 0.2 mlabru pep8 style conventions 2014.nov 0.1 mlabru initial version (Linux/Python) """ # < imports >---------------------------------------------------------------------------------- # python library import logging # local import coords.coord_defs as cdf # < logging >---------------------------------------------------------------------------------- # logger M_LOG = logging.getLogger(__name__) M_LOG.setLevel(cdf.DI_LOG_LEVEL) # < CPosXY >----------------------------------------------------------------------------------- class CPosXY: """ DOCUMENT ME! """ # ----------------------------------------------------------------------------------------- def __init__(self, ff_x=0., ff_y=0.): """ constructor """ # logger M_LOG.info(">> constructor") # check input # assert f_control # init super classe super(CPosXY, self).__init__() self.__f_x = ff_x M_LOG.debug("self._f_x:[%f]" % self.__f_x) self.__f_y = ff_y M_LOG.debug("self._f_y:[%f]" % self.__f_y) # ========================================================================================= # data # ========================================================================================= # ----------------------------------------------------------------------------------------- @property def f_x(self): """X.""" return self.__f_x @f_x.setter def f_x(self, f_val): """X.""" self.__f_x = f_val # ----------------------------------------------------------------------------------------- @property def f_y(self): """Y.""" return self.__f_y @f_y.setter def f_y(self, f_val): """Y.""" self.__f_y = f_val # < the end >----------------------------------------------------------------------------------
25.675325
95
0.316641
165
1,977
3.406061
0.387879
0.106762
0.053381
0.037367
0.049822
0
0
0
0
0
0
0.010152
0.202833
1,977
76
96
26.013158
0.346447
0.553364
0
0.083333
0
0
0.0525
0
0
0
0
0
0
1
0.208333
false
0
0.083333
0
0.416667
0
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
1
0
0
0
0
0
0
0
2
36d98648a0c36bd93bf3b48ca406dee51349fcc6
824
py
Python
authentication/auth.py
morfat/djangorest_start
093b6ea878ec51bfc10b99f0801f989d09bc3f88
[ "MIT" ]
1
2017-01-27T13:24:57.000Z
2017-01-27T13:24:57.000Z
authentication/auth.py
morfat/djangorest_start
093b6ea878ec51bfc10b99f0801f989d09bc3f88
[ "MIT" ]
null
null
null
authentication/auth.py
morfat/djangorest_start
093b6ea878ec51bfc10b99f0801f989d09bc3f88
[ "MIT" ]
null
null
null
from users.models import User class CustomBackend(object): """authenticate when given email,phone number or secret key and password """ def get_by_email(self,email,password): try: user = User.objects.get(email=email) if password: if user.check_password(password): return user else: return user except User.DoesNotExist: pass def authenticate(self, email=None, password=None, **kwargs): if email: return self.get_by_email(email, password) return None def get_user(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: return None
23.542857
80
0.525485
85
824
5.023529
0.411765
0.070258
0.046838
0
0
0
0
0
0
0
0
0
0.404126
824
35
81
23.542857
0.869654
0.083738
0
0.380952
0
0
0
0
0
0
0
0
0
1
0.142857
false
0.285714
0.047619
0
0.52381
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
36e3d4c70fb343840a68e8f08b71b963f4d78eff
36,213
py
Python
src/main/Client.py
jhmvin/SimpleChatClient
6f59d3f7e69b35d91256892bf1c7ae92032697d6
[ "MIT" ]
null
null
null
src/main/Client.py
jhmvin/SimpleChatClient
6f59d3f7e69b35d91256892bf1c7ae92032697d6
[ "MIT" ]
null
null
null
src/main/Client.py
jhmvin/SimpleChatClient
6f59d3f7e69b35d91256892bf1c7ae92032697d6
[ "MIT" ]
null
null
null
#**************************** #* IMPORTS * #**************************** from Tkinter import * import tkMessageBox from socket import* import threading import json from time import sleep import unicodedata from pip.cmdoptions import editable try: import tkinter.ttk as ttk except ImportError: import Tkinter as tk import ttk import atexit import sys ''' CLASS DECLARATIONS -------------------------------------- ''' ''' TIME ZONE MANAGER -------------------------------------- ''' from datetime import datetime,tzinfo,timedelta class Zone(tzinfo): def __init__(self,offset,isdst,name): self.offset = offset self.isdst = isdst self.name = name def utcoffset(self, dt): return timedelta(hours=self.offset) + self.dst(dt) def dst(self, dt): return timedelta(hours=1) if self.isdst else timedelta(0) def tzname(self,dt): return self.name pass #end of zone #EST = Zone(-5,False,'EST') #print datetime.utcnow().strftime('%m/%d/%Y %H:%M:%S %Z') ''' GMT = Zone(8,False,'GMT') print datetime.now(GMT).strftime('%m/%d/%Y %I:%M:%S %p') ''' #print datetime.now(EST).strftime('%m/%d/%Y %H:%M:%S %Z') #t = datetime.strptime('2011-01-21 02:37:21','%Y-%m-%d %H:%M:%S') #t = t.replace(tzinfo=GMT) #print t #print t.astimezone(EST) ''' MONOCLIENT SERVER CONNECTIVITY -------------------------------------- ''' class MonoClient(): def __init__(self): #self.mime_result = {'type':'null','result':'null'} self.HOST = '127.0.0.1' #'192.168.15.4' self.PORT = 2224 try: self.mono_socket = socket(AF_INET, SOCK_STREAM) self.mono_socket.connect((self.HOST,self.PORT)) except: self.showInfoMsg("Server Information","Server is unreachable. Please try again.") print "Server is unreachable" pass #self.graph = GUI() pass #end of construct def send_request(self,request): try: data_json = json.dumps(request, ensure_ascii=False).encode('utf-8') self.mono_socket.send(data_json) return self.mono_socket.recv(131072) except Exception as e: print e return "-143" # cannot reach the server pass # end request pass # end of class #**************************** #* MAIN * #**************************** ''' CLASS GUI --------------------------------------------------------------- ''' class GUI(): def __init__(self): self.client = MonoClient() self.broadcast_reciever = threading.Thread(target=self.fetch_broadcast) self.client_lister = threading.Thread(target=self.fetch_clients) self.graphics_render = threading.Thread(target=self.showLoginForm) self.messenger = threading.Thread(target=self.fetch_messages) self.private_records = [] print "BROADCAST SET" self.auth_user = "USER" self.GMT = Zone(8,False,'GMT') # +8 GMT ASIA TAIPEI print datetime.now(self.GMT).strftime('%m/%d/%Y %I:%M:%S %p') self.fetch_message_block = 1 # infinite loop all codes below will not be called #self.showLoginForm() self.graphics_render.start() #self.rcv_brod = 0 #self.broadcast_reciever.start() pass # end init def showErrorMsg(self,title,message): window = Tk() window.wm_withdraw() window.geometry("3x2+200+200") tkMessageBox.showerror(title=title,message=message,parent=window) def showInfoMsg(self,title,msg): window = Tk() window.wm_withdraw() window.geometry("3x2+"+str(window.winfo_screenwidth()/2)+"+"+str(window.winfo_screenheight()/2)) tkMessageBox.showinfo(title=title, message=msg) def authenticate(self): request = {} request['type'] = 'LOGIN' global text_font text_font = ('Calibri', '12') request['username'] = self.txt_user.get() request['password'] = self.txt_password.get() data = self.client.send_request(request) response = json.loads(data) res = response['result'] if(res == "0"): self.showErrorMsg("Account Error","Account not found.") print "Account Not Existing" elif(res == "-1"): self.showErrorMsg("Account Error","Incorrect password.") print "Wrong Password" elif(res == "2"): self.showInfoMsg("Account Information","Account is already online. Please use another account.") print "Account is already online" elif(res == "3"): self.showErrorMsg("Account Error","Maximum client reached. Try again later.") print "MAX CLIENT REACHED" elif(res == "1"): self.showInfoMsg("Account Information","Successfully Logged in!") print "Login Success" self.auth_user = self.txt_user.get() self.frm_login.destroy() self.rcv_brod = 1 self.showMainForm() else: self.showErrorMsg("Unknown Error","An error occured. Try again.") print "An Error Occured" pass def register(self): request = {} request['type'] = 'REGISTER' request['username'] = self.reg_username.get() request['password'] = self.reg_password.get() data = self.client.send_request(request) response = json.loads(data) res = response['result'] if(res == "-1"): self.showInfoMsg("Account Information","Account already exists.") print "Account Already Exists" elif(res == "1"): self.showInfoMsg("Account Information","Account created.") print "Account Created" self.frm_register.destroy() self.showLoginForm() else: self.showErrorMsg("Unknown Error","An error occured. Try again.") print "An Error Occured" self.frm_register.destroy() pass def verifyPass(self): username = self.reg_username.get() passwrd = self.reg_password.get() reenter = self.reg_confirm.get() if(username==""): self.showInfoMsg("Account Information","Please enter your username.") elif(passwrd==""): self.showInfoMsg("Account Information","Please enter your password.") elif(reenter==""): self.showInfoMsg("Account Information","Please re-enter your password.") elif(passwrd==reenter): self.fromRegToLogin() else: self.showErrorMsg("Account Error","Password not matched.") pass def broadcast(self,event): msg = self.msgBox.get("1.0",END) print "msg here: ", msg bad_words = ['fuck', 'bitch', 'shit', 'damn', 'piss', 'asshole', 'slut', 'tangina', 'puta', 'gago', 'hudas', 'lintik', 'ulol', 'tarantado', 'buwisit', 'burat', 'kupal', 'leche', 'ungas', 'punyeta', 'hinayupak', 'pucha', 'pesteng yawa', 'pakshet', 'tanga'] index=0 ctr=0 while 1: if(index==len(bad_words)): break if(bad_words[index] in msg.lower()): ctr=1 break index+=1 if ctr==1: self.showErrorMsg("Content Error","Please avoid bad or foul words.") else: msg_nrm = unicodedata.normalize('NFKD', msg).encode('ascii','ignore').strip() request = {} request['type'] = 'BROADCAST' request['sender'] = self.auth_user request['content'] = msg_nrm request['send_date'] = datetime.now(self.GMT).strftime('%m/%d/%Y %I:%M:%S %p') while(1==1): try: data = self.client.send_request(request) response = json.loads(data) except: self.showInfoMsg("Message Information","Retrying to send message.") print "Retrying to send" sleep(0.5) continue pass break try: if(response['type'] == "BROADCAST"): print response self.msgBox.delete("0.0",END) except Exception as e: print e #self.fetch_broadcast() pass # end of broadcast def fetch_messages(self): request = {} request['type'] = 'FETCH_PRIVATE' while self.fetch_message_block==1: # ok while 1==1: # ok try: data = self.client.send_request(request) response = json.loads(data) except Exception as e: print "Retrieving Messages: ",e sleep(0.5) continue pass break pass # end loop if(response['type'] == "FETCH_PRIVATE"): #print try: self.private_records = [] msg_counter = 0 while(msg_counter<(len(response)-1)): line = response[str(msg_counter)] arrange_me = json.loads(line) msg_counter+=1 self.private_records.append(arrange_me) pass #print 'CHATBOX REFRESHED' except: self.showErrorMsg("Message Error","Cannot retrieve private messages.") print "CANNOT RETRIEVED PRIVATE MESSAGES" break pass pass # end of if sleep(2) pass # end of infinite loop pass # end fetch # this function refreshes the message box def fetch_broadcast(self): request = {} request['type'] = 'FETCH_BROADCAST' while 1==1: # ok sleep(1) while 1==1: # ok try: data = self.client.send_request(request) response = json.loads(data) except Exception as e: print "Retrieving Messages: ",e sleep(0.5) continue pass break pass # end loop if(response['type'] == "FETCH_BROADCAST"): #print msg_counter = 0 public_message_string = "" #message loop while(msg_counter<(len(response)-1)): line = response[str(msg_counter)] arrange_me = json.loads(line) msg_counter+=1 public_message_string += (arrange_me['send_date'] +" >>> [ "+arrange_me['sender'] + " ] : " +arrange_me['content'] + "\n") pass # end of message loop try: self.publicList.configure(state='normal') self.publicList.delete('1.0', END) self.publicList.insert(END, public_message_string) self.publicList.see(END) self.publicList.configure(state='disabled') #print 'CHATBOX REFRESHED' except: self.showErrorMsg("Message Error","Cannot retrieve messages.") print "CANNOT RETRIEVED MESSAGES" break pass pass # end of if pass # end of infinite loop pass # end fetch def listClick(self,evt): try: selected_index = self.clientList.curselection() select_string = self.clientList.get(selected_index) st,name = select_string.split("-") self.showPrivateMsgForm(name.strip()) except: print "BAD INDEX at 255" pass pass def fetch_clients(self): request = {} request['type'] = 'FETCH_CLIENTS' while 1==1: # ok sleep(2) while 1==1: # ok try: data = self.client.send_request(request) response = json.loads(data) except Exception as e: print "Retrieving CLIENTS: ",e sleep(0.5) continue pass break pass # end loop if(response['type'] == "FETCH_CLIENTS"): #print try: self.publicList.configure(state='disabled') #-0---------------Populate online client user_count = (len(response) - 1) self.clientList.delete(0,END) x = 0 while(x < user_count): user_item = response[str(x)] user_state = "[ " + user_item['state'] + " ] - " + user_item['username'] self.clientList.insert(END,user_state) x+=1 pass #--------------------------------------- pass #print 'CHATBOX REFRESHED' except: self.showErrorMsg("Account Error","Cannot retrieve client list.") print "CANNOT RETRIEVED CLIENT LIST" break pass pass # end of if pass # end of infinite loop pass # end fetch def change_pass(self,old_pass,new_pass): request = {} if(old_pass.get()==""): self.showInfoMsg("Acount Information", "Please enter your old password.") return 0 elif(new_pass.get() == ""): self.showInfoMsg("Account Information", "Please enter a valid new password.") return 0 elif(new_pass.get() != self.change_confirm_pass.get()): self.showErrorMsg("Account Error", "New password not matched.") return 0 request['type'] = 'CHANGE_PASS' request['user'] = self.auth_user request['old_pass'] = old_pass.get() request['new_pass'] = new_pass.get() data = self.client.send_request(request) response = json.loads(data) res = response['result'] if(res=="-1"): self.showErrorMsg("Acount Error","Old password not matched.") elif(res=="1"): self.showInfoMsg("Account Information", "Password sucessfully changed.") print res pass def logout(self): self.frm_public.destroy() exit() pass def change_profile(self): self.showInfoMsg("Application Information","No available process.") def change_font(self, event): global combo_box print combo_box.get() font = combo_box.get() if(font=="Arial Black"): self.publicList.configure(height=22) text_font = (font,'9') elif(font=="Cambria"): self.publicList.configure(width=70) self.publicList.configure(height=25) text_font = (font,'10') elif(font=="Arial"): self.publicList.configure(width=70) self.publicList.configure(height=25) text_font = (font,'9') else: self.publicList.configure(height=20) text_font = (font,'12') print text_font self.publicList.configure(font=text_font) self.clientList.configure(font=text_font) self.msgBox.configure(font=text_font) def btn_pm(self): self.showInfoMsg("Application Information","Double click the user you want to send private message.") #**************************************************** # THEMES #**************************************************** def theme1(self): self.frm_public.configure(background='dodgerblue2') print "theme1" pass def theme2(self): self.frm_public.configure(background='springgreen2') print "theme2" pass def theme3(self): self.frm_public.configure(background='midnight blue') print "theme3" pass def theme4(self): self.frm_public.configure(background='dark slate gray') print "theme4" pass def theme5(self): self.frm_public.configure(background='Coral') print "theme5" pass def default(self): self.frm_public.configure(background='white smoke') print "default" pass ''' ------------------------------------------------------------------------------------------------------ UI MODULE ------------------------------------------------------------------------------------------------------ ''' def showLoginForm(self): #createWindow("Login", "350x400+100+200") self.frm_login = Tk() self.frm_login.geometry("430x430+"+str((430/2)+(430/2))+"+"+str(430/2-70)) self.frm_login.title("Login") self.frm_login.resizable(width="false", height="false") #self.frm_login.geometry("430x430+100+200") lbl1 = Label(self.frm_login, text="Login", width=10, height=3, fg="#1A4AA0", font="Calibri 19") lbl1.pack(side=TOP) usernameFrame = Frame(self.frm_login) usernameFrame.pack() lbl2 = Label(usernameFrame, text="Username:", width=10, fg="#1A4AA0", font="Calibri 14") lbl2.pack(side=LEFT) self.txt_user = Entry(usernameFrame, fg="#1A4AA0", font="Calibri 14") self.txt_user.pack(side=LEFT) passFrame = Frame(self.frm_login) passFrame.pack() lbl3 = Label(passFrame, text="Password:", width=10, height=3, fg="#1A4AA0", font="Calibri 14") lbl3.pack(side=LEFT) self.txt_password = Entry(passFrame, show="*", fg="#1A4AA0", font="Calibri 14") self.txt_password.pack(side=LEFT) buttonFrame = Frame(self.frm_login) buttonFrame.pack(side=RIGHT, padx=25) btnLogin = Button(buttonFrame, text="Login", height=1, width=12, command=self.authenticate, fg="#F0F0F0", bg="#2A3540", font="Calibri 14") btnLogin.pack(pady=5) btnRegister = Button(buttonFrame, text="Register", height=1, width=12, command=self.showRegisterForm, fg="#F0F0F0", bg="#2A3540", font="Calibri 14") btnRegister.pack(pady=5) btnSettings = Button(buttonFrame, text="Connection Settings", height=2, width=17, command=self.showConnectionForm, fg="#F0F0F0", bg="#2A3540", font="Calibri 10") #btnSettings.pack(pady=5) self.frm_login.mainloop() def showConnectionForm(self): con_set = Tk() con_set.title("Connection Settings") con_set.resizable(width="false", height="false") con_set.geometry("430x430+"+str((430/2)+(430/2))+"+"+str(380/2)) #con_set.geometry("430x430+100+200") frm1 = Frame(con_set) frm1.pack(pady=15, padx=10) lbl2 = Label(frm1, text="Server IP:", width=8, fg="#1A4AA0", font="Calibri 14") lbl2.pack(side=LEFT) entry1 = Entry(frm1, fg="#1A4AA0", font="Calibri 14") entry1.pack(side=LEFT) frm2 = Frame(con_set) frm2.pack() lbl3 = Label(frm2, text="Port:", width=8, height=3, fg="#1A4AA0", font="Calibri 14") lbl3.pack(side=LEFT) entry2 = Entry(frm2, fg="#1A4AA0", font="Calibri 14") entry2.pack(side=LEFT) buttonFrame = Frame(con_set) buttonFrame.pack(fill=BOTH) btnSubmit = Button(buttonFrame, text="Submit", height=1, width=12, command=self.authenticate, fg="#F0F0F0", bg="#2A3540", font="Calibri 14") btnSubmit.pack(pady=5) frm3 = Frame(con_set) frm3.pack(fill=BOTH) lbl3 = Label(frm3, text="Result:", width=8, height=1, fg="#1A4AA0", font="Calibri 14") lbl3.pack(side=LEFT, padx=48) frm4 = Frame(con_set) frm4.pack(fill=BOTH) con_list = Listbox(frm4, relief=SUNKEN, width=37, height=10, font="Calibri 12") con_list.pack(pady=2, padx=5) ''' REGISTRATION ''' def showRegisterForm(self): self.frm_login.destroy() #destroy the login self.frm_register = Tk() self.frm_register.title("Register") self.frm_register.resizable(width="false", height="false") self.frm_register.geometry("430x430+"+str((430/2)+(430/2))+"+"+str(380/2)) #self.frm_register.geometry("430x380+100+200") frmLbl = Frame(self.frm_register) frmLbl.pack(fill=BOTH, pady=5) lbl1 = Label(frmLbl, text="Registration", width=10, height=3, fg="#1A4AA0", font="Calibri 19") lbl1.pack(side=RIGHT, padx=25) usernameFrame = Frame(self.frm_register) usernameFrame.pack() lbl2 = Label(usernameFrame, text="Username:", width=15, height=2, fg="#1A4AA0", font="Calibri 14") lbl2.pack(side=LEFT) self.reg_username = Entry(usernameFrame, fg="#1A4AA0", font="Calibri 14") self.reg_username.pack(side=LEFT) passFrame = Frame(self.frm_register) passFrame.pack() lbl3 = Label(passFrame, text="Password:", width=15, height=2, fg="#1A4AA0", font="Calibri 14") lbl3.pack(side=LEFT) self.reg_password = Entry(passFrame, show="*", fg="#1A4AA0", font="Calibri 14") self.reg_password.pack(side=LEFT) reTypePassFrame = Frame(self.frm_register) reTypePassFrame.pack() lbl3 = Label(reTypePassFrame, text="Retype-Password:", width=15, height=2, fg="#1A4AA0", font="Calibri 14") lbl3.pack(side=LEFT) self.reg_confirm = Entry(reTypePassFrame, show="*", fg="#1A4AA0", font="Calibri 14") self.reg_confirm.pack(side=LEFT) buttonFrame = Frame(self.frm_register) buttonFrame.pack(side=RIGHT, padx=30) btnRegister = Button(buttonFrame, text="Register", width=12, command=self.verifyPass, fg="#F0F0F0", bg="#2A3540", font="Calibri 14") btnRegister.pack(pady=2) btnBack = Button(buttonFrame, text="Back", width=12, command=self.btnBack, fg="#F0F0F0", bg="#2A3540", font="Calibri 14") btnBack.pack(pady=2) pass def btnBack(self): self.frm_register.destroy() self.showLoginForm() pass def fromRegToLogin(self): self.register() #self.frm_register.destroy() #self.showLoginForm() pass ''' END REGISTRATION ''' global text_font def showMainForm(self): #createWindow("Main", "1000x565+100+200") self.frm_public = Tk() self.frm_public.title("Main") self.frm_public.resizable(width="false", height="false") self.frm_public.geometry("900x565+"+str((900/2)-200)+"+"+str(565/2-200)) #self.frm_public.geometry("900x565+100+200") #MENU menu = Menu(self.frm_public) self.frm_public.config(menu=menu) subMenuFile = Menu(menu) menu.add_cascade(label="File", menu=subMenuFile) subMenuFile.add_command(label="Logout", command=self.logout) subMenuEdit = Menu(menu) menu.add_cascade(label="Edit", menu=subMenuEdit) subMenuEdit.add_command(label="Change profile", command=self.showChangePassForm) subMenuView = Menu(menu) menu.add_cascade(label="View", menu=subMenuView) subMenuView.add_command(label="Default | White Smoke", command=self.default) subMenuView.add_command(label="Theme 1 | Dodger Blue", command=self.theme1) subMenuView.add_command(label="Theme 2 | Spring Green", command=self.theme2) subMenuView.add_command(label="Theme 3 | Midnight Blue", command=self.theme3) subMenuView.add_command(label="Theme 4 | Dark Slate Gray", command=self.theme4) subMenuView.add_command(label="Theme 5 | Coral", command=self.theme5) #Public Chat Frame publicChatLogs = Frame(self.frm_public) publicChatLogs.pack(side=LEFT, padx=10, pady=5) frm1 = Frame(publicChatLogs) frm1.pack(fill=BOTH) lbl1 = Label(frm1, text="Public Chat", fg="#1A4AA0", font="Calibri 12") lbl1.pack(side=LEFT) #publicList = Listbox(publicChatLogs, relief=SUNKEN, width=50, height=18, font=text_font) self.publicList = Text (publicChatLogs, fg="#232C35", font=text_font, relief=GROOVE, height=20, width=50) # # create a Scrollbar and associate it with txt # self.publicList.pack(fill=BOTH, pady=5) frm2 = Frame(publicChatLogs) frm2.pack(fill=BOTH) global combo_box combo_box = ttk.Combobox(frm2, font=text_font) # apply font to combobox combo_box.bind("<<ComboboxSelected>>", self.change_font) combo_box.pack(side=LEFT) combo_box['values'] = ('Arial', "Arial Black", 'Calibri', 'Cambria') self.msgBox = Text (publicChatLogs, fg="#232C35", font=text_font, relief=GROOVE, height=3) self.msgBox.pack(expand=1, fill=BOTH, pady=5) btnSend = Button(publicChatLogs, text="Send", height=2, width=12, command=lambda: self.broadcast('<Return>'), fg="#F0F0F0", bg="#2A3540") btnSend.pack(side=RIGHT, pady=5) ############################################ self.frm_public.bind_all('<Return>', self.broadcast) ############################################ #Private Message Frame privateMsgFrame = Frame(self.frm_public) privateMsgFrame.pack(side=TOP, pady=8, padx=10) frm2 = Frame(privateMsgFrame) frm2.pack(fill=BOTH) lbl2 = Label(frm2, text="Connected Clients:", fg="#1A4AA0", font="Calibri 12") lbl2.pack(side=LEFT) #---------------------------------------------------------------------------- self.clientList = Listbox(privateMsgFrame, relief=SUNKEN, width=45, height=22, font=text_font) self.clientList.pack(pady=5) self.clientList.bind('<Double-Button-1>',self.listClick) btnPrivateMsg = Button(privateMsgFrame, text="Private Message", height=2, width=50,# remove command fg="#F0F0F0", bg="#2A3540", command=self.btn_pm) btnPrivateMsg.pack(pady=5) #RUN DAEMON self.broadcast_reciever.start() self.client_lister.start() def showPrivateMsgForm(self,reciever): pm = Tk() pm.title(reciever) pm.resizable(width="false", height="false") #self.pm.geometry("600x450+"+str((600/2)+(600/2+200))+"+"+str(450/2+20)) pm.geometry("600x450+400+150") text_font = ('Calibri', '12') frm1 = Frame(pm) frm1.pack(fill=BOTH) lbl1 = Label(frm1, text="Private Chat", fg="#1A4AA0", font="Calibri 12") lbl1.pack(side=LEFT, padx=10, pady=5) privateList = Text (pm, fg="#232C35", font=text_font, relief=GROOVE, height=11) privateList.pack(fill=BOTH, padx=10, pady=5) frm = Frame(pm) frm.pack(fill=BOTH) combo_box = ttk.Combobox(frm, font=text_font) # apply font to combobox combo_box.pack(side=LEFT, padx=10) combo_box['values'] = ('Arial', "Arial Black", 'Calibri', 'Cambria') msgBox = Text(pm, fg="#232C35", font=text_font, relief=GROOVE, height=3) msgBox.pack(fill=BOTH, pady=5, padx=10) # --------------------------------------------------- ERROR def load_messages(rec): x= 1 while(x==1): sleep(1) try: privateList.delete("1.0", END) #print "INSIDE LE:", len(self.private_records) #print "THREAD STATE:", self.messenger.is_alive() if(len(self.private_records) > 0): temp = self.private_records print "recieve" for mymsg in temp: if((mymsg['to'] == rec and mymsg['from'] == self.auth_user) or (mymsg['to'] == self.auth_user and mymsg['from'] == rec)): privateList.insert(END,mymsg['send_date'] + " >> " + mymsg['from'] + ": " + mymsg['message'] + "\n") #privateList.insert(END,"Hiiii") else: continue pass #privateList.see(0) #sleep(1) except Exception as e: if(str(e) == "invalid command name \".66008448\""): print "super error" pass elif(str(e) == "out of stack space (infinite loop?)"): print "stupid error" pass elif(str(e) == "invalid command name \".70163552\""): print "stupid error" pass elif(str(e) == "invalid command name \".70238896\""): print "stupid error" pass else: print "PRIVATE CLOSE" + str(e) x=0 break pass ''' for each_record in self.private_records: print "FROM: " + each_record['from'] + " TO: " + each_record['to'] + " MESSAGE " + each_record['message'] pass ''' pass message_displayer = threading.Thread(target = load_messages,args=(reciever,)) message_displayer.start() #---------------------------------- ERROR def send_message(evt,reciever): #get message msg = msgBox.get("1.0",END) print "msg here: ", msg bad_words = ['fuck', 'bitch', 'shit', 'damn', 'piss', 'asshole', 'slut', 'tangina', 'puta', 'gago', 'hudas', 'lintik', 'ulol', 'tarantado', 'buwisit', 'burat', 'kupal', 'leche', 'ungas', 'punyeta', 'hinayupak', 'pucha', 'pesteng yawa', 'pakshet', 'tanga'] index=0 ctr=0 while 1: if(index==len(bad_words)): break if(bad_words[index] in msg.lower()): ctr=1 break index+=1 if ctr==1: self.showErrorMsg("Content Error","Please avoid bad or foul words.") else: msg_nrm = unicodedata.normalize('NFKD', msg).encode('ascii','ignore').strip() request = {} request['type'] = "PRIVATE" request['from'] = self.auth_user request['to'] = reciever request['message'] = msg_nrm request['send_date'] = datetime.now(self.GMT).strftime('%m/%d/%Y %I:%M:%S %p') print request #retru if no response was recieve x=1 while(x==1): try: data = self.client.send_request(request) response = json.loads(data) except: self.showInfoMsg("Message Information","Retrying to send message.") print "Retrying to send" sleep(0.5) continue pass x=0 break if(response['type'] == "PRIVATE"): print response pass msgBox.delete("1.0", END) pass btnSend = Button(pm, text="Send", height=2, width=12, command=lambda: send_message('<Return>',reciever), fg="#F0F0F0", bg="#2A3540") btnSend.pack(side=RIGHT, pady=5, padx=10) #use lambda event to bind function with parameters ############################################ pm.bind_all('<Return>',lambda event: send_message('<Return>',reciever)) ############################################ if(self.messenger.is_alive()): print "ALREADY LIVE" pass else: self.fetch_message_block = 1 self.messenger.start() print "THREAD STARTED" pass pass def showChangePassForm(self): cp = Tk() cp.title("Change Profile") cp.geometry("500x320+400+150") text_font = ('Calibri', '12') frme1 = Frame(cp) frme1.pack(fill=BOTH) lbel1 = Label(frme1, text="Change Password", font="Calibri 22", fg="#1A4AA0") lbel1.pack(side=LEFT, padx=10, pady=5) usernameFrame = Frame(cp) usernameFrame.pack() lbl2 = Label(usernameFrame, text="Old Password:", width=15, height=2, fg="#1A4AA0", font="Calibri 14") lbl2.pack(side=LEFT) self.change_old_pass = Entry(usernameFrame, show="*", fg="#1A4AA0", font="Calibri 14") self.change_old_pass.pack(side=LEFT) passFrame = Frame(cp) passFrame.pack() lbl3 = Label(passFrame, text="New Password:", width=15, height=2, fg="#1A4AA0", font="Calibri 14") lbl3.pack(side=LEFT) self.change_new_pass = Entry(passFrame, show="*", fg="#1A4AA0", font="Calibri 14") self.change_new_pass.pack(side=LEFT) reTypePassFrame = Frame(cp) reTypePassFrame.pack() lbl3 = Label(reTypePassFrame, text="Retype-New Password:", width=20, height=2, fg="#1A4AA0", font="Calibri 14") lbl3.pack(side=LEFT) self.change_confirm_pass = Entry(reTypePassFrame, show="*", fg="#1A4AA0", font="Calibri 14") self.change_confirm_pass.pack(side=LEFT) buttonFrame = Frame(cp) buttonFrame.pack(side=RIGHT, padx=30) btnSave = Button(buttonFrame, text="Save changes", width=12, fg="#F0F0F0", bg="#2A3540", font="Calibri 14",command=lambda: self.change_pass(self.change_old_pass, self.change_new_pass)) btnSave.pack(pady=2) btnBack = Button(buttonFrame, text="Back", width=12, fg="#F0F0F0", bg="#2A3540", font="Calibri 14",) #btnBack.pack(pady=2) pass # end of class GUI GUI()
36.213
162
0.505923
3,676
36,213
4.905604
0.14309
0.016692
0.020185
0.027394
0.47463
0.389785
0.351023
0.303666
0.259691
0.241335
0
0.03736
0.347334
36,213
999
163
36.249249
0.725619
0.066578
0
0.412518
0
0
0.13497
0
0
0
0
0
0
0
null
null
0.163585
0.021337
null
null
0.064011
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
36e48c1eb7dab50e4b7f65d8039e1428e3378b49
185
py
Python
Basics/Google Dictionary Exmpale 1.py
bhoot929/Google-Interview-prep
3ea493bb8937c8db51bfc7d8e8592d4b5419348b
[ "MIT" ]
29
2017-06-03T15:54:14.000Z
2022-03-18T10:57:41.000Z
Basics/Google Dictionary Exmpale 1.py
bhoot929/Google-Interview-prep
3ea493bb8937c8db51bfc7d8e8592d4b5419348b
[ "MIT" ]
null
null
null
Basics/Google Dictionary Exmpale 1.py
bhoot929/Google-Interview-prep
3ea493bb8937c8db51bfc7d8e8592d4b5419348b
[ "MIT" ]
9
2017-10-08T04:39:26.000Z
2021-09-14T14:29:23.000Z
table = {'1985': 'Test movie' , '1983': 'Test Movie2' , '2000': 'Test Movie 3'} year = '1983' movie = table[year] print(movie) for year in table: print(year + '\t' + movie + '\t')
23.125
79
0.583784
27
185
4
0.481481
0.166667
0
0
0
0
0
0
0
0
0
0.121622
0.2
185
8
80
23.125
0.608108
0
0
0
0
0
0.284946
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
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
36fb0f450d8c7fdde4d9687433830befd3a9c6db
247
py
Python
split_spec.py
thetobysiu/transfer-pytorch-dc-tts
20d0c381970a01f0e343c65aeac2f325be436a7e
[ "MIT" ]
null
null
null
split_spec.py
thetobysiu/transfer-pytorch-dc-tts
20d0c381970a01f0e343c65aeac2f325be436a7e
[ "MIT" ]
null
null
null
split_spec.py
thetobysiu/transfer-pytorch-dc-tts
20d0c381970a01f0e343c65aeac2f325be436a7e
[ "MIT" ]
null
null
null
import zarr voice = 'Yennefer' spec = zarr.open(f'datasets/{voice}/spec.zip', mode='r', synchronizer=zarr.ThreadSynchronizer()) zarr.save_group(f'datasets/{voice}/mels.zip', **spec.mels) zarr.save_group(f'datasets/{voice}/mags.zip', **spec.mags)
35.285714
96
0.732794
37
247
4.837838
0.459459
0.150838
0.234637
0.156425
0.301676
0.301676
0
0
0
0
0
0
0.060729
247
6
97
41.166667
0.771552
0
0
0
0
0
0.340081
0.303644
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
7fdccd884b6606106af0ecdc7341a57f1fb4f110
2,350
py
Python
fhirclient/models/medicinalproductindication_tests.py
carolinarsm/client-py
db1b6e3e28036dee11da75412003c7d90e591c6d
[ "Apache-2.0" ]
418
2015-07-01T08:23:16.000Z
2022-03-31T14:02:30.000Z
fhirclient/models/medicinalproductindication_tests.py
carolinarsm/client-py
db1b6e3e28036dee11da75412003c7d90e591c6d
[ "Apache-2.0" ]
312
2017-09-08T15:42:13.000Z
2022-03-23T18:21:40.000Z
fhirclient/models/medicinalproductindication_tests.py
carolinarsm/client-py
db1b6e3e28036dee11da75412003c7d90e591c6d
[ "Apache-2.0" ]
185
2015-03-30T20:23:16.000Z
2022-03-30T14:39:26.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07. # 2019, SMART Health IT. import os import io import unittest import json from . import medicinalproductindication from .fhirdate import FHIRDate class MedicinalProductIndicationTests(unittest.TestCase): def instantiate_from(self, filename): datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or '' with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle: js = json.load(handle) self.assertEqual("MedicinalProductIndication", js["resourceType"]) return medicinalproductindication.MedicinalProductIndication(js) def testMedicinalProductIndication1(self): inst = self.instantiate_from("medicinalproductindication-example.json") self.assertIsNotNone(inst, "Must have instantiated a MedicinalProductIndication instance") self.implMedicinalProductIndication1(inst) js = inst.as_json() self.assertEqual("MedicinalProductIndication", js["resourceType"]) inst2 = medicinalproductindication.MedicinalProductIndication(js) self.implMedicinalProductIndication1(inst2) def implMedicinalProductIndication1(self, inst): self.assertEqual(inst.comorbidity[0].coding[0].code, "Hipsurgery") self.assertEqual(inst.comorbidity[0].coding[0].system, "http://ema.europa.eu/example/comorbidity") self.assertEqual(inst.diseaseSymptomProcedure.coding[0].code, "Venousthromboembolismprophylaxis") self.assertEqual(inst.diseaseSymptomProcedure.coding[0].system, "http://ema.europa.eu/example/indicationasdisease-symptom-procedure") self.assertEqual(inst.id, "example") self.assertEqual(inst.intendedEffect.coding[0].code, "PRYLX") self.assertEqual(inst.intendedEffect.coding[0].system, "http://ema.europa.eu/example/intendedeffect") self.assertEqual(inst.meta.tag[0].code, "HTEST") self.assertEqual(inst.meta.tag[0].display, "test health data") self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason") self.assertEqual(inst.population[0].ageRange.low.unit, "a") self.assertEqual(inst.population[0].ageRange.low.value, 18) self.assertEqual(inst.text.status, "generated")
47.959184
141
0.722128
251
2,350
6.741036
0.390438
0.132979
0.145981
0.030142
0.361111
0.296099
0.1513
0.062057
0
0
0
0.022099
0.152766
2,350
48
142
48.958333
0.827725
0.050638
0
0.057143
1
0
0.218427
0.076404
0
0
0
0
0.457143
1
0.085714
false
0
0.171429
0
0.314286
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
1
0
0
0
0
0
0
0
0
0
2
7fe0e0f8ede55e5e77e0d514ad4b5022dce84216
2,544
py
Python
OracleSOASuite/kubernetes/monitoring-service/scripts/deploy-weblogic-monitoring-exporter.py
pratdash-orcl/fmw-kubernetes
afd406b0d2fffcff73511c27d08441c7708aa15d
[ "UPL-1.0", "MIT" ]
null
null
null
OracleSOASuite/kubernetes/monitoring-service/scripts/deploy-weblogic-monitoring-exporter.py
pratdash-orcl/fmw-kubernetes
afd406b0d2fffcff73511c27d08441c7708aa15d
[ "UPL-1.0", "MIT" ]
null
null
null
OracleSOASuite/kubernetes/monitoring-service/scripts/deploy-weblogic-monitoring-exporter.py
pratdash-orcl/fmw-kubernetes
afd406b0d2fffcff73511c27d08441c7708aa15d
[ "UPL-1.0", "MIT" ]
1
2020-10-08T05:34:05.000Z
2020-10-08T05:34:05.000Z
# Copyright (c) 2021, Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. # import sys #======================================================= # Function for fresh plain deployment #======================================================= def newDeploy(appName,target): try: print 'Deploying .........' deploy(appName,'/u01/oracle/wls-exporter-deploy/'+appName+'.war', target, upload="true",remote="true") startApplication(appName) except Exception, ex: print ex.toString() #======================================================== # Main program here... # Target you can change as per your need #======================================================== def usage(): print sys.arg[0] + '-domainName <domainUID> -domainType <domaintype> -adminServerName <adminServerName> -adminURL <adminURL> -username <username> -password <password>' sys.exit(0) if len(sys.argv) < 1: usage() #domainName will be passed by command line parameter -domainName. domainName = "soainfra" #domaintype will be passed by command line parameter -domaintype domaintype = "soa" #adminServerName will be passed by command line parameter -adminServerName adminServerName = "AdminServer" #adminURL will be passed by command line parameter -adminURL adminURL = "soainfra-adminserver:7001" #username will be passed by command line parameter -username username = "weblogic" #password will be passed by command line parameter -password password = "Welcome1" i=1 while i < len(sys.argv): if sys.argv[i] == '-domainName': domainName = sys.argv[i+1] i += 2 elif sys.argv[i] == '-domainType': domaintype = sys.argv[i+1] i += 2 elif sys.argv[i] == '-adminServerName': adminServerName = sys.argv[i+1] i += 2 elif sys.argv[i] == '-adminURL': adminURL = sys.argv[i+1] i += 2 elif sys.argv[i] == '-username': username = sys.argv[i+1] i += 2 elif sys.argv[i] == '-password': password = sys.argv[i+1] i += 2 else: print 'Unexpected argument switch at position ' + str(i) + ': ' + str(sys.argv[i]) usage() sys.exit(1) # Deployment connect(username, password, 't3://' + adminURL) cd('AppDeployments') newDeploy('wls-exporter-adminserver',adminServerName) if 'soa' in domaintype: newDeploy('wls-exporter-soa','soa_cluster') if 'osb' in domaintype: newDeploy('wls-exporter-osb','osb_cluster') disconnect() exit()
30.285714
171
0.608097
299
2,544
5.167224
0.351171
0.067961
0.067314
0.054369
0.255016
0.213592
0.206472
0.074434
0.074434
0.074434
0
0.014854
0.179638
2,544
83
172
30.650602
0.725443
0.340409
0
0.153846
0
0.019231
0.289759
0.048795
0
0
0
0
0
0
null
null
0.096154
0.019231
null
null
0.076923
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
7fe61bb40d4d0c3653c258a5341aa70b770798e2
241
py
Python
examples/hello.py
ridgek/iscli
f81181f2c2fc5842f716784605594203c1b24921
[ "BSD-2-Clause" ]
null
null
null
examples/hello.py
ridgek/iscli
f81181f2c2fc5842f716784605594203c1b24921
[ "BSD-2-Clause" ]
null
null
null
examples/hello.py
ridgek/iscli
f81181f2c2fc5842f716784605594203c1b24921
[ "BSD-2-Clause" ]
null
null
null
from iscli.cli import CommandSet, Cli hello = CommandSet() @hello.install('hello world') def cmd_hello_world(cli, args): print 'Hello World!' if __name__ == '__main__': cli = Cli('> ') cli.load(hello) cli.commandloop()
15.0625
37
0.655602
31
241
4.774194
0.548387
0.202703
0
0
0
0
0
0
0
0
0
0
0.19917
241
15
38
16.066667
0.766839
0
0
0
0
0
0.136929
0
0
0
0
0
0
0
null
null
0
0.111111
null
null
0.111111
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
7fecd5b2152d53ebac0c88e070408ea02320e49d
170
py
Python
dump_env.py
gkapkowski/dovecot-userpassdb
80e09aaaf5e1744dc17dd05dbd2e28bda3406f05
[ "BSD-3-Clause" ]
1
2016-03-12T20:58:03.000Z
2016-03-12T20:58:03.000Z
dump_env.py
koniiiik/dovecot-userpassdb
9fc474c611a1f4fc2c64ed3a0c9e9806276a828e
[ "BSD-3-Clause" ]
null
null
null
dump_env.py
koniiiik/dovecot-userpassdb
9fc474c611a1f4fc2c64ed3a0c9e9806276a828e
[ "BSD-3-Clause" ]
2
2019-01-18T11:53:12.000Z
2021-07-21T21:23:17.000Z
#!/usr/bin/env python import json import os def main(): with os.fdopen(4, 'w') as f: json.dump(dict(os.environ), f) if __name__ == "__main__": main()
13.076923
38
0.594118
27
170
3.444444
0.740741
0
0
0
0
0
0
0
0
0
0
0.007692
0.235294
170
12
39
14.166667
0.707692
0.117647
0
0
0
0
0.060403
0
0
0
0
0
0
1
0.142857
true
0
0.285714
0
0.428571
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
7ff3f519b1f766d1e75cc576fbad7b84c47454db
801
py
Python
p021.py
janhenke/project-euler
db82193ef2ae12e45dabd893c4ee780d270c6da2
[ "MIT" ]
null
null
null
p021.py
janhenke/project-euler
db82193ef2ae12e45dabd893c4ee780d270c6da2
[ "MIT" ]
null
null
null
p021.py
janhenke/project-euler
db82193ef2ae12e45dabd893c4ee780d270c6da2
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """Solves problem 021 from the Project Euler website""" first_twenty_amicable_numbers = [(220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368), (10744, 10856), (12285, 14595), (17296, 18416), (63020, 76084), (66928, 66992), (67095, 71145), (69615, 87633), (79750, 88730), (100485, 124155), (122265, 139815), (122368, 123152), (141664, 153176), (142310, 168730)] def solve(): """Solve the problem and return the result""" result = 0 for n in first_twenty_amicable_numbers: if n[0] < 10000: result += n[0] result += n[1] else: break return result if __name__ == '__main__': print(solve())
30.807692
118
0.526841
89
801
4.58427
0.775281
0.053922
0.093137
0.127451
0
0
0
0
0
0
0
0.353704
0.325843
801
25
119
32.04
0.401852
0.138577
0
0
0
0
0.011782
0
0
0
0
0
0
1
0.066667
false
0
0
0
0.133333
0.066667
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
3d00513d56e047652ec13109ee80bcadedc87fcb
15,521
py
Python
authlete/api/authlete_api_impl.py
authlete/authlete-python
751514c525cd04a930373de78463a1fe71b6da60
[ "Apache-2.0" ]
5
2019-07-30T01:37:04.000Z
2021-02-15T05:55:55.000Z
authlete/api/authlete_api_impl.py
DestinyCall/authlete-python
751514c525cd04a930373de78463a1fe71b6da60
[ "Apache-2.0" ]
null
null
null
authlete/api/authlete_api_impl.py
DestinyCall/authlete-python
751514c525cd04a930373de78463a1fe71b6da60
[ "Apache-2.0" ]
1
2021-02-15T05:55:56.000Z
2021-02-15T05:55:56.000Z
# # Copyright (C) 2019-2020 Authlete, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific # language governing permissions and limitations under the # License. import json import requests from authlete.api.authlete_api import AuthleteApi from authlete.api.authlete_api_exception import AuthleteApiException from authlete.api.settings import Settings from authlete.dto import * from authlete.conf.authlete_configuration import AuthleteConfiguration from authlete.types.jsonable import Jsonable class AuthleteApiImpl(AuthleteApi): def __init__(self, cnf): """Implementation of AuthleteApi. Args: cnf (authlete.dto.AuthleteConfiguration) """ if isinstance(cnf, AuthleteConfiguration) == False: raise RuntimeError("'cnf' must be an instance of AuthleteConfiguration.") if cnf.baseUrl is None: raise RuntimeError("'baseUrl' of the configuration is None.") self._baseUrl = cnf.baseUrl.rstrip('/') self._serviceOwnerCredentials = (cnf.serviceOwnerApiKey, cnf.serviceOwnerApiSecret) self._serviceCredentials = (cnf.serviceApiKey, cnf.serviceApiSecret) self._settings = Settings() def __callApi(self, method, credentials, path, queryParams, requestBody, responseClass): # The URL of the Authlete API. url = self._baseUrl + path # Convert 'requestBody' to an instance of str. The format is JSON. if requestBody is None: data = None elif isinstance(requestBody, Jsonable): data = requestBody.to_json() else: data = json.dumps(requestBody) try: # Call the Authlete API. response = self.__sendRequest(method, url, queryParams, data, credentials) except Exception as cause: raise AuthleteApiException( url, queryParams, data, "API call to " + path + " failed.", cause) # If the HTTP status code is not 2XX. if response.status_code < 200 or 300 <= response.status_code: message = self.__extractResultMessage(response.text) if message is None: message = "{} API returned {}".format(path, response.status_code) raise AuthleteApiException(url, queryParams, data, message, None, response) # Create an instance of responseClass from the HTTP message body of the response. return self.__deserializeResponseBody(response.text, responseClass) def __sendRequest(self, method, url, params, data, credentials): # headers headers = { "Accept": "application/json", "Content-Type": "application/json" } # timeout timeout = (self._settings.connectionTimeout, self._settings.readTimeout) return requests.request(method, url, params=params, data=data, headers=headers, auth=credentials, timeout=timeout) def __extractResultMessage(self, body): if body is None: return None # The response body may be JSON which contains 'resultMessage'. try: # Convert the JSON string into a Python dictionary. dct = json.loads(body) return dct['resultMessage'] except Exception: return None def __deserializeResponseBody(self, body, responseClass): if body is None: return None if responseClass is None: return body return responseClass.from_json(body) def __callGetApi(self, credentials, path, responseClass, queryParams): return self.__callApi('GET', credentials, path, queryParams, None, responseClass) def __callPostApi(self, credentials, path, requestBody, responseClass): return self.__callApi('POST', credentials, path, None, requestBody, responseClass) def __callDeleteApi(self, credentials, path, queryParams): return self.__callApi('DELETE', credentials, path, queryParams, None, None) def __callServiceGetApi(self, path, responseClass=None, queryParams=None): return self.__callGetApi(self._serviceCredentials, path, responseClass, queryParams) def __callServicePostApi(self, path, requestBody, responseClass=None): return self.__callPostApi(self._serviceCredentials, path, requestBody, responseClass) def __callServiceDeleteApi(self, path, queryParams=None): return self.__callDeleteApi(self._serviceCredentials, path, queryParams) def __callServiceOwnerGetApi(self, path, responseClass=None, queryParams=None): return self.__callGetApi(self._serviceOwnerCredentials, path, responseClass, queryParams) def __callServiceOwnerPostApi(self, path, requestBody, responseClass=None): return self.__callPostApi(self._serviceOwnerCredentials, path, requestBody, responseClass) def __callServiceOwnerDeleteApi(self, path, queryParams=None): return self.__callDeleteApi(self._serviceOwnerCredentials, path, queryParams) def __buildDict(self, **kwargs): dct = {} for key, value in kwargs.items(): if value is not None: dct[key] = value return dct def getSettings(self): return self._settings def authorization(self, request): return self.__callServicePostApi( '/api/auth/authorization', request, AuthorizationResponse) def authorizationFail(self, request): return self.__callServicePostApi( '/api/auth/authorization/fail', request, AuthorizationFailResponse) def authorizationIssue(self, request): return self.__callServicePostApi( '/api/auth/authorization/issue', request, AuthorizationIssueResponse) def token(self, request): return self.__callServicePostApi( '/api/auth/token', request, TokenResponse) def tokenCreate(self, request): return self.__callServicePostApi( '/api/auth/token/create', request, TokenCreateResponse) def tokenDelete(self, token): self.__callServiceDeleteApi( '/api/auth/token/delete/{}'.format(token)) def tokenFail(self, request): return self.__callServicePostApi( '/api/auth/token/fail', request, TokenFailResponse) def tokenIssue(self, request): return self.__callServicePostApi( '/api/auth/token/issue', request, TokenIssueResponse) def tokenUpdate(self, request): return self.__callServicePostApi( '/api/auth/token/update', request, TokenUpdateResponse) def getTokenList(self, clientIdentifier=None, subject=None, start=None, end=None): params = self.__buildDict( clientIdentifier=clientIdentifier, subject=subject, start=start, end=end) return self.__callServiceGetApi( '/api/auth/token/get/list', TokenListResponse, params) def revocation(self, request): return self.__callServicePostApi( '/api/auth/revocation', request, RevocationResponse) def userinfo(self, request): return self.__callServicePostApi( '/api/auth/userinfo', request, UserInfoResponse) def userinfoIssue(self, request): return self.__callServicePostApi( '/api/auth/userinfo/issue', request, UserInfoIssueResponse) def introspection(self, request): return self.__callServicePostApi( '/api/auth/introspection', request, IntrospectionResponse) def standardIntrospection(self, request): return self.__callServicePostApi( '/api/auth/introspection/standard', request, StandardIntrospectionResponse) def createService(self, service): return self.__callServiceOwnerPostApi( '/api/service/create', service, Service) def deleteService(self, apiKey): self.__callServiceOwnerDeleteApi( '/api/service/delete/{}'.format(apiKey)) def getService(self, apiKey): return self.__callServiceOwnerGetApi( '/api/service/get/{}'.format(apiKey), Service) def getServiceList(self, start=None, end=None): params = self.__buildDict(start=start, end=end) return self.__callServiceOwnerGetApi( '/api/service/get/list', ServiceListResponse, params) def updateService(self, service): return self.__callServiceOwnerPostApi( '/api/service/update/{}'.format(service.apiKey), service, Service) def getServiceJwks(self, pretty=True, includePrivateKeys=False): params = self.__buildDict( pretty=pretty, includePrivateKeys=includePrivateKeys) return self.__callServiceGetApi( '/api/service/jwks/get', None, params) def getServiceConfiguration(self, pretty=True): params = self.__buildDict(pretty=pretty) return self.__callServiceGetApi( '/api/service/configuration', None, params) def createClient(self, client): return self.__callServicePostApi( '/api/client/create', client, Client) def dynamicClientRegister(self, request): return self.__callServicePostApi( '/api/client/registration', request, ClientRegistrationResponse) def dynamicClientGet(self, request): return self.__callServicePostApi( '/api/client/registration/get', request, ClientRegistrationResponse) def dynamicClientUpdate(self, request): return self.__callServicePostApi( '/api/client/registration/update', request, ClientRegistrationResponse) def dynamicClientDelete(self, request): return self.__callServicePostApi( '/api/client/registration/delete', request, ClientRegistrationResponse) def deleteClient(self, clientId): return self.__callServiceDeleteApi( '/api/client/delete/{}'.format(clientId)) def getClient(self, clientId): return self.__callServiceGetApi( '/api/client/get/{}'.format(clientId), Client) def getClientList(self, developer=None, start=None, end=None): params = self.__buildDict( developer=developer, start=start, end=end) return self.__callServiceGetApi( '/api/client/get/list', ClientListResponse, params) def updateClient(self, client): return self.__callServicePostApi( '/api/client/update/{}'.format(client.clientId), client, Client) def getRequestableScopes(self, clientId): responseBody = self.__callServiceGetApi( '/api/client/extension/requestable_scopes/get/{}'.format(clientId)) dct = json.loads(responseBody) return dct['requestableScopes'] def setRequestableScopes(self, clientId, scopes): requestBody = { 'requestableScopes': scopes } responseBody = self.__callServicePostApi( '/api/client/extension/requestable_scopes/update/{}'.format(clientId), requestBody) dct = json.loads(responseBody) return dct['requestableScopes'] def deleteRequestableScopes(self, clientId): self.__callServiceDeleteApi( '/api/client/extension/requestable_scopes/delete/{}'.format(clientId)) def getGrantedScopes(self, clientId, subject): requestBody = { 'subject': subject } return self.__callServicePostApi( '/api/client/granted_scopes/get/{}'.format(clientId), requestBody, GrantedScopesGetResponse) def deleteGrantedScopes(self, clientId, subject): requestBody = { 'subject': subject } self.__callServicePostApi( '/api/client/granted_scopes/delete/{}'.format(clientId), requestBody, ApiResponse) def deleteClientAuthorization(self, clientId, subject): request = ClientAuthorizationDeleteRequest() request.subject = subject self.__callServicePostApi( '/api/client/authorization/delete/{}'.format(clientId), request, ApiResponse) def getClientAuthorizationList(self, request): return self.__callServicePostApi( '/api/client/authorization/get/list', request, AuthorizedClientListResponse) def updateClientAuthorization(self, clientId, request): self.__callServicePostApi( '/api/client/authorization/update/{}'.format(clientId), request, ApiResponse) def refreshClientSecret(self, clientId): return self.__callServiceGetApi( '/api/client/secret/refresh/{}'.format(clientId), ClientSecretRefreshResponse) def updateClientSecret(self, clientId, clientSecret): request = ClientSecretUpdateRequest() request.clientId = clientId request.clilentSecret = clientSecret return self.__callServicePostApi( '/api/client/secret/update/{}'.format(clientId), request, ClientSecretUpdateResponse) def verifyJose(self, request): return self.__callServicePostApi( '/api/jose/verify', request, JoseVerifyResponse) def backchannelAuthentication(self, request): return self.__callServicePostApi( '/api/backchannel/authentication', request, BackchannelAuthenticationResponse) def backchannelAuthenticationIssue(self, request): return self.__callServicePostApi( '/api/backchannel/authentication/issue', request, BackchannelAuthenticationIssueResponse) def backchannelAuthenticationFail(self, request): return self.__callServicePostApi( '/api/backchannel/authentication/fail', request, BackchannelAuthenticationFailResponse) def backchannelAuthenticationComplete(self, request): return self.__callServicePostApi( '/api/backchannel/authentication/complete', request, BackchannelAuthenticationCompleteResponse) def deviceAuthorization(self, request): return self.__callServicePostApi( '/api/device/authorization', request, DeviceAuthorizationResponse) def deviceComplete(self, request): return self.__callServicePostApi( '/api/device/complete', request, DeviceCompleteResponse) def deviceVerification(self, request): return self.__callServicePostApi( '/api/device/verification', request, DeviceVerificationResponse) def pushAuthorizationRequest(self, request): return self.__callServicePostApi( '/api/pushed_auth_req', request, PushedAuthReqResponse)
31.482759
98
0.656079
1,352
15,521
7.386834
0.220414
0.053069
0.087614
0.096225
0.339642
0.283368
0.236608
0.179433
0.025033
0.012817
0
0.001642
0.254623
15,521
492
99
31.546748
0.861613
0.064751
0
0.245847
0
0
0.110911
0.078343
0
0
0
0
0
1
0.219269
false
0
0.026578
0.149502
0.458472
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
3d05b3781563da9b73a47ac5d6b7e33b936e0b25
1,198
py
Python
examples/other/printc.py
CommanderPho/vedo
a0784a47d1b1a92f71b81f153c12856ccf7ec242
[ "MIT" ]
1
2022-03-22T21:49:29.000Z
2022-03-22T21:49:29.000Z
examples/other/printc.py
CommanderPho/vedo
a0784a47d1b1a92f71b81f153c12856ccf7ec242
[ "MIT" ]
null
null
null
examples/other/printc.py
CommanderPho/vedo
a0784a47d1b1a92f71b81f153c12856ccf7ec242
[ "MIT" ]
null
null
null
# Available modifiers: # c (foreground color), bc (background color) # bold, blink, underLine, dim, invert, box from vedo import printc printc(" 1- Change the world by being yourself - Amy Poehler\world", c=1) printc(" 2- Never regret anything that made you smile - Mark Twain\smile", c="r", bold=0) printc(" 3- Every moment is a fresh beginning - T.S Eliot", c="m", underline=1) printc(" 4- Die with memories, not dreams - Unknown\ethumbup", blink=1, bold=0) printc(" 5- When words fail, music speaks - Shakespeare \pin") printc(" 6- Everything you can imagine is real - Pablo Picasso\erocket", c=3) printc(" 7- Simplicity is the ultimate sophistication - Leonardo da Vinci\idea", c=4) printc(" 8- Whatever you do, do it well - Walt Disney\erainbow", c=3, bc=1) printc(" 9- What we think, we become - Buddha \etarget", c=6, invert=1) printc("10- All limitations are self-imposed - Oliver Wendell Holmes\sparks", c=7, dim=1) printc("11- If you tell the truth you dont have to remember anything - Mark Twain\checked", underline=True, invert=True, dim=True, c=6, ) from vedo.colors import emoji for k in sorted(emoji.keys()): print(emoji[k] + " \t" + repr(k))
46.076923
91
0.689482
194
1,198
4.257732
0.64433
0.042373
0.026634
0
0
0
0
0
0
0
0
0.027467
0.179466
1,198
25
92
47.92
0.812818
0.089316
0
0
0
0
0.607176
0
0
0
0
0
0
1
0
false
0
0.1
0
0.1
0.65
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
3d1220d41bccb379b96f18725e1c972c88aa7a27
761
py
Python
fabfile.py
alpae/pyham
e30a018794ce39adf5b77df8bc057841eb142a15
[ "MIT" ]
7
2019-03-29T18:23:28.000Z
2021-12-07T07:41:27.000Z
fabfile.py
alpae/pyham
e30a018794ce39adf5b77df8bc057841eb142a15
[ "MIT" ]
14
2019-04-29T07:57:01.000Z
2022-03-05T04:00:40.000Z
fabfile.py
alpae/pyham
e30a018794ce39adf5b77df8bc057841eb142a15
[ "MIT" ]
3
2019-07-18T12:54:45.000Z
2021-04-22T07:25:47.000Z
from fabric.api import * # TO UPDATE PIP PACKAGE # 1 -> update __version__ variable in pyham/__init__.py # 2 -> fab test clean pack deploy def clean(): # remove old package local('rm -rf dist/', capture=False) local('rm -rf build/', capture=False) def test(): # run unit test local('python -m unittest discover tests/', capture=False) local('python tests/functional_test.py', capture=False) def pack(): # build the package local('python setup.py bdist_wheel', capture=False) local('python setup.py sdist', capture=False) def deploy_test(): # update the pipy pyham package local('twine upload dist/* -r testpypi') def deploy(): # update the pipy pyham package local('twine upload dist/* -r pypi')
21.138889
62
0.671485
107
761
4.672897
0.46729
0.144
0.102
0.092
0.184
0.184
0.184
0.184
0.184
0.184
0
0.003322
0.208936
761
35
63
21.742857
0.827243
0.286465
0
0
0
0
0.37051
0.045369
0
0
0
0
0
1
0.357143
true
0
0.071429
0
0.428571
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
1
0
0
0
0
0
0
2
3d2384c3df9323589f039d03b4600f86c145d261
706
py
Python
pypedriver/util.py
matumaros/pypedrive
69f921a3a970d43aba7aa5002eb82b5d4f903eae
[ "MIT" ]
2
2017-05-30T19:59:19.000Z
2018-06-27T17:40:38.000Z
pypedriver/util.py
pyfection/pypedriver
69f921a3a970d43aba7aa5002eb82b5d4f903eae
[ "MIT" ]
12
2016-07-11T08:16:55.000Z
2017-04-14T20:34:32.000Z
pypedriver/util.py
pyfection/pypedriver
69f921a3a970d43aba7aa5002eb82b5d4f903eae
[ "MIT" ]
7
2016-09-30T15:36:33.000Z
2018-06-27T22:15:36.000Z
import re def urljoin(*pieces): """Join a URL Joins the pieces together to an URL. Cannot be replaced by urllib.parse.urljoin, because that doesn't join parts of a path and doesn't allow for multiple pieces to be joined. Arguments: *pieces {str} -- pieces of URL """ return '/'.join(s.strip('/') for s in pieces) def clean(string): """Clean string Cleans a string to be a valid Python variable name. It replaces all invalid characters with an underscore. Arguments: string {str} -- string to be formatted Returns: str -- formatted string """ string = re.sub('\W|^(?=\d)', '_', string).lower() return string
20.764706
58
0.621813
98
706
4.469388
0.581633
0.027397
0.045662
0
0
0
0
0
0
0
0
0
0.271955
706
33
59
21.393939
0.85214
0.633144
0
0
0
0
0.069149
0
0
0
0
0
0
1
0.333333
false
0
0.166667
0
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
1
0
0
0
0
1
0
0
2
3d2c50719068afbfbdff9e179ad0e8dea8a292ab
565
py
Python
setup.py
yabellini/mccole
c122db14f2c7231a9c158f8e217eeb6bd2341d49
[ "MIT" ]
null
null
null
setup.py
yabellini/mccole
c122db14f2c7231a9c158f8e217eeb6bd2341d49
[ "MIT" ]
null
null
null
setup.py
yabellini/mccole
c122db14f2c7231a9c158f8e217eeb6bd2341d49
[ "MIT" ]
null
null
null
import setuptools setuptools.setup( name="mccole", version="0.1.0", url="https://github.com/gvwilson/mccole", author="Greg Wilson", author_email="gvwilson@third-bit.com", description="A simple publishing system", long_description=open("README.md").read(), packages=setuptools.find_packages(), install_requires=["markdown-it-py>=2.0.0", "mdit-py-plugins>=0.3.0"], classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.9", ], )
29.736842
73
0.640708
67
565
5.343284
0.671642
0.159218
0.209497
0.145251
0
0
0
0
0
0
0
0.026087
0.185841
565
18
74
31.388889
0.752174
0
0
0
0
0
0.456637
0.115044
0
0
0
0
0
1
0
true
0
0.058824
0
0.058824
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
3d3c6c00e8213096ef9f806405c7eecace48608f
489
py
Python
project_name/settings/__init__.py
thnee/django-template
d1e4f8dfe65c86f64c9a06c8cc195dbe6658320e
[ "MIT" ]
1
2018-07-20T23:35:32.000Z
2018-07-20T23:35:32.000Z
project_name/settings/__init__.py
thnee/django-template
d1e4f8dfe65c86f64c9a06c8cc195dbe6658320e
[ "MIT" ]
null
null
null
project_name/settings/__init__.py
thnee/django-template
d1e4f8dfe65c86f64c9a06c8cc195dbe6658320e
[ "MIT" ]
null
null
null
import os import importlib env = os.environ.get('DJANGO_SETTINGS_ENV') app = os.environ.get('DJANGO_SETTINGS_APP') module_paths = [] module_paths.append('settings.base') if env: module_paths.append('settings.envs.{env}'.format(env=env)) if app: module_paths.append('settings.apps.{app}'.format(app=app)) module_paths.append('settings.allowed_hosts') for module_path in module_paths: module = importlib.import_module(module_path) globals().update(module.__dict__)
19.56
62
0.748466
69
489
5.043478
0.362319
0.189655
0.195402
0.287356
0.310345
0
0
0
0
0
0
0
0.112474
489
24
63
20.375
0.801843
0
0
0
0
0
0.227459
0.045082
0
0
0
0
0
1
0
false
0
0.214286
0
0.214286
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
3d47cabdc9fd960cbd605a3d8ff3bf1583c25772
20,461
py
Python
projects/jist/jist/datasets/generate2Ddataset.py
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
projects/jist/jist/datasets/generate2Ddataset.py
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
projects/jist/jist/datasets/generate2Ddataset.py
Cryptum169/gpmp2
f361baac4917b9a4d1220411e9c69dc9f96f4277
[ "BSD-3-Clause" ]
null
null
null
import numpy as np from gtsam import * from gpmp2 import * import math from random import Random dataset_random = Random() class Obstacle: """docstring for Dataset""" def __init__(self): self.x = None self.y = None self.v_x = None self.v_y = None self.a_x = None self.a_y = None self.size = None class Dataset: """docstring for Dataset""" def __init__(self): self.cols = None self.rows = None self.origin_x = None self.origin_y = None self.cell_size = None self.map = None def random_number(min_val, max_val): return min_val + (max_val - min_val) * dataset_random.random() def get_center(x, y, dataset): center = ( np.asarray([y - dataset.origin_y, x - dataset.origin_x]) / dataset.cell_size ) return center.astype(int) def get_dim(w, h, dataset): return np.asarray([h, w]) / dataset.cell_size def add_obstacle( position, size, map, landmarks=None, origin_x=None, origin_y=None, cell_size=None ): half_size_row = int(math.floor((size[0] - 1) / 2)) half_size_col = int(math.floor((size[1] - 1) / 2)) # occupency grid. here map is assumed to be numpy array temp = map[ max(0, position[0] - half_size_row - 1) : min(map.shape[0],position[0] + half_size_row), max(0, position[1] - half_size_col - 1) : min(map.shape[1],position[1] + half_size_col), ] map[ max(0, position[0] - half_size_row - 1) :min(map.shape[0], position[0] + half_size_row), max(0, position[1] - half_size_col - 1) :min(map.shape[1], position[1] + half_size_col), ] = np.ones(temp.shape) # landmarks if landmarks is not None and origin_x is not None and origin_y is not None: raise NotImplementedError return map def generate2Ddataset(dataset_str): # GENERATE2DDATASET Generate 2D dataset evidence grid # # Usage: dataset = GENERATE2DDATASET(dataset_str) # @dataset_str dataset string, existing datasets: # 'OneObstacleDataset', 'TwoObstaclesDataset' # # Output Format: # dataset.map ground truth evidence grid # dataset.rows number of rows (y) # dataset.cols number of cols (x) # dataset.origin_x origin of map x # dataset.origin_y origin of map y # dataset.cell_size cell size dataset = Dataset() # dataset 5: 1 obs dataset for 2D Arm obs avoid if dataset_str is "OneObstacleDataset": # params dataset.cols = 300 dataset.rows = 300 dataset.origin_x = -1 dataset.origin_y = -1 dataset.cell_size = 0.01 # map dataset.map = np.zeros((dataset.rows, dataset.cols)) # obstacles dataset.map = add_obstacle([190, 160], [60, 80], dataset.map) # dataset 6: obs dataset for 3D Arm obs avoid elif dataset_str is "Empty": # params dataset.cols = 300 dataset.rows = 300 dataset.origin_x = -1 dataset.origin_y = -1 dataset.cell_size = 0.01 # map dataset.map = np.zeros((dataset.rows, dataset.cols)) # obstacles # dataset.map = add_obstacle([200, 200], [80, 100], dataset.map) # dataset.map = add_obstacle([160, 80], [30, 80], dataset.map) elif dataset_str is "TwoObstaclesDataset": # params dataset.cols = 300 dataset.rows = 300 dataset.origin_x = -1 dataset.origin_y = -1 dataset.cell_size = 0.01 # map dataset.map = np.zeros((dataset.rows, dataset.cols)) # obstacles dataset.map = add_obstacle([200, 200], [80, 100], dataset.map) dataset.map = add_obstacle([160, 80], [30, 80], dataset.map) # dataset 7: multiple obs dataset for 2D Arm obs avoid elif dataset_str is "MultiObstacleDataset": # params dataset.cols = 400 # x dataset.rows = 300 # y dataset.origin_x = -20 dataset.origin_y = -10 dataset.cell_size = 0.1 # map dataset.map = np.zeros((dataset.rows, dataset.cols)) # obstacles dataset.map = add_obstacle( get_center(12, 10, dataset), get_dim(5, 7, dataset), dataset.map ) dataset.map = add_obstacle( get_center(-7, 10, dataset), get_dim(10, 7, dataset), dataset.map ) dataset.map = add_obstacle( get_center(0, -5, dataset), get_dim(10, 5, dataset), dataset.map ) # mobile 2d map elif dataset_str is "MobileMap1": # params dataset.cols = 500 # x dataset.rows = 500 # y dataset.origin_x = -10 dataset.origin_y = -10 dataset.cell_size = 0.01 # map dataset.map = np.zeros((dataset.rows, dataset.cols)) # obstacles dataset.map = add_obstacle( get_center(0, 0, dataset), get_dim(1, 5, dataset), dataset.map ) # dataset.map = add_obstacle(get_center(-2.5,-2,dataset), get_dim(5,1,dataset), dataset.map); # wall dataset.map = add_obstacle( get_center(0, 4.5, dataset), get_dim(10, 1, dataset), dataset.map ) dataset.map = add_obstacle( get_center(0, -4.5, dataset), get_dim(10, 1, dataset), dataset.map ) dataset.map = add_obstacle( get_center(4.5, 0, dataset), get_dim(1, 10, dataset), dataset.map ) dataset.map = add_obstacle( get_center(-4.5, 0, dataset), get_dim(1, 10, dataset), dataset.map ) # no such dataset else: raise NameError("No such dataset exist") return dataset class Patrol2Ddataset(object): # keep track of objets, and their velocity. # add big boundary stationary walls on all 4 sides. # randomly intialize objets of same size at different x, y # set random velocity magnitudes and directions for each objects # simulate / move by dt time. # if y is less than bottow or y is > top vy *= -1 # if x is less than left or x is > right vx *= -1 def __init__( self, rows=400, cols=200, # rows corresponds to y origin_x=0.0, origin_y=0.0, cell_size=0.1, ): self.dataset = Dataset() self.dataset.cols = cols self.dataset.rows = rows self.dataset.origin_x = origin_x self.dataset.origin_y = origin_y self.dataset.cell_size = cell_size # map self.static_obstacles = [] self.dynamic_obstacles = [] # left, right, bottom, up self.bounds = [ origin_x, origin_x + cell_size * cols, origin_y, origin_y + cell_size * rows, ] def init_obstacles(self, seed_val=None, obstacle_num=100, vel_limit=0.8, acc_limit=None,): if seed_val is None: seed_val = 0 dataset_random.seed(seed_val) # make static obstacles self.static_obstacles.append( self.make_obstacle(10.0, 15.0, np.asarray([1.0, 3.0])) ) self.static_obstacles.append(self.make_obstacle(3.0, 20.0, np.asarray([4, 40]))) self.static_obstacles.append( self.make_obstacle(17.0, 20.0, np.asarray([4, 40])) ) # make dynamic obstacles self.dynamic_bounds = np.asarray(self.bounds) self.dynamic_bounds[0] = 8.0 self.dynamic_bounds[1] = 12.0 self.dynamic_obstacles.append( self.make_obstacle( random_number(self.dynamic_bounds[0], self.dynamic_bounds[1]), 10, np.asarray([5.0, 3.0]), ) ) self.dynamic_obstacles[0].v_y = 0.0 self.dynamic_obstacles[0].v_x = vel_limit# * (2.0/3.0) if obstacle_num == 2: self.dynamic_obstacles.append( self.make_obstacle( random_number(self.dynamic_bounds[0], self.dynamic_bounds[1]), 25, np.asarray([5.0, 3.0]), ) ) self.dynamic_obstacles[1].v_y = 0.0 self.dynamic_obstacles[1].v_x = vel_limit self.static_obstacles.append( self.make_obstacle(10.0, 30.0, np.asarray([1.0, 3.0])) ) self.obstacles = self.static_obstacles + self.dynamic_obstacles def make_obstacle(self, x, y, size): obs = Obstacle() obs.x = x obs.y = y obs.size = size return obs def simulate(self, dt): for obs in self.dynamic_obstacles: obs.x += dt * obs.v_x obs.y += dt * obs.v_y # change velocities if obs.x <= self.dynamic_bounds[0] or obs.x >= self.dynamic_bounds[1]: obs.v_x *= -1 if obs.y <= self.dynamic_bounds[2] or obs.y >= self.dynamic_bounds[3]: obs.v_y *= -1 def get_dataset(self, pose=None, map_size=None): # size in meters self.dataset.map = np.zeros((self.dataset.rows, self.dataset.cols)) for obs in self.static_obstacles: self.dataset.map = add_obstacle( get_center(obs.x, obs.y, self.dataset), get_dim(obs.size[0], obs.size[1], self.dataset), self.dataset.map, ) for obs in self.dynamic_obstacles: self.dataset.map = add_obstacle( get_center(obs.x, obs.y, self.dataset), get_dim(obs.size[0], obs.size[1], self.dataset), self.dataset.map, ) if pose is None or map_size is None: return self.dataset temp_dataset = Dataset() temp_dataset.origin_x = pose[0] - float(map_size[0]) / 2.0 temp_dataset.origin_y = pose[1] - float(map_size[1]) / 2.0 temp_dataset.cell_size = self.dataset.cell_size lower_left = get_center( temp_dataset.origin_x, temp_dataset.origin_y, self.dataset ) if lower_left[0] < 0: lower_left[0] = 0 temp_dataset.origin_y = self.dataset.origin_y if lower_left[1] < 0: lower_left[1] = 0 temp_dataset.origin_x = self.dataset.origin_x upper_right = get_center( pose[0] + float(map_size[0]) / 2.0, pose[1] + float(map_size[1]) / 2.0, self.dataset, ) if upper_right[0] >= self.dataset.map.shape[0]: upper_right[0] = self.dataset.map.shape[0] - 1 if upper_right[1] >= self.dataset.map.shape[1]: upper_right[1] = self.dataset.map.shape[1] - 1 if ( upper_right[0] < 0 or upper_right[1] < 0 or lower_left[0] >= self.dataset.map.shape[0] or lower_left[1] >= self.dataset.map.shape[1] ): temp_dataset.map = np.zeros((5, 5)) # some map of zeros else: temp_dataset.map = self.dataset.map[ lower_left[0] : upper_right[0] + 1, lower_left[1] : upper_right[1] + 1 ] temp_dataset.rows = temp_dataset.map.shape[0] temp_dataset.cols = temp_dataset.map.shape[1] return temp_dataset class Dynamic2Ddataset(object): # keep track of objets, and their velocity. # add big boundary stationary walls on all 4 sides. # randomly intialize objets of same size at different x, y # set random velocity magnitudes and directions for each objects # simulate / move by dt time. # if y is less than bottow or y is > top vy *= -1 # if x is less than left or x is > right vx *= -1 def __init__( self, rows=900, cols=1200, origin_x=0.0, origin_y=0.0, cell_size=0.1, ): self.dataset = Dataset() self.dataset.cols = cols self.dataset.rows = rows self.dataset.origin_x = origin_x self.dataset.origin_y = origin_y self.dataset.cell_size = cell_size # map self.obstacles = [] # left, right, bottom, up self.bounds = [ origin_x, origin_x + cell_size * cols, origin_y, origin_y + cell_size * rows, ] self.obs_size = (self.bounds[1] - self.bounds[0]) / 20.0 self.obs_dist = 10.0 self.goal = None self.start = None self.uniform_grid = False def init_obstacles(self, seed_val=None, obstacle_num=100, vel_limit=None, acc_limit=None, start=None, goal=None): if obstacle_num == -1: self.uniform_grid = True x = self.bounds[0] while x < self. bounds[1]: y = self.bounds[2] while y < self.bounds[3]: obs = Obstacle() obs.x = x obs.y = y obs.size = np.asarray([self.obs_size, self.obs_size]) y += 15.0 if goal is not None: if np.linalg.norm(np.array([obs.x-goal[0], obs.y-goal[1]])) < self.obs_dist: continue if start is not None: if np.linalg.norm(np.array([obs.x-start[0], obs.y-start[1]])) < self.obs_dist: continue self.obstacles.append(obs) x += 15.0 return if start is not None: self.start = start if goal is not None: self.goal = goal if seed_val is None: seed_val = 0 dataset_random.seed(seed_val) if vel_limit is None: vel_limit = self.obs_size / 6 self.obs_velocity = vel_limit if acc_limit is None: acc_limit = self.obs_size / 10 self.obs_acc = acc_limit # change in acceleration with time self.acc_dt = self.obs_acc / 10 while len(self.obstacles) < obstacle_num: # choose random x,y for obstacles. obs = Obstacle() obs.x = random_number(self.bounds[0], self.bounds[1]) obs.y = random_number(self.bounds[2], self.bounds[3]) if goal is not None: if np.linalg.norm(np.array([obs.x-goal[0], obs.y-goal[1]])) < self.obs_dist: continue if start is not None: if np.linalg.norm(np.array([obs.x-start[0], obs.y-start[1]])) < self.obs_dist: continue obs.v_x = random_number(-1 * self.obs_velocity, self.obs_velocity) obs.v_y = random_number(-1 * self.obs_velocity, self.obs_velocity) obs.a_x = random_number(-1 * self.obs_acc, self.obs_acc) obs.a_y = random_number(-1 * self.obs_acc, self.obs_acc) obs.size = np.asarray([self.obs_size, self.obs_size]) self.obstacles.append(obs) # print('bounds', self.bounds, self.obs_size) def simulate(self, dt): if self.uniform_grid: return for obs in self.obstacles: # Set accelerations if random_number(0.0, 1.0) > 0.5: obs.a_x += self.acc_dt else: obs.a_x -= self.acc_dt obs.a_x = min(obs.a_x, self.obs_acc) obs.a_x = max(obs.a_x, -1 * self.obs_acc) if random_number(0.0, 1.0) > 0.5: obs.a_y += self.acc_dt else: obs.a_y -= self.acc_dt obs.a_y = min(obs.a_y, self.obs_acc) obs.a_y = max(obs.a_y, -1 * self.obs_acc) obs.v_x += dt * obs.a_x obs.v_y += dt * obs.a_y obs.v_x = min(obs.v_x, self.obs_velocity) obs.v_x = max(obs.v_x, -1 * self.obs_velocity) obs.v_y = min(obs.v_y, self.obs_velocity) obs.v_y = max(obs.v_y, -1 * self.obs_velocity) obs.x += dt * obs.v_x obs.y += dt * obs.v_y if self.goal is not None: if np.linalg.norm(np.array([obs.x-self.goal[0], obs.y-self.goal[1]])) < self.obs_dist: # bounce off the circle around goal v1 = np.array([obs.x-self.goal[0], obs.y-self.goal[1]]) v1 = v1/np.linalg.norm(v1) v2 = -1 * np.array([obs.v_x, obs.v_y]) v2 = v2/np.linalg.norm(v2) theta = math.acos(np.linalg.norm( np.dot(v1, v2))) alpha = math.atan2(obs.v_y, obs.v_x) beta = math.atan2(obs.y - self.goal[1], obs.x - self.goal[0]) vel_vect = np.array([obs.v_x, obs.v_y]) angle = beta - alpha - theta rot_mat = np.array([[math.cos(angle), -1* math.sin(angle)], [ math.sin(angle), math.cos(angle)]]) new_vels = np.matmul(np.asarray([obs.v_x, obs.v_y]) , rot_mat.T) obs.v_x = new_vels[0] obs.v_y = new_vels[1] if self.start is not None: if np.linalg.norm(np.array([obs.x-self.start[0], obs.y-self.start[1]])) < self.obs_dist: # bounce off the circle around start v1 = np.array([obs.x-self.start[0], obs.y-self.start[1]]) v1 = v1/np.linalg.norm(v1) v2 = -1 * np.array([obs.v_x, obs.v_y]) v2 = v2/np.linalg.norm(v2) theta = math.acos(np.linalg.norm( np.dot(v1, v2))) alpha = math.atan2(obs.v_y, obs.v_x) beta = math.atan2(obs.y - self.start[1], obs.x - self.start[0]) vel_vect = np.array([obs.v_x, obs.v_y]) angle = beta - alpha - theta rot_mat = np.array([[math.cos(angle), -1* math.sin(angle)], [ math.sin(angle), math.cos(angle)]]) new_vels = np.matmul(np.asarray([obs.v_x, obs.v_y]) , rot_mat.T) obs.v_x = new_vels[0] obs.v_y = new_vels[1] # change velocities if obs.x <= self.bounds[0] or obs.x >= self.bounds[1]: obs.v_x *= -1 if obs.y <= self.bounds[2] or obs.y >= self.bounds[3]: obs.v_y *= -1 def get_dataset(self, pose=None, map_size=None): # size in meters self.dataset.map = np.zeros((self.dataset.rows, self.dataset.cols)) for obs in self.obstacles: self.dataset.map = add_obstacle( get_center(obs.x, obs.y, self.dataset), get_dim(obs.size[0], obs.size[1], self.dataset), self.dataset.map, ) if pose is None or map_size is None: return self.dataset temp_dataset = Dataset() temp_dataset.origin_x = pose[0] - float(map_size[0]) / 2.0 temp_dataset.origin_y = pose[1] - float(map_size[1]) / 2.0 temp_dataset.cell_size = self.dataset.cell_size lower_left = get_center( temp_dataset.origin_x, temp_dataset.origin_y, self.dataset ) if lower_left[0] < 0: lower_left[0] = 0 temp_dataset.origin_y = self.dataset.origin_y if lower_left[1] < 0: lower_left[1] = 0 temp_dataset.origin_x = self.dataset.origin_x upper_right = get_center( pose[0] + float(map_size[0]) / 2.0, pose[1] + float(map_size[1]) / 2.0, self.dataset, ) if upper_right[0] >= self.dataset.map.shape[0]: upper_right[0] = self.dataset.map.shape[0] - 1 if upper_right[1] >= self.dataset.map.shape[1]: upper_right[1] = self.dataset.map.shape[1] - 1 if ( upper_right[0] < 0 or upper_right[1] < 0 or lower_left[0] >= self.dataset.map.shape[0] or lower_left[1] >= self.dataset.map.shape[1] ): temp_dataset.map = np.zeros((5, 5)) # some map of zeros else: temp_dataset.map = self.dataset.map[ lower_left[0] : upper_right[0] + 1, lower_left[1] : upper_right[1] + 1 ] temp_dataset.rows = temp_dataset.map.shape[0] temp_dataset.cols = temp_dataset.map.shape[1] return temp_dataset
31.920437
117
0.541909
2,836
20,461
3.750353
0.080395
0.060173
0.028958
0.033565
0.749812
0.718785
0.685032
0.654757
0.64686
0.62138
0
0.039828
0.342261
20,461
640
118
31.970313
0.750483
0.107717
0
0.575472
0
0
0.005119
0
0
0
0
0
0
1
0.037736
false
0
0.011792
0.004717
0.087264
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
3d4f6da0c97765197cecb412ea6a94dc404e7932
335
py
Python
Parte 1/Lista 01/002.py
Raiane-nepomuceno/Python
acf8bd0436c717614fe7fd4f62e9fa2e432c386a
[ "MIT" ]
null
null
null
Parte 1/Lista 01/002.py
Raiane-nepomuceno/Python
acf8bd0436c717614fe7fd4f62e9fa2e432c386a
[ "MIT" ]
null
null
null
Parte 1/Lista 01/002.py
Raiane-nepomuceno/Python
acf8bd0436c717614fe7fd4f62e9fa2e432c386a
[ "MIT" ]
null
null
null
n1 = float(input('Digite o primeiro número:')) n2 = float(input('Digite o segundo número:')) n3 = float(input('Digite o terceiroo número:')) if n1 > n2 and n1 > n3: print('O maior número é {}'.format(n1)) elif n2 > n1 and n2 > n3: print('O maior número é {}'.format(n2)) else: print('O maior número é {}'.format(n3))
27.916667
47
0.623881
55
335
3.8
0.345455
0.143541
0.229665
0.244019
0.363636
0.363636
0.248804
0
0
0
0
0.052434
0.202985
335
11
48
30.454545
0.730337
0
0
0
0
0
0.39403
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
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
3d5673abbc84a79b57c56a6a63a187bba7fc7012
426
py
Python
src/gallery/settings.py
jsmesami/naovoce
235c6e05ef37be23d3b9bd0b76d80080c58617a0
[ "BSD-3-Clause" ]
18
2016-02-23T15:34:58.000Z
2022-02-28T08:15:30.000Z
src/gallery/settings.py
jsmesami/naovoce
235c6e05ef37be23d3b9bd0b76d80080c58617a0
[ "BSD-3-Clause" ]
66
2016-03-15T19:59:09.000Z
2022-03-11T23:25:41.000Z
src/gallery/settings.py
jsmesami/naovoce
235c6e05ef37be23d3b9bd0b76d80080c58617a0
[ "BSD-3-Clause" ]
7
2016-03-24T09:13:07.000Z
2018-09-16T17:04:50.000Z
from django.conf import settings # Iterable of lowercase model names, whose instances are allowed to store images # POSTed by authenticated users (default is empty list). GALLERY_PUBLIC_CONTAINERS = getattr(settings, 'GALLERY_PUBLIC_CONTAINERS', []) # Integer number of maximum bytes available for image storage (default is 5MB). GALLERY_IMAGE_MAX_FILESIZE = getattr(settings, 'GALLERY_IMAGE_MAX_FILESIZE', 5 * 1024 * 1024)
47.333333
93
0.802817
58
426
5.724138
0.724138
0.054217
0.138554
0.138554
0
0
0
0
0
0
0
0.026954
0.129108
426
8
94
53.25
0.867925
0.495305
0
0
0
0
0.241706
0.241706
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
3d56dba0a631b06f5405faa58f3c1200f89797f1
1,912
py
Python
setup.py
xeddmc/transformationInvariantImageSearch
10800ace74441382a41be1a48fe2e01cd8e89a9f
[ "MIT" ]
285
2017-08-06T06:15:22.000Z
2022-01-24T14:52:33.000Z
setup.py
xeddmc/transformationInvariantImageSearch
10800ace74441382a41be1a48fe2e01cd8e89a9f
[ "MIT" ]
7
2017-08-13T11:10:28.000Z
2019-07-25T10:22:26.000Z
setup.py
xeddmc/transformationInvariantImageSearch
10800ace74441382a41be1a48fe2e01cd8e89a9f
[ "MIT" ]
41
2017-08-10T07:24:12.000Z
2021-12-26T15:24:20.000Z
#!/usr/bin/env python from setuptools import setup, find_packages """ TODO - copy or link `python` folder to `transformation_invariant_image_search` """ def readme(): with open('README.md') as f: return f.read() setup( name='transformation-invariant-image-search', version='0.0.1', description='a reverse image search algorithm which performs 2D affine ' 'transformation-invariant partial image-matching in sublinear time with ' 'respect to the number of images in our database.', long_description=readme(), long_description_content_type="text/markdown", author='Tom Murphy', author_email='murphyt7@tcd.ie', maintainer='Rachmadani Haryono', maintainer_email='foreturiga@gmail.com', license='MIT', url='https://github.com/pippy360/transformationInvariantImageSearch', packages=find_packages(), include_package_data=True, zip_safe=False, python_requires='>=3.6', install_requires=[ 'hiredis', 'numpy', 'redis', 'scikit-learn', 'scipy', 'tqdm>=4.29.1', ], entry_points={ 'console_scripts': [ 'transformation-invariant-image-search = transformation_invariant_image_search.main:main'] }, classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Indexing/Search', 'Topic :: Utilities' ] )
31.866667
102
0.633891
200
1,912
5.955
0.665
0.096558
0.094039
0.11419
0
0
0
0
0
0
0
0.014354
0.234833
1,912
59
103
32.40678
0.799727
0.01046
0
0
0
0
0.54903
0.080332
0
0
0
0.016949
0
1
0.019608
true
0
0.019608
0
0.058824
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
1
0
0
0
0
0
0
2
e9e2b96b8719f04eb61ae338d24ecbc4574e9900
5,066
py
Python
tests/integration/controller/test_featuregeographicalposition_controller.py
faysal-ishtiaq/climsoft-api
46dacdeba5d935ee3b944df00731640170b87ccd
[ "MIT" ]
null
null
null
tests/integration/controller/test_featuregeographicalposition_controller.py
faysal-ishtiaq/climsoft-api
46dacdeba5d935ee3b944df00731640170b87ccd
[ "MIT" ]
2
2022-03-01T13:10:22.000Z
2022-03-24T08:47:20.000Z
tests/integration/controller/test_featuregeographicalposition_controller.py
openclimateinitiative/climsoft-api
3591d7499dd7777617b8086332dc83fab1af9588
[ "MIT" ]
2
2021-12-22T21:50:19.000Z
2022-01-28T12:53:32.000Z
import datetime import json import pytest from opencdms.models.climsoft import v4_1_1_core as climsoft_models from sqlalchemy.orm.session import Session from climsoft_api.api.featuregeographicalposition import ( schema as featuregeographicalposition_schema, ) from tests.datagen import ( featuregeographicalposition as climsoft_feature_geographical_position, synopfeature as climsoft_synop_feature, ) from fastapi.testclient import TestClient @pytest.fixture def get_synop_feature(session: Session): synop_feature = climsoft_models.Synopfeature( **climsoft_synop_feature.get_valid_synop_feature_input().dict() ) session.add(synop_feature) session.commit() yield synop_feature @pytest.fixture def get_feature_geographical_position( get_synop_feature: climsoft_models.Synopfeature, session: Session ): feature_geographical_position = climsoft_models.Featuregeographicalposition( **climsoft_feature_geographical_position.get_valid_feature_geographical_position_input( synop_feature_abbreviation=get_synop_feature.abbreviation ).dict() ) session.add(feature_geographical_position) session.commit() yield feature_geographical_position @pytest.fixture def get_feature_geographical_positions( get_synop_feature: climsoft_models.Synopfeature, session: Session ): for _ in range(10): feature_geographical_position = climsoft_models.Featuregeographicalposition( **climsoft_feature_geographical_position.get_valid_feature_geographical_position_input( synop_feature_abbreviation=get_synop_feature.abbreviation ).dict() ) session.add(feature_geographical_position) session.commit() yield feature_geographical_position def test_should_return_first_five_feature_geographical_positions( client: TestClient, get_feature_geographical_positions ): response = client.get( "/v1/feature-geographical-positions", params={"limit": 5}, ) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 5 def test_should_return_single_feature_geographical_position( client: TestClient, get_feature_geographical_position: climsoft_models.Featuregeographicalposition, ): response = client.get( f"/v1/feature-geographical-positions/{get_feature_geographical_position.belongsTo}", ) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_create_a_feature_geographical_position( client: TestClient, get_synop_feature: climsoft_models.Synopfeature, ): feature_geographical_position_data = climsoft_feature_geographical_position.get_valid_feature_geographical_position_input( synop_feature_abbreviation=get_synop_feature.abbreviation ).dict( by_alias=True ) response = client.post( "/v1/feature-geographical-positions", data=json.dumps(feature_geographical_position_data, default=str), ) assert response.status_code == 200 response_data = response.json() assert len(response_data["result"]) == 1 def test_should_raise_validation_error( client: TestClient, get_synop_feature: climsoft_models.Synopfeature, ): response = client.post( "/v1/feature-geographical-positions", data=json.dumps({"belongs_to": get_synop_feature.abbreviation}, default=str), ) assert response.status_code == 422 def test_should_update_feature_geographical_position( client: TestClient, get_feature_geographical_position: climsoft_models.Featuregeographicalposition, ): feature_geographical_position_data = ( featuregeographicalposition_schema.FeatureGeographicalPosition.from_orm( get_feature_geographical_position ).dict(by_alias=True) ) belongs_to = feature_geographical_position_data.pop("belongs_to") updates = { **feature_geographical_position_data, "observed_on": datetime.datetime.utcnow().isoformat(), } response = client.put( f"/v1/feature-geographical-positions/{belongs_to}", data=json.dumps(updates, default=str), ) response_data = response.json() assert response.status_code == 200 assert response_data["result"][0]["observed_on"] == updates["observed_on"] def test_should_delete_feature_geographical_position( client: TestClient, get_feature_geographical_position ): feature_geographical_position_data = ( featuregeographicalposition_schema.FeatureGeographicalPosition.from_orm( get_feature_geographical_position ).dict(by_alias=True) ) belongs_to = feature_geographical_position_data.pop("belongs_to") response = client.delete( f"/v1/feature-geographical-positions/{belongs_to}", ) assert response.status_code == 200 response = client.get( f"/v1/feature-geographical-positions/{belongs_to}", ) assert response.status_code == 404
33.111111
126
0.754639
540
5,066
6.701852
0.164815
0.215253
0.231279
0.058027
0.690522
0.65543
0.613982
0.602929
0.523073
0.502901
0
0.00899
0.165614
5,066
152
127
33.328947
0.847173
0
0
0.534884
0
0
0.081919
0.063758
0
0
0
0
0.085271
1
0.069767
false
0
0.062016
0
0.131783
0
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
e9e492d963155e561195c8335810cd4412129303
535
py
Python
alge.py
DwarflinDeveloping/pyalge
53e305732e9b13354528d0ae7fcf8f6fc7408236
[ "MIT" ]
1
2021-07-08T12:23:16.000Z
2021-07-08T12:23:16.000Z
alge.py
DwarflinDeveloping/pyalge
53e305732e9b13354528d0ae7fcf8f6fc7408236
[ "MIT" ]
null
null
null
alge.py
DwarflinDeveloping/pyalge
53e305732e9b13354528d0ae7fcf8f6fc7408236
[ "MIT" ]
null
null
null
import random alges = ["Alge 2", "Alge 3", "Alge 4", "Alge 5", "Alge 6"] megaalges = ["Grün", "Rot", "Blau", "Gelb"] colours = ["Grün", "Rot"] # Generates a random Alge from the lists above def generate_alge(): alge = random.choice(alges) return alge # Generates a random Megaalge colour from the lists above def generate_megaalge(): colour = random.choice(megaalges) return colour # Generates a random colour from the normal Alge game def generate_colour(): colour = random.choice(colours) return colour
23.26087
58
0.68785
74
535
4.932432
0.391892
0.082192
0.131507
0.093151
0.153425
0.153425
0
0
0
0
0
0.011601
0.194393
535
22
59
24.318182
0.835267
0.284112
0
0.153846
1
0
0.137203
0
0
0
0
0
0
1
0.230769
false
0
0.076923
0
0.538462
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
e9f7d5e00f1cd1410d3513589c9e7bc05b89f168
2,369
py
Python
combine.py
rubyhung0529/c620
e46db591ad48b67732d0e20097954f54d9c4e84a
[ "MIT" ]
null
null
null
combine.py
rubyhung0529/c620
e46db591ad48b67732d0e20097954f54d9c4e84a
[ "MIT" ]
null
null
null
combine.py
rubyhung0529/c620
e46db591ad48b67732d0e20097954f54d9c4e84a
[ "MIT" ]
null
null
null
from model import C620_OP,C620_SF,TR_C620,C660_MF,TR_C620_T651,C660_OP,C660_SF,TR_C660,C670_OP,C670_SF,TR_C670 import torch from torch import nn from torch.utils.tensorboard import SummaryWriter class Model(nn.Module): def __init__(self): super().__init__() self.c620_op = C620_OP() self.c620_sf = C620_SF() self.tr_c620 = TR_C620() self.c660_mf = C660_MF() self.tr_c620_t651 = TR_C620_T651() self.c660_op = C660_OP() self.c660_sf = C660_SF() self.tr_c660 = TR_C660() self.c670_op = C670_OP() self.c670_sf = C670_SF() self.tr_c670 = TR_C670() def forward(self,c620_case,c620_feed,t651_feed,c660_case): # 620 c620_op = self.c620_op(c620_case,c620_feed) c620_s1, c620_s2, c620_s3, c620_s4 = self.c620_sf(c620_case, c620_feed) c620_w1, c620_w2, c620_w3, c620_w4 = self.tr_c620(c620_feed, c620_s1, c620_s2, c620_s3, c620_s4) # 651 m_c620,m_t651 = self.c660_mf(t651_feed, c620_w3) print(c620_w3.shape,t651_feed.shape,m_c620.shape,m_t651.shape) c660_feed = self.tr_c620_t651(c620_w3,t651_feed,m_c620,m_t651) # 660 c660_op = self.c660_op(c660_case,c660_feed) c660_s1, c660_s2 ,c660_s3 ,c660_s4 = self.c660_sf(c660_case,c660_feed) c660_w1, c660_w2, c660_w3 ,c660_w4 = self.tr_c660(c660_feed, c660_s1, c660_s2, c660_s3, c660_s4) # 670 c670_op = self.c670_op(c620_w4,c660_w4) c670_s1, c670_s2 = self.c670_sf(c620_w4,c660_w4) c670_w1 , c670_w2 = self.tr_c670(c620_w4+c660_w4,c670_s1,c670_s2) return c620_op, c620_w1, c620_w2, c620_w3, c620_w4 , \ c660_op, c660_w1, c660_w2, c660_w3, c660_w4 , \ c670_op, c670_w1, c670_w2 if __name__ == '__main__': # fake data c620_case = torch.rand(64,3) c660_case = torch.rand(64,2) feed_c620 = torch.rand(64,41) feed_t651 = torch.rand(64,41) # forward test model = Model() x = [c620_case,feed_c620,feed_t651,c660_case] y = model(*x) print('can forward') # backward test loss = 0 for p in y: loss += p.mean() loss.backward() print('can backward') # writer writer = SummaryWriter() writer.add_graph(model,x) print('can tensorboard') writer.close()
33.366197
110
0.640777
386
2,369
3.53886
0.170984
0.035139
0.029283
0.035139
0.245974
0.199122
0.199122
0.199122
0.093704
0.093704
0
0.271139
0.251161
2,369
71
111
33.366197
0.498873
0.024905
0
0
0
0
0.019983
0
0
0
0
0
0
1
0.038462
false
0
0.076923
0
0.153846
0.076923
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
e9f8ffcd330367d283c2595d762a0ff1c4b4bda6
1,602
py
Python
python/caty/core/casm/finder.py
hidaruma/caty
f71d2ab0a001ea4f7a96a6e02211187ebbf54773
[ "MIT" ]
null
null
null
python/caty/core/casm/finder.py
hidaruma/caty
f71d2ab0a001ea4f7a96a6e02211187ebbf54773
[ "MIT" ]
null
null
null
python/caty/core/casm/finder.py
hidaruma/caty
f71d2ab0a001ea4f7a96a6e02211187ebbf54773
[ "MIT" ]
null
null
null
#coding:utf-8 from caty.core.resource import ResourceFinder from caty.core.facility import ReadOnlyFacility from caty.core.language import split_colon_dot_path from caty.core.casm.language.casmparser import parse from caty.core.casm.language.ast import ModuleName import caty.core.runtimeobject as ro import caty.core.schema as schema from caty.core.casm.cursor import SchemaBuilder, ReferenceResolver, ProfileBuilder, TypeVarApplier, TypeNormalizer from topdown import * class SchemaFinder(ResourceFinder, ReadOnlyFacility): u"""スキーマ検索オブジェクト。 通常のコマンドクラスから参照されるので、ファシリティとして扱う。 """ def __init__(self, module, app, system, LocalModule): self._module = module ResourceFinder.__init__(self, app, system) self._local = LocalModule(self) self.get_type = lambda key: self._get_resource(key, ) def add_local(self, string): u"""ローカルスキーマの追加は一見すると破壊的操作だが、 実際には永続的な効果を及ぼさず、またそもそも CatyFIT など限られた用途にしか用いない。 そのため、書き込み処理としては扱わない。 """ self._local.compile(string) def clone(self): return self def to_name_tree(self): return self._module.to_name_tree() def items(self): return self._module.command_ns.items() def __setitem__(self, key, value): raise Exception(ro.i18n.get('Uneable to add command at runtime: $name', name=key)) def __delitem__(self, key): raise Exception(ro.i18n.get('Uneable to add command at runtime: $name', name=key)) def update(self, arg): raise Exception(ro.i18n.get('Uneable to add command at runtime: $name', name=key))
31.411765
114
0.714732
199
1,602
5.58794
0.396985
0.057554
0.064748
0.043165
0.215827
0.172662
0.172662
0.172662
0.172662
0.172662
0
0.005393
0.189763
1,602
50
115
32.04
0.85131
0.09613
0
0.096774
0
0
0.085714
0
0
0
0
0
0
1
0.258065
false
0
0.290323
0.096774
0.677419
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
e9fba91a5fa9461202ccb69b2edb3a3502dde595
4,135
py
Python
python/ec2_cpu_utilization/isolation_forest.py
JBris/time_series_anomaly_detection_examples
c0bb36be4d20128c3aca911dcce156f7e36ae6da
[ "MIT" ]
11
2020-03-20T07:42:23.000Z
2022-03-27T11:52:42.000Z
python/ec2_cpu_utilization/isolation_forest.py
JBris/time_series_anomaly_detection_examples
c0bb36be4d20128c3aca911dcce156f7e36ae6da
[ "MIT" ]
2
2021-04-30T21:06:31.000Z
2022-02-10T01:27:07.000Z
python/ec2_cpu_utilization/isolation_forest.py
JBris/time_series_anomaly_detection_examples
c0bb36be4d20128c3aca911dcce156f7e36ae6da
[ "MIT" ]
1
2020-07-15T03:29:21.000Z
2020-07-15T03:29:21.000Z
#!/usr/bin/env python import matplotlib.pyplot as plt import pandas as pd from dataset import load_data, filter_data from datetime import datetime from sklearn.ensemble import IsolationForest def iqr_bounds(scores,k=1.5): q1 = scores.quantile(0.25) q3 = scores.quantile(0.75) iqr = q3 - q1 lower_bound=(q1 - k * iqr) upper_bound=(q3 + k * iqr) print("Lower bound:{} \nUpper bound:{}".format(lower_bound,upper_bound)) return lower_bound,upper_bound def view_anomalies(df): #Fixed contamination value clf=IsolationForest(n_estimators=10, max_samples='auto', contamination=float(.04), \ max_features=1.0, bootstrap=False, n_jobs=-1, random_state=42, verbose=0) clf.fit(df[['value']]) df['scores']=clf.decision_function(df[['value']]) df['anomaly']=clf.predict(df[['value']]) df.head() df.loc[df['anomaly'] == 1,'anomaly'] = 0 df.loc[df['anomaly'] == -1,'anomaly'] = -1 print(df['anomaly'].value_counts()) # visualization fig, ax = plt.subplots(figsize=(10,6)) a = df.loc[df['anomaly'] == -1, ['timestamp', 'value']] #anomaly ax.plot(df['timestamp'], df['value'], color='blue', label = 'Normal') ax.scatter(a['timestamp'],a['value'], color='red', label = 'Anomaly') plt.legend() plt.show(); df['scores'].hist() plt.show(); #IQR-based print() lower_bound,upper_bound=iqr_bounds(df['scores'],k=2) df['anomaly']=0 df['anomaly']=(df['scores'] < lower_bound) |(df['scores'] > upper_bound) df['anomaly']=df['anomaly'].astype(int) fig, ax = plt.subplots(figsize=(10,6)) a = df.loc[df['anomaly'] == 1, ['timestamp', 'value']] #anomaly ax.plot(df['timestamp'], df['value'], color='blue', label = 'Normal') ax.scatter(a['timestamp'],a['value'], color='red', label = 'Anomaly') plt.title('IQR-based'); plt.legend() plt.show(); print("Percentage of anomalies in data: {:.2f}".format((len(df.loc[df['anomaly']==1])/len(df))*100)) return df def validate_model(full_df): start_date = datetime.strptime('14-02-17 00:00:00', '%y-%m-%d %H:%M:%S') end_date = datetime.strptime('14-02-17 23:59:59', '%y-%m-%d %H:%M:%S') df=full_df.loc[ (full_df['timestamp'] > start_date) & (full_df['timestamp'] < end_date) ] # Using graph_objects df.plot(x='timestamp', y='value', figsize=(12,6)) plt.xlabel('Date time') plt.ylabel('CPU Utilization') plt.title('Distribution of Validation Data'); plt.show(); #Fixed contamination value clf=IsolationForest(n_estimators=10, max_samples='auto', contamination=float(.04), \ max_features=1.0, bootstrap=False, n_jobs=-1, random_state=42, verbose=0) clf.fit(df[['value']]) df['scores']=clf.decision_function(df[['value']]) df['anomaly']=clf.predict(df[['value']]) df.loc[df['anomaly'] == 1,'anomaly'] = 0 df.loc[df['anomaly'] == -1,'anomaly'] = -1 fig, ax = plt.subplots(figsize=(10,6)) a = df.loc[df['anomaly'] == -1, ['timestamp', 'value']] #anomaly ax.plot(df['timestamp'], df['value'], color='blue', label = 'Normal') ax.scatter(a['timestamp'],a['value'], color='red', label = 'Anomaly') plt.legend() plt.show(); print("Percentage of anomalies in data: {:.2f}".format((len(df.loc[df['anomaly']==1])/len(df))*100)) df['scores'].hist() plt.show(); #IQR-based lower_bound,upper_bound=iqr_bounds(df['scores'],k=2) df['anomaly']=0 df['anomaly']=(df['scores'] < lower_bound) |(df['scores'] > upper_bound) df['anomaly']=df['anomaly'].astype(int) fig, ax = plt.subplots(figsize=(10,6)) a = df.loc[df['anomaly'] == 1, ['timestamp', 'value']] #anomaly ax.plot(df['timestamp'], df['value'], color='blue', label = 'Normal') ax.scatter(a['timestamp'],a['value'], color='red', label = 'Anomaly') plt.title('IQR-based'); plt.legend() plt.show(); print("Percentage of anomalies in data: {:.2f}".format((len(df.loc[df['anomaly']==1])/len(df))*100)) full_df = load_data() df = filter_data(full_df) df = view_anomalies(df) validate_model(full_df)
37.252252
104
0.614994
594
4,135
4.19697
0.218855
0.079422
0.030886
0.061773
0.716406
0.716406
0.690734
0.669073
0.669073
0.669073
0
0.030277
0.169287
4,135
110
105
37.590909
0.695488
0.037243
0
0.651163
0
0
0.213854
0
0
0
0
0
0
1
0.034884
false
0
0.05814
0
0.116279
0.069767
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e9ff01f085b150757604e0c223d2dacf02d4f03d
1,641
py
Python
quadruped_spring/env/sensors/sensor.py
francescovezzi/quadruped_spring
23848496ac7a4508e8a0f527e961c7956fd12f95
[ "MIT" ]
3
2022-02-21T22:30:21.000Z
2022-03-03T12:59:25.000Z
quadruped_spring/env/sensors/sensor.py
francescovezzi/quadruped_spring
23848496ac7a4508e8a0f527e961c7956fd12f95
[ "MIT" ]
1
2022-03-28T09:22:50.000Z
2022-03-28T16:44:46.000Z
quadruped_spring/env/sensors/sensor.py
francescovezzi/quadruped_spring
23848496ac7a4508e8a0f527e961c7956fd12f95
[ "MIT" ]
null
null
null
import numpy as np class Sensor: """A prototype class for a generic sensor""" def __init__(self): self._data = None self._robot = None self._name = "please give me a name" def _check_dimension(self): assert np.shape(self._high) == np.shape(self._low), "high limit and low limits are different in size" assert np.shape(self._high) == np.shape(self._data), "Observation different from sensor observation limits" def _update_sensor_info(self, high, low, noise_std): self._high = high self._low = low self._noise_std = noise_std self._dim = np.shape(self._high) def _sample_noise(self): if np.all(self._noise_std > 0.0): self._add_obs_noise = np.random.normal(scale=self._noise_std) elif np.all(self._noise_std == 0.0): self._add_obs_noise = np.zeros(np.shape(self._noise_std)) else: raise ValueError(f"Noise standard deviation should be >= 0.0. not {self._noise_std}") def _set_sensor(self, robot): """Call it at init""" self._robot = robot def _init_sensor(self, robot_config): self._robot_config = robot_config def _reset_sensor(self): """Call it at reset""" pass def _read_data(self): """Get Sensor data without noise""" return self._data def _read_dirty_data(self): """Get Sensor data with noise""" return self._data + self._add_obs_noise def _on_step(self): """Callback for step method""" pass def _get_data(self): """Get sensor data""" pass
29.303571
115
0.616697
227
1,641
4.162996
0.339207
0.067725
0.069841
0.047619
0.210582
0.143915
0.143915
0.143915
0.07619
0.07619
0
0.005038
0.274223
1,641
55
116
29.836364
0.788413
0.102986
0
0.085714
0
0
0.128134
0
0
0
0
0
0.057143
1
0.314286
false
0.085714
0.028571
0
0.428571
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
1812ea22875050fd27c53bacef5856e5657bd76b
152
py
Python
Contests/Nowcoder/2019牛客国庆集训派对day5/a.py
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
Contests/Nowcoder/2019牛客国庆集训派对day5/a.py
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
Contests/Nowcoder/2019牛客国庆集训派对day5/a.py
DCTewi/My-Codes
9904f8057ec96e21cbc8cf9c62a49658a0f6d392
[ "MIT" ]
null
null
null
import sys, math while True: line = sys.stdin.readline() if not line: break a, b = (int(x) for x in line.split()) print(a // b)
19
41
0.552632
25
152
3.36
0.76
0.047619
0
0
0
0
0
0
0
0
0
0
0.309211
152
7
42
21.714286
0.8
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0.142857
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
1813dac14062ae3add86a1ebee2a5fe9309f4955
1,120
py
Python
virtual/lib/python3.7/site-packages/bp/tests/test_readonly.py
candycrushpro/pitch-project
8f850153fa3debcd858c5a58e7296d7cbda3918b
[ "MIT" ]
null
null
null
virtual/lib/python3.7/site-packages/bp/tests/test_readonly.py
candycrushpro/pitch-project
8f850153fa3debcd858c5a58e7296d7cbda3918b
[ "MIT" ]
null
null
null
virtual/lib/python3.7/site-packages/bp/tests/test_readonly.py
candycrushpro/pitch-project
8f850153fa3debcd858c5a58e7296d7cbda3918b
[ "MIT" ]
null
null
null
# Copyright (C) 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy # of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from bp.readonly import ReadOnlyPath from bp.tests.test_paths import AbstractFilePathTestCase class ReadOnlyPathTestCase(AbstractFilePathTestCase): def setUp(self): AbstractFilePathTestCase.setUp(self) self.path = ReadOnlyPath(self.path) def test_createDirectory(self): """ createDirectory() cannot create new directories on a read-only file path. """ self.assertRaises(Exception, self.path.child(b"directory").createDirectory)
33.939394
77
0.724107
144
1,120
5.618056
0.652778
0.074166
0.032138
0.039555
0
0
0
0
0
0
0
0.008959
0.202679
1,120
32
78
35
0.896976
0.575
0
0
0
0
0.020833
0
0
0
0
0
0.111111
1
0.222222
false
0
0.222222
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
181989633c09b63b9232d25e921d1c1e592980d4
1,584
py
Python
tests/tests.py
gregplaysguitar/django-fileman
66f3d30116a35ec6b59437c747a6a2f10f16072b
[ "BSD-3-Clause" ]
7
2017-11-06T12:09:37.000Z
2019-09-26T14:49:00.000Z
tests/tests.py
gregplaysguitar/django-fileman
66f3d30116a35ec6b59437c747a6a2f10f16072b
[ "BSD-3-Clause" ]
9
2017-02-07T23:14:11.000Z
2018-11-29T20:59:08.000Z
tests/tests.py
gregplaysguitar/django-fileman
66f3d30116a35ec6b59437c747a6a2f10f16072b
[ "BSD-3-Clause" ]
9
2017-03-17T08:25:19.000Z
2020-06-24T14:32:58.000Z
import os from django.test import TestCase, Client from django.contrib.auth.models import User try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse from fileman.views import read_dir, get_full_path USER = 'test' ADMIN = 'admin' PASSWORD = '123' TEST_FILE = 'test.txt' class FilemanTestCase(TestCase): def setUp(self): self.admin = User.objects.create_user( username=ADMIN, password=PASSWORD) self.admin.is_staff = True self.admin.save() self.user = User.objects.create_user( username=USER, password=PASSWORD) # TODO # test rename # test delete def test_upload(self): url = reverse('admin:fileman_upload_upload') login_url = reverse('admin:login') c = Client() response = c.post(login_url, {'username': USER, 'password': PASSWORD}) self.assertEqual(response.status_code, 200) with open(get_full_path(TEST_FILE)) as fp: response = c.post(url, {'upload': fp}) # should be redirected to login self.assertEqual(response.status_code, 302) self.assertEqual(response.url.find(login_url) != -1, True) response = c.post(login_url, {'username': ADMIN, 'password': PASSWORD}) with open(get_full_path(TEST_FILE)) as fp: response = c.post(url, {'upload': fp}) self.assertEqual(response.status_code, 200) def test_file_listing(self): results = read_dir('') self.assertEqual(results['list'][0]['name'], TEST_FILE)
28.8
79
0.651515
200
1,584
5.025
0.355
0.039801
0.051741
0.086567
0.329353
0.238806
0.109453
0.109453
0.109453
0.109453
0
0.011513
0.232323
1,584
54
80
29.333333
0.814967
0.036616
0
0.162162
0
0
0.072321
0.017751
0
0
0
0.018519
0.135135
1
0.081081
false
0.135135
0.189189
0
0.297297
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
18258761bb58d33e903e06a5c8f82a559d3ed418
923
py
Python
src/zen/algorithms/community/community_common.py
networkdynamics/zenlib
860d7ea81903caa3418c3ed0ba8f1816fee6d44f
[ "BSD-3-Clause" ]
41
2015-01-13T19:49:50.000Z
2021-05-02T04:11:19.000Z
src/zen/algorithms/community/community_common.py
networkdynamics/zenlib
860d7ea81903caa3418c3ed0ba8f1816fee6d44f
[ "BSD-3-Clause" ]
9
2015-01-28T10:46:27.000Z
2022-03-12T06:32:39.000Z
src/zen/algorithms/community/community_common.py
networkdynamics/zenlib
860d7ea81903caa3418c3ed0ba8f1816fee6d44f
[ "BSD-3-Clause" ]
19
2015-01-27T12:19:42.000Z
2019-07-20T21:30:56.000Z
# TODO: Add preamble # Returns a list of the keys which have the maximal value in a dictionary def keys_of_max_value(dct): it = dct.iteritems() try: key, val = it.next() except: return [] max_val = val candidates = [key] while True: try: key, val = it.next() if val == max_val: candidates.append(key) elif val > max_val: candidates = [key] max_val = val except StopIteration: break return candidates # Modifies a community table so that the community indices range from 0 to # N - 1. Returns the number of communities. def normalize_communities(G,comm_table): old_to_new_comms = {} max_cidx = 0 for i in G.nodes_(): #range(len(comm_table)): cidx = comm_table[i] if cidx in old_to_new_comms: new_cidx = old_to_new_comms[cidx] comm_table[i] = new_cidx else: old_to_new_comms[cidx] = max_cidx comm_table[i] = max_cidx max_cidx += 1 return max_cidx
21.465116
75
0.686891
150
923
4.006667
0.4
0.074875
0.053245
0.086522
0.106489
0
0
0
0
0
0
0.005563
0.221018
923
42
76
21.97619
0.83032
0.248104
0
0.25
0
0
0
0
0
0
0
0.02381
0
0
null
null
0
0
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
1
0
1
0
0
0
0
0
0
0
0
2
182cc61969a828906cd2bd43b1e07c3a9c77fba4
297
py
Python
squeezy/models/roles_users.py
k0machi/squeezy
46e2030645539c6a7b4532dd475d3d62b16a85c4
[ "BSD-3-Clause" ]
1
2021-07-12T15:03:30.000Z
2021-07-12T15:03:30.000Z
squeezy/models/roles_users.py
k0machi/squeezy
46e2030645539c6a7b4532dd475d3d62b16a85c4
[ "BSD-3-Clause" ]
null
null
null
squeezy/models/roles_users.py
k0machi/squeezy
46e2030645539c6a7b4532dd475d3d62b16a85c4
[ "BSD-3-Clause" ]
null
null
null
from database import db class RolesUsers(db.Model): __tablename__ = 'roles_users' id = db.Column(db.Integer(), primary_key=True) user_id = db.Column('user_id', db.Integer(), db.ForeignKey('user.id')) role_id = db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
33
75
0.666667
43
297
4.372093
0.44186
0.106383
0.159574
0.138298
0.244681
0
0
0
0
0
0
0
0.164983
297
8
76
37.125
0.758065
0
0
0
0
0
0.134948
0
0
0
0
0
0
1
0
false
0
0.166667
0
1
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
0
1
0
0
2
183b10cea440b5b30cb26a3af910591def7b5a7b
189
py
Python
nabeletter/editor/api/reviews.py
lenfestlab/monorepo
ef59cbd9b98c4c2857d7a5da16fe68c80f7ac60f
[ "MIT" ]
8
2018-11-30T22:59:39.000Z
2021-12-02T16:10:23.000Z
nabeletter/editor/api/reviews.py
lenfestlab/monorepo
ef59cbd9b98c4c2857d7a5da16fe68c80f7ac60f
[ "MIT" ]
37
2018-12-21T14:36:20.000Z
2020-06-03T19:59:20.000Z
nabeletter/editor/api/reviews.py
lenfestlab/monorepo
ef59cbd9b98c4c2857d7a5da16fe68c80f7ac60f
[ "MIT" ]
3
2019-05-27T20:50:13.000Z
2019-09-17T17:49:26.000Z
import requests import arrow def fetch(): url = """https://extry.herokuapp.com/fna/meetings""" response = requests.request("GET", url) data = response.json() return data
14.538462
54
0.656085
23
189
5.391304
0.782609
0
0
0
0
0
0
0
0
0
0
0
0.195767
189
13
55
14.538462
0.815789
0
0
0
0
0
0.226316
0
0
0
0
0
0
1
0.142857
false
0
0.285714
0
0.571429
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
184789a79182a74141c1adf308e80dfaf2edb489
283
py
Python
src/app/domains/user.py
hap0n/employee-management-system
b52e86ce2ec67702f4f3f9df61ea3e8f057bf940
[ "MIT" ]
null
null
null
src/app/domains/user.py
hap0n/employee-management-system
b52e86ce2ec67702f4f3f9df61ea3e8f057bf940
[ "MIT" ]
1
2021-12-25T13:24:07.000Z
2021-12-25T13:24:07.000Z
src/app/domains/user.py
hap0n/employee-management-system
b52e86ce2ec67702f4f3f9df61ea3e8f057bf940
[ "MIT" ]
null
null
null
from dataclasses import dataclass from enum import Enum from typing import Optional class Role(str, Enum): user = "user" hr = "hr" admin = "admin" @dataclass class User: username: str password_hash: str id: Optional[int] = None role: Role = Role.user
15.722222
33
0.664311
38
283
4.921053
0.5
0.085562
0
0
0
0
0
0
0
0
0
0
0.250883
283
17
34
16.647059
0.882075
0
0
0
0
0
0.038869
0
0
0
0
0
0
1
0
false
0.076923
0.230769
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
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
1848308e2f9beb44457209fd0297f8e3485549ad
6,586
py
Python
RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/lisp/lisp.py
ralfjon/IxNetwork
c0c834fbc465af69c12fd6b7cee4628baba7fff1
[ "MIT" ]
null
null
null
RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/lisp/lisp.py
ralfjon/IxNetwork
c0c834fbc465af69c12fd6b7cee4628baba7fff1
[ "MIT" ]
null
null
null
RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/lisp/lisp.py
ralfjon/IxNetwork
c0c834fbc465af69c12fd6b7cee4628baba7fff1
[ "MIT" ]
null
null
null
# Copyright 1997 - 2018 by IXIA Keysight # # 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. from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class Lisp(Base): """The Lisp class encapsulates a required lisp node in the ixnetwork hierarchy. An instance of the class can be obtained by accessing the Lisp property from a parent instance. The internal properties list will contain one and only one set of properties which is populated when the property is accessed. """ _SDM_NAME = 'lisp' def __init__(self, parent): super(Lisp, self).__init__(parent) @property def Router(self): """An instance of the Router class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.lisp.router.router.Router) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.lisp.router.router import Router return Router(self) @property def SiteEidRange(self): """An instance of the SiteEidRange class. Returns: obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.lisp.siteeidrange.siteeidrange.SiteEidRange) Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.lisp.siteeidrange.siteeidrange import SiteEidRange return SiteEidRange(self) @property def BurstIntervalInMs(self): """It shows the details abou the burst interval in micro seconds Returns: number """ return self._get_attribute('burstIntervalInMs') @BurstIntervalInMs.setter def BurstIntervalInMs(self, value): self._set_attribute('burstIntervalInMs', value) @property def Enabled(self): """If true, it shows enabled. Returns: bool """ return self._get_attribute('enabled') @Enabled.setter def Enabled(self, value): self._set_attribute('enabled', value) @property def Ipv4MapRegisterPacketsPerBurst(self): """It gives details about the ip v4 map register packets per burst Returns: number """ return self._get_attribute('ipv4MapRegisterPacketsPerBurst') @Ipv4MapRegisterPacketsPerBurst.setter def Ipv4MapRegisterPacketsPerBurst(self, value): self._set_attribute('ipv4MapRegisterPacketsPerBurst', value) @property def Ipv4MapRequestPacketsPerBurst(self): """It gives details about the ip v4 map requests packets per burst Returns: number """ return self._get_attribute('ipv4MapRequestPacketsPerBurst') @Ipv4MapRequestPacketsPerBurst.setter def Ipv4MapRequestPacketsPerBurst(self, value): self._set_attribute('ipv4MapRequestPacketsPerBurst', value) @property def Ipv4SmrPacketsPerBurst(self): """It gives details about the Ip v4 Smr packets per bursts Returns: number """ return self._get_attribute('ipv4SmrPacketsPerBurst') @Ipv4SmrPacketsPerBurst.setter def Ipv4SmrPacketsPerBurst(self, value): self._set_attribute('ipv4SmrPacketsPerBurst', value) @property def Ipv6MapRegisterPacketsPerBurst(self): """It gives details about the ip v6 map register packets per burst Returns: number """ return self._get_attribute('ipv6MapRegisterPacketsPerBurst') @Ipv6MapRegisterPacketsPerBurst.setter def Ipv6MapRegisterPacketsPerBurst(self, value): self._set_attribute('ipv6MapRegisterPacketsPerBurst', value) @property def Ipv6MapRequestPacketsPerBurst(self): """It gives details about the ip v6 map requests packets per burst Returns: number """ return self._get_attribute('ipv6MapRequestPacketsPerBurst') @Ipv6MapRequestPacketsPerBurst.setter def Ipv6MapRequestPacketsPerBurst(self, value): self._set_attribute('ipv6MapRequestPacketsPerBurst', value) @property def Ipv6SmrPacketsPerBurst(self): """It gives details about the Ip v6 Smr packets per bursts Returns: number """ return self._get_attribute('ipv6SmrPacketsPerBurst') @Ipv6SmrPacketsPerBurst.setter def Ipv6SmrPacketsPerBurst(self, value): self._set_attribute('ipv6SmrPacketsPerBurst', value) @property def ProtocolState(self): """Shows different protocol states (read-only) Returns: str(stopped|unknown|stopping|started|starting) """ return self._get_attribute('protocolState') def Start(self): """Executes the start operation on the server. NOT DEFINED Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/vport?deepchild=lisp)): The method internally sets Arg1 to the current href for this instance Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ Arg1 = self.href return self._execute('Start', payload=locals(), response_object=None) def Stop(self): """Executes the stop operation on the server. NOT DEFINED Args: Arg1 (str(None|/api/v1/sessions/1/ixnetwork/vport?deepchild=lisp)): The method internally sets Arg1 to the current href for this instance Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ Arg1 = self.href return self._execute('Stop', payload=locals(), response_object=None)
32.93
141
0.752505
784
6,586
6.252551
0.283163
0.024684
0.023868
0.040392
0.422481
0.361281
0.354141
0.354141
0.341901
0.317421
0
0.009925
0.173854
6,586
199
142
33.095477
0.891013
0.534771
0
0.183099
0
0
0.142194
0.115756
0
0
0
0
0
1
0.309859
false
0
0.056338
0
0.577465
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
1851287d4d26a37bc4534fc036021d8c0c90ca8e
232
py
Python
conanfile.py
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
1,101
2019-04-02T13:59:40.000Z
2022-03-31T23:14:00.000Z
conanfile.py
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
108
2019-04-08T23:46:13.000Z
2022-03-31T15:13:58.000Z
conanfile.py
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
144
2019-04-09T22:06:47.000Z
2022-03-31T13:09:43.000Z
from conans import ConanFile class ArgparseConan(ConanFile): name = "argparse" version = "1.0" exports_sources = "include/argparse.hpp" no_copy_source = True def package(self): self.copy("argparse.hpp")
23.2
44
0.676724
28
232
5.5
0.785714
0.142857
0
0
0
0
0
0
0
0
0
0.010989
0.215517
232
10
45
23.2
0.835165
0
0
0
0
0
0.184549
0
0
0
0
0
0
1
0.125
false
0
0.125
0
0.875
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
1868e1850a733706b5c33bcfd80f3bc3dd5a9246
15,678
py
Python
pysnmp/VMWARE-VMINFO-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/VMWARE-VMINFO-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/VMWARE-VMINFO-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 VMWARE-VMINFO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-VMINFO-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:27:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") ModuleIdentity, IpAddress, Counter32, TimeTicks, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Unsigned32, MibIdentifier, Integer32, Gauge32, iso, ObjectIdentity, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "IpAddress", "Counter32", "TimeTicks", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Unsigned32", "MibIdentifier", "Integer32", "Gauge32", "iso", "ObjectIdentity", "Counter64") DisplayString, TextualConvention, PhysAddress = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "PhysAddress") vmwESXNotifications, = mibBuilder.importSymbols("VMWARE-ENV-MIB", "vmwESXNotifications") vmwVirtMachines, vmwTraps = mibBuilder.importSymbols("VMWARE-ROOT-MIB", "vmwVirtMachines", "vmwTraps") VmwConnectedState, = mibBuilder.importSymbols("VMWARE-TC-MIB", "VmwConnectedState") vmwVmInfoMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 6876, 2, 10)) vmwVmInfoMIB.setRevisions(('2011-09-17 00:00', '2010-06-22 00:00', '2008-10-23 00:00', '2007-12-27 00:00',)) if mibBuilder.loadTexts: vmwVmInfoMIB.setLastUpdated('201109170000Z') if mibBuilder.loadTexts: vmwVmInfoMIB.setOrganization('VMware, Inc') vmwVmTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 1), ) if mibBuilder.loadTexts: vmwVmTable.setStatus('current') vmwVmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwVmIdx")) if mibBuilder.loadTexts: vmwVmEntry.setStatus('current') vmwVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwVmIdx.setStatus('current') vmwVmDisplayName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmDisplayName.setStatus('current') vmwVmConfigFile = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmConfigFile.setStatus('current') vmwVmGuestOS = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmGuestOS.setStatus('current') vmwVmMemSize = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 5), Integer32()).setUnits('megabytes').setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmMemSize.setStatus('current') vmwVmState = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 6), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmState.setStatus('current') vmwVmVMID = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmVMID.setStatus('obsolete') vmwVmGuestState = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmGuestState.setStatus('current') vmwVmCpus = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmCpus.setStatus('current') vmwVmUUID = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 1, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(36, 72))).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmUUID.setStatus('current') vmwVmHbaTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 2), ) if mibBuilder.loadTexts: vmwVmHbaTable.setStatus('current') vmwVmHbaEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwHbaVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwVmHbaIdx")) if mibBuilder.loadTexts: vmwVmHbaEntry.setStatus('current') vmwHbaVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwHbaVmIdx.setStatus('current') vmwVmHbaIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwVmHbaIdx.setStatus('current') vmwHbaNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwHbaNum.setStatus('current') vmwHbaVirtDev = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwHbaVirtDev.setStatus('current') vmwHbaTgtTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 3), ) if mibBuilder.loadTexts: vmwHbaTgtTable.setStatus('current') vmwHbaTgtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwHbaTgtVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwHbaTgtIdx")) if mibBuilder.loadTexts: vmwHbaTgtEntry.setStatus('current') vmwHbaTgtVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwHbaTgtVmIdx.setStatus('current') vmwHbaTgtIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwHbaTgtIdx.setStatus('current') vmwHbaTgtNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 3, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwHbaTgtNum.setStatus('current') vmwVmNetTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 4), ) if mibBuilder.loadTexts: vmwVmNetTable.setStatus('current') vmwVmNetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwVmNetVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwVmNetIdx")) if mibBuilder.loadTexts: vmwVmNetEntry.setStatus('current') vmwVmNetVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwVmNetVmIdx.setStatus('current') vmwVmNetIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwVmNetIdx.setStatus('current') vmwVmNetNum = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmNetNum.setStatus('current') vmwVmNetName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmNetName.setStatus('current') vmwVmNetConnType = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmNetConnType.setStatus('obsolete') vmwVmNetConnected = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 6), VmwConnectedState()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmNetConnected.setStatus('current') vmwVmMAC = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 4, 1, 7), PhysAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwVmMAC.setStatus('current') vmwFloppyTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 5), ) if mibBuilder.loadTexts: vmwFloppyTable.setStatus('current') vmwFloppyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwFdVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwFdIdx")) if mibBuilder.loadTexts: vmwFloppyEntry.setStatus('current') vmwFdVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwFdVmIdx.setStatus('current') vmwFdIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwFdIdx.setStatus('current') vmwFdName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwFdName.setStatus('current') vmwFdConnected = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 5, 1, 4), VmwConnectedState()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwFdConnected.setStatus('current') vmwCdromTable = MibTable((1, 3, 6, 1, 4, 1, 6876, 2, 6), ) if mibBuilder.loadTexts: vmwCdromTable.setStatus('current') vmwCdromEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1), ).setIndexNames((0, "VMWARE-VMINFO-MIB", "vmwCdVmIdx"), (0, "VMWARE-VMINFO-MIB", "vmwCdromIdx")) if mibBuilder.loadTexts: vmwCdromEntry.setStatus('current') vmwCdVmIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwCdVmIdx.setStatus('current') vmwCdromIdx = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: vmwCdromIdx.setStatus('current') vmwCdromName = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwCdromName.setStatus('current') vmwCdromConnected = MibTableColumn((1, 3, 6, 1, 4, 1, 6876, 2, 6, 1, 4), VmwConnectedState()).setMaxAccess("readonly") if mibBuilder.loadTexts: vmwCdromConnected.setStatus('current') vmwVmID = MibScalar((1, 3, 6, 1, 4, 1, 6876, 50, 101), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: vmwVmID.setStatus('current') vmwVmConfigFilePath = MibScalar((1, 3, 6, 1, 4, 1, 6876, 50, 102), DisplayString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: vmwVmConfigFilePath.setStatus('current') vmwVmPoweredOn = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 1)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName")) if mibBuilder.loadTexts: vmwVmPoweredOn.setStatus('current') vmwVmPoweredOff = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 2)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName")) if mibBuilder.loadTexts: vmwVmPoweredOff.setStatus('current') vmwVmHBLost = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 3)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName")) if mibBuilder.loadTexts: vmwVmHBLost.setStatus('current') vmwVmHBDetected = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 4)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName")) if mibBuilder.loadTexts: vmwVmHBDetected.setStatus('current') vmwVmSuspended = NotificationType((1, 3, 6, 1, 4, 1, 6876, 4, 1, 0, 5)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmDisplayName")) if mibBuilder.loadTexts: vmwVmSuspended.setStatus('current') vmwVmInfoMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2)) vmwVmInfoMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 1)) vmwVmInfoMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2)) vmwResMIBBasicCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 1, 2)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmInfoGroup"), ("VMWARE-VMINFO-MIB", "vmwVmInfoNotificationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): vmwResMIBBasicCompliance = vmwResMIBBasicCompliance.setStatus('current') vmwVmInfoGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2, 1)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmDisplayName"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFile"), ("VMWARE-VMINFO-MIB", "vmwVmGuestOS"), ("VMWARE-VMINFO-MIB", "vmwVmMemSize"), ("VMWARE-VMINFO-MIB", "vmwVmState"), ("VMWARE-VMINFO-MIB", "vmwVmGuestState"), ("VMWARE-VMINFO-MIB", "vmwHbaNum"), ("VMWARE-VMINFO-MIB", "vmwHbaVirtDev"), ("VMWARE-VMINFO-MIB", "vmwHbaTgtNum"), ("VMWARE-VMINFO-MIB", "vmwVmNetNum"), ("VMWARE-VMINFO-MIB", "vmwVmNetName"), ("VMWARE-VMINFO-MIB", "vmwVmNetConnected"), ("VMWARE-VMINFO-MIB", "vmwVmMAC"), ("VMWARE-VMINFO-MIB", "vmwFdName"), ("VMWARE-VMINFO-MIB", "vmwFdConnected"), ("VMWARE-VMINFO-MIB", "vmwCdromName"), ("VMWARE-VMINFO-MIB", "vmwCdromConnected"), ("VMWARE-VMINFO-MIB", "vmwVmID"), ("VMWARE-VMINFO-MIB", "vmwVmConfigFilePath"), ("VMWARE-VMINFO-MIB", "vmwVmCpus"), ("VMWARE-VMINFO-MIB", "vmwVmUUID")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): vmwVmInfoGroup = vmwVmInfoGroup.setStatus('current') vmwVmInfoNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2, 2)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmPoweredOn"), ("VMWARE-VMINFO-MIB", "vmwVmPoweredOff"), ("VMWARE-VMINFO-MIB", "vmwVmHBLost"), ("VMWARE-VMINFO-MIB", "vmwVmHBDetected"), ("VMWARE-VMINFO-MIB", "vmwVmSuspended")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): vmwVmInfoNotificationGroup = vmwVmInfoNotificationGroup.setStatus('current') vmwVmObsoleteGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6876, 2, 10, 2, 2, 3)).setObjects(("VMWARE-VMINFO-MIB", "vmwVmVMID"), ("VMWARE-VMINFO-MIB", "vmwVmNetConnType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): vmwVmObsoleteGroup = vmwVmObsoleteGroup.setStatus('obsolete') mibBuilder.exportSymbols("VMWARE-VMINFO-MIB", vmwVmUUID=vmwVmUUID, vmwCdromTable=vmwCdromTable, vmwVmSuspended=vmwVmSuspended, vmwVmHbaIdx=vmwVmHbaIdx, vmwVmNetTable=vmwVmNetTable, vmwVmNetName=vmwVmNetName, vmwVmVMID=vmwVmVMID, vmwVmDisplayName=vmwVmDisplayName, vmwVmHbaTable=vmwVmHbaTable, vmwVmConfigFile=vmwVmConfigFile, vmwFdVmIdx=vmwFdVmIdx, vmwCdromConnected=vmwCdromConnected, vmwVmGuestState=vmwVmGuestState, vmwVmEntry=vmwVmEntry, vmwHbaTgtIdx=vmwHbaTgtIdx, vmwVmTable=vmwVmTable, vmwVmInfoMIB=vmwVmInfoMIB, PYSNMP_MODULE_ID=vmwVmInfoMIB, vmwVmGuestOS=vmwVmGuestOS, vmwVmState=vmwVmState, vmwFloppyTable=vmwFloppyTable, vmwVmNetConnType=vmwVmNetConnType, vmwVmPoweredOn=vmwVmPoweredOn, vmwVmNetVmIdx=vmwVmNetVmIdx, vmwHbaTgtEntry=vmwHbaTgtEntry, vmwVmIdx=vmwVmIdx, vmwHbaVmIdx=vmwHbaVmIdx, vmwVmHbaEntry=vmwVmHbaEntry, vmwVmNetConnected=vmwVmNetConnected, vmwVmCpus=vmwVmCpus, vmwCdromIdx=vmwCdromIdx, vmwVmID=vmwVmID, vmwVmObsoleteGroup=vmwVmObsoleteGroup, vmwCdromEntry=vmwCdromEntry, vmwHbaTgtTable=vmwHbaTgtTable, vmwFdName=vmwFdName, vmwCdVmIdx=vmwCdVmIdx, vmwVmInfoGroup=vmwVmInfoGroup, vmwCdromName=vmwCdromName, vmwFdIdx=vmwFdIdx, vmwResMIBBasicCompliance=vmwResMIBBasicCompliance, vmwVmHBDetected=vmwVmHBDetected, vmwVmInfoMIBGroups=vmwVmInfoMIBGroups, vmwHbaTgtVmIdx=vmwHbaTgtVmIdx, vmwVmInfoMIBCompliances=vmwVmInfoMIBCompliances, vmwFdConnected=vmwFdConnected, vmwVmInfoMIBConformance=vmwVmInfoMIBConformance, vmwVmConfigFilePath=vmwVmConfigFilePath, vmwVmNetNum=vmwVmNetNum, vmwVmNetEntry=vmwVmNetEntry, vmwVmPoweredOff=vmwVmPoweredOff, vmwVmHBLost=vmwVmHBLost, vmwFloppyEntry=vmwFloppyEntry, vmwVmInfoNotificationGroup=vmwVmInfoNotificationGroup, vmwHbaTgtNum=vmwHbaTgtNum, vmwHbaVirtDev=vmwHbaVirtDev, vmwVmNetIdx=vmwVmNetIdx, vmwHbaNum=vmwHbaNum, vmwVmMemSize=vmwVmMemSize, vmwVmMAC=vmwVmMAC)
111.985714
1,819
0.745312
1,837
15,678
6.359826
0.10724
0.012326
0.015407
0.0202
0.439613
0.394077
0.347171
0.347171
0.294702
0.274073
0
0.075624
0.085725
15,678
139
1,820
112.791367
0.739431
0.020921
0
0.030534
0
0
0.193729
0.004563
0
0
0
0
0
1
0
false
0
0.068702
0
0.068702
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
186cee62b669ef99512e1ff647f0324728524654
402
py
Python
clinicaltrials/custom_logging.py
chadmiller/clinicaltrials-act-tracker
d16f5ff7b1fde673e7b00cd674666a19b19bf092
[ "MIT" ]
13
2018-02-20T12:48:42.000Z
2022-03-09T01:55:23.000Z
clinicaltrials/custom_logging.py
chadmiller/clinicaltrials-act-tracker
d16f5ff7b1fde673e7b00cd674666a19b19bf092
[ "MIT" ]
134
2018-02-19T08:42:54.000Z
2021-12-13T19:50:15.000Z
clinicaltrials/custom_logging.py
chadmiller/clinicaltrials-act-tracker
d16f5ff7b1fde673e7b00cd674666a19b19bf092
[ "MIT" ]
3
2018-03-10T19:56:27.000Z
2019-05-03T15:29:30.000Z
import logging.handlers import os class GroupWriteRotatingFileHandler(logging.handlers.RotatingFileHandler): """A logging filehandler that ensures group writable logs. Ref: https://stackoverflow.com/questions/1407474/ """ def _open(self): umask = os.umask(0o002) handle = logging.handlers.RotatingFileHandler._open(self) os.umask(umask) return handle
26.8
74
0.711443
42
402
6.761905
0.642857
0.158451
0.239437
0
0
0
0
0
0
0
0
0.034056
0.196517
402
14
75
28.714286
0.845201
0.263682
0
0
0
0
0
0
0
0
0
0
0
1
0.125
false
0
0.25
0
0.625
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
43e7d758c653358c3a9ac5167899e97d9aa92203
4,775
py
Python
Main.py
EdoardoVignati/MongoLib
6b0f233d2744028236d6a23ce159ccdaca228a66
[ "CC0-1.0" ]
null
null
null
Main.py
EdoardoVignati/MongoLib
6b0f233d2744028236d6a23ce159ccdaca228a66
[ "CC0-1.0" ]
null
null
null
Main.py
EdoardoVignati/MongoLib
6b0f233d2744028236d6a23ce159ccdaca228a66
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/python import json import pymongo import time import csv import bson import pandas import pprint as pp from GinfoMongoPython.EdoLib.BaseLib import mongoLib #To import use : # from BaseLib import * m = mongoLib("gamesdb", "games") """ ############################## EVERYTHING ON JSON ############################## m.printCurrentJsonInfo() print("\nCurrent json collections:", m.returnCurrentJsonCollections()) ############################## WORK ON DB ############################## m.saveJsonInDb() m.printCurrentDbsInfo() print("\nDb stored collections in", m.dbName, ":", m.returnDbCollections()) ############################## PRINT DATA ############################## print("\nBOARDGAMES --------------------------------------------------------------------") for record in m.returnEverythingGivenColl("boardgames"): print(record) print("\nVIDEOGAMES --------------------------------------------------------------------") for record in m.returnEverythingGivenColl("videogames"): print(record) ############################## COUNT RECORDS ############################## print("\nRecords per collection:") for k,v in m.countRecordsPerColl().items(): print(k , ":", v) ############################## GET TIMER ############################## totalTime=0; for line in m.getTimer(): totalTime+=(line[1]*1000) print("\nBaseLib total execution time:", totalTime, "ms") ############################## GET KEYS ############################## for line in m.getKeysPerColl("videogames"): print(line) for line in m.getKeysPerColl("boardgames"): print(line) ############################## QUERIES ############################## p = {} for record in m.findDbDataPerColl("videogames"): pp.pprint(record) # With ID p={} q=m.buildProjectionToDisplay(["title","publisher"]) print(q) for record in m.findDbDataPerColl("videogames",p,q): pp.pprint(record) # Without ID p = {} q = m.buildProjectionToDisplay(["title","publisher"],0) print(q) for record in m.findDbDataPerColl("videogames", p, q): pp.pprint(record) ############################## CSV MANAGER ############################## m.csvToDb("./stations.csv", "stations") m.csvToJson() ############################## COLLECTIONS ############################## # Create new collection and add data data = m.findDbDataPerColl("videogames") m.createCollection("NuoviVideogames") m.saveDataIntoCollection("NuoviVideogames") # Append new data to existing collection data = m.findDbDataPerColl("altriVideogames") m.appendDataIntoCollection("NuoviGiochi",data) #Drop collection m.dropCollection("NuoviVideogames") ############################## FILTERING DATA ############################## sum=0 for record in m.getAllValuesOfField("platforms", "videogames"): sum+=1 print(sum) sum=0 for record in m.getSingledOutValuesOfField("platforms", "videogames"): sum+=1 print(sum) ############################## USEFUL AGGREGATIONS ############################## # Group by year and count total years ########################################## p1 = { '$group': { '_id': '$year' } } p2 = { '$count': 'Anni totali' } pipeline=[p1,p2] for record in m.execPipeline("videogames",pipeline): print(record) ########################################## # Count total games per year ########################################## p1 = { '$group': { '_id': '$year', 'giochi_per_anno': { '$sum': 1 } } } pipeline=[p1] ########################################## # Round average per number of games per year ########################################### p1 = { '$group': { '_id': '$year', 'giochi_per_anno': { '$sum': 1 } } } p2 = { '$group': { '_id': None, 'media': { '$avg': '$giochi_per_anno' } } } p3 = {'$project':{"media" : {"$divide":[{"$subtract":[{"$multiply":["$media",10]},{"$mod":[{"$multiply":["$media",10]}, 1]}]},10]}} } pipeline = [p1, p2, p3] ########################################### # Unpack an array ( unwind() ) ########################################### p1 = { '$unwind': '$platforms' } pipeline = [p1] ########################################### # Unpack, match only 'Ninentdo Wii' and count ########################################### p1 = { '$unwind': '$platforms' } p2 = { '$match': { 'platforms': 'Nintendo Wii' } } p3 = {'$count': 'Tot'} pipeline = [p1, p2, p3] ########################################### # Project only publisher name and sort (09-AZ-az) ########################################### p1 = { '$project': { 'publisher.name': 1, '_id': 0 } } p2 = { '$sort':{ 'publisher.name':1 } } pipeline=[p1, p2] ########################################### """ m.printCurrentDbsInfo() print(m.getTimer()) #pipeline=[] #for record in m.execPipeline("videogames",pipeline): # print(record)
19.813278
133
0.482932
424
4,775
5.412736
0.341981
0.018301
0.043137
0.047059
0.284532
0.231373
0.17342
0.135948
0.135948
0.08976
0
0.011628
0.117487
4,775
240
134
19.895833
0.532985
0.027225
0
0
0
0
0.049793
0
0
0
0
0
0
1
0
false
0
0.727273
0
0.727273
0.272727
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
43ef8d0f1b6e2202ecc2db6f1e3c3ba0d33e660a
1,005
py
Python
thekingsescape/game/pawn.py
antoine-sachet/thekingsescape
ae994cbe798480130134c1cb9c404114dbc60492
[ "MIT" ]
null
null
null
thekingsescape/game/pawn.py
antoine-sachet/thekingsescape
ae994cbe798480130134c1cb9c404114dbc60492
[ "MIT" ]
null
null
null
thekingsescape/game/pawn.py
antoine-sachet/thekingsescape
ae994cbe798480130134c1cb9c404114dbc60492
[ "MIT" ]
null
null
null
from .cell import CellType class Pawn: def __init__(self, player): self.owner = player self.cell = None def setPosition(self, cell): self.cell = cell def belongs_to(self, player): return self.owner == player def can_go_on(self, cell): return cell.type == CellType.NORMAL def __str__(self): return 'P' def __repr__(self): return "Pawn(player=%r)" % self.owner class Attacker(Pawn): def __str__(self): return '♂' def __repr__(self): return "Attacker(player=%r)" % self.owner class Defender(Pawn): def __str__(self): return '♀' def __repr__(self): return "Defender(player=%r)" % self.owner class King(Pawn): def can_go_on(self, cell): return cell.type in [CellType.NORMAL, CellType.CASTLE] def __str__(self): return '♦' def __repr__(self): return "King(player=%r)" % self.owner
20.1
63
0.566169
122
1,005
4.352459
0.270492
0.150659
0.07533
0.120527
0.314501
0.120527
0.120527
0.120527
0.120527
0
0
0
0.317413
1,005
49
64
20.510204
0.769679
0
0
0.3125
0
0
0.075314
0
0
0
0
0
0
1
0.40625
false
0
0.03125
0.34375
0.90625
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
43f6bf4d6a4134f5402c8f21ee66c4c398070e02
493
py
Python
component/forms.py
boycatbay/its100-2
7be2c83e9948813ea6a0e74977f5822d2c1cecba
[ "MIT" ]
1
2019-03-28T10:08:46.000Z
2019-03-28T10:08:46.000Z
component/forms.py
boycatbay/its100-2
7be2c83e9948813ea6a0e74977f5822d2c1cecba
[ "MIT" ]
5
2021-04-08T18:56:02.000Z
2022-02-10T08:42:25.000Z
component/forms.py
boycatbay/its100-2
7be2c83e9948813ea6a0e74977f5822d2c1cecba
[ "MIT" ]
1
2019-04-30T06:51:30.000Z
2019-04-30T06:51:30.000Z
from django import forms class announces(forms.Form): textarea = forms.CharField(label='Textarea',max_length=300) material = forms.CharField(label='Material',max_length=100) class uploads(forms.Form): title = forms.CharField(label='Assignment Title',max_length=100) description = forms.CharField(label='Assignment Description',max_length=300) scores = forms.IntegerField(label='Maximum Scores') material = forms.CharField(label='Materials',max_length=300)
27.388889
80
0.744422
60
493
6.033333
0.383333
0.19337
0.262431
0.149171
0
0
0
0
0
0
0
0.035129
0.133874
493
18
81
27.388889
0.812646
0
0
0
0
0
0.15587
0
0
0
0
0
0
1
0
false
0
0.111111
0
1
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
a125e8d82bc0d9d0761e9ba633d697a8f41c675b
526
py
Python
data/Human36M/skeleton.py
GuillaumeRochette/HumanViewSynthesis
d65ea8744e284ec956bbc04f294f05e47731360f
[ "Apache-2.0" ]
10
2021-11-30T05:56:10.000Z
2022-03-16T07:06:16.000Z
data/Human36M/skeleton.py
GuillaumeRochette/HumanViewSynthesis
d65ea8744e284ec956bbc04f294f05e47731360f
[ "Apache-2.0" ]
1
2022-01-10T09:27:22.000Z
2022-01-10T09:27:22.000Z
data/Human36M/skeleton.py
GuillaumeRochette/HumanViewSynthesis
d65ea8744e284ec956bbc04f294f05e47731360f
[ "Apache-2.0" ]
null
null
null
JOINTS = { "HipCenter": 0, "RHip": 1, "RKnee": 2, "RFoot": 3, "LHip": 4, "LKnee": 5, "LFoot": 6, "Spine": 7, "Thorax": 8, "Neck/Nose": 9, "Head": 10, "LShoulder": 11, "LElbow": 12, "LWrist": 13, "RShoulder": 14, "RElbow": 15, "RWrist": 16, } EDGES = ( (0, 1), (1, 2), (2, 3), (0, 4), (4, 5), (5, 6), (0, 7), (7, 8), (8, 9), (9, 10), (8, 11), (11, 12), (12, 13), (8, 14), (14, 15), (15, 16), )
13.487179
20
0.342205
69
526
2.608696
0.536232
0
0
0
0
0
0
0
0
0
0
0.210031
0.393536
526
38
21
13.842105
0.354232
0
0
0
0
0
0.195817
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
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
a13fd2979b8fb321f975b462907cde105f062595
4,188
py
Python
mietrechtspraxis/config/mietrechtspraxis.py
libracore/mietrechtspraxis
7b2320a70b98b086be136a86b1ab4fadfce215ff
[ "MIT" ]
1
2021-07-15T13:25:23.000Z
2021-07-15T13:25:23.000Z
mietrechtspraxis/config/mietrechtspraxis.py
libracore/mietrechtspraxis
7b2320a70b98b086be136a86b1ab4fadfce215ff
[ "MIT" ]
1
2022-01-27T13:30:56.000Z
2022-01-27T13:30:56.000Z
mietrechtspraxis/config/mietrechtspraxis.py
libracore/mietrechtspraxis
7b2320a70b98b086be136a86b1ab4fadfce215ff
[ "MIT" ]
2
2021-08-14T22:23:08.000Z
2021-09-08T09:31:51.000Z
from __future__ import unicode_literals from frappe import _ def get_data(): return[ { "label": _("Subscription"), "icon": "fa fa-money", "items": [ { "type": "doctype", "name": "mp Abo", "label": _("mp Abo"), "description": _("mp Abo") }, { "type": "doctype", "name": "mp Abo Settings", "label": _("mp Abo Settings"), "description": _("mp Abo Settings") } ] }, { "label": _("Tools"), "icon": "fa fa-money", "items": [ { "type": "doctype", "name": "Customers Search Mask", "label": _("Customers Search Mask"), "description": _("Customers Search Mask") }, { "type": "page", "name": "invoice_and_print", "label": _("Invoice run and collective printing"), "description": _("Invoice run and collective printing") }, { "type": "doctype", "name": "RM Log", "label": _("Massenlauf Logfile"), "description": _("Massenlauf Logfile") }, { "type": "doctype", "name": "CAMT Import", "label": _("CAMT Import"), "description": _("CAMT Import") } ] }, { "label": _("Master Data"), "icon": "fa fa-money", "items": [ { "type": "doctype", "name": "Customer", "label": _("Customer"), "description": _("Customer") }, { "type": "doctype", "name": "Contact", "label": _("Contact"), "description": _("Contact") }, { "type": "doctype", "name": "Address", "label": _("Address"), "description": _("Address") }, { "type": "doctype", "name": "Sales Invoice", "label": _("Sales Invoice"), "description": _("Sales Invoice") }, { "type": "doctype", "name": "Payment Entry", "label": _("Payment Entry"), "description": _("Payment Entry") } ] }, { "label": _("Schlichtungsbehörden"), "icon": "fa fa-money", "items": [ { "type": "doctype", "name": "Arbitration Authority", "label": _("Schlichtungsbehörden"), "description": _("Schlichtungsbehörden") }, { "type": "doctype", "name": "Kantonsinformationen", "label": _("Kantonsinformationen"), "description": _("Kantonsinformationen") } ] }, { "label": _("API"), "icon": "fa fa-money", "items": [ { "type": "doctype", "name": "mietrechtspraxis API", "label": _("API Einstellungen"), "description": _("API Einstellungen") } ] } ]
34.61157
78
0.302531
201
4,188
6.094527
0.263682
0.116735
0.159184
0.053061
0.205714
0.134694
0.134694
0.134694
0
0
0
0
0.569962
4,188
120
79
34.9
0.680178
0
0
0.210084
0
0
0.289876
0
0
0
0
0
0
1
0.008403
true
0
0.042017
0.008403
0.05042
0.02521
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
a15dac9794a8783caaf3553449cc24904c13778f
270
py
Python
file-exception/self-throw-except.py
misizeji/python_study_notes
b0f5a224ac65f962c6255ab7cf8a1912704d1617
[ "MIT" ]
null
null
null
file-exception/self-throw-except.py
misizeji/python_study_notes
b0f5a224ac65f962c6255ab7cf8a1912704d1617
[ "MIT" ]
1
2018-05-23T06:35:37.000Z
2018-05-23T06:36:12.000Z
file-exception/self-throw-except.py
misizeji/python_study_notes
b0f5a224ac65f962c6255ab7cf8a1912704d1617
[ "MIT" ]
null
null
null
#!/usr/bin/python3 class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError(2 * 2) except MyError as err: print('My Exception occurred, value: ', err.value)
18
54
0.640741
36
270
4.583333
0.611111
0.163636
0
0
0
0
0
0
0
0
0
0.014563
0.237037
270
14
55
19.285714
0.786408
0.062963
0
0
0
0
0.119048
0
0
0
0
0
0
1
0.222222
false
0
0
0.111111
0.444444
0.111111
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
a17a2b8d33bd3dc1e28b6f1a3c4c4df8d2ac81b5
2,282
py
Python
tests/test_models.py
rachmadaniHaryono/google-images-download
e44773a298556c4128ae313fc1fbecd874eb8a19
[ "MIT" ]
5
2017-05-20T17:58:14.000Z
2017-12-29T20:28:53.000Z
tests/test_models.py
rachmadaniHaryono/gbooru-images-download
e44773a298556c4128ae313fc1fbecd874eb8a19
[ "MIT" ]
null
null
null
tests/test_models.py
rachmadaniHaryono/gbooru-images-download
e44773a298556c4128ae313fc1fbecd874eb8a19
[ "MIT" ]
3
2017-09-28T18:22:03.000Z
2017-12-08T16:31:27.000Z
"""Test for models module.""" from urllib.parse import urlparse, parse_qs import os from PIL import Image import pytest import vcr from gbooru_images_download import models @pytest.fixture() def tmp_pic(tmpdir): """Temporary pic.""" img_input = tmpdir.join("test.jpg") img = Image.new('RGB', (500, 500), 'red') img.save(img_input.strpath) return { 'image_input': img_input, 'image': img, 'checksum': '0deee6f6b714650064a6b42b9b306e0a95f12b2e3df54d77c9b8eb2cae78e075', 'thumb_checksum': '9e5ffe7f0af13b394210ff8991eb7d75ade95ba2124a084c9d21fa2234a49428', 'image_size': (500, 500), 'thumb_size': (250, 250), 'image_guess': 'check for dead pixels', 'search_url': 'http://www.google.com/search?' 'tbs=sbi:AMhZZivJeVMaIy-Czt346tQLdTKhmNlzyMCacQBuRdR3KsVoGDZl7bwKFXeTOX8aRP8_1rrffzyqe' 'vAHM-ZLF66B4dawe_1IgVqNQgJokBnCO8-hSrXOLBJfT1dCB4uTj1A3wa-z8qKvyhRVN2txG_1BtlXYUmtHOF' 'z8Te9iHANJk-_1f44BXXWI9Zbq9Yd-JOgXPmaIjzT6FHT4UFGJ2S69P1ixik_1pTLhXQp0Yp0V2aGhs396O93' 'tCrTnkIpqroTlyVHd5h_1iX6FfD0Vcw60Z9DLnPXOFLAyLmB-HILSFgYxH72V5GjCxDDv4GGwhG-8tV6n4dmk' 'CgGVhs', 'similar_search_url': 'https://www.google.com/search?' 'tbs=simg:CAEShgIJAGUUt_1bm7g0a-gELEKjU2AQaBAgVCAgMCxCwjKcIGl8KXQgDEiVH_1wi0As8B_1ggos' 'gLyAvgIKaArsyqIJ9conTehK4QjnjesNtMnGjDr2WYL3JwKke7gjGUtkou0VlOLR40JczbbhOx4-RDy03I_1k' 'UV6WgCRiPqIUovom1AgBAwLEI6u_1ggaCgoICAESBM9Xj5QMCxCd7cEJGmkKGAoGb3Jhbmdl2qWI9gMKCggvb' 'S8wamNfcAoYCgVwZWFjaNqliPYDCwoJL20vMDNyMTh5ChkKB3BhdHRlcm7apYj2AwoKCC9tLzBod2t5ChgKBW' 'FtYmVy2qWI9gMLCgkvbS8wNGQwMWYM&' 'q=check+for+dead+pixels&tbm=isch&sa=X&ved=0ahUKEwi3o6zp3IrXAhUJahoKHfAKCekQsw4INQ', 'size_search_url': 'https://www.google.com/search?' 'q=check+for+dead+pixels&' 'tbm=isch&tbs=simg:CAQSlAEJAGUUt_1bm7g0aiAELEKjU2AQaBAgVCAgMCxCwjKcIGl8KXQgDEiVH_1wi0A' 's8B_1ggosgLyAvgIKaArsyqIJ9conTehK4QjnjesNtMnGjDr2WYL3JwKke7gjGUtkou0VlOLR40JczbbhOx4-' 'RDy03I_1kUV6WgCRiPqIUovom1AgBAwLEI6u_1ggaCgoICAESBM9Xj5QM&sa=X&' 'ved=0ahUKEwi3o6zp3IrXAhUJahoKHfAKCekQ2A4IIygB'}
47.541667
99
0.732252
168
2,282
9.75
0.60119
0.014652
0.021978
0.032967
0.08547
0.070818
0.070818
0
0
0
0
0.125201
0.180982
2,282
47
100
48.553191
0.751204
0.016652
0
0.04878
0
0.02439
0.65562
0.547246
0
0
0
0
0
1
0.02439
false
0
0.146341
0
0.195122
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
a1952e9927cb5eb2a36f353e533d473a1239f770
2,583
py
Python
pyml/decomposition/pca.py
gf712/PyML
83849ff6e1c1bbcf9b87826ef673fb34622a0539
[ "MIT" ]
4
2018-11-23T07:45:51.000Z
2020-12-29T19:32:06.000Z
pyml/decomposition/pca.py
gf712/PyML
83849ff6e1c1bbcf9b87826ef673fb34622a0539
[ "MIT" ]
18
2017-11-16T08:32:42.000Z
2017-12-27T15:19:58.000Z
pyml/decomposition/pca.py
gf712/PyML
83849ff6e1c1bbcf9b87826ef673fb34622a0539
[ "MIT" ]
3
2018-10-31T17:09:22.000Z
2020-03-02T22:40:23.000Z
from pyml.base import BaseLearner, Transformer from pyml.maths import covariance, eigen, mean, dot_product, transpose, subtract, add class PCA(BaseLearner, Transformer): """ Principal component analysis """ def __init__(self, n_components=0.95, tolerance=1.0e-9, max_iterations=1000): BaseLearner.__init__(self) Transformer.__init__(self) self._n_components = n_components self._tolerance = tolerance self._max_iterations = max_iterations def _train(self, X, y=None): """ Calculates the feature vector of X with PCA algorithm """ self._X = X self._n = len(X) self._m = len(X[0]) if self._m > 20: raise NotImplementedError("Jacobi decomposition can be unstable with N>20 symmetric matrices!") if isinstance(self._n_components, float): self._n_components = int(round(self._n_components * self._m)) # get the mean of each column self._X_means = mean(self._X, axis=0) # subtract each column by its mean X_whitened = subtract(self._X, self._X_means) # covariance matrix cov = covariance(X_whitened) # eigen decomposition of covariance matrix self._v, self._w = eigen(cov, self.tolerance, self.max_iterations, normalise=False, sort=True) # create feature vector self._feat_vect = [[self._w[row][column] for column in range(self.n_components)] for row in range(self._m)] return self def _transform(self, X): """ :param X: :param y: :return: """ # subtract X by mean X_whitened = subtract(X, self._X_means) return transpose(dot_product(transpose(self._feat_vect), transpose(X_whitened))) def _inverse(self, X): """ :return: """ return add(dot_product(X, transpose(self.eigenvectors)), self._X_means) @property def tolerance(self): return self._tolerance @property def max_iterations(self): return self._max_iterations @property def eigenvalues(self): return self._v @property def eigenvectors(self): return self._feat_vect @property def explained_variance(self): return self._v @property def explained_variance_ratio(self): return [eig / sum(self.eigenvalues) for eig in self.eigenvalues] @property def n_components(self): """ :rtype: int :return: """ return self._n_components
25.07767
115
0.619822
310
2,583
4.919355
0.316129
0.032787
0.068852
0.034098
0.034098
0.034098
0
0
0
0
0
0.008658
0.284553
2,583
102
116
25.323529
0.816558
0.117305
0
0.183673
0
0
0.030856
0
0
0
0
0
0
1
0.22449
false
0
0.040816
0.122449
0.489796
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
a198b3fdc877d33dd3eed2b8ee1b7006f0d3b830
339
py
Python
dsql/api/models/snowflake.py
gustavwilliam/discordSQL
95ba62dd9b9d7bffa1e8c2a9fc60d35c916b7b45
[ "MIT" ]
4
2021-07-08T12:24:39.000Z
2022-03-03T02:51:18.000Z
dsql/api/models/snowflake.py
gustavwilliam/discordSQL
95ba62dd9b9d7bffa1e8c2a9fc60d35c916b7b45
[ "MIT" ]
1
2021-12-28T00:13:33.000Z
2021-12-28T00:13:33.000Z
dsql/api/models/snowflake.py
gustavwilliam/discordSQL
95ba62dd9b9d7bffa1e8c2a9fc60d35c916b7b45
[ "MIT" ]
null
null
null
from datetime import datetime class Snowflake: def __init__(self, id: str) -> None: self.id = id binary = format(int(id), '064b') unix_s = (int(binary[:42], 2) + 1420070400000) / 1000 self.timestamp = datetime.fromtimestamp(unix_s) def __str__(self) -> str: return self.id def __int__(self) -> int: return int(self.id)
19.941176
55
0.675516
49
339
4.387755
0.489796
0.111628
0
0
0
0
0
0
0
0
0
0.083032
0.182891
339
16
56
21.1875
0.693141
0
0
0
0
0
0.011799
0
0
0
0
0
0
1
0.272727
false
0
0.090909
0.181818
0.636364
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
a199dddcdc34c7f6ede2cf8e519c2ae81fc9b8e8
911
py
Python
tests/hook_details/test_hook_details.py
futuresimple/triggear
d6b8511ba8550225e7c34bd52232327b2b89d972
[ "MIT" ]
14
2017-08-17T16:48:26.000Z
2019-07-10T12:11:49.000Z
tests/hook_details/test_hook_details.py
futuresimple/triggear
d6b8511ba8550225e7c34bd52232327b2b89d972
[ "MIT" ]
null
null
null
tests/hook_details/test_hook_details.py
futuresimple/triggear
d6b8511ba8550225e7c34bd52232327b2b89d972
[ "MIT" ]
null
null
null
import pytest from mockito import mock from app.hook_details.hook_details import HookDetails pytestmark = pytest.mark.asyncio @pytest.mark.usefixtures('unstub') class TestHookDetails: async def test__hook_details__is_pure_interface(self): with pytest.raises(NotImplementedError): f"{HookDetails()}" with pytest.raises(NotImplementedError): HookDetails().get_allowed_parameters() with pytest.raises(NotImplementedError): HookDetails().get_query() with pytest.raises(NotImplementedError): HookDetails().get_ref() with pytest.raises(NotImplementedError): HookDetails().setup_final_param_values(mock()) with pytest.raises(NotImplementedError): await HookDetails().should_trigger(mock(), mock()) with pytest.raises(NotImplementedError): HookDetails().get_event_type()
35.038462
62
0.695939
89
911
6.910112
0.460674
0.113821
0.182114
0.398374
0.463415
0.318699
0
0
0
0
0
0
0.208562
911
25
63
36.44
0.852982
0
0
0.333333
0
0
0.023052
0
0
0
0
0
0
1
0
false
0
0.142857
0
0.190476
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
a1a7abfcd8a57c07877d5a0c85b62f22b07f2b51
438
py
Python
simone/forms.py
zuhalcakir/simone
88e04e6a228570d7d2a4c8bbf683e4903eeb592b
[ "BSD-3-Clause" ]
16
2015-03-27T12:39:23.000Z
2020-05-09T13:10:24.000Z
simone/forms.py
zuhalcakir/simone
88e04e6a228570d7d2a4c8bbf683e4903eeb592b
[ "BSD-3-Clause" ]
2
2016-09-03T18:22:01.000Z
2018-01-04T12:20:01.000Z
simone/forms.py
zuhalcakir/simone
88e04e6a228570d7d2a4c8bbf683e4903eeb592b
[ "BSD-3-Clause" ]
8
2015-08-26T18:17:54.000Z
2017-05-17T13:28:32.000Z
from django import forms from .models import ImapServer, SmtpServer class ImapServerForm(forms.ModelForm): class Meta: model = ImapServer exclude = ['user'] widgets = { 'passwd': forms.PasswordInput(), } class SmtpServerForm(forms.ModelForm): class Meta: model = SmtpServer exclude = ['user'] widgets = { 'passwd': forms.PasswordInput(), }
23.052632
44
0.582192
37
438
6.891892
0.486486
0.109804
0.14902
0.180392
0.54902
0.329412
0
0
0
0
0
0
0.317352
438
18
45
24.333333
0.852843
0
0
0.5
0
0
0.045662
0
0
0
0
0
0
1
0
false
0.125
0.125
0
0.375
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
a1b2198550b08d95752ec66db8ea880a7ebf194b
170
py
Python
scripts/expression-matrix.py
merfishtools/merfishtools-evaluation
5499abe9d9f1e0e5bf649bdc38001592cbe1a159
[ "MIT" ]
1
2017-03-28T14:33:17.000Z
2017-03-28T14:33:17.000Z
scripts/expression-matrix.py
merfishtools/merfishtools-evaluation
5499abe9d9f1e0e5bf649bdc38001592cbe1a159
[ "MIT" ]
null
null
null
scripts/expression-matrix.py
merfishtools/merfishtools-evaluation
5499abe9d9f1e0e5bf649bdc38001592cbe1a159
[ "MIT" ]
null
null
null
import pandas as pd # load data exprs = pd.read_table(snakemake.input[0], index_col=[0, 1])["expr_map"].unstack(0).fillna(0) exprs.to_csv(snakemake.output[0], sep="\t")
28.333333
92
0.711765
31
170
3.774194
0.774194
0
0
0
0
0
0
0
0
0
0
0.03871
0.088235
170
5
93
34
0.716129
0.052941
0
0
0
0
0.062893
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
a1b716cd5c84416816fb23a4cbc40686dfd79876
6,721
py
Python
run.py
MosesGakuhi1857/password-locker
04b242413f9fa665ca3a9268635c7b42d42748b1
[ "MIT" ]
null
null
null
run.py
MosesGakuhi1857/password-locker
04b242413f9fa665ca3a9268635c7b42d42748b1
[ "MIT" ]
null
null
null
run.py
MosesGakuhi1857/password-locker
04b242413f9fa665ca3a9268635c7b42d42748b1
[ "MIT" ]
null
null
null
# import pyperclip from user import User from credentials import Credentials def create_user(myusername,loginpass): """ Function to create a new user's account """ new_user = User(myusername,loginpass) return new_user def save_user(user): """ Function to save user """ user.save_user() def verify_user(login_username,password): """ function that verifies user's credentials """ checking_user = Credentials.check_user(login_username,password) return checking_user def generate_newpassword(): """ function to generate password """ gen_pass = Credentials.generate_newpassword() return gen_pass def create_credentials(socialM,username,passcode): """ Function to add a new social media's credentials """ new_credentials = Credentials(socialM,username,passcode) return new_credentials def save_credentials(credentials): """ Function to save user's credentials """ credentials.save_credentials() def display_credentials(socialM): """ Function that returns all the saved credentials """ return Credentials.display_credentials(socialM) def main(): print(' ') print("Hello Welcome to Password Locker.") while True: print( " ") print("."*40) print("Kindly use the short codes: \n cc=create a new account on password locker, \n log = to login, \n dlt= To delete the credentials, \n dc = to display the credentials list, \n ex = exit") short_code = input ("Choose a short code: ").lower().strip() if short_code == "ex": break elif short_code == "cc": print("."*35) print(" ") print("Create a new account:") login_username = input ("Input the username:").strip() password = input ("Input the password not less than 9 characters and must have an uppercase and lowercase characters with both letters and numbers: =>").strip() save_user(create_user(login_username,password)) print (f"New user created for: {login_username} using password: {password} ") elif short_code == "log": print("."*30) print(" ") print("to login enter your account details:") login_username = (input ("Enter your username :")) password = str(input("Enter your password :")) user_exist = verify_user(login_username,password) if user_exist == login_username: print(" ") print(f"Welcome {login_username} .Please choose any option to continue.") print(" ") while True: print("_"*40) print('to navigate to account use code:\n sm = to add a social media account, \n dc = to display accounts \n dlt = to delete \n ex- Exit') short_code=input('Enter a choice: ').lower().strip() print("_"*40) if short_code =='ex': print(' ') print(f'Thank you! {login_username}.') break elif short_code == 'dlt': print("_"*40) print(' ') print('Successfully Deleted!') break elif short_code =='sm': print(' ') print('Enter your account name: ') socialM = input('enter the the social media\'s name: ').strip() username = input('enter your account\'s username: ').strip() while True: print(' ') print("_"*50) print("please enter the choose for entering password for your account: \n pwd = enter existing password \n gp-generate a new password \n del- delete \n ex- Exit") opt_choice = input('Enter an option: ').lower().strip() print("-"*80) if opt_choice == 'pwd': print(" ") passcode = input('enter your password: ').strip() break elif short_code == 'del': print("_"*80) print(' ') print('Successfully Deleted!') break elif opt_choice == 'gp': password = generate_newpassword() break elif opt_choice == 'ex': break else: print('Try Again!.') save_credentials(create_credentials(socialM,username,passcode)) print(' ') print(f'Account Created: Name: {socialM}, userName:{username}, Password:{passcode}') print(' ') elif short_code == 'dc': print(' ') if display_credentials(socialM): print('Here is a list of all accounts') print(' ') for account in display_credentials(socialM): print(f'social media name: {credentials.socialM} - username: {credentials.username} - Password: {credentials.passcode}') print(' ') else: print(' ') print("you don't seem to have any account") print(' ') else: print('TRY Again') else: print(' ') print('TRY Again or create another account.') else: print("_"*40) print(' ') print("try Again") if __name__ == '__main__': main()
36.527174
199
0.443386
576
6,721
5.055556
0.222222
0.048077
0.026786
0.034341
0.089286
0.040522
0
0
0
0
0
0.005859
0.466746
6,721
184
200
36.527174
0.806641
0.042256
0
0.358974
0
0.042735
0.232312
0.010265
0
0
0
0
0
1
0.068376
false
0.188034
0.017094
0
0.128205
0.435897
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
1
0
2
a1c4efe71e23c841c50e3eb94fb015ee387440a7
707
bzl
Python
tools/build/bazel/angular_workspace.bzl
MohiK98/onos
a2dbcdade1eccc8cc1d04ead4c9b39827da76aee
[ "Apache-2.0" ]
1,091
2015-01-06T11:10:40.000Z
2022-03-30T09:09:05.000Z
tools/build/bazel/angular_workspace.bzl
MohiK98/onos
a2dbcdade1eccc8cc1d04ead4c9b39827da76aee
[ "Apache-2.0" ]
39
2015-02-13T19:58:32.000Z
2022-03-02T02:38:07.000Z
tools/build/bazel/angular_workspace.bzl
MohiK98/onos
a2dbcdade1eccc8cc1d04ead4c9b39827da76aee
[ "Apache-2.0" ]
914
2015-01-05T19:42:35.000Z
2022-03-30T09:25:18.000Z
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@npm//@bazel/protractor:package.bzl", "npm_bazel_protractor_dependencies") load("@npm//@bazel/karma:package.bzl", "npm_bazel_karma_dependencies") load("@io_bazel_rules_webtesting//web:repositories.bzl", "web_test_repositories") load("@io_bazel_rules_webtesting//web/versioned:browsers-0.3.2.bzl", "browser_repositories") load("@io_bazel_rules_sass//sass:sass_repositories.bzl", "sass_repositories") def load_angular(): npm_bazel_protractor_dependencies() npm_bazel_karma_dependencies() web_test_repositories() browser_repositories( chromium = True, firefox = True, ) sass_repositories()
33.666667
92
0.759547
89
707
5.651685
0.359551
0.095427
0.107356
0.095427
0.194831
0.115308
0
0
0
0
0
0.004717
0.100424
707
20
93
35.35
0.786164
0
0
0
0
0
0.560113
0.490806
0
0
0
0
0
1
0.066667
true
0
0
0
0.066667
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
1
0
0
0
0
0
0
2
a1c9e4b55d38ff38a8d106cc5f8c446ad22aa47d
131
py
Python
Estrutura_sequencial/Exercicio_7.py
Guga-crypto/Exercicios_Iniciante
e9bdf352aacf3a67b0cc879ac969df486d01f86d
[ "MIT" ]
null
null
null
Estrutura_sequencial/Exercicio_7.py
Guga-crypto/Exercicios_Iniciante
e9bdf352aacf3a67b0cc879ac969df486d01f86d
[ "MIT" ]
null
null
null
Estrutura_sequencial/Exercicio_7.py
Guga-crypto/Exercicios_Iniciante
e9bdf352aacf3a67b0cc879ac969df486d01f86d
[ "MIT" ]
null
null
null
lado = float(input('Digite um dos lados do quadrado: ')) area = lado * 4 dobro = area * 2 print(f'\nO dobro da área é {dobro}.')
18.714286
56
0.641221
23
131
3.652174
0.826087
0
0
0
0
0
0
0
0
0
0
0.019231
0.206107
131
6
57
21.833333
0.788462
0
0
0
0
0
0.465649
0
0
0
0
0
0
1
0
false
0
0
0
0
0.25
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
a1d7cb7c4f0700f1669029c149c3fc786b048fa9
15,047
py
Python
django/docs/topics/testing/overview.txt.py
roshanba/mangal
f7b428811dc07214009cc33f0beb665ead402038
[ "bzip2-1.0.6", "MIT" ]
null
null
null
django/docs/topics/testing/overview.txt.py
roshanba/mangal
f7b428811dc07214009cc33f0beb665ead402038
[ "bzip2-1.0.6", "MIT" ]
null
null
null
django/docs/topics/testing/overview.txt.py
roshanba/mangal
f7b428811dc07214009cc33f0beb665ead402038
[ "bzip2-1.0.6", "MIT" ]
null
null
null
XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XXX XXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXX XXXXXXXXXX XXXXXXX XXXXX XXX XXXXXX XXXXXXXXXXXXX XX XXXXXXXXX XXX XXXXXXXXXXXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXX XXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXXXXXXXXXXXX XXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXXXXXX XX XXXXX XXXX XXX XXXXXXX XXXXXXXXX XXXXXX XX XXXXXXX XXX XX XXXXX XXXXX XXXX XXXXXXX XXXXX XX XXXXXXX XXX XX XXX XXXXX XXXXXXX XXXXX XXXXXXXXXXXXX XXXXXXXX XXXX XXXXX XXX X XXXXXX XXXXXXXX XXXXXXX XXXXXXX XXXXXXXXXXXXXXXX XXXX XXXXXX XXXXXXX XXXXX XXXXX X XXXXXXXXXXX XXXXXXXXX XXXX XX XX XXXXXXX XXXXX XXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XX X XXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXXXX X XXXXXXXXXXX XX XXXXXXX XXXXXXXXXXX XXXX XXXXXXXXXXX XXXXXX XXXXXXXX XXXX XXXXXXXXXXXX XXXXXX XXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXX XXX XXXXX XXX XXXXXXXXX XXXXXXXXXXXXX XXXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XXXX XXXXXXXX XXXX XXX XXXXXXXXX XXXX XXXXX XXXXXXXXXXXXXXXXX XXX XXXXXXX XXXXXXXX XX XXX XXXX XXXXXXX XX XX XXXX XXX XXX XXXX XXXXX XXXXX XXX XXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXX XXXX XXXXX XXXX XXXXXX XXXX XXXXXXXXX XXXXXXXXXXXXX XXXXX X XXXX XXXXX XXX XX XXXXX XXXX XXXXXX XXX XXX XXXX XXXXXX XXX XXXX XXXXXXX XXXXX XXXXXXXXXXXXXXXX XXX XXX XXXXXX XXXXXXXXXXXXXX XX XXXXXXXXXXXX XXXXX XXXXXX XXX XXXXX XXXXX XXX XXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXX X XXXXXXXXXXXX XXXX XX XXX XXX XXXXXXXXXXXX XXXX XXXXX XX XXXX XX XXX XXXX XXXX X XXX XXXXXX XXX XX XXXX XXXX XXXXX XXXXX XXXXXX XXXXXX XXXX XX XXXXXXXXXXX XX XXXX X XXXXX XXXXXXX XX XXX XXX XXXXX XXXX XXXXX XXXX XXXXXXXXX XXXXXXXXXX XXXX XX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXX XXXX XXXX XXXX XX XXXX XXXXXXXX XXXXXXXXXXXXXX XXXXXX XXX XXXXX XXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXX XX XXXX XXXXX XXXX XX XXXXXXXX XXXXXX XXXX XX XXXXXXXX XX XXXXXXXX XXXXXXX XX XXXX XX XXXXXX XXXX XXXX XXXXXXX XX XXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXX XXXX XX XXXXXXX XXXX XXXX XX X XXXXXXXXXXX XXX XXXXXXXX XXX XXXXXXXXX XXX XX XXXX XXXXX XXXXXXXX XXXX XXX XXXXXXXX XXXXX XXXXXXXX XXXX XXXX XXXXX XX XXX XXXXX XXXX XXX XXXX XXXXXX XXXXXXXX XXXXX XXXX XXX XXXX XX XXXX XXXXX XXXX XXXX XXXX XXX XX XXXXXXXXX XXX XXXX XXXX XXX XX X XXXXXX XX XXXXXXXXXXXXXXX XXXXXXX XXXXX XXXXXXXXXXXXX XXXX XXXXXX XXXXXXX XXXXXX XXX XXXX XXXXX XXX XXXXXXXXXXXXXXX XXXXXXX XX XXXX XXXXXXXXX XXXXXXXXXXXXX XXXXXXXXX X XXXXXXXXXXX XXXX XXXX XXXXXXXXX XX XXXXX XX XXX XXXXXXXX XXXXXXXX XXXXXXXXXXXXXXXXX XXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XXXX XXXX XXXXXXXX XXXXX XX XXX XXXX XXXXX XXXXXXXXXX XXXXX XXX XXXXXXX XXXXXXX XXXXXXXXXX XXX XXX XXXXXXX XXXXXXXXXX XXXXX XX XXX XX XXXXXXXXX XXX XXXXXX XX XXXXX XXXXXXX XX XXXXXXXXXXXXX XXXXXXX XXXX XXXX XXXXX XXX XX X XXXX XXXXXX XXXXXX XXXX XX X XXXXXXXX XXXXXXX XXXXXXXXXXXX XXXXXXXXX XX XXXX XXXXXXX XXX XXXXXXXXXX X XXX XXX XXX XXXXX XX XXX XXXXXXXXXXXXX XXXXXX X XXXXXXXXXXX XXXX XXXXXXXXXXXXX X XXX XXX XXX XXXXX XXXXX XXXXXX XXX XXXXXXXXX XXXXXXX X XXXXXXXXXXX XXXX XXXXXXX X XXX XXXX XXX XXXX XXXX X XXXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXX XXXX XXX XXXX XXXXXX X XXXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXX XXXXXXX X XXXX XX X XXXXXXXXX XX XXXXXXXX XXXXX XXXXX XXXX XXXXXXXXXXX X XXXXXXXXXXX XXXX XXXXXXXX XXX XXX XXXXXXX X XXXXXX XXXXXXXX XXXXXXX XXXXX XXXXX XXX XXXXXX XXX XXXXXXXXXXXXXX XXXXXXX XX XXXX XXXX XXXXX XXX XXXXX XXXXXXXXXXX XXXX XXX XXXXXXXXXXXX XXXXXXXXX X XXXXXXXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXX XX XXX XXXXX XXXXXXXXXX XXXXX XXX XXXXX XXX XXXXXXXX XXX XXXX XXXXXX XXXX XXXX XXX XXX XXXXXXXXX XXXXXXX XXXX XX XXXXXXXX XXX XXXX XXXX XXXXXXXXXXX XXXXXX X XXXXXXXX XXXX XXX XXXX XXXXXX XXXX XXXXXX XXXXXXX XX XXX XXXX XXXXXXXXX XXXXXX XX XXX XXXX XXXXX XXXX XXX XXX XXX XXXX XXXXXX XXX XXXXXXXX XXXX XXXXXXXXXXXX XXX XXXXXXX XXX XXXX XXXXXXXXX XX XXXXXX XXXX XXXXXXXX XXXXXXXXXX XXX XX XXXX XXXXXX XX XXX XXXXXX XX XXXX XXX XXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXX XXXXXXX XXXXXX XXXX XXXX XXXXX XXX XXXXXXXXXXXX XXXXXXX XXX XXXX XX XXX XXXXXXX XX XXX XXXXXXXX XXXXXXX XXXXXXX XXX XXX XXXX XXXX XXX XX XXXXXXXXX XX XXX XX XXX XXXX XX XXXX XXX XXX XXXXXXXXX XXXXXXX XXXX XX XXXXXXX XXX XXX XXXXX XXXXXXXXXX X XXXXXX XXXX XXX XXX XXXX XXX XXXX XXXX XXXXXXXXXXXX XXX XXX XXXXXXXXXXX XX XXXXXXX XX XXX XXXXX XXX XXXXXX XXX XXXXXXXXXXXX XXXX XX XXXXXXXXX XXX XXX XXXX XXXXXXXXX XXXXXXX XX XXX XXX XXXX XXX XX XXXXXXXXXX XX XXXXXXXXXXXX XXXX XXXX XXXXXXXX XXXXXXX XXXX X XXXX XXXX XX XXX XXXX XXXXX XXXX XXXXXX XXXXXXXX XXXXXXXX XXXXXXXX XXX XXXXXXXXX XXXXXXX XXX XXXXXXX XXXX XXXXX XXXXXX XX XXXXXXX XXXXXXXXXXX XXXXXXXXX XXXXXXX XXXX XXXX XXXXX XXXXXX XXXXXXXXXX XXXX XXXXX XXXXXXXX XX XXXX XXXX XXXXXXXX XXX XXXXX XXXXX XX XXXX XXXXX XXXX XXXXX XX XXXX XXXX XXXX XXXXXX XXXXXXXX XXXXX XXX XXXXX XXXXXXX XXXX X XXXXXX XXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXX XXX XXXX XXXXXXXX XXXXXXXXXXXXXXXXX XXXXX XXXX XXXXXXX X XXXXXXXX XXXXXXXX XXXXX XXXXXX XXXX XXX XXX XXXX XXXXXX XXXXXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXX XXXXXXXXX XXX XXXXXXX XXX XXX XXXXXX XXXXXXXXXX XX XXXXXXX XXX XXXXX XXXX XX XXXXX XXX XXXX XXXXXXXXX XXX XXXXXXXXX XXXX XXX XXX XXXXX XXXX XXXX XXXXXXXXX XXX XXX XXXXXXX XXX XXXX XXXXXXXXX XXXX XXXXX XXXXXXXXX XX XXXXX XXX XXXXXXXXXXXXX XXXXXXXXX XXXXXXX XXXX XXXX XXXXXXXX XXX XXXX XXXXXXXX XXXXXXX XXXXX XX XXX XXXXXXXX XXXX XXX XXXXXX XX XXXX XXXXX XX XXXXXXXX XXX XXXXXXXXXX XXXX XXXX XX XXXXXXX XX XXXXX XX XXXX XX XX XX XXXXX XX XXXXXXXXX XX XXX XXXXXXXX XXXXXXXX XX X XXXX XXX XX XXXXXXXXXX XXXXXXXXXXXX XXX XXXX XXXXXXXX XXX XXX XX XXXXXXXXXX XX XXX XXXX XXXX XXXXXX XX XXXXX XXXXXXX XXX XXXX XX XXXXX XX XXXXXXX XXX XXXXXXXXX XXX XXX XXXXXXXXXXXXX XXXXXXXXXX XXXXXX XX XXXXXXXX XXXX XXXXXX XXX XXXXXXXXXXXXX XXXXXXX XXX XXXXXXXXX XXXX XXX XX XXXXXX XXXX XXXXXXX XXXXX XX X XXXXXXXXXX XXXXXXXXXXX XXXXXX XXXXX XXXXX XXX XX XXXXXXXXXXX XX X XXXXXXXX XXX XXXXXXXX XXX XXXXXXX XXXX XXXXXXXX XXXXX XXX XXXXXXX XX XXXXXXXXXX XXXXXXXXX XX XXX XXXXX XX XXXX XXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXX XXXX XXXXX XXXXXXX XXX XXXXX XXXX XXX XX XXXXXXXXX XXXXXXXX XX XXXXXXX XXXXXX XXX XXXXXXXX XXXX XX XXXXXXX XX XXXXXXX XXXXXXXXX XXX XXXXXXXXXX XXXXXXXXXXX XXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXX XXXXXX X XXXXXX XX XXXXXXXX XX XXXXXXXXX XXXX XXXX XXXXXXXXX XXX XXXXXXXX XX XXX XXXX XX XXX X XXXXXXXXX XXXXXXXX XXXXX XXXXXXX XXXXXXXXXXXXXX XXXXXXXXXXXX XX XXX XXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXX XXX XXX XXXXX XXXXXXXX XX XXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXX XXXXXXXXXXXXXXX XXXX XXXX XXXX XXXX XXXXXX XX XXX XXXXXXXX XXXXXXXXXXXX XXXXXXXXX XXXXX XXXX XXXXX X XXXXXXXX XXXXXXXXX XXX XXXX XXXXXX XXXX XXXXXXXXX XXX XXX XX XXX XXXX XXXXXXXX XXXXXXXX XXX XXXX XX XXXX XXXXXXXX XXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXXX XXX XXXX XXXXXXXX XX XXXXXXX XX XXX XXXX XXXXXXXXX XX XXXXXXXXXXXXXXXX XX XXXXXX XXXX XX XXXX XXXX XXXX XXX XXXXX XXXX XXXXXXX XXX XXXXXXXXXX XXXXXXXXXX XX XXXXXX X XXX XXXXXXXX XX XXX XXXXXXX XXX XXXXXXXXXXXX XXXXXXX XXXX XXX XXXXXXXXX XXXXXXXX XX XXXX XXXX XXXXXXXXX XXX XXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX XXXX XXXXXXX XX XXXXXX XXXXX XXXXXX XXX XXX XXXX XXX XXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX XXXXXX XX XXXXXXX XXX XXXXXXXXXX XXXXXXXXX XXXX XX XXX XXXX XXXXXXXXX XXX XXX XXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXX XXX XXXXXXX XX XXXXX XXX XXXXX XXXXXXXX XXXXXXXXX XX XXXXX XX XXXXXX XXXXXXXXX XXXXXXXX XXXX XXXXXXX XXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXX XX XXX XXX XXXXX XXXXX XXXX XXXXXXX XX XXXXX XXX XXXXXXXX XXXXXXX XXXXXXXX XX XXXXXXXXXXXX XXXXXXX XXXX XXXX XXXX XXXXXXXXXX XXXXXXXX XXXX XXXXXXX XXXXXX XX XXXX XXXX XXXXXXXX XX XXXXXX XXX XXXXXXXX XXXX XXX XXXXXXX XXX XXXXXXXXX XXXX XXXX XXXXX XXXXXXXX XXX XXXX XXXXXXXX XX XXX XXX XXXX XXXXXXXXXXX XXXXXXXXXX XXXXXXXX XXX XXXXXXXX XX XXX XXXX X XXXXXXXX XXXXX XX XXXXXXXXXXXX XXXX XXX X XXXX XXXXXXXX XXXXXXX XXXXXXXXXX XXXX XXXXX XXXXXXX XXXX XXXXXX XXX XX X XXX XXXX XX XXXX XXXX XXXXXXXXXXX XXXXXXXX XXXXXXX XX XXXX XXXXX XXXXXX X XXXXXXX XXXX XXXX XX XXXX XX XXXXXXX XX XXXXX XXXX XXXX XXXXXXX XX XXXXXXXXXX XXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXX XXX XXXXXXXXXXXXXX XXXXXXXX XXXXXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXX XXXXX XX XXXXX XXXXX XXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXX XX XXXXXXXXX XXXX XXX XXXXXXXXXXXX XXXX XXXXXX XXXX X XXXXX XXXXXXXXX XXX XXXXXX XXXX XXXXXX XXXXXXXX XXXXX XX XXX XXXXXXXXX XXXX X XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXX XXX XXXXXX X XXXXX XXX XXXXX XXXXXXXXXXXX XXXXX XXXXX XXXXX XXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXX XXXX XX XXXXXXXXXX XXXXXXXX XXXXXXXXXX XXX XXXXXXXX XXXXX XXXXX X XXXX XXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXX XXXXXXXXX XXXX XXX XXXXX XXX XXXXXXXX XXXXXXX XXXXXXXXX XX XX XXX XXXXXXXX XXXXX XXX XXXX XX XXXXXX XXX XXX XXXXXXXX XX XXXXX XXX XXXXXX XXXXXXXXXX XXXXXXXXXXXX XX XXXX XXXX XXXXXXXXX XXXX XX XXX XXXX XXXX XXXXXXXX XXXX XXXXXX XX XXXXX XXXX XX XXX XXXXXXXX XX X XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXX XXXX XX XXXXXXX XX XX XXXX XX XXX XXXXXXXXXXXXXX XXX XXX XXXXXXX XXX XXXXXXXXX XXXXX XXXXXX XXXXXX XXXXX XXX XXXXXXXXXXXXX XXXXXXXXXX XXXXXXX XXXX XXX XXXX XXXX XXXXXXXX XXXX XXXXX XXX XXXXXXXXXXX XXXX XXXX XXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXX XXX XXXXXXX XXXX XXXXXX XX XXXXXXXXXX XXXX XXXX XX XXXXXXXXX XX XXXXXXXXXXXX XXXXX XXX XXX XX XXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXX XXXXXXXXXXXX XXXX XX XXXXXXXX XXXXX XXXXXXXXXXXX XXX XXXXXXXXX XXXX XXXX XXXXXXXXX XXXXXXXXX XXXXX XXXXXXXX XXXX XX XXXX XXXX XXX XXXXX XXXXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXX XXXXXX XXXX XXXX XXX XXX XX X XXXXXXXXXXXX XXXXX XX XXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXX XXXXXX XX XXXXXXXX XX XXX XXXX XX XXX XXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXX XXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXX XXXXX XX XXXXXXXXXXXXX XXX XXXXXXXXXXX XXXX XX XXXXX XXXXXXXXXX XXXXXXX XXXXXX XXXX XXXX XX XXX XXXXX XX XXXXXXXX XXXXXXXX XXX XXXXXX XX XXXXXXXXXX XXXX XXX XXXXXXXX XXXXXXX X XXXXXXXXXXXXX XXXXXXXX XXX XX XXXXX XXXXXXXXXXXX XXX XXXX XXXXXX XXX XXXX XXX XXXX XXXX XXXXXXXX XXX XXXXXXX XXXXXXXXXXXXX XX XXXXXXX XXXX XXXXXX XXX XX XXX XXXX XX XXXXXXX XXXX XXXX XXXX XXXX XXXXXXX XXXX XXXXX XX XXXX XXXX XXXXXXXXXX XXX XXX XXX XXXXX XXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXX XXXXXXXXXX XXXX XXXX XXXXX XXXXXX XXXXXX XXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXX XXXXXXXX XXX XXXX XXXXXXXXX XXXXX XXXX XXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XX XXX XXXXX XX XXX XXXXXXXXXXXXXXXX XXXXXXX XX XXXX XXXXXXXXXXXXX XXXXX XXX XXXXXX XXXXX XXX XXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXX XX XX XXXXXX XXXX XXX XXXXXXXX XXXXXX XX XXXX XXXX XXXXXXX XXXX XXXX XX XXXX XX X XXXXXXXXXX XXXXXXXX XXXXXX XXX XXX XXXXXXX XXXXX XXXX XXXXX XXX XXXXXXX XXXXXXXXXX XXXX XXXXXXX XXX XXXXXX XXXX XXXX XXX XXXXX XXXX XXX XXXXX XX X XXXX XXXXXX XX XXX XXX XXXX XXXXX XX XXXXXXXXXX XXXXXXXX XXXXXX XXXXXXXXXX X XXXXXXXX XXXXX XXXXXX XX XXX XXXXX XXXX XXXXXXXX XXXXXXXXXXXX XXXXXX XXXXXXXX XX XXX XXXXXXX XXXXXXXXXXXXX XXX XXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XXX XXXX XXXXXX XXXXXX XXX X XXXXXX XX XXXXXXXX XX XXX XXXX XXXXXX XXXXXXXX XXXXXXX XXX XXX XXXXXXX XXX XXXXX XX XXXXXX XX XXXXX XXXXXXXX XXXX XXX XXXXXXXXXXXXX XXXXXX XX XXX XXXXXXX XXXXXX XXXXXXXX XXXX XXXXXXXXXXX XXXXXXXX XXXXX XXXXXXXXXXXX XXXXXXXX XXXXX XXXXXXXXXXXXX XXXX XXXXX XXX XXXX XXX XXXX XXXXXX XX XXXXXXXX X XXXX XXXXXXXXX XX XXXXXXXXX XX XXX XXXXXXXX XXXXXXXX XXXX XXX XXXX XXXXXXXX XXX XXXX XXXXXXXX XXXXXX XXXX XXX XXXX XXXXXX XX XXXXXXXXXX XXXX XXXXX XXXXXX XXX XXXXXXXXX XXXX XXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XX XXXXX XX XXXXXX XX XX XXXXX XXX XXXX XXXXXXXXX XXXXXXXX XXXXXX XXX XXXX XXXXXXX XXXXX XXXXX XXXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXX XXXXXX XXXX XXXXXX XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXX XXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX XXXXXXXXXXXXXXX XXXX XX XXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX X XXXX XX XXXXXX XXXXXX XXXXXXXXXXXX X XXXX XXXXXXXXXXX XX XXXX XXXXX XXXXXX XX XXXXXX XXX XXXXX XX XXXX XXXXXXXXX XXX XXXX XXXXXX XXXXXXXXXX XXX XXX XXXXXXX XXX XXXXXXXXXXXXX XX XXXXXXXX XXXXXXXXXXXXXXX XXXXXXX XXX XXXXXXXX XXXX XXXX XXX XXXXXX XXXX XXX XXX XXXXXXXXXXX XXXXXX XX X XXX XXX XXXXXX XX XXXXXX XXX XXXXXXXXX XXXXXX XX XXX XXX XXXXX XXXXX XXX XXXXXX XXXX XX XX XXXX XXXXXXX XX XXXXXX XX XXXXXX XXXXX XXX XXXXXXXXXXX XXXXXX XX X XXXXX XXXXXX XXX XXXX XX XXXX XXX XXXXXXX XX XXXXXXX XX XXXX XXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX XX XXX XXXXX XXXXXXXXXXXXXXXXXXXXX XXXXXXX XXXXX XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XX XXXX XX XXXX XXXXX XXX XXXXXXXX XXXXXXXXX XXX XXX XXX XXXX XX XXXXXXXX XX XXXX X XXXXX XX XX XXXXXXXXXX XXXXXXXXX XXX XXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXXXXXX XXX XXXXXXX XXXXXXXX XXXXXX XX XXXXXX XXXX XX XXXXXXX XX XXXXXX XXXXXXXXXXXXXX XXXX XXXXX XX XXXX XXXXXX XXX XXX XXXX XX XXX X XXXXXX XXXXXXXX XXXX XXX XXX XXX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXX XX X XXXXXX XXXXXXX XXXXXXXXXXX XXXXXXXXXXXXXXXX X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXXX XXXXXX XX XXXX XXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXX XXXXXXXXX XXXX XX XXXXXXXXX XX XXXX XXXXXXXXXX XXX XXXX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXX XXXXXXXXXXXXX XXXXXXXXX XXXXXX XXXXXXXXX XXX XXXX XXXXXXXX XXXXXXX XXXX XXXXX XX XXXXX XXX XXXXXX XXX XXXXXXX XXXXXXX XXXXX XXX XXXXXXX XXXXXXXX XXX XXXX XX XXX XXXXXX
42.030726
97
0.830863
2,048
15,047
6.104492
0.022461
0.047032
0.017277
0.010238
0.137578
0.030315
0.007679
0
0
0
0
0
0.169137
15,047
357
98
42.148459
1
0
0
0.958015
0
0
0
0
0
0
0
0
0
0
null
null
0
0
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
1
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
a1e564dbeb0e05b9cf8f0e444e5f3477c3a10d9e
447
py
Python
src/ywcnvlib/__init__.py
peter88213/pywlo
b3e1e4e6bee95208d6773203b0354f8b75b17dca
[ "MIT" ]
null
null
null
src/ywcnvlib/__init__.py
peter88213/pywlo
b3e1e4e6bee95208d6773203b0354f8b75b17dca
[ "MIT" ]
null
null
null
src/ywcnvlib/__init__.py
peter88213/pywlo
b3e1e4e6bee95208d6773203b0354f8b75b17dca
[ "MIT" ]
null
null
null
"""The ywcnvlib package - Link yw-cnv to the UNO API. Modules: yw_cnv_uno -- Provide a converter class for universal import and export. ui_uno -- Provide a UNO user interface facade class. uno_tools -- Provide Python wrappers for UNO widgets. Copyright (c) 2022 Peter Triesberger For further information see https://github.com/peter88213/yw-cnv Published under the MIT License (https://opensource.org/licenses/mit-license.php) """
34.384615
82
0.753915
67
447
4.970149
0.701493
0.045045
0.066066
0
0
0
0
0
0
0
0
0.024
0.161074
447
12
83
37.25
0.864
0.955257
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
a1f4fb0056170cae8b8505ca6fefff5fb0d7d733
286
py
Python
app/requests.py
glasses-png/Charlotte-p-Bog
3ff5d2279b2e97d1b2daf0348a258bd7cf04bbb4
[ "MIT" ]
null
null
null
app/requests.py
glasses-png/Charlotte-p-Bog
3ff5d2279b2e97d1b2daf0348a258bd7cf04bbb4
[ "MIT" ]
null
null
null
app/requests.py
glasses-png/Charlotte-p-Bog
3ff5d2279b2e97d1b2daf0348a258bd7cf04bbb4
[ "MIT" ]
null
null
null
import urllib.request,json from . import create_app import requests def get_quotes(): response = requests.get('http://quotes.stormconsultancy.co.uk/random.json (Links to an external site.)') if response.status_code == 200: quote = response.json() return quote
26
108
0.706294
38
286
5.236842
0.736842
0
0
0
0
0
0
0
0
0
0
0.012876
0.185315
286
10
109
28.6
0.841202
0
0
0
0
0
0.269231
0
0
0
0
0
0
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
a1ffe7ebda7ac44367ced90cb1a5095a66d664fe
716
py
Python
Eager/github-scraper/python/getrepos.py
UCSB-CS-RACELab/eager-appscale
d58fe64bb867ef58af19c1d84a5e1ec68ecddd3d
[ "Apache-2.0" ]
3
2016-06-12T01:18:49.000Z
2018-07-16T18:20:23.000Z
Eager/github-scraper/python/getrepos.py
UCSB-CS-RACELab/eager-appscale
d58fe64bb867ef58af19c1d84a5e1ec68ecddd3d
[ "Apache-2.0" ]
null
null
null
Eager/github-scraper/python/getrepos.py
UCSB-CS-RACELab/eager-appscale
d58fe64bb867ef58af19c1d84a5e1ec68ecddd3d
[ "Apache-2.0" ]
1
2020-05-25T02:59:15.000Z
2020-05-25T02:59:15.000Z
import requests import json from json import dumps #r = requests.get('https://api.github.com/repos/django/django') r = requests.get('https://api.github.com/legacy/repos/search/:app engine') if(r.ok): repoItem = json.loads(r.text or r.content) print "created_at: " + repoItem['created_at'] print "pushed: " + repoItem['pushed_at'] print "private: " + str(repoItem['private']) print "id: " + str(repoItem['id']) print "owner: " + repoItem['owner']['login'] print "description: " + repoItem['description'] print "forks: " + str(repoItem['forks']) print "watchers: " + str(repoItem['watchers']) print "has downloads: " + str(repoItem['has_downloads']) # print dumps(repoItem, indent=4)
35.8
74
0.668994
93
716
5.107527
0.430108
0.115789
0.050526
0.071579
0.122105
0.122105
0.122105
0
0
0
0
0.001637
0.146648
716
19
75
37.684211
0.775777
0.134078
0
0
0
0
0.346278
0
0
0
0
0
0
0
null
null
0
0.2
null
null
0.6
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
0
0
0
1
0
2
b8009fc359dbe298ba7e59c66a8ad289cc16e54c
912
py
Python
app/modules/test_data/users.py
davidespihernandez/mockbackend
9ba05c5983fe203cec65ffdfd30b5551cccf91c6
[ "Apache-2.0" ]
null
null
null
app/modules/test_data/users.py
davidespihernandez/mockbackend
9ba05c5983fe203cec65ffdfd30b5551cccf91c6
[ "Apache-2.0" ]
null
null
null
app/modules/test_data/users.py
davidespihernandez/mockbackend
9ba05c5983fe203cec65ffdfd30b5551cccf91c6
[ "Apache-2.0" ]
null
null
null
from app.modules.models.users import User objects = { "00000000-0000-0000-0000-000000000000": User( token="00000000-0000-0000-0000-000000000000", title="Mr", login="test1@test.com", first_name="Test 1", last_name="User", email="test1@test.com", address="Address", postcode="12345", town="Gent", country="BE", phone="+33 444 555 666", language="en_US", birthday=None ), "10000000-0000-0000-0000-000000000000": User( token="10000000-0000-0000-0000-000000000000", title="Mr", login="test2@test.com", first_name="Test 2", last_name="User", email="test2@test.com", address="Address", postcode="12345", town="Gent", country="BE", phone="+33 444 555 666", language="en_US", birthday=None ), }
26.057143
53
0.54386
102
912
4.803922
0.421569
0.130612
0.097959
0.195918
0.8
0.653061
0.518367
0.371429
0.371429
0.371429
0
0.260188
0.300439
912
34
54
26.823529
0.507837
0
0
0.606061
0
0
0.328947
0.157895
0
0
0
0
0
1
0
false
0
0.030303
0
0.030303
0
0
0
0
null
0
0
1
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
0
0
0
0
0
0
0
2
b800e4a22c52d33c10f93210f9639b7ef5983580
172
py
Python
Chapter 06/Praktikum-2/2.py
icaksh/Python-Projects-Protek
dfd56ea5afc637a8850911a9296131652de383c5
[ "MIT" ]
null
null
null
Chapter 06/Praktikum-2/2.py
icaksh/Python-Projects-Protek
dfd56ea5afc637a8850911a9296131652de383c5
[ "MIT" ]
null
null
null
Chapter 06/Praktikum-2/2.py
icaksh/Python-Projects-Protek
dfd56ea5afc637a8850911a9296131652de383c5
[ "MIT" ]
null
null
null
def luasSegitiga2(a,t): luas = a * t / 2 print('Luas segitiga dengan alas ',alas,'dan tinggi ',tinggi,' adalah ',luas) alas=10 tinggi=20 luasSegitiga2(alas,tinggi)
24.571429
81
0.686047
26
172
4.538462
0.576923
0.033898
0
0
0
0
0
0
0
0
0
0.048951
0.168605
172
7
82
24.571429
0.776224
0
0
0
0
0
0.260116
0
0
0
0
0
0
1
0.166667
false
0
0
0
0.166667
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
b808aae02d12f3182d183d70af58819eada1e273
1,090
py
Python
highlander/engine/default_engine.py
StephenTao/stephen
06da7cbc93b40fcd089eeed2972adc1fe6bd3cb9
[ "Apache-2.0" ]
null
null
null
highlander/engine/default_engine.py
StephenTao/stephen
06da7cbc93b40fcd089eeed2972adc1fe6bd3cb9
[ "Apache-2.0" ]
null
null
null
highlander/engine/default_engine.py
StephenTao/stephen
06da7cbc93b40fcd089eeed2972adc1fe6bd3cb9
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 - Mirantis, Inc. # Copyright 2015 - StackStorm, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from highlander.engine import base from highlander.openstack.common import log as logging LOG = logging.getLogger(__name__) # Submodules of highlander.engine will throw NoSuchOptError if configuration # options required at top level of this __init__.py are not imported before # the submodules are referenced. class DefaultEngine(base.Engine): def __init__(self, engine_client): self._engine_client = engine_client
29.459459
77
0.743119
151
1,090
5.258278
0.635762
0.075567
0.032746
0.040302
0
0
0
0
0
0
0
0.013683
0.195413
1,090
36
78
30.277778
0.891676
0.729358
0
0
0
0
0
0
0
0
0
0
0
1
0.166667
false
0
0.333333
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
b809ec79a4fbda27e03720a539c30ecd15c9dd5e
898
py
Python
google/datalab/notebook/__init__.py
freyrsae/pydatalab
9aba1ac6bbe8e1384e7a4b07c5042af84348797d
[ "Apache-2.0" ]
198
2016-07-14T19:47:52.000Z
2022-03-15T08:45:21.000Z
google/datalab/notebook/__init__.py
freyrsae/pydatalab
9aba1ac6bbe8e1384e7a4b07c5042af84348797d
[ "Apache-2.0" ]
534
2016-07-15T19:12:43.000Z
2022-03-11T23:11:39.000Z
google/datalab/notebook/__init__.py
freyrsae/pydatalab
9aba1ac6bbe8e1384e7a4b07c5042af84348797d
[ "Apache-2.0" ]
86
2016-07-13T17:39:05.000Z
2021-11-03T03:39:41.000Z
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under the License # is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express # or implied. See the License for the specific language governing permissions and limitations under # the License. """Google Cloud Datalab - notebook extension functionality.""" try: import IPython as _ except ImportError: raise Exception('This package requires an IPython notebook installation') __all__ = ['_'] def _jupyter_nbextension_paths(): return [dict(section="notebook", src="static", dest="gcpdatalab")]
35.92
99
0.76392
127
898
5.330709
0.716535
0.088626
0.038405
0.047267
0
0
0
0
0
0
0
0.010526
0.153675
898
24
100
37.416667
0.880263
0.693764
0
0
0
0
0.305019
0
0
0
0
0
0
1
0.142857
false
0
0.285714
0.142857
0.571429
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
62bf300fbe14d43cae880956a6ff0d9599490f0a
25,496
py
Python
src/ralph/virtual/tests/test_api.py
elubik/ralph
ac39be38cbd7c80ac64984848423fc92b8661b16
[ "Apache-2.0" ]
1,668
2015-01-01T12:51:20.000Z
2022-03-29T09:05:35.000Z
src/ralph/virtual/tests/test_api.py
elubik/ralph
ac39be38cbd7c80ac64984848423fc92b8661b16
[ "Apache-2.0" ]
2,314
2015-01-02T13:26:26.000Z
2022-03-29T04:06:03.000Z
src/ralph/virtual/tests/test_api.py
elubik/ralph
ac39be38cbd7c80ac64984848423fc92b8661b16
[ "Apache-2.0" ]
534
2015-01-05T12:40:28.000Z
2022-03-29T21:10:12.000Z
from ddt import data, ddt, unpack from django.core.urlresolvers import reverse from rest_framework import status from ralph.api.tests._base import RalphAPITestCase from ralph.assets.models.assets import ServiceEnvironment from ralph.assets.models.choices import ComponentType from ralph.assets.models.components import ComponentModel from ralph.assets.tests.factories import ( EnvironmentFactory, EthernetFactory, ServiceEnvironmentFactory, ServiceFactory ) from ralph.data_center.tests.factories import ( ClusterFactory, DataCenterAssetFactory ) from ralph.networks.tests.factories import IPAddressFactory from ralph.virtual.models import ( CloudFlavor, CloudHost, CloudProject, CloudProvider, VirtualComponent, VirtualServer, VirtualServerType ) from ralph.virtual.tests.factories import ( CloudFlavorFactory, CloudHostFactory, CloudProjectFactory, CloudProviderFactory, VirtualServerFullFactory ) @ddt class OpenstackModelsTestCase(RalphAPITestCase): def setUp(self): super().setUp() self.envs = EnvironmentFactory.create_batch(2) self.services = ServiceFactory.create_batch(2) self.service_env = [] for i in range(0, 2): self.service_env.append(ServiceEnvironment.objects.create( service=self.services[i], environment=self.envs[i] )) self.service_env[0].service.business_owners = [self.user1] self.service_env[0].service.technical_owners = [self.user2] self.service_env[0].save() self.cloud_provider = CloudProviderFactory(name='openstack') self.cloud_flavor = CloudFlavorFactory() self.cloud_project = CloudProjectFactory( service_env=self.service_env[0] ) self.cloud_host = CloudHostFactory( parent=self.cloud_project, cloudflavor=self.cloud_flavor ) self.cloud_host2 = CloudHostFactory() self.test_cpu = ComponentModel.objects.create( name='vcpu1', cores=5, family='vCPU', type=ComponentType.processor, ) self.test_mem = ComponentModel.objects.create( name='2000 MiB vMEM', size='2000', type=ComponentType.memory, ) self.test_disk = ComponentModel.objects.create( name='4 GiB vDISK', size='4096', type=ComponentType.disk, ) VirtualComponent.objects.create( base_object=self.cloud_flavor, model=self.test_cpu, ) VirtualComponent.objects.create( base_object=self.cloud_flavor, model=self.test_mem, ) VirtualComponent.objects.create( base_object=self.cloud_flavor, model=self.test_disk, ) @data('cloudflavor', 'cloudproject', 'cloudprovider') def test_get_list(self, field): url = reverse(field + '-list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_cloudhost_list(self): url = reverse('cloudhost-list') with self.assertNumQueries(12): response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 2) @unpack @data( ('cores', 5), ('memory', 2000), ('disk', 4096), ) def test_get_cloudflavor_detail(self, field, value): url = reverse('cloudflavor-detail', args=(self.cloud_flavor.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data[field], value) def test_get_cloudhost_detail(self): url = reverse('cloudhost-detail', args=(self.cloud_host.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['host_id'], self.cloud_host.host_id) self.assertEqual(response.data['hostname'], self.cloud_host.hostname) self.assertEqual(response.data['service_env']['id'], self.cloud_host.service_env.id) self.assertEqual(response.data['parent']['name'], self.cloud_project.name) self.assertEqual(response.data['cloudflavor']['cores'], self.cloud_flavor.cores) self.assertEqual(response.data['cloudflavor']['memory'], self.cloud_flavor.memory) self.assertEqual(response.data['cloudflavor']['disk'], self.cloud_flavor.disk) self.assertEqual(response.data['cloudflavor']['name'], self.cloud_flavor.name) self.assertEqual( response.data['business_owners'][0]['username'], 'user1' ) self.assertEqual( response.data['technical_owners'][0]['username'], 'user2' ) def test_filter_cloudhost_by_service_uid(self): cloud_host = CloudHostFactory() url = ( reverse('cloudhost-list') + '?service_env__service__uid={}'.format(cloud_host.service_env.service.uid) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_get_cloudproject_detail(self): url = reverse('cloudproject-detail', args=(self.cloud_project.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['id'], self.cloud_project.id) self.assertEqual(response.data['name'], self.cloud_project.name) self.assertEqual(response.data['service_env']['id'], self.cloud_project.service_env.id) def test_get_cloudprovider_detail(self): url = reverse('cloudprovider-detail', args=(self.cloud_provider.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['name'], self.cloud_provider.name) def test_create_cloudhost(self): url = reverse('cloudhost-list') args = { 'cloudprovider': self.cloud_provider.id, 'host_id': 'id_1', 'hostname': 'name_1', 'parent': self.cloud_project.id, 'ip_addresses': ['10.0.0.1', '10.0.0.2'], 'cloudflavor': self.cloud_flavor.id, 'tags': ['prod', 'db'], } response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) host = CloudHost.objects.get(host_id=args['host_id']) self.assertEqual(host.cloudprovider, self.cloud_provider) self.assertEqual(host.host_id, args['host_id']) self.assertEqual(host.hostname, args['hostname']) self.assertEqual(host.parent.id, self.cloud_project.id) self.assertEqual(host.cloudflavor, self.cloud_flavor) self.assertEqual(set(host.tags.names()), set(args['tags'])) self.assertEqual(host.service_env, self.service_env[0]) self.assertEqual(set(host.ip_addresses), set(args['ip_addresses'])) def test_create_cloudflavor(self): url = reverse('cloudflavor-list') args = { 'flavor_id': 'id1', 'name': 'name_2', 'cores': 4, 'memory': 1024, 'disk': 10240, 'tags': ['prod', 'db'], 'cloudprovider': self.cloud_provider.id, } response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) flavor = CloudFlavor.objects.get(name=args['name']) self.assertEqual(flavor.cloudprovider, self.cloud_provider) self.assertEqual(flavor.flavor_id, args['flavor_id']) self.assertEqual(flavor.name, args['name']) self.assertEqual(flavor.cores, args['cores']) self.assertEqual(flavor.memory, args['memory']) self.assertEqual(flavor.disk, args['disk']) self.assertEqual(set(flavor.tags.names()), set(args['tags'])) def test_create_cloudproject(self): url = reverse('cloudproject-list') args = { 'cloudprovider': self.cloud_provider.id, 'project_id': 'id_1', 'name': 'name_1', 'service_env': self.service_env[0].id, 'tags': ['prod', 'db'], } response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) project = CloudProject.objects.get(project_id=args['project_id']) self.assertEqual(project.cloudprovider, self.cloud_provider) self.assertEqual(project.project_id, args['project_id']) self.assertEqual(project.name, args['name']) self.assertEqual(set(project.tags.names()), set(args['tags'])) self.assertEqual(project.service_env, self.service_env[0]) def test_create_cloudprovider(self): url = reverse('cloudprovider-list') args = {'name': 'test1'} response = self.client.post(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) provider = CloudProvider.objects.get(name=args['name']) self.assertEqual(provider.name, args['name']) def test_patch_cloudhost(self): url = reverse('cloudhost-detail', args=(self.cloud_host.id,)) args = { 'cloudprovider': self.cloud_provider.id, 'host_id': 'id_1', 'hostname': 'name_1', 'parent': self.cloud_project.id, 'ip_addresses': ['10.0.0.1', '10.0.0.2'], 'cloudflavor': self.cloud_flavor.id, 'tags': ['prod', 'db'], } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) host = CloudHost.objects.get(host_id=args['host_id']) self.assertEqual(host.cloudprovider, self.cloud_provider) self.assertEqual(host.host_id, args['host_id']) self.assertEqual(host.hostname, args['hostname']) self.assertEqual(host.parent.id, self.cloud_project.id) self.assertEqual(host.cloudflavor, self.cloud_flavor) self.assertEqual(set(host.tags.names()), set(args['tags'])) self.assertEqual(set(host.ip_addresses), set(args['ip_addresses'])) def test_patch_cloudflavor(self): url = reverse('cloudflavor-detail', args=(self.cloud_flavor.id,)) args = { 'flavor_id': 'id1', 'name': 'name_2', 'cores': 4, 'memory': 1024, 'disk': 10240, 'tags': ['prod', 'db'], 'cloudprovider': self.cloud_provider.id, } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) flavor = CloudFlavor.objects.get(name=args['name']) self.assertEqual(flavor.cloudprovider, self.cloud_provider) self.assertEqual(flavor.flavor_id, args['flavor_id']) self.assertEqual(flavor.name, args['name']) self.assertEqual(flavor.cores, args['cores']) self.assertEqual(flavor.memory, args['memory']) self.assertEqual(flavor.disk, args['disk']) self.assertEqual(set(flavor.tags.names()), set(args['tags'])) def test_patch_cloudproject(self): url = reverse('cloudproject-detail', args=(self.cloud_project.id,)) args = { 'cloudprovider': self.cloud_provider.id, 'project_id': 'id_1', 'name': 'name_1', 'service_env': self.service_env[1].id, 'tags': ['prod', 'db'], } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) project = CloudProject.objects.get(project_id=args['project_id']) self.assertEqual(project.cloudprovider, self.cloud_provider) self.assertEqual(project.project_id, args['project_id']) self.assertEqual(project.name, args['name']) self.assertEqual(set(project.tags.names()), set(args['tags'])) self.assertEqual(project.service_env, self.service_env[1]) def test_patch_cloudprovider(self): url = reverse('cloudprovider-detail', args=(self.cloud_provider.id,)) args = {'name': 'test1'} response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) provider = CloudProvider.objects.get(name=args['name']) self.assertEqual(provider.name, args['name']) def test_delete_cloud_flavor_returns_409_if_is_used_by_cloud_hosts(self): # given cloud_flavor = CloudFlavorFactory() CloudHostFactory(cloudflavor=cloud_flavor) # when url = reverse('cloudflavor-detail', args=(cloud_flavor.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT) self.assertIn( 'Cloud flavor is in use and hence is not deletable.', resp.data['detail'] ) self.assertTrue( CloudFlavor.objects.filter(pk=cloud_flavor.pk).exists() ) def test_unused_cloud_flavor_can_be_deleted(self): # given cloud_flavor = CloudFlavorFactory() # when url = reverse('cloudflavor-detail', args=(cloud_flavor.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudFlavor.DoesNotExist, cloud_flavor.refresh_from_db ) def test_used_cloud_flavor_can_be_deleted_with_force(self): # given cloud_flavor = CloudFlavorFactory() CloudHostFactory(cloudflavor=cloud_flavor) # when url = reverse('cloudflavor-detail', args=(cloud_flavor.pk,)) data = {'force': True} resp = self.client.delete(url, data=data) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudFlavor.DoesNotExist, cloud_flavor.refresh_from_db ) @data(CloudFlavorFactory, CloudHostFactory, CloudProjectFactory) def test_delete_cloud_provider_returns_409_if_has_child_objects( self, child_type ): # given cloud_provider = CloudProviderFactory(name="test-cloud-provider") child_type(cloudprovider=cloud_provider) # when url = reverse('cloudprovider-detail', args=(cloud_provider.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_409_CONFLICT) self.assertIn( 'Cloud provider is in use and hence is not deletable.', resp.data['detail'] ) self.assertTrue( CloudProvider.objects.filter(pk=cloud_provider.pk).exists() ) def test_empty_cloud_provider_can_be_deleted(self): # given cloud_provider = CloudProviderFactory(name="test-cloud-provider") # when url = reverse('cloudprovider-detail', args=(cloud_provider.pk,)) resp = self.client.delete(url) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudProvider.DoesNotExist, cloud_provider.refresh_from_db ) @data(CloudFlavorFactory, CloudHostFactory, CloudProjectFactory) def test_non_empty_cloud_provider_can_be_deleted_with_force( self, child_type ): # given cloud_provider = CloudProviderFactory(name="test-cloud-provider") child_type(cloudprovider=cloud_provider) # when url = reverse('cloudprovider-detail', args=(cloud_provider.pk,)) data = {'force': True} resp = self.client.delete(url, data=data) # then self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT) self.assertRaises( CloudProvider.DoesNotExist, cloud_provider.refresh_from_db ) def test_inheritance_of_service_env_on_change_in_a_cloud_project(self): url = reverse('cloudproject-detail', args=(self.cloud_project.id,)) args = { 'service_env': self.service_env[1].id, } response = self.client.patch(url, args, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) host = CloudHost.objects.get(host_id=self.cloud_host.host_id) self.assertEqual(host.service_env, self.service_env[1]) class VirtualServerAPITestCase(RalphAPITestCase): def setUp(self): super().setUp() self.hypervisor = DataCenterAssetFactory() self.cloud_hypervisor = CloudHostFactory() self.cluster = ClusterFactory() self.type = VirtualServerType.objects.create(name='XEN') self.virtual_server = VirtualServerFullFactory( service_env__environment__name='some_env', ) self.virtual_server.parent.service_env.service.uid = 's-12345' self.virtual_server.parent.service_env.service.save() self.virtual_server.service_env.service.business_owners = [self.user1] self.virtual_server.service_env.service.technical_owners = [self.user2] self.virtual_server.service_env.save() self.virtual_server2 = VirtualServerFullFactory() self.ip = IPAddressFactory( ethernet=EthernetFactory(base_object=self.virtual_server2) ) def test_get_virtual_server_list(self): url = reverse('virtualserver-list') with self.assertNumQueries(13): response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data['count'], 2) def test_get_virtual_server_details(self): url = reverse('virtualserver-detail', args=(self.virtual_server.id,)) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['hostname'], self.virtual_server.hostname ) self.assertEqual(len(response.data['ethernet']), 2) self.assertCountEqual( [ eth['ipaddress']['address'] for eth in response.data['ethernet'] if eth['ipaddress'] ], self.virtual_server.ipaddresses.values_list('address', flat=True) ) self.assertEqual(len(response.data['memory']), 2) self.assertEqual(response.data['memory'][0]['speed'], 1600) self.assertEqual(response.data['memory'][0]['size'], 8192) self.assertEqual( response.data['business_owners'][0]['username'], 'user1' ) self.assertEqual( response.data['technical_owners'][0]['username'], 'user2' ) def test_create_virtual_server(self): virtual_server_count = VirtualServer.objects.count() url = reverse('virtualserver-list') data = { 'hostname': 's1234.local', 'type': self.type.id, 'sn': '143ed36a-3e86-457d-9e19-3dcfe4d5ed26', 'hypervisor': self.hypervisor.id, } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( VirtualServer.objects.count(), virtual_server_count + 1 ) virtual_server = VirtualServer.objects.get(pk=response.data['id']) self.assertEqual(virtual_server.hostname, data['hostname']) self.assertEqual(virtual_server.parent.id, self.hypervisor.id) self.assertEqual(virtual_server.sn, data['sn']) def test_create_virtual_server_with_cloud_host_as_parent(self): virtual_server_count = VirtualServer.objects.count() url = reverse('virtualserver-list') data = { 'hostname': 's1234.local', 'type': self.type.id, 'sn': '143ed36a-3e86-457d-9e19-3dcfe4d5ed26', 'hypervisor': self.cloud_hypervisor.id, } response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual( VirtualServer.objects.count(), virtual_server_count + 1 ) virtual_server = VirtualServer.objects.get(pk=response.data['id']) self.assertEqual(virtual_server.hostname, data['hostname']) self.assertEqual(virtual_server.parent.id, self.cloud_hypervisor.id) self.assertEqual(virtual_server.sn, data['sn']) def test_patch_virtual_server(self): url = reverse('virtualserver-detail', args=(self.virtual_server.id,)) data = { 'hostname': 's111111.local' } response = self.client.patch(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.virtual_server.refresh_from_db() self.assertEqual(self.virtual_server.hostname, 's111111.local') def test_filter_by_configuration_path(self): url = reverse('virtualserver-list') + '?configuration_path={}'.format( self.virtual_server.configuration_path.path, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_hostname(self): url = reverse('virtualserver-list') + '?hostname={}'.format( self.virtual_server.hostname, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_ip_address(self): url = reverse('virtualserver-list') + '?ip={}'.format( self.ip.address, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_uid(self): url = reverse('virtualserver-list') + '?service={}'.format( self.virtual_server.service_env.service.uid, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_uid2(self): url = ( reverse('virtualserver-list') + '?service_env__service__uid={}'.format( self.virtual_server.service_env.service.uid, ) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_id(self): url = ( reverse('virtualserver-list') + '?service_env__service__id={}'.format( self.virtual_server.service_env.service.id, ) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_name(self): url = reverse('virtualserver-list') + '?service={}'.format( self.virtual_server.service_env.service.name, ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_service_name2(self): url = ( reverse('virtualserver-list') + '?service_env__service__name={}'.format( self.virtual_server.service_env.service.name, ) ) response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_env_name(self): url = reverse('virtualserver-list') + '?env=some_env' response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) def test_filter_by_hypervisor_service(self): url = reverse('virtualserver-list') + '?hypervisor_service=s-12345' response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual( response.data['count'], 1 ) self.assertEqual( response.data['results'][0]['id'], self.virtual_server.id )
39.775351
86
0.630844
2,787
25,496
5.577323
0.081808
0.11966
0.096179
0.047607
0.781652
0.727548
0.69448
0.673379
0.657553
0.627509
0
0.017017
0.246313
25,496
640
87
39.8375
0.791892
0.003726
0
0.540636
0
0
0.100819
0.009337
0
0
0
0
0.238516
1
0.068905
false
0
0.021201
0
0.09364
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2