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
24783a2e37df647e06f273eb81d5911d00ebd364
396
py
Python
Ar_Script/ar_096_魔法方法_统计属性个数.py
archerckk/PyTest
610dd89df8d70c096f4670ca11ed2f0ca3196ca5
[ "MIT" ]
null
null
null
Ar_Script/ar_096_魔法方法_统计属性个数.py
archerckk/PyTest
610dd89df8d70c096f4670ca11ed2f0ca3196ca5
[ "MIT" ]
1
2020-01-19T01:19:57.000Z
2020-01-19T01:19:57.000Z
Ar_Script/ar_096_魔法方法_统计属性个数.py
archerckk/PyTest
610dd89df8d70c096f4670ca11ed2f0ca3196ca5
[ "MIT" ]
null
null
null
class Counter: def __init__(self): '添加一个初始化couner属性,并且初始值为0' super().__setattr__('counter', 0) def __setattr__(self, name, value): '计算初始值+1' super().__setattr__('counter', self.counter + 1) super().__setattr__(name, value) def __delattr__(self, name): super().__setattr__('counter', self.counter - 1) super().__delattr__(name)
30.461538
56
0.613636
41
396
5.146341
0.365854
0.227488
0.270142
0.218009
0.341232
0.341232
0.341232
0
0
0
0
0.016611
0.239899
396
13
57
30.461538
0.684385
0.078283
0
0
0
0
0.128463
0.057935
0
0
0
0
0
1
0.272727
false
0
0
0
0.363636
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
4
247e4733ede0e5e7addb8ec3d84e83ee6ffd8fb0
1,228
py
Python
utilities/bounce.py
leviathanindustries/noddy
d6c5b130b558ecdcd50e9d5b59e66e5d25e693a2
[ "MIT" ]
2
2019-07-30T14:16:45.000Z
2020-09-16T10:44:14.000Z
utilities/bounce.py
leviathanindustries/noddy
d6c5b130b558ecdcd50e9d5b59e66e5d25e693a2
[ "MIT" ]
null
null
null
utilities/bounce.py
leviathanindustries/noddy
d6c5b130b558ecdcd50e9d5b59e66e5d25e693a2
[ "MIT" ]
null
null
null
import json, requests, os # available on the main machine, set up an nginx pass to the script # check status endpoint - if all fine, do nothing # check if local machine has any running instances of the meteor app # if it does, what screen names are they running in? # (start instances in named screens to make this more useful) # if they are running, bounce them in the normal way # if local ones are not running, go into their screens and rerun the last command # (which should be the one that started them - check it is, and the settings it had) # check that after bounce everything is running as normal # also check status to see if that caused cluster to come back up (if it was down) # if cluster did not come back up, get the list of IPs of the cluster machines (in the settings files) # (could be dev or live list or both) # ssh to those machines # do the same check on their running processes # if not running, get into their screens and redo the last command (check it is the command to bring them up) # once all report that they have done that, re-check status # if status still not good, try a bounce again # if status still not good, give up and log the problem # email whoever needs emailed about this
36.117647
109
0.753257
222
1,228
4.166667
0.518018
0.035676
0.034595
0.041081
0.043243
0
0
0
0
0
0
0
0.207655
1,228
33
110
37.212121
0.950668
0.936482
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
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
1
0
1
0
0
4
24a5e1f2a81ce68aadb58c41bdc1f6e01173d134
300
py
Python
src/cmp/cool_lang/ast/block_node.py
codestrange/cool-compiler-2020
30508965d75a1a1d1362d0b51bef8da3978fd0c2
[ "MIT" ]
3
2020-01-14T04:47:32.000Z
2020-09-10T17:57:20.000Z
src/cmp/cool_lang/ast/block_node.py
codestrange/cool-compiler-2020
30508965d75a1a1d1362d0b51bef8da3978fd0c2
[ "MIT" ]
5
2020-01-14T06:06:35.000Z
2020-02-19T01:01:33.000Z
src/cmp/cool_lang/ast/block_node.py
codestrange/cool-compiler-2020
30508965d75a1a1d1362d0b51bef8da3978fd0c2
[ "MIT" ]
3
2020-01-14T04:58:24.000Z
2020-01-14T16:23:41.000Z
from typing import List from .expresion_node import ExpressionNode class BlockNode(ExpressionNode): def __init__(self, expressions: List[ExpressionNode], line: int, column: int): super(BlockNode, self).__init__(line, column) self.expressions: List[ExpressionNode] = expressions
33.333333
82
0.753333
33
300
6.575758
0.515152
0.138249
0.175115
0.304147
0
0
0
0
0
0
0
0
0.156667
300
8
83
37.5
0.857708
0
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
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
24b1e8c66fd9b9e43b76ae93dab8160071dfb488
89
py
Python
vessels/apps.py
ksamuel/smit
a7cf54f2953678804f69182951bbe98214d5c9f6
[ "MIT" ]
null
null
null
vessels/apps.py
ksamuel/smit
a7cf54f2953678804f69182951bbe98214d5c9f6
[ "MIT" ]
null
null
null
vessels/apps.py
ksamuel/smit
a7cf54f2953678804f69182951bbe98214d5c9f6
[ "MIT" ]
null
null
null
from django.apps import AppConfig class VesselsConfig(AppConfig): name = 'vessels'
14.833333
33
0.752809
10
89
6.7
0.9
0
0
0
0
0
0
0
0
0
0
0
0.168539
89
5
34
17.8
0.905405
0
0
0
0
0
0.078652
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
24d8d9e23d71faf27c17dacc8af62e0cc1f22776
122
py
Python
setup.py
bergercookie/colcon-cargo
bd2ad8cf2928205a834c537030bb05caf6d6d986
[ "Apache-2.0" ]
20
2019-03-06T01:44:32.000Z
2022-03-24T06:20:32.000Z
setup.py
bergercookie/colcon-cargo
bd2ad8cf2928205a834c537030bb05caf6d6d986
[ "Apache-2.0" ]
15
2018-09-12T01:26:46.000Z
2022-03-30T11:12:02.000Z
setup.py
bergercookie/colcon-cargo
bd2ad8cf2928205a834c537030bb05caf6d6d986
[ "Apache-2.0" ]
13
2018-09-01T15:59:43.000Z
2022-03-26T18:54:04.000Z
# Copyright 2018 Easymov Robotics # Licensed under the Apache License, Version 2.0 from setuptools import setup setup()
17.428571
48
0.786885
17
122
5.647059
0.941176
0
0
0
0
0
0
0
0
0
0
0.058824
0.163934
122
6
49
20.333333
0.882353
0.639344
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
70496df660a2fd1a6d5cff63ceb84a73d961d7fa
188
py
Python
kickstart_template.py
yonghuatang/python
6d53bf2f1e75ac03b07eb56ff83e26d8b5155bb1
[ "MIT" ]
null
null
null
kickstart_template.py
yonghuatang/python
6d53bf2f1e75ac03b07eb56ff83e26d8b5155bb1
[ "MIT" ]
null
null
null
kickstart_template.py
yonghuatang/python
6d53bf2f1e75ac03b07eb56ff83e26d8b5155bb1
[ "MIT" ]
null
null
null
t = int(input()) for tc in range(1, t+1): # for multiple input in single line # x, y = map(int, input().split()) # arr = list(map(int, input().split())) print(f"Case #{tc}: {ans}")
18.8
39
0.574468
33
188
3.272727
0.636364
0.222222
0.203704
0.296296
0
0
0
0
0
0
0
0.013158
0.191489
188
9
40
20.888889
0.697368
0.553191
0
0
0
0
0.2125
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
70634b91cd5df53417182e8b144c61257fe08153
207
py
Python
gtam_tools/__init__.py
sap-toronto/gtam-tools
9f36e0afdc25e84862804e2b633f4996c2d97d02
[ "MIT" ]
null
null
null
gtam_tools/__init__.py
sap-toronto/gtam-tools
9f36e0afdc25e84862804e2b633f4996c2d97d02
[ "MIT" ]
null
null
null
gtam_tools/__init__.py
sap-toronto/gtam-tools
9f36e0afdc25e84862804e2b633f4996c2d97d02
[ "MIT" ]
null
null
null
from .microsim_data import MicrosimData from ._version import get_versions __version__ = get_versions()['version'] del get_versions from balsa.logging import init_root init_root('gtam_tools') del init_root
23
39
0.830918
30
207
5.3
0.5
0.207547
0.226415
0
0
0
0
0
0
0
0
0
0.101449
207
8
40
25.875
0.854839
0
0
0
0
0
0.082126
0
0
0
0
0
0
1
0
false
0
0.428571
0
0.428571
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
7076a8d4359e393b6133a1ed083fc8f6174286b0
204
py
Python
api/config/base.py
phamtanvinh/victor-backend
edb52903a9db6b549fc412ff11570bc54deedba2
[ "MIT" ]
null
null
null
api/config/base.py
phamtanvinh/victor-backend
edb52903a9db6b549fc412ff11570bc54deedba2
[ "MIT" ]
1
2019-09-15T17:31:01.000Z
2019-09-15T17:31:01.000Z
api/config/base.py
phamtanvinh/victor-backend
edb52903a9db6b549fc412ff11570bc54deedba2
[ "MIT" ]
1
2019-10-28T10:23:14.000Z
2019-10-28T10:23:14.000Z
import os from . import POSTGRES_DATABASE_URI class Config(object): DEBUG = False TESTING = False SQLALCHEMY_DATABASE_URI = POSTGRES_DATABASE_URI SQLALCHEMY_TRACK_MODIFICATIONS = False
18.545455
51
0.769608
24
204
6.208333
0.625
0.221477
0.255034
0
0
0
0
0
0
0
0
0
0.191176
204
10
52
20.4
0.90303
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.285714
0
1
0
1
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
1
0
0
4
70a6fb14e5fe125662f0d48981cc54e7b17cdb96
131
py
Python
jumpgate/compute/drivers/sl/extra_specs.py
Neetuj/jumpgate
509c1d43a5f4b91c7f3ad5c0cd34abf61bb0a3ee
[ "MIT" ]
null
null
null
jumpgate/compute/drivers/sl/extra_specs.py
Neetuj/jumpgate
509c1d43a5f4b91c7f3ad5c0cd34abf61bb0a3ee
[ "MIT" ]
null
null
null
jumpgate/compute/drivers/sl/extra_specs.py
Neetuj/jumpgate
509c1d43a5f4b91c7f3ad5c0cd34abf61bb0a3ee
[ "MIT" ]
null
null
null
class ExtraSpecsFlavorV2(object): def on_get(self, req, resp, tenant_id, flavor_id): resp.body = {'extra_specs': ''}
21.833333
54
0.656489
17
131
4.823529
0.882353
0
0
0
0
0
0
0
0
0
0
0.009524
0.198473
131
5
55
26.2
0.771429
0
0
0
0
0
0.085271
0
0
0
0
0
0
1
0.333333
false
0
0
0
0.666667
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
4
561ce5bb626219a9fb08565750f3ac3909b1e89a
61
py
Python
api/chalicelib/singletons.py
joseph-behrens/vaccine-availability-notifications
aa8c0be201899c4b789d6599af83959a01c92ad9
[ "MIT" ]
9
2021-03-31T16:10:19.000Z
2022-01-20T22:31:30.000Z
api/chalicelib/singletons.py
joseph-behrens/vaccine-availability-notifications
aa8c0be201899c4b789d6599af83959a01c92ad9
[ "MIT" ]
6
2021-04-17T02:20:46.000Z
2021-05-11T03:19:55.000Z
api/chalicelib/singletons.py
joseph-behrens/vaccine-availability-notifications
aa8c0be201899c4b789d6599af83959a01c92ad9
[ "MIT" ]
1
2021-04-18T00:23:12.000Z
2021-04-18T00:23:12.000Z
from typing import Any, Optional app: Optional[Any] = None
12.2
32
0.737705
9
61
5
0.777778
0
0
0
0
0
0
0
0
0
0
0
0.180328
61
4
33
15.25
0.9
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
565b8a9c386a5dc584dc3bfd9995a392837e5d69
271
py
Python
packages/jsii-pacmak/test/expected.jsii-calc/python/src/jsii_calc/_jsii/__init__.py
ddinu/jsii
7b3b059ff4cf1e7f02ddb4234ec8185967df207d
[ "Apache-2.0" ]
null
null
null
packages/jsii-pacmak/test/expected.jsii-calc/python/src/jsii_calc/_jsii/__init__.py
ddinu/jsii
7b3b059ff4cf1e7f02ddb4234ec8185967df207d
[ "Apache-2.0" ]
1
2019-10-01T06:22:28.000Z
2019-10-01T06:22:28.000Z
packages/jsii-pacmak/test/expected.jsii-calc/python/src/jsii_calc/_jsii/__init__.py
ddinu/jsii
7b3b059ff4cf1e7f02ddb4234ec8185967df207d
[ "Apache-2.0" ]
null
null
null
import abc import datetime import enum import typing import jsii import jsii.compat import publication from jsii.python import classproperty import scope.jsii_calc_base import scope.jsii_calc_base_of_base import scope.jsii_calc_lib __all__ = [] publication.publish()
15.055556
37
0.841328
40
271
5.4
0.45
0.152778
0.208333
0.263889
0.319444
0
0
0
0
0
0
0
0.118081
271
17
38
15.941176
0.903766
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.846154
0
0.846154
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
1
0
1
0
0
4
567eedc8919d8ab7720d60174383fcac92b506f8
13,115
py
Python
code/libs/algos_vec.py
mfzimmer/Neograd
ade7583fff00a56ad7768c114e0a2945faa4babc
[ "MIT" ]
10
2020-10-16T13:42:55.000Z
2021-06-23T09:30:40.000Z
code/libs/algos_vec.py
mfzimmer/Neograd
ade7583fff00a56ad7768c114e0a2945faa4babc
[ "MIT" ]
null
null
null
code/libs/algos_vec.py
mfzimmer/Neograd
ade7583fff00a56ad7768c114e0a2945faa4babc
[ "MIT" ]
null
null
null
import numpy as np import costgrad_vec as cg import common as co import params as pm import common_vec as cv # ==================================================================== def get_dp_momentum( beta, grad, v, i, alpha ): v = beta * v + (1-beta) * grad v_est = v / (1 - np.power(beta, i+1)) dp = -alpha * v_est return(dp,v) # ==================================================================== def get_dp_Nesterov( name, p, beta, grad, v, alpha ): v = beta * v + alpha * cg.get_grad(name, p -beta*v) dp = -v return(dp,v) # ==================================================================== def get_dp_RMS( eps, beta2, grad, v2, i, alpha ): v2 = beta2 * v2 + (1-beta2) * grad*grad #element-wise product v2_est = v2 / (1 - np.power(beta2, i+1)) temp = grad / np.sqrt(v2_est + eps) dp = -alpha * temp return(dp,v2) # ==================================================================== def get_dp_Adam( eps, beta, beta2, grad, v, v2, i, alpha ): v = beta * v + (1-beta) * grad v2 = beta2 * v2 + (1-beta2) * grad*grad #element-wise product v_est = v / (1 - np.power(beta, i+1)) v2_est = v2 / (1 - np.power(beta2, i+1)) temp = v_est / np.sqrt(v2_est + eps) dp = -alpha * temp return(dp,v,v2) # ==================================================================== # This allows the use of any of these optimization algos according to parameter "type_opt" def get_dp_choice(type_opt, grad, p_old, v, v2, i, alpha): eps = pm.g_eps_adam beta = pm.g_beta beta2 = pm.g_beta2 if type_opt == "dp_GD_basic": dp = -alpha * grad elif type_opt == "dp_GD_momentum": dp,v = get_dp_momentum( beta, grad, v, i, alpha ) elif type_opt == "dp_GD_Nesterov": dp,v = get_dp_Nesterov( name, p_old, beta, grad, v, alpha ) elif type_opt == "dp_RMSProp": dp,v2 = get_dp_RMS( eps, beta2, grad, v2, i, alpha ) elif type_opt == "dp_Adam": dp,v,v2 = get_dp_Adam( eps, beta, beta2, grad, v, v2, i, alpha ) else: print("ERROR in get_dp_choice. type_opt=", type_opt) return(None,None) return( dp, v, v2 ) # ==================================================================== # This is the algorithm to run gradient descent (GD), whether it be plain GD, GD with momentum, Adam, etc def do_GDFamily(name, alpha, num, p_old, p_target, type_opt, rho_targ, b_print, i_manual, i_factor, rho_type): v = np.zeros(p_old.shape, dtype=np.float128) v2 = np.zeros(p_old.shape, dtype=np.float128) # init --------------------------- p_ref = p_old.copy() #a copy of initial p, to compute sumd_y cost_old = cg.get_cost(name, p_old) print("cost_old = ", cost_old) dp_old = None dist = cv.get_dist(p_old, p_target) d_res = co.init_results( ["cost","rho","dotp","sumd_x","sumd_y","p","rho_error","dist"] ) co.update_results( d_res, {"p":p_old.copy(), "cost":cost_old, "sumd_x":0.0, "sumd_y":0.0, "dist":dist} ) sumd_x = 0 for i in range(num): # Extra booast at i==i_manual ---------------- if i == i_manual: alpha *= i_factor # grad ------------------------- grad = cg.get_grad(name, p_old) # optimize --------------------- dp,v,v2 = get_dp_choice(type_opt, grad, p_old, v, v2, i, alpha) # cost ------------------------- p_new = cv.get_p_new(p_old, dp) cost_new = cg.get_cost(name, p_new) # diagnostics ------------------ est_diff = cv.get_est_diff(grad, dp) rho = co.get_rho(cost_old, cost_new, est_diff, rho_type) rho_error = co.get_rho_error( rho, rho_targ ) dotp = cv.get_dotp_2(dp_old, dp) sumd_x += cv.get_sumd_x(dp) #a running total sumd_y = cv.get_sumd_y(p_ref, p_new) #a point measurement # updates ---------------------- p_old = p_new.copy() cost_old = cost_new dp_old = dp.copy() dist = cv.get_dist(p_old, p_target) co.update_results(d_res, {"rho":rho, "p":p_old.copy(), "cost":cost_old, "dotp":dotp, "sumd_x":sumd_x, "sumd_y":sumd_y, "rho_error":rho_error, "dist":dist} ) # printout --------------------- if(b_print): co.do_printout(d_res, i, nfreq=1) return(d_res) # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # ==================================================================== # The list of input arguments can be cleaned up. Eg, v and v2 are no longer needed, and type_opt is fixed, # so that can be dropped too. Also, even the call to "get_dp_choice" can be replaced by Basic GD version # (although this isn't a big deal). Also, pass in value for n_rep. Maybe also for rhomin & rhomax, # in case I want to create a conditional based on those. def get_starting_alpha(name, p_old, type_opt, v, v2, rho_targ, cost_old, rho_type, alpha = 0.000001): cost_old = cg.get_cost(name, p_old) grad = cg.get_grad(name, p_old) # Turn these two params into input parameters n_rep = 20 alpha_last = None rho_last = None for j in range(n_rep): # optimize --------------------- type_opt = "dp_GD_basic" i = 0 dp,v_temp,v2_temp = get_dp_choice(type_opt, grad, p_old, v, v2, i, alpha) # cost ------------------------- p_new = cv.get_p_new(p_old, dp) cost_new = cg.get_cost(name, p_new) est_diff = cv.get_est_diff(grad, dp) # new stuff -------------------- rho = co.get_rho(cost_old, cost_new, est_diff, rho_type) rerr = (rho - rho_targ) / rho_targ print(j, ": alpha,rho,rerr = ", alpha,rho,rerr) if rho > 0.0: if rho_last is None: rho_last = rho alpha_last = alpha elif rho <= rho_targ and rho > rho_last: rho_last = rho alpha_last = alpha if rho > rho_targ: return(alpha_last) #it's possible this is None if rho == 0.0: #Do this because sometimes it gets rounded down to 0.0 alpha *= 2 else: cost_est = cost_old + est_diff A = (cost_new - cost_est)/(alpha*alpha) B = (cost_est - cost_old)/alpha rho_prime = co.get_rho_prime( rho, rho_targ ) alpha = co.get_alpha_prime_0( A, B, rho_prime, rho_type ) return(alpha) # ==================================================================== def do_Neograd(name, alpha, num, p_old, p_target, type_opt, rho_targ, b_print, rho_type): # These variables are used as needed, according to value of 'type_opt' v = np.zeros(p_old.shape, dtype=np.float128) v2 = np.zeros(p_old.shape, dtype=np.float128) # init --------------------------- p_ref = p_old.copy() #a copy of initial p, to compute sumd_y cost_old = cg.get_cost(name, p_old) # print("cost_old = ", cost_old) dp_old = None dist = cv.get_dist(p_old, p_target) sumd_x = 0 rho_prime = rho_targ # Get a starting alpha if unspecified ----------------- if alpha is None: alpha = get_starting_alpha(name, p_old, type_opt, v, v2, rho_targ, cost_old, rho_type) print("starting alpha = ", alpha) alpha_hat = alpha d_res = co.init_results( ["cost","rho","dotp","sumd_x","sumd_y","p","alpha","rho_error","dist","step"] ) co.update_results( d_res, {"p":p_old.copy(), "cost":cost_old, "sumd_x":0.0, "sumd_y":0.0, "alpha":alpha, "dist":dist} ) for i in range(num): print(i, " ============================================") # grad ------------------------- grad = cg.get_grad(name, p_old) # optimize --------------------- dp,v,v2 = get_dp_choice(type_opt, grad, p_old, v, v2, i, alpha) # cost ------------------------- p_new = cv.get_p_new(p_old, dp) cost_new = cg.get_cost(name, p_new) est_diff = cv.get_est_diff(grad, dp) # diagnostics ------------------ rho = co.get_rho(cost_old, cost_new, est_diff, rho_type) rho_error = co.get_rho_error( rho, rho_targ ) dotp = cv.get_dotp_2(dp_old, dp) sumd_x += cv.get_sumd_x(dp) #a running total sumd_y = cv.get_sumd_y(p_ref, p_new) #a point measurement # new stuff -------------------- cost_est = cost_old + est_diff A = (cost_new - cost_est)/(alpha*alpha) B = (cost_est - cost_old)/alpha # print(" A = ", A) # print(" B = ", B) # updates ---------------------- dist = cv.get_dist(p_old, p_target) p_old = p_new.copy() cost_old = cost_new dp_old = dp.copy() step = cv.get_step_size(dp_old) alpha_hat = alpha rho_prime = co.get_rho_prime( rho, rho_targ ) alpha = co.get_alpha_prime_0( A, B, rho_prime, rho_type ) # alpha = co.get_alpha_prime_0( A, B, rho_targ, rho_type ) co.update_results(d_res, {"rho":rho, "p":p_old.copy(), "cost":cost_old, "dotp":dotp, "sumd_x":sumd_x, "sumd_y":sumd_y, "alpha":alpha_hat, "rho_error":rho_error, "dist":dist, "step":step} ) # printout --------------------- print("alpha,rho = ", alpha, rho, " ---------------" ) if(b_print): co.do_printout(d_res, i, nfreq=1) return(d_res) # ==================================================================== def do_Neograd_dbl(name, alpha, num, p_old, p_target, type_opt, rho_targ, b_print, rho_type, n_rep=2): # These variables are used as needed, according to value of 'type_opt' v = np.zeros(p_old.shape, dtype=np.float128) v2 = np.zeros(p_old.shape, dtype=np.float128) # init --------------------------- p_ref = p_old.copy() #a copy of initial p, to compute sumd_y cost_old = cg.get_cost(name, p_old) # print("cost_old = ", cost_old) dp_old = None dist = cv.get_dist(p_old, p_target) sumd_x = 0 rho_prime = rho_targ # Get a starting alpha if unspecified ----------------- if alpha is None: alpha = get_starting_alpha(name, p_old, type_opt, v, v2, rho_targ, cost_old, rho_type) print("starting alpha = ", alpha) alpha_hat = alpha d_res = co.init_results( ["cost","rho","dotp","sumd_x","sumd_y","p","alpha","rho_error","dist"] ) co.update_results( d_res, {"p":p_old.copy(), "cost":cost_old, "sumd_x":0.0, "sumd_y":0.0, "alpha":alpha, "dist":dist} ) for i in range(num): print(i, " ------------------------------") # grad ------------------------- grad = cg.get_grad(name, p_old) for j in range(n_rep): # print(j, " - - - - - - - - - - - - ") # optimize --------------------- dp,v_temp,v2_temp = get_dp_choice(type_opt, grad, p_old, v, v2, i, alpha) # cost ------------------------- p_new = cv.get_p_new(p_old, dp) cost_new = cg.get_cost(name, p_new) est_diff = cv.get_est_diff(grad, dp) # new stuff -------------------- rho = co.get_rho(cost_old, cost_new, est_diff, rho_type) print(" j,rho = ", j, rho) cost_est = cost_old + est_diff A = (cost_new - cost_est)/(alpha*alpha) B = (cost_est - cost_old)/alpha alpha_hat = alpha rho_prime = co.get_rho_prime( rho, rho_targ ) alpha = co.get_alpha_prime_0( A, B, rho_prime, rho_type ) # alpha = co.get_alpha_prime_0( A, B, rho_targ, rho_type ) v = v_temp.copy() #check for memory leaks with v,v2 and temps v2 = v2_temp.copy() # diagnostics ------------------ # rho_error = co.get_rho_error( rho, rho_prime ) rho_error = co.get_rho_error( rho, rho_targ ) dotp = cv.get_dotp_2(dp_old, dp) sumd_x += cv.get_sumd_x(dp) #a running total sumd_y = cv.get_sumd_y(p_ref, p_new) #a point measurement dist = cv.get_dist(p_old, p_target) # updates ---------------------- p_old = p_new.copy() cost_old = cost_new dp_old = dp.copy() # print("i,rho = ", i, rho) co.update_results(d_res, {"rho":rho, "p":p_old.copy(), "cost":cost_old, "dotp":dotp, "sumd_x":sumd_x, "sumd_y":sumd_y, "alpha":alpha_hat, "rho_error":rho_error, "dist":dist} ) # printout --------------------- if(b_print): co.do_printout(d_res, i, nfreq=1) return(d_res)
39.384384
196
0.498361
1,840
13,115
3.288587
0.106522
0.03173
0.015865
0.016361
0.775409
0.747149
0.725169
0.721699
0.683028
0.667493
0
0.013001
0.272741
13,115
332
197
39.503012
0.621409
0.254594
0
0.665
0
0
0.062171
0.00763
0
0
0
0
0
1
0.045
false
0
0.025
0
0.07
0.09
0
0
0
null
0
0
0
0
1
1
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
3b385665b420942e0e572d50604f509b29d2b818
583
py
Python
condiment/tests/test_bounds.py
WeilerWebServices/Kivy
54e3438156eb0c853790fd3cecc593f09123f892
[ "MIT" ]
3
2015-01-02T16:18:28.000Z
2018-12-12T16:16:16.000Z
condiment/tests/test_bounds.py
WeilerWebServices/Kivy
54e3438156eb0c853790fd3cecc593f09123f892
[ "MIT" ]
2
2018-03-16T22:01:12.000Z
2020-01-13T10:33:22.000Z
condiment/tests/test_bounds.py
WeilerWebServices/Kivy
54e3438156eb0c853790fd3cecc593f09123f892
[ "MIT" ]
2
2015-04-26T15:31:40.000Z
2017-09-12T12:36:14.000Z
#exclude import condiment; condiment.install() #endexclude def hello(): if WITH_TIMEBOMB: print 'timebomb feature is activated' if WITH_INAPP_PURCHASE: print 'this would be activated only if timebomb + inapp purchase' if WITH_TIMEBOMB and not WITH_INAPP_PURCHASE: print 'only timebomb has been activated, no inapp_purchase' if not WITH_TIMEBOMB and WITH_INAPP_PURCHASE: print 'only inapp_purchase has been activated, no timebomb' if WITH_TIMEBOMB and WITH_INAPP_PURCHASE: print 'both features have been activated'
36.4375
77
0.727273
77
583
5.324675
0.363636
0.221951
0.165854
0.214634
0.253659
0.180488
0.180488
0
0
0
0
0
0.226415
583
15
78
38.866667
0.909091
0.02916
0
0
0
0
0.391844
0
0
0
0
0
0
0
null
null
0
0.083333
null
null
0.416667
0
0
0
null
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
1
0
4
3b4c882c251b3babe4b819fa5e7f0ff43b061f11
372
py
Python
code/src/evaluate_rules/fidelity.py
ZohrehShams/IntegrativeRuleExtractionMethodology
fd7b569d11de540ffe94e0cc588e78305e45689e
[ "MIT" ]
1
2022-03-20T12:33:16.000Z
2022-03-20T12:33:16.000Z
code/src/evaluate_rules/fidelity.py
ZohrehShams/IntegrativeRuleExtractionMethodology
fd7b569d11de540ffe94e0cc588e78305e45689e
[ "MIT" ]
null
null
null
code/src/evaluate_rules/fidelity.py
ZohrehShams/IntegrativeRuleExtractionMethodology
fd7b569d11de540ffe94e0cc588e78305e45689e
[ "MIT" ]
1
2022-03-20T12:33:58.000Z
2022-03-20T12:33:58.000Z
""" Evaluate fidelity of rules generated i.e. how well do they mimic the performance of the Neural Network """ import pandas as pd def fidelity(predicted_labels, network_labels): assert (len(predicted_labels) == len(network_labels)), "Error: number of labels inconsistent !" fid = sum(predicted_labels == network_labels) / len(predicted_labels) return fid
28.615385
102
0.747312
51
372
5.313725
0.607843
0.221402
0.162362
0.206642
0
0
0
0
0
0
0
0
0.163978
372
12
103
31
0.871383
0.274194
0
0
1
0
0.145038
0
0
0
0
0
0.2
1
0.2
false
0
0.2
0
0.6
0
0
0
0
null
1
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
1
0
0
4
3b825c4d702c8c5c43b6c4a4ac550d1ec446e9be
10,768
py
Python
bayespy/inference/vmp/nodes/tests/test_gate.py
dungvtdev/upsbayescpm
f6ee877c689046d3c57a2ac06742cfe4a0b6550e
[ "MIT" ]
5
2015-04-16T11:50:18.000Z
2020-11-04T20:18:12.000Z
bayespy/inference/vmp/nodes/tests/test_gate.py
dungvtdev/upsbayescpm
f6ee877c689046d3c57a2ac06742cfe4a0b6550e
[ "MIT" ]
null
null
null
bayespy/inference/vmp/nodes/tests/test_gate.py
dungvtdev/upsbayescpm
f6ee877c689046d3c57a2ac06742cfe4a0b6550e
[ "MIT" ]
3
2015-04-16T11:50:19.000Z
2021-12-14T08:39:24.000Z
################################################################################ # Copyright (C) 2014 Jaakko Luttinen # # This file is licensed under the MIT License. ################################################################################ """ Unit tests for `gate` module. """ import numpy as np from bayespy.nodes import (Gate, GaussianARD, Gamma, Categorical, Bernoulli, Multinomial) from bayespy.inference.vmp.nodes.gaussian import GaussianMoments from bayespy.utils import random from bayespy.utils import linalg from bayespy.utils.misc import TestCase class TestGate(TestCase): """ Unit tests for Gate node. """ def test_init(self): """ Test the creation of Gate node """ # Gating scalar node Z = Categorical(np.ones(3)/3) X = GaussianARD(0, 1, shape=(), plates=(3,)) Y = Gate(Z, X) self.assertEqual(Y.plates, ()) self.assertEqual(Y.dims, ( (), () )) # Gating non-scalar node Z = Categorical(np.ones(3)/3) X = GaussianARD(0, 1, shape=(2,), plates=(3,)) Y = Gate(Z, X) self.assertEqual(Y.plates, ()) self.assertEqual(Y.dims, ( (2,), (2,2) )) # Plates from Z Z = Categorical(np.ones(3)/3, plates=(4,)) X = GaussianARD(0, 1, shape=(2,), plates=(3,)) Y = Gate(Z, X) self.assertEqual(Y.plates, (4,)) self.assertEqual(Y.dims, ( (2,), (2,2) )) # Plates from X Z = Categorical(np.ones(3)/3) X = GaussianARD(0, 1, shape=(2,), plates=(4,3)) Y = Gate(Z, X) self.assertEqual(Y.plates, (4,)) self.assertEqual(Y.dims, ( (2,), (2,2) )) # Plates from Z and X Z = Categorical(np.ones(3)/3, plates=(5,)) X = GaussianARD(0, 1, shape=(2,), plates=(4,1,3)) Y = Gate(Z, X) self.assertEqual(Y.plates, (4,5)) self.assertEqual(Y.dims, ( (2,), (2,2) )) # Gating non-default plate Z = Categorical(np.ones(3)/3) X = GaussianARD(0, 1, shape=(), plates=(3,4)) Y = Gate(Z, X, gated_plate=-2) self.assertEqual(Y.plates, (4,)) self.assertEqual(Y.dims, ( (), () )) # Fixed gating Z = 2 X = GaussianARD(0, 1, shape=(2,), plates=(3,)) Y = Gate(Z, X) self.assertEqual(Y.plates, ()) self.assertEqual(Y.dims, ( (2,), (2,2) )) # Fixed X Z = Categorical(np.ones(3)/3) X = [1, 2, 3] Y = Gate(Z, X, moments=GaussianMoments(())) self.assertEqual(Y.plates, ()) self.assertEqual(Y.dims, ( (), () )) # Do not accept non-negative cluster plates Z = Categorical(np.ones(3)/3) X = GaussianARD(0, 1, plates=(3,)) self.assertRaises(ValueError, Gate, Z, X, gated_plate=0) # None of the parents have the cluster plate axis Z = Categorical(np.ones(3)/3) X = GaussianARD(0, 1) self.assertRaises(ValueError, Gate, Z, X) # Inconsistent cluster plate Z = Categorical(np.ones(3)/3) X = GaussianARD(0, 1, plates=(2,)) self.assertRaises(ValueError, Gate, Z, X) pass def test_message_to_child(self): """ Test the message to child of Gate node. """ # Gating scalar node Z = 2 X = GaussianARD([1,2,3], 1, shape=(), plates=(3,)) Y = Gate(Z, X) u = Y._message_to_child() self.assertEqual(len(u), 2) self.assertAllClose(u[0], 3) self.assertAllClose(u[1], 3**2+1) # Fixed X Z = 2 X = [1, 2, 3] Y = Gate(Z, X, moments=GaussianMoments(())) u = Y._message_to_child() self.assertEqual(len(u), 2) self.assertAllClose(u[0], 3) self.assertAllClose(u[1], 3**2) # Uncertain gating Z = Categorical([0.2,0.3,0.5]) X = GaussianARD([1,2,3], 1, shape=(), plates=(3,)) Y = Gate(Z, X) u = Y._message_to_child() self.assertAllClose(u[0], 0.2*1 + 0.3*2 + 0.5*3) self.assertAllClose(u[1], 0.2*2 + 0.3*5 + 0.5*10) # Plates in Z Z = [2, 0] X = GaussianARD([1,2,3], 1, shape=(), plates=(3,)) Y = Gate(Z, X) u = Y._message_to_child() self.assertAllClose(u[0], [3, 1]) self.assertAllClose(u[1], [10, 2]) # Plates in X Z = 2 X = GaussianARD([1,2,3], 1, shape=(), plates=(4,3,)) Y = Gate(Z, X) u = Y._message_to_child() self.assertAllClose(np.ones(4)*u[0], np.ones(4)*3) self.assertAllClose(np.ones(4)*u[1], np.ones(4)*10) # Gating non-default plate Z = 2 X = GaussianARD([[1],[2],[3]], 1, shape=(), plates=(3,4)) Y = Gate(Z, X, gated_plate=-2) u = Y._message_to_child() self.assertAllClose(np.ones(4)*u[0], np.ones(4)*3) self.assertAllClose(np.ones(4)*u[1], np.ones(4)*10) # Gating non-scalar node Z = 2 X = GaussianARD([1*np.ones(4), 2*np.ones(4), 3*np.ones(4)], 1, shape=(4,), plates=(3,)) Y = Gate(Z, X) u = Y._message_to_child() self.assertAllClose(u[0], 3*np.ones(4)) self.assertAllClose(u[1], 9*np.ones((4,4)) + 1*np.identity(4)) # Broadcasting the moments on the cluster axis Z = 2 X = GaussianARD(1, 1, shape=(), plates=(3,)) Y = Gate(Z, X) u = Y._message_to_child() self.assertEqual(len(u), 2) self.assertAllClose(u[0], 1) self.assertAllClose(u[1], 1**2+1) pass def test_message_to_parent(self): """ Test the message to parents of Gate node. """ # Unobserved and broadcasting Z = 2 X = GaussianARD(0, 1, shape=(), plates=(3,)) F = Gate(Z, X) Y = GaussianARD(F, 1) m = F._message_to_parent(0) self.assertEqual(len(m), 1) self.assertAllClose(m[0], 0*np.ones(3)) m = F._message_to_parent(1) self.assertEqual(len(m), 2) self.assertAllClose(m[0]*np.ones(3), [0, 0, 0]) self.assertAllClose(m[1]*np.ones(3), [0, 0, 0]) # Gating scalar node Z = 2 X = GaussianARD([1,2,3], 1, shape=(), plates=(3,)) F = Gate(Z, X) Y = GaussianARD(F, 1) Y.observe(10) m = F._message_to_parent(0) self.assertAllClose(m[0], [10*1-0.5*2, 10*2-0.5*5, 10*3-0.5*10]) m = F._message_to_parent(1) self.assertAllClose(m[0], [0, 0, 10]) self.assertAllClose(m[1], [0, 0, -0.5]) # Fixed X Z = 2 X = [1,2,3] F = Gate(Z, X, moments=GaussianMoments(())) Y = GaussianARD(F, 1) Y.observe(10) m = F._message_to_parent(0) self.assertAllClose(m[0], [10*1-0.5*1, 10*2-0.5*4, 10*3-0.5*9]) m = F._message_to_parent(1) self.assertAllClose(m[0], [0, 0, 10]) self.assertAllClose(m[1], [0, 0, -0.5]) # Uncertain gating Z = Categorical([0.2, 0.3, 0.5]) X = GaussianARD([1,2,3], 1, shape=(), plates=(3,)) F = Gate(Z, X) Y = GaussianARD(F, 1) Y.observe(10) m = F._message_to_parent(0) self.assertAllClose(m[0], [10*1-0.5*2, 10*2-0.5*5, 10*3-0.5*10]) m = F._message_to_parent(1) self.assertAllClose(m[0], [0.2*10, 0.3*10, 0.5*10]) self.assertAllClose(m[1], [-0.5*0.2, -0.5*0.3, -0.5*0.5]) # Plates in Z Z = [2, 0] X = GaussianARD([1,2,3], 1, shape=(), plates=(3,)) F = Gate(Z, X) Y = GaussianARD(F, 1) Y.observe([10, 20]) m = F._message_to_parent(0) self.assertAllClose(m[0], [[10*1-0.5*2, 10*2-0.5*5, 10*3-0.5*10], [20*1-0.5*2, 20*2-0.5*5, 20*3-0.5*10]]) m = F._message_to_parent(1) self.assertAllClose(m[0], [20, 0, 10]) self.assertAllClose(m[1], [-0.5, 0, -0.5]) # Plates in X Z = 2 X = GaussianARD([[1,2,3], [4,5,6]], 1, shape=(), plates=(2,3,)) F = Gate(Z, X) Y = GaussianARD(F, 1) Y.observe([10, 20]) m = F._message_to_parent(0) self.assertAllClose(m[0], [10*1-0.5*2 + 20*4-0.5*17, 10*2-0.5*5 + 20*5-0.5*26, 10*3-0.5*10 + 20*6-0.5*37]) m = F._message_to_parent(1) self.assertAllClose(m[0], [[0, 0, 10], [0, 0, 20]]) self.assertAllClose(m[1]*np.ones((2,3)), [[0, 0, -0.5], [0, 0, -0.5]]) # Gating non-default plate Z = 2 X = GaussianARD([[1],[2],[3]], 1, shape=(), plates=(3,1)) F = Gate(Z, X, gated_plate=-2) Y = GaussianARD(F, 1) Y.observe([10]) m = F._message_to_parent(0) self.assertAllClose(m[0], [10*1-0.5*2, 10*2-0.5*5, 10*3-0.5*10]) m = F._message_to_parent(1) self.assertAllClose(m[0], [[0], [0], [10]]) self.assertAllClose(m[1], [[0], [0], [-0.5]]) # Gating non-scalar node Z = 2 X = GaussianARD([[1,4],[2,5],[3,6]], 1, shape=(2,), plates=(3,)) F = Gate(Z, X) Y = GaussianARD(F, 1) Y.observe([10,20]) m = F._message_to_parent(0) self.assertAllClose(m[0], [10*1-0.5*2 + 20*4-0.5*17, 10*2-0.5*5 + 20*5-0.5*26, 10*3-0.5*10 + 20*6-0.5*37]) m = F._message_to_parent(1) I = np.identity(2) self.assertAllClose(m[0], [[0,0], [0,0], [10,20]]) self.assertAllClose(m[1], [0*I, 0*I, -0.5*I]) # Broadcasting the moments on the cluster axis Z = 2 X = GaussianARD(2, 1, shape=(), plates=(3,)) F = Gate(Z, X) Y = GaussianARD(F, 1) Y.observe(10) m = F._message_to_parent(0) self.assertAllClose(m[0], [10*2-0.5*5, 10*2-0.5*5, 10*2-0.5*5]) m = F._message_to_parent(1) self.assertAllClose(m[0], [0, 0, 10]) self.assertAllClose(m[1], [0, 0, -0.5]) pass def test_mask_to_parent(self): """ Test the mask handling in Gate node """ pass
32.239521
80
0.465175
1,548
10,768
3.176357
0.071059
0.020744
0.034167
0.040268
0.830995
0.771609
0.723409
0.689852
0.656905
0.63616
0
0.097068
0.347511
10,768
333
81
32.336336
0.602761
0.082467
0
0.682403
0
0
0
0
0
0
0
0
0.287554
1
0.017167
false
0.017167
0.025751
0
0.04721
0
0
0
0
null
0
0
0
1
1
1
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
4
3b93b37b1d3af11e900399b40fbbcb4506593f26
2,098
py
Python
scripts/test.dlint2.py
thannd/jalangi
d8607e55d73c717f3a6eb27fd6a57b586d73298f
[ "Apache-2.0" ]
86
2020-08-05T21:04:32.000Z
2022-02-08T08:55:41.000Z
scripts/test.dlint2.py
thannd/jalangi
d8607e55d73c717f3a6eb27fd6a57b586d73298f
[ "Apache-2.0" ]
7
2015-01-07T02:00:48.000Z
2017-09-29T12:43:34.000Z
scripts/test.dlint2.py
thannd/jalangi
d8607e55d73c717f3a6eb27fd6a57b586d73298f
[ "Apache-2.0" ]
24
2015-01-26T07:57:27.000Z
2021-08-08T17:20:34.000Z
import sj import sys analyses = ['../src/js/analyses2/ChainedAnalyses2.js', '../src/js/analyses2/dlint/Utils.js', '../src/js/analyses2/dlint/FunCalledWithMoreArguments.js', '../src/js/analyses2/dlint/CompareFunctionWithPrimitives.js', '../src/js/analyses2/dlint/UndefinedOffset.js', '../src/js/analyses2/dlint/CheckNaN.js', '../src/js/analyses2/dlint/ConcatUndefinedToString.js', '../src/js/analyses2/dlint/ShadowProtoProperty.js'] analysesStr = ' --analysis '+(' --analysis '.join(analyses)) def testDlint (file, output): sj.create_and_cd_jalangi_tmp() sj.execute_np(sj.INSTRUMENTATION_SCRIPT+' ../tests/dlint/'+file+'.js') out = sj.execute_return_np(sj.ANALYSIS2_SCRIPT+ analysesStr+' ../tests/dlint/'+file+'_jalangi_.js') if output != out: print "{} failed".format(file) print out print output else: print "{} passed".format(file) sj.cd_parent() out="""Observed NaN at (/Users/ksen/Dropbox/jalangi/tests/dlint/testNaN.js:7:5) 1 time(s). """ testDlint('testNaN',out) out = """Accessed property 'undefined' at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint1.js:7:1) 1 time(s). Accessed property 'undefined' at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint1.js:9:10) 1 time(s). Written property x at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint1.js:19:1) 1 time(s) and it shadows the property in its prototype. """ testDlint('dlint1',out) out="""Function at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint2.js:6:1) called 1 time(s) with more arguments that expected. Function at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint2.js:14:1) called 1 time(s) with more arguments that expected. """ testDlint('dlint2',out) out="""Concatenated undefined to a string at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint3.js:6:5) 1 time(s). Concatenated undefined to a string at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint3.js:7:5) 1 time(s). """ testDlint('dlint3',out) out="""Comparing a function with a number or string or boolean at (/Users/ksen/Dropbox/jalangi/tests/dlint/dlint4.js:4:5) 1 time(s). """ testDlint('dlint4',out)
39.584906
134
0.718303
309
2,098
4.838188
0.294498
0.073579
0.066221
0.108361
0.521739
0.412709
0.412709
0.341806
0.341806
0.313043
0
0.027748
0.106768
2,098
52
135
40.346154
0.770011
0
0
0.121951
0
0.219512
0.70734
0.412774
0
0
0
0
0
0
null
null
0.02439
0.04878
null
null
0.097561
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
1
1
1
null
0
0
0
0
1
0
0
0
0
0
0
0
0
4
8e5b6ec44797822e05037d4b5c952ba9977676e5
225
py
Python
topCoder/srms/400s/srm431/div2/mega_cool_numbers.py
ferhatelmas/algo
a7149c7a605708bc01a5cd30bf5455644cefd04d
[ "WTFPL" ]
25
2015-01-21T16:39:18.000Z
2021-05-24T07:01:24.000Z
topCoder/srms/400s/srm431/div2/mega_cool_numbers.py
ferhatelmas/algo
a7149c7a605708bc01a5cd30bf5455644cefd04d
[ "WTFPL" ]
2
2020-09-30T19:39:36.000Z
2020-10-01T17:15:16.000Z
topCoder/srms/400s/srm431/div2/mega_cool_numbers.py
ferhatelmas/algo
a7149c7a605708bc01a5cd30bf5455644cefd04d
[ "WTFPL" ]
15
2015-01-21T16:39:27.000Z
2020-10-01T17:00:22.000Z
class MegaCoolNumbersEasy: def count(self, N): def is_mega(s): return len(set(ord(s[i]) - ord(s[i - 1]) for i in range(1, len(s)))) < 2 return sum([is_mega(str(e)) for e in xrange(1, N + 1)])
32.142857
84
0.546667
41
225
2.95122
0.560976
0.099174
0.082645
0
0
0
0
0
0
0
0
0.030675
0.275556
225
6
85
37.5
0.711656
0
0
0
0
0
0
0
0
0
0
0
0
1
0.4
false
0
0
0.2
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
1
0
0
0
1
1
0
0
4
8e97e30fadd961bb4546dce7a3710341dcc1a9db
272
py
Python
efficient/display.py
antonydeepak/Efficient
ef12058a0d880ebdcf063ad2300ce6b9cd8ebb20
[ "MIT" ]
null
null
null
efficient/display.py
antonydeepak/Efficient
ef12058a0d880ebdcf063ad2300ce6b9cd8ebb20
[ "MIT" ]
2
2018-11-27T07:00:06.000Z
2019-02-15T06:12:51.000Z
efficient/display.py
antonydeepak/Efficient
ef12058a0d880ebdcf063ad2300ce6b9cd8ebb20
[ "MIT" ]
null
null
null
from abc import ABC from abc import abstractmethod class Display(ABC): @abstractmethod def write(self, message, color): raise NotImplementedError('abstract type') @abstractmethod def clear(self): raise NotImplementedError('abstract type')
24.727273
50
0.713235
29
272
6.689655
0.551724
0.072165
0.134021
0.371134
0
0
0
0
0
0
0
0
0.209559
272
11
51
24.727273
0.902326
0
0
0.444444
0
0
0.095238
0
0
0
0
0
0
1
0.222222
false
0
0.222222
0
0.555556
0
1
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
1
0
0
4
8ed15dff4fd01ba1eacf7b3e54cecc2743631352
227
py
Python
examples/helpers/post/upload_image_to_feed.py
javad94/instauto
8d4d068863176b0a1df13e5be3d5e32388036921
[ "MIT" ]
79
2020-08-24T23:32:57.000Z
2022-02-20T19:03:17.000Z
examples/helpers/post/upload_image_to_feed.py
klaytonpaiva/instauto
7f8c26b22f84d3d966625c7fa656e91cc623bb2e
[ "MIT" ]
146
2020-07-25T16:27:48.000Z
2021-10-02T09:03:50.000Z
examples/helpers/post/upload_image_to_feed.py
klaytonpaiva/instauto
7f8c26b22f84d3d966625c7fa656e91cc623bb2e
[ "MIT" ]
41
2020-09-07T14:19:04.000Z
2022-02-07T23:08:10.000Z
from instauto.api.client import ApiClient from instauto.helpers.post import upload_image_to_feed client = ApiClient.initiate_from_file('.instauto.save') upload_image_to_feed(client, "./test-feed.jpg", "Hello from instauto!")
32.428571
71
0.810573
33
227
5.333333
0.545455
0.204545
0.147727
0.193182
0.261364
0
0
0
0
0
0
0
0.079295
227
6
72
37.833333
0.842105
0
0
0
0
0
0.216814
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
0
0
0
null
1
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
1
0
0
0
0
4
d916cfaf064231858e711c92613a053f86382e83
65
py
Python
hdlConvertorAst/to/hwt/__init__.py
mewais/hdlConvertorAst
64c8c1deee923ffae17e70e0fb1ad763cb69608c
[ "MIT" ]
null
null
null
hdlConvertorAst/to/hwt/__init__.py
mewais/hdlConvertorAst
64c8c1deee923ffae17e70e0fb1ad763cb69608c
[ "MIT" ]
null
null
null
hdlConvertorAst/to/hwt/__init__.py
mewais/hdlConvertorAst
64c8c1deee923ffae17e70e0fb1ad763cb69608c
[ "MIT" ]
null
null
null
""" Convert HdlConvertor AST to a HWT component declarations """
16.25
56
0.753846
8
65
6.125
1
0
0
0
0
0
0
0
0
0
0
0
0.153846
65
3
57
21.666667
0.890909
0.861538
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
794f87bedecad232fbf4083f635b29ec07adc499
23
py
Python
APIs/Oauth/venv/lib/python3.8/site-packages/sanic/__version__.py
clarencejlee/jdp
d3d31db0138ff06f2f5ec592d85317941af4f280
[ "MIT" ]
null
null
null
APIs/Oauth/venv/lib/python3.8/site-packages/sanic/__version__.py
clarencejlee/jdp
d3d31db0138ff06f2f5ec592d85317941af4f280
[ "MIT" ]
null
null
null
APIs/Oauth/venv/lib/python3.8/site-packages/sanic/__version__.py
clarencejlee/jdp
d3d31db0138ff06f2f5ec592d85317941af4f280
[ "MIT" ]
null
null
null
__version__ = "21.3.4"
11.5
22
0.652174
4
23
2.75
1
0
0
0
0
0
0
0
0
0
0
0.2
0.130435
23
1
23
23
0.35
0
0
0
0
0
0.26087
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
7961311657f99e1842f7c425c65ae79dbdc8de30
127
py
Python
src/carica/models/__init__.py
Trimatix/carica
074be16bdf50541eb3ba92ca42d0ad901cc51bd0
[ "Apache-2.0" ]
5
2021-09-08T07:29:23.000Z
2021-11-24T00:18:22.000Z
src/carica/models/__init__.py
Trimatix/Carica
074be16bdf50541eb3ba92ca42d0ad901cc51bd0
[ "Apache-2.0" ]
42
2021-09-08T07:31:25.000Z
2022-01-16T17:39:34.000Z
src/carica/models/__init__.py
Trimatix/carica
074be16bdf50541eb3ba92ca42d0ad901cc51bd0
[ "Apache-2.0" ]
null
null
null
from .dataclasses import SerializableDataClass from .path import SerializablePath from .timedelta import SerializableTimedelta
31.75
46
0.88189
12
127
9.333333
0.666667
0
0
0
0
0
0
0
0
0
0
0
0.094488
127
3
47
42.333333
0.973913
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
79860d69bbe78c6aa79323ed7829a087b8de514f
41
py
Python
smktest/__init__.py
cecilio-cannav/smktest
4839fcf2cb127fea56a62591833500540b49b9bc
[ "MIT" ]
null
null
null
smktest/__init__.py
cecilio-cannav/smktest
4839fcf2cb127fea56a62591833500540b49b9bc
[ "MIT" ]
null
null
null
smktest/__init__.py
cecilio-cannav/smktest
4839fcf2cb127fea56a62591833500540b49b9bc
[ "MIT" ]
null
null
null
import smktest.check __all__=["smktest"]
13.666667
20
0.780488
5
41
5.6
0.8
0
0
0
0
0
0
0
0
0
0
0
0.073171
41
3
21
13.666667
0.736842
0
0
0
0
0
0.166667
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
799e255b698199ea6080f765b0fc94ea17776024
497
py
Python
my.py
pscly/shua_shouji
1c03056c8f5db4a3a1222b2d31fdf44c3ab07cf6
[ "MulanPSL-1.0" ]
null
null
null
my.py
pscly/shua_shouji
1c03056c8f5db4a3a1222b2d31fdf44c3ab07cf6
[ "MulanPSL-1.0" ]
null
null
null
my.py
pscly/shua_shouji
1c03056c8f5db4a3a1222b2d31fdf44c3ab07cf6
[ "MulanPSL-1.0" ]
null
null
null
class Dy: def __init__(self): pass def qidongdouyin(self): # [{'result': (911, 749), 'rectangle': ((853, 680), (853, 818), (970, 818), (970, 680)), 'confidence': 0.9559186100959778}] # a1 = find_all(Template(r"tpl1607562338061.png", rgb=True, record_pos=(0.343, -0.39), resolution=(1079, 2340))) # if a1: # click(a1[0].get('result')) # return Ture # return False start_app("com.ss.android.ugc.aweme.lite")
26.157895
131
0.547284
61
497
4.344262
0.786885
0.045283
0
0
0
0
0
0
0
0
0
0.217631
0.269618
497
18
132
27.611111
0.512397
0.60161
0
0
0
0
0.154255
0.154255
0
0
0
0
0
1
0.4
false
0.2
0
0
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
4
79a1e8be94723bd1ce7fced553ae78a86acea660
192
py
Python
e2db/views.py
ron-wolf/e2db
768732f8660d6012161754659947d3c794710d36
[ "MIT" ]
1
2019-01-12T17:08:16.000Z
2019-01-12T17:08:16.000Z
e2db/views.py
ron-wolf/e2db
768732f8660d6012161754659947d3c794710d36
[ "MIT" ]
null
null
null
e2db/views.py
ron-wolf/e2db
768732f8660d6012161754659947d3c794710d36
[ "MIT" ]
null
null
null
from django.http import HttpResponse def qr(request): from e2db.utils import qr_page param = request.GET.get('q', '') result = qr_page(param) return HttpResponse(result)
21.333333
36
0.682292
26
192
4.961538
0.615385
0.093023
0.170543
0
0
0
0
0
0
0
0
0.006623
0.213542
192
8
37
24
0.847682
0
0
0
0
0
0.005208
0
0
0
0
0
0
1
0.166667
false
0
0.333333
0
0.666667
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
79be94b583d882563047cb02f461bca6e9ebf5cb
910
py
Python
managerapi/EmpApi/models.py
anushiv25/Assignment
8eefb9a038019c1a126b0b3040107e87e0964998
[ "MIT" ]
null
null
null
managerapi/EmpApi/models.py
anushiv25/Assignment
8eefb9a038019c1a126b0b3040107e87e0964998
[ "MIT" ]
null
null
null
managerapi/EmpApi/models.py
anushiv25/Assignment
8eefb9a038019c1a126b0b3040107e87e0964998
[ "MIT" ]
null
null
null
from django.db import models from django.conf import settings from authentication.models import User from django.core.validators import RegexValidator #Employee Table class Employee(models.Model): emp_id = models.CharField(max_length=15, unique=True) email = models.EmailField(max_length=255, unique=True) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) password = models.CharField(max_length=50) address = models.CharField(max_length=255) dob = models.DateField(auto_now=False, auto_now_add=False) company = models.CharField(max_length=255) mobile = models.CharField(max_length=15, validators=[RegexValidator(r'^\d{1,10}$')]) city = models.CharField(max_length=100) class Meta: ordering = ['firstname', 'lastname'] #To retreive data first by firstname then by lastname def __str__(self): return emp_id
39.565217
98
0.745055
122
910
5.409836
0.47541
0.122727
0.218182
0.290909
0.283333
0
0
0
0
0
0
0.035019
0.152747
910
23
99
39.565217
0.821012
0.072527
0
0
0
0
0.032028
0
0
0
0
0
0
1
0.052632
false
0.052632
0.210526
0.052632
0.947368
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
1
0
0
1
0
0
4
79ca5eda919f60a8180fa12a3829c66eded13a27
3,369
py
Python
JOI2013-D/test_pasted_from_page.py
staguchi0703/ant_book_dp
7609579696eb34ee1f0d95cc0c68d3ad28c19261
[ "MIT" ]
null
null
null
JOI2013-D/test_pasted_from_page.py
staguchi0703/ant_book_dp
7609579696eb34ee1f0d95cc0c68d3ad28c19261
[ "MIT" ]
null
null
null
JOI2013-D/test_pasted_from_page.py
staguchi0703/ant_book_dp
7609579696eb34ee1f0d95cc0c68d3ad28c19261
[ "MIT" ]
null
null
null
# from resolve import resolve #################################### #################################### # 以下にプラグインの内容をペーストする # import sys from io import StringIO import unittest class TestClass(unittest.TestCase): def assertIO(self, input, output): stdout, stdin = sys.stdout, sys.stdin sys.stdout, sys.stdin = StringIO(), StringIO(input) resolve() sys.stdout.seek(0) out = sys.stdout.read()[:-1] sys.stdout, sys.stdin = stdout, stdin print('------------') print(out) print('------------') self.assertEqual(out, output) def test_入力例_3(self): input = """195 200 42 42 46 45 8 33 10 30 5 52 17 47 60 0 56 41 27 40 40 53 45 36 52 55 26 31 35 43 19 42 16 7 44 49 28 21 13 1 30 6 26 48 41 28 25 30 6 38 0 0 27 35 37 44 59 4 49 1 27 20 6 35 12 54 3 6 33 46 60 48 13 44 27 17 34 17 48 48 34 51 58 60 34 31 22 27 1 14 1 56 21 17 31 55 9 15 19 28 13 54 10 15 8 55 4 44 25 1 20 21 23 43 51 42 58 33 39 49 29 13 43 32 18 32 9 13 5 40 58 55 57 18 13 42 33 9 10 9 43 26 21 15 23 4 59 32 5 57 32 47 13 25 41 4 58 59 43 37 34 14 43 33 51 48 53 14 55 13 33 3 41 6 50 30 7 60 41 18 3 24 51 39 0 52 50 0 23 36 52 15 24 18 21 6 32 3 11 72 9 24 52 4 34 6 5 47 72 23 48 68 45 47 90 21 29 89 26 55 28 42 60 74 9 11 23 16 18 69 52 53 32 19 55 2 5 42 75 18 50 37 7 58 24 16 45 20 3 20 75 9 21 15 20 36 10 17 20 34 31 59 86 24 46 82 15 43 64 13 14 94 13 36 64 35 55 86 24 33 61 22 54 69 2 48 24 38 48 88 6 23 34 29 37 49 20 26 52 11 28 25 26 51 13 26 51 32 32 54 79 34 53 83 43 53 65 43 49 60 42 59 49 23 42 11 15 55 46 25 45 65 35 45 40 9 37 7 0 50 39 18 49 9 8 24 41 24 50 53 24 39 26 49 49 21 34 40 62 19 30 94 33 45 57 1 43 23 6 42 8 55 59 92 20 39 92 32 34 39 11 33 48 17 37 5 5 14 9 8 41 97 3 55 100 43 60 45 39 43 60 32 45 80 23 49 39 9 12 21 43 48 71 44 45 33 30 38 60 4 6 55 22 39 90 20 59 53 26 36 99 11 14 21 25 59 7 25 38 53 21 25 28 40 58 35 34 58 62 7 31 1 22 26 51 41 49 47 21 53 86 16 46 96 20 40 24 8 18 87 19 51 57 13 54 57 19 60 73 34 49 74 47 53 42 42 47 69 21 31 39 8 32 64 11 26 86 31 34 19 3 50 19 10 14 79 47 50 89 53 58 6 23 34 82 19 46 82 29 44 38 23 38 14 26 60 93 14 45 53 7 8 73 34 36 42 42 53 9 12 28 40 3 12 64 41 49 94 3 34 54 3 3 17 0 48 28 2 57 29 3 16 38 13 21 95 13 47 50 3 18 78 9 25 39 38 56 49 33 56 56 14 36 67 10 39 93 10 22 92 12 54 66 20 20 17 0 48 4 22 40 4 41 50 97 48 50 24 37 50 2 59 59 44 30 56 70 1 40 40 19 48 91 9 27 13 1 56 46 9 60 20 2 58 71 40 49 84 31 33 69 10 47 13 37 57 7 20 57 83 17 18 49 33 54 79 14 53 88 5 45 73 18 31 61 9 57 36 19 43 43 44 44 27 9 28 94 40 60 17 3 54 4 25 60 41 42 46 3 16 53 28 0 34 71 21 37 42 28 30 21 1 38 20 35 38 29 36 40 40 34 37 13 10 43 11 8 52 49 24 42 27 0 12 69 41 44 92 40 44 53 17 33 36 6 54 25 35 36 16 12 32 41 34 59 36 31 45 29 49 52 90 10 22 1 2 49 45 18 44 24 25 31 97 16 24 97 30 56 66 4 36 48 23 33 21 30 40 65 15 19 43 7 7 60 4 38 78 16 24 11 21 29 65 45 50 46""" output = """18586""" self.assertIO(input, output) def test_入力例_1(self): input = """3 4 31 27 35 20 25 30 23 29 90 21 35 60 28 33 40""" output = """80""" self.assertIO(input, output) def test_入力例_2(self): input = """5 2 26 28 32 29 34 30 35 0 25 30 100""" output = """300""" self.assertIO(input, output) if __name__ == "__main__": unittest.main()
7.437086
59
0.609083
927
3,369
2.19849
0.137001
0.02208
0.017664
0.025025
0.051521
0.032385
0.032385
0
0
0
0
0.684072
0.323538
3,369
452
60
7.45354
0.21018
0.005343
0
0.387244
0
0
0.736553
0
0
1
0
0
0.01139
1
0.009112
false
0
0.009112
0
0.020501
0.006834
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
1
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
4
79cd980a9b8d8a38ea7c7fe000439f6d598e65ce
80
py
Python
simulador/__init__.py
dantebarba/disk-scheduling-simulator
566a07f1f23bc0a74bbbb51607de98b247ad563f
[ "MIT" ]
null
null
null
simulador/__init__.py
dantebarba/disk-scheduling-simulator
566a07f1f23bc0a74bbbb51607de98b247ad563f
[ "MIT" ]
null
null
null
simulador/__init__.py
dantebarba/disk-scheduling-simulator
566a07f1f23bc0a74bbbb51607de98b247ad563f
[ "MIT" ]
null
null
null
import interface import data data.Config.load_config() interface.main()
11.428571
26
0.7375
10
80
5.8
0.6
0
0
0
0
0
0
0
0
0
0
0
0.175
80
6
27
13.333333
0.878788
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
8db738dd401da79056f53bf3711bb9a840f4e685
60
py
Python
code/abc086_b_03.py
KoyanagiHitoshi/AtCoder
731892543769b5df15254e1f32b756190378d292
[ "MIT" ]
3
2019-08-16T16:55:48.000Z
2021-04-11T10:21:40.000Z
code/abc086_b_03.py
KoyanagiHitoshi/AtCoder
731892543769b5df15254e1f32b756190378d292
[ "MIT" ]
null
null
null
code/abc086_b_03.py
KoyanagiHitoshi/AtCoder
731892543769b5df15254e1f32b756190378d292
[ "MIT" ]
null
null
null
print("No" if int(input().replace(" ",""))**.5%1 else "Yes")
60
60
0.55
10
60
3.3
1
0
0
0
0
0
0
0
0
0
0
0.036364
0.083333
60
1
60
60
0.563636
0
0
0
0
0
0.098361
0
0
0
0
0
0
1
0
true
0
0
0
0
1
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
1
0
4
8dc27663d2afbe05e8159277edb60fd629fee7e6
239
py
Python
idseq_pipeline/commands/host_indexing.py
cdebourcy/idseq-pipeline
0f3d58ab36896bb01ab3929d8386c0e2774765f4
[ "MIT" ]
null
null
null
idseq_pipeline/commands/host_indexing.py
cdebourcy/idseq-pipeline
0f3d58ab36896bb01ab3929d8386c0e2774765f4
[ "MIT" ]
159
2018-01-11T01:54:12.000Z
2021-01-13T23:11:48.000Z
idseq_pipeline/commands/host_indexing.py
cdebourcy/idseq-pipeline
0f3d58ab36896bb01ab3929d8386c0e2774765f4
[ "MIT" ]
2
2019-04-17T18:10:36.000Z
2020-03-11T08:30:54.000Z
"""The host-indexing command.""" from .base import Base class Host_indexing(Base): """Perform indexing""" def run(self): from .host_indexing_functions import * set_up_stdout() make_indexes(self.version)
18.384615
46
0.65272
29
239
5.172414
0.655172
0.24
0
0
0
0
0
0
0
0
0
0
0.230126
239
12
47
19.916667
0.815217
0.179916
0
0
0
0
0
0
0
0
0
0
0
1
0.166667
false
0
0.333333
0
0.666667
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
8dcb690687eb2616d65ca467e668274b285ee6f2
32
py
Python
tests/__init__.py
kleekaai/cc
5f4302b3c5018c60589949a29fdd4027ae20f2ba
[ "MIT" ]
null
null
null
tests/__init__.py
kleekaai/cc
5f4302b3c5018c60589949a29fdd4027ae20f2ba
[ "MIT" ]
null
null
null
tests/__init__.py
kleekaai/cc
5f4302b3c5018c60589949a29fdd4027ae20f2ba
[ "MIT" ]
null
null
null
"""Unit test package for cc."""
16
31
0.625
5
32
4
1
0
0
0
0
0
0
0
0
0
0
0
0.15625
32
1
32
32
0.740741
0.78125
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
8dfb017506cac21c3aa9d0296b68f9536981ceaa
692
py
Python
api/app/models/time.py
HotMaps/Toolbox
ba1e287dbc63e34bf9feb80b65b02c1db93ce91c
[ "Apache-2.0" ]
4
2020-10-01T10:38:06.000Z
2021-12-28T03:11:18.000Z
api/app/models/time.py
HotMaps/Toolbox
ba1e287dbc63e34bf9feb80b65b02c1db93ce91c
[ "Apache-2.0" ]
9
2017-11-08T17:29:10.000Z
2020-08-31T15:28:31.000Z
api/app/models/time.py
HotMaps/Toolbox
ba1e287dbc63e34bf9feb80b65b02c1db93ce91c
[ "Apache-2.0" ]
4
2019-03-25T13:24:14.000Z
2021-07-16T20:52:51.000Z
from app import dbGIS as db class Time(db.Model): __tablename__ = 'time' __table_args__ = ( {"schema": 'stat'} ) id = db.Column(db.Integer, primary_key=True) granularity = db.Column(db.String(14)) date = db.Column(db.Date) hour_of_year = db.Column(db.BigInteger) hour_of_day = db.Column(db.SmallInteger) season = db.Column(db.String(14)) weekday = db.Column(db.String(14)) day = db.Column(db.SmallInteger) month = db.Column(db.SmallInteger) year = db.Column(db.SmallInteger) timestamp = db.Column(db.DateTime(timezone=False)) def __repr__(self): return "<Time(%s)>" % (self.timestamp.strftime("%Y-%m-%d %H:%M"))
28.833333
73
0.641618
97
692
4.391753
0.484536
0.206573
0.258216
0.206573
0.244131
0
0
0
0
0
0
0.01083
0.199422
692
23
74
30.086957
0.758123
0
0
0
0
0
0.054913
0
0
0
0
0
0
1
0.052632
false
0
0.052632
0.052632
0.894737
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
4
5c120ed90337e22bd4658b43ccf13c8f26e78395
181
py
Python
content/notebooks/demo.py
ueapy/ueapy.github.io
920f25f4189512a77aa6b79eae133db0f14e514a
[ "MIT" ]
2
2016-02-02T06:15:38.000Z
2016-11-28T10:31:43.000Z
content/notebooks/demo.py
ueapy/ueapy.github.io
920f25f4189512a77aa6b79eae133db0f14e514a
[ "MIT" ]
null
null
null
content/notebooks/demo.py
ueapy/ueapy.github.io
920f25f4189512a77aa6b79eae133db0f14e514a
[ "MIT" ]
3
2016-01-22T11:27:08.000Z
2018-02-09T16:20:57.000Z
# A demo module def show_me_a(): """Prints a.""" print('a') def show_me_b(): """Prints b.""" print('b') c = 2 d = 2 if __name__ == '__main__': show_me_a()
10.055556
26
0.508287
29
181
2.689655
0.517241
0.230769
0.230769
0
0
0
0
0
0
0
0
0.015385
0.281768
181
17
27
10.647059
0.584615
0.187845
0
0
0
0
0.073529
0
0
0
0
0
0
1
0.25
false
0
0
0
0.25
0.25
1
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
1
0
0
0
0
0
0
0
4
5c24430d8a1848d22bf829b5101632598a9406f3
149
py
Python
png.py
apricis/rel_import
f8bf38ca9aee2798221a8d29e5c05a3fe1e0eea8
[ "MIT" ]
null
null
null
png.py
apricis/rel_import
f8bf38ca9aee2798221a8d29e5c05a3fe1e0eea8
[ "MIT" ]
null
null
null
png.py
apricis/rel_import
f8bf38ca9aee2798221a8d29e5c05a3fe1e0eea8
[ "MIT" ]
1
2020-01-21T02:51:42.000Z
2020-01-21T02:51:42.000Z
import gif class Png: pass if __name__ == "__main__": # will print that if this file is iterpreted print "Gif imported successfully"
13.545455
48
0.684564
20
149
4.7
0.85
0
0
0
0
0
0
0
0
0
0
0
0.255034
149
10
49
14.9
0.846847
0.281879
0
0
0
0
0.314286
0
0
0
0
0
0
0
null
null
0.2
0.4
null
null
0.2
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
1
0
0
0
0
4
5c3ebfd52c4c6e44b245810f5397bfc8542b0504
343
py
Python
mpunet/evaluate/__init__.py
alexsosn/MultiPlanarUNet
2d1cecdee391be8e9f72da95e33077ed82a2183a
[ "MIT" ]
156
2018-12-19T19:21:30.000Z
2022-03-10T13:14:52.000Z
mpunet/evaluate/__init__.py
alexsosn/MultiPlanarUNet
2d1cecdee391be8e9f72da95e33077ed82a2183a
[ "MIT" ]
25
2019-07-30T07:45:26.000Z
2022-02-10T00:38:31.000Z
mpunet/evaluate/__init__.py
alexsosn/MultiPlanarUNet
2d1cecdee391be8e9f72da95e33077ed82a2183a
[ "MIT" ]
33
2019-01-26T16:34:50.000Z
2022-02-20T13:48:44.000Z
from .metrics import dice_all from .loss_functions import (SparseExponentialLogarithmicLoss, SparseDiceLoss, SparseExpLogDice, SparseFocalLoss, SparseGeneralizedDiceLoss, SparseJaccardDistanceLoss)
42.875
62
0.51312
15
343
11.6
0.866667
0
0
0
0
0
0
0
0
0
0
0
0.460641
343
7
63
49
0.940541
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.285714
0
0.285714
0
1
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
5c43191601dfbaef10bb38220167bfa11e4bedcc
57
py
Python
atcoder/abc/a107.py
tomato-300yen/coding
db6f440a96d8c83f486005c650461a69f27e3926
[ "MIT" ]
null
null
null
atcoder/abc/a107.py
tomato-300yen/coding
db6f440a96d8c83f486005c650461a69f27e3926
[ "MIT" ]
null
null
null
atcoder/abc/a107.py
tomato-300yen/coding
db6f440a96d8c83f486005c650461a69f27e3926
[ "MIT" ]
null
null
null
N, i = tuple(map(int, input().split())) print(N - i + 1)
19
39
0.54386
11
57
2.818182
0.818182
0.129032
0
0
0
0
0
0
0
0
0
0.021277
0.175439
57
2
40
28.5
0.638298
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0
0
0
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
1
0
4
3091139069dd0c5c1ef63027068ea7997d94533c
33,748
py
Python
src/members/views.py
GMNaim/Online-Project-Tracking-System
d727c6033c4abbacb5288179ee6ae5889a7a83a9
[ "MIT" ]
null
null
null
src/members/views.py
GMNaim/Online-Project-Tracking-System
d727c6033c4abbacb5288179ee6ae5889a7a83a9
[ "MIT" ]
null
null
null
src/members/views.py
GMNaim/Online-Project-Tracking-System
d727c6033c4abbacb5288179ee6ae5889a7a83a9
[ "MIT" ]
null
null
null
# members/views.py from datetime import datetime from accounts.decorators import has_access, has_access_to_assigned_task from accounts.models import User from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from django.forms import model_to_dict from django.shortcuts import render, get_object_or_404, redirect from projectmanager.models import Task, SubmittedToQATask, user_directory_path, TaskHistory, Module # Role Names role_super_user = 'Super User' role_pm = 'Project Manager' role_department_head = 'Department Head' role_team_leader = 'Team Leader' role_team_member = 'Team Member' role_employee = 'Employee' role_tester = 'Tester' default_password = 'test123' # default pass # getting user group group_super_user = Group.objects.get(name__iexact=role_super_user) group_pm = Group.objects.get(name__iexact=role_pm) group_department_head = Group.objects.get(name__iexact=role_department_head) group_team_leader = Group.objects.get(name__iexact=role_team_leader) group_team_member = Group.objects.get(name__iexact=role_team_member) group_employee = Group.objects.get(name__iexact=role_employee) group_tester = Group.objects.get(name__iexact=role_tester) @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader]) def member_all_task(request): # user_notification_item = Module.objects.filter( # assigned_team__team_member_user__username__iexact=request.user.username, status__gte=2) # print(user_notification_item, ' = user_notification_item') assigned_tasks_list_to_member = Task.objects.filter(assigned_member=request.user, status__gte=2).order_by('-assigned_at', 'status', ) # print('assigned_tasks_list_to_member == ', assigned_tasks_list_to_member) """ CHANGING THE NOTIFICATION COUNT TO ZERO as he see the notification """ # current_user = User.objects.get(id=request.user.id) # current_user.notification_count = 0 # current_user.save() """ LIST OF NOTIFICATION ITEMS """ # user_notification_item = Task.objects.filter(assigned_member=request.user, status=2).order_by( # '-assigned_at', 'status') # print('user_notification_item: -- ', user_notification_item) # if current_user.notification_count == 0: # user_notification_item = None context = {'assigned_tasks_list_to_member': assigned_tasks_list_to_member, } return render(request, 'members/member_all_task.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader, role_department_head, role_pm, role_super_user]) @has_access_to_assigned_task # this decorator is for to see the task by the assigned member only not other member. def member_task_details(request, task_id): if request.user.is_authenticated: # user_notification_item = Project.objects.filter(department_id=request.user.department.id, status=2) selected_task = get_object_or_404(Task, id=task_id) selected_task.team_member_notified = True # as member visit detail page so he is notified selected_task.save() module_of_the_task = selected_task.module # getting the module of the task """ CHANGING THE NOTIFICATION COUNT TO ZERO as he see the notification """ current_user = User.objects.get(id=request.user.id) # current_user.notification_count = 0 # current_user.save() """ LIST OF NOTIFICATION ITEMS """ # user_notification_item = Task.objects.filter(assigned_member=request.user, status=2).order_by( # '-assigned_at', 'status') # print('user_notification_item: -- ', user_notification_item) # if current_user.notification_count == 0: # user_notification_item = None # If member see details of the task then team_member_notified will be true and module's status will be 3 # if selected_task.status != 7: # if selected_task.status != 6: # if selected_task.status != 5: # if selected_task.status != 4: # if selected_task.team_member_notified: # module_of_the_task.status = 3 # if there is any task then status will be 3 means running # module_of_the_task.save() # selected_task.status = 3 # selected_task.save() """ START THE TASK BY CLICKING ON START WORKING """ if request.GET.get('status', None) == '3': if selected_task.status == 2: # if assigned if selected_task.status != 7 and selected_task.status != 6 and selected_task.status != 5 and selected_task.status != 4 and selected_task.team_member_notified: try: module_of_the_task.status = 3 # if there is any task then status will be 3 means running module_of_the_task.save() selected_task.status = 3 selected_task.save() messages.success(request, f"You have started the task.") return redirect('member-task-details', task_id=task_id) except Exception as e: # print('error at task send to leader...', e) return render(request, 'members/member_task_details.html') # history of the task submitted which are verified or need modification status all_submitted_task_to_tester = SubmittedToQATask.objects.filter(task=selected_task, status__gt=2).order_by( '-created_at') context = {'selected_task': selected_task, 'all_submitted_task_to_tester': all_submitted_task_to_tester} """ SENDING TASK TO THE LEADER BY CLICKING THE BUTTON """ if request.GET.get('status', None) == '7': if selected_task.status == 6: # if test passed... try: # Task completed and sending to leader selected_task.status = 7 # now completed... selected_task.completed_at = datetime.now() selected_task.is_send_to_leader = True selected_task.save() """ Setting notification count number as completed task is send to team leader """ # getting the team leader task_send_to_team_leader = User.objects.get(team_member=module_of_the_task.assigned_team, role__name__exact=role_team_leader) # print(task_send_to_team_leader) # setting the notification count number as task is completed task_send_to_team_leader.notification_count += 1 task_send_to_team_leader.save() # print(task_send_to_team_leader.id, 'ddddddddddddddddd') # create new task history object as task is completed task_history = TaskHistory() task_history.task = selected_task task_history.module = module_of_the_task task_history.description = (model_to_dict(selected_task)) task_history.status = 'Task Completed' task_history.user = task_send_to_team_leader task_history.save() """ =============Checking whether the Module is completed =============""" task_list = Task.objects.filter(module=module_of_the_task) all_task = task_list.count() task_complete_counter = 0 # print(task_list, all_task) for task in task_list: # print(task.get_status_display()) if task.status == 7: task_complete_counter += 1 # if task is completed then increment then compare it with total task. if all_task != 0: module_of_the_task.progress = ( task_complete_counter / all_task) * 100 # progress of the module... module_of_the_task.save() # print(module_of_the_task.progress, '% == progress of the module....') if all_task == task_complete_counter: module_of_the_task.status = 4 module_of_the_task.is_completed = True module_of_the_task.completed_at = datetime.now() module_of_the_task.save() """ Setting notification for head as the module is completed. """ # getting the head head_of_the_dep = User.objects.get(department=request.user.department, role__name__iexact=role_department_head) # print('head_of_the_dep: ', head_of_the_dep) # setting the notification count number as task is completed head_of_the_dep.notification_count += 1 head_of_the_dep.save() # create new task history object as module is completed task_history = TaskHistory() task_history.module = module_of_the_task task_history.project = module_of_the_task.project task_history.description = (model_to_dict(module_of_the_task)) task_history.status = 'Module Completed' task_history.user = head_of_the_dep task_history.save() else: module_of_the_task.is_completed = False module_of_the_task.status = 3 module_of_the_task.completed_at = None module_of_the_task.save() # print('---------.///', module_of_the_task.name, module_of_the_task.get_status_display()) """ =============Checking whether the Project is completed =============""" project_of_the_modules = module_of_the_task.project # getting the project of the tasks/modules # print(project_of_the_modules) list_of_modules_of_a_project = Module.objects.filter( project=project_of_the_modules) # all module of the project total_modules_of_a_project = list_of_modules_of_a_project.count() # print(f'total_modules_of__project= {project_of_the_modules} = ', total_modules_of_a_project) # module_complete_counter = 0 # for module in list_of_modules_of_a_project: # print(module.get_status_display()) # if module.status == 4: # module_complete_counter += 1 # if module is completed then increment then compare it with total task. # # if total_modules_of_a_project == module_complete_counter: # project_of_the_modules.status = 4 # print(project_of_the_modules.get_status_display(), 'showing status after setting 4') # # project_of_the_modules.is_completed = True # project_of_the_modules.completed_at = datetime.now() # project_of_the_modules.save() """ if all task's status is 7 then project is completed... below code is for that""" # total_task_of_the_project = 0 # projects_task_complete_counter = 0 # for module in list_of_modules_of_a_project: # # total_task += module.task_set.all().count() # for task in module.task_set.all(): # total_task_of_the_project += 1 # if task.status == 7: # projects_task_complete_counter += 1 # # print(f'total task of the project {project_of_the_modules.name} is : ====== ', total_task_of_the_project) # # changing the status of the project based on task completion # if total_task_of_the_project == projects_task_complete_counter: # project_of_the_modules.status = 4 # project_of_the_modules.completed_at = datetime.now() # project_of_the_modules.save() selected_task.get_project_progress_status() # running the method to get project progress and status... if project_of_the_modules.status == 4: """ Setting notification for pm as the project is completed. """ # getting the project manager all_pm = User.objects.filter(role__name__iexact=role_pm) pm = project_of_the_modules.assigned_by # print('All pm are: : ', pm, all_pm) for p_m in all_pm: # setting the notification count number as task is completed p_m.notification_count += 1 p_m.save() # create new task history object as module is completed task_history = TaskHistory() task_history.project = project_of_the_modules task_history.description = (model_to_dict(project_of_the_modules)) task_history.status = 'Project Completed' task_history.user = p_m task_history.save() else: # project_of_the_modules.is_completed = False project_of_the_modules.status = 3 # print(project_of_the_modules.get_status_display(), 'showing status in else...') project_of_the_modules.completed_at = None project_of_the_modules.save() # print('---------.///', module_of_the_task.name, module_of_the_task.get_status_display()) # Changing the progress of the project # project_of_the_modules.progress = int((projects_task_complete_counter / total_task_of_the_project) * 100) # progress of the project # project_of_the_modules.save() # print(project_of_the_modules.progress, '% == progress of the project....') messages.success(request, f"Congratulation! You have completed the task. Task Send to Team Leader.") return redirect('member-completed-task') except Exception as e: # print('error at task send to leader...', e) return render(request, 'members/member_task_details.html', context) # task_history = TaskHistory.objects.filter(task=selected_task) # print(task_history) return render(request, 'members/member_task_details.html', context) @login_required(login_url='login') @has_access( allowed_roles=[role_team_member, role_team_leader, role_pm, role_super_user, role_department_head, role_tester]) def notification_number_zero(request): """""" """BY CLICKING ON THE BELL BUTTON, CHANGING THE NOTIFICATION COUNT TO ZERO as he see the notification """ if request.method == "POST": current_user = User.objects.get(id=request.user.id) button_clicked = request.POST.get('button_clicked', '') if button_clicked == 'clicked': current_user.notification_count = 0 current_user.save() # print(current_user.notification_count, 'notification count after ajax post request =========') return redirect('dashboard') @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader]) def member_running_tasks(request): if request.user.is_authenticated: running_task = Task.objects.filter(status__in=[3], assigned_member=request.user).order_by( '-assigned_at') # 3 means running task context = {'running_task': running_task} return render(request, 'members/member_running_tasks.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader]) def member_test_passed_tasks(request): if request.user.is_authenticated: completed_task = Task.objects.filter(status=6, assigned_member=request.user).order_by( '-assigned_at') # 5 means completed task context = {'completed_task': completed_task} return render(request, 'members/member_test_passed_tasks.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader]) def member_completed_tasks(request): if request.user.is_authenticated: completed_task = Task.objects.filter(status=7, assigned_member=request.user).order_by( '-assigned_at') # 5 means completed task context = {'completed_task': completed_task} # print(completed_task, '3333333333333333') return render(request, 'members/member_completed_tasks.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader]) def member_submitted_tasks(request): if request.user.is_authenticated: submitted_to_qa_task = Task.objects.filter(status=4, assigned_member=request.user).order_by( '-assigned_at') # 4 means submitted to qa task context = {'submitted_to_qa_task': submitted_to_qa_task} return render(request, 'members/member_submitted_tasks.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader]) def submit_task_to_tester(request, task_id): if request.user.is_authenticated: get_task = get_object_or_404(Task, id=task_id) testers = User.objects.filter(department__name__iexact=request.user.department.name, is_tester=True) # print(testers) last_submitted_task = [] # print(get_task.submittedtoqatask_set.all().count()) if get_task.submittedtoqatask_set.all().count() != 0: last_submitted_task = SubmittedToQATask.objects.filter(task=get_task).last() # print(last_submitted_task, '8888888') # print(last_submitted_task, '8888888') context = {'task': get_task, 'testers': testers, 'last_submitted_task': last_submitted_task} if request.method == 'POST': submitted_task_file = request.FILES.get('submitted_task_file', '') description = request.POST['description'] select_tester = request.POST.get('select_tester', '') # print(submitted_task_file, description) if description.strip() == "": context.update({'description': description}) messages.warning(request, "Please write some description of your submitted task.") return render(request, 'members/submit_task.html', context) elif select_tester == '': messages.warning(request, "Please select a tester") return render(request, 'members/submit_task.html', context) else: """Adding submitted task in the SubmittedToQATask model""" try: # this function is for saving the file under each user's folder. assigned_member_of_task = get_task.assigned_member.username user_directory_path(assigned_member_of_task, submitted_task_file) if select_tester != '': get_tester = User.objects.get(id=select_tester) # getting the tester obj submitted_task = SubmittedToQATask() submitted_task.assigned_member = get_tester submitted_task.task = get_task submitted_task.description = description.strip() submitted_task.submitted_file = submitted_task_file submitted_task.save() # after submit the task change the task status get_task.status = 4 # 4 means submitted to qa team. get_task.is_send_tester = True get_task.submitted_to_tester_at = datetime.now() # making team_member_notified false cause to get the color of the new notification item. get_task.team_member_notified = False get_task.save() # create new task history object task_history = TaskHistory() # task_history.task = get_task task_history.submitted_task = submitted_task task_history.task = get_task task_history.description = (model_to_dict(get_task)) task_history.status = 'New Task' task_history.user = get_tester task_history.save() # Assign this task to the tester... """ Setting notification count number as task is send to a tester """ # setting the notification count number as task is assigned to tester get_tester.notification_count += 1 get_tester.save() messages.success(request, "Your task is successfully submitted to tester.") return redirect('member-submitted-task') except Exception as e: # print(e, 'exception -----at task submit to qa !!!') messages.error(request, f"Error: {e}") return render(request, 'members/submit_task.html') # submitted_to_qa_task = Task.objects.filter(status=4, assigned_member=request.user).order_by( # '-assigned_at') # 4 means submitted to qa task # context = {'submitted_to_qa_task': submitted_to_qa_task} return render(request, 'members/submit_task.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_team_member, role_team_leader]) def member_need_modification_tasks(request): if request.user.is_authenticated: need_modification_task = Task.objects.filter(status=5, assigned_member=request.user).order_by( '-assigned_at') # 3 means running task # fix_bug_tasks = SubmittedToQATask.objects.filter(task__assigned_member=request.user, status=3).order_by( # '-verified_at') context = {'need_modification_task': need_modification_task} return render(request, 'members/member_need_modification_tasks.html', context) # # # @login_required(login_url='login') # @has_access(allowed_roles=[role_team_member]) # def member_task_send_to_leader(request, task_id): # if request.user.is_authenticated: # selected_task = get_object_or_404(Task, id=task_id) # # module_of_the_task = selected_task.module # getting the module of the task # # current_user = User.objects.get(id=request.user.id) # # current_user.notification_count = 0 # # current_user.save() # # if current_user.notification_count == 0: # # user_notification_item = None # # # # # If member see details of the task then team_member_notified will be true and module's status will be 3 # # if selected_task.status != 6: # # if selected_task.status != 5: # # if selected_task.status != 4: # # if selected_task.team_member_notified: # # module_of_the_task.status = 3 # if there is any task then status will be 3 means running # # module_of_the_task.save() # # selected_task.status = 3 # # selected_task.save() # # # # history of the task submitted which are verified or need modification status # all_submitted_task_to_tester = SubmittedToQATask.objects.filter(task=selected_task, status__gt=2).order_by( # '-created_at') # context = {'selected_task': selected_task, # 'all_submitted_task_to_tester': all_submitted_task_to_tester} # # # except Exception as e: # print('error at task send to leader...', e) # return render(request, 'members/member_task_details.html', context) # # return render(request, 'members/member_task_details.html') # """ ================================== TESTER WORK = ===========================================""" @login_required(login_url='login') @has_access(allowed_roles=[role_tester]) def tester_all_task(request): # user_notification_item = Module.objects.filter( # assigned_team__team_member_user__username__iexact=request.user.username, status__gte=2) # print(user_notification_item, ' = user_notification_item') tasks_list_of_tester = SubmittedToQATask.objects.filter(assigned_member=request.user).order_by('-created_at', ) # print('tasks_list_of_tester == ', tasks_list_of_tester) """ CHANGING THE NOTIFICATION COUNT TO ZERO as he see the notification """ # current_user = User.objects.get(id=request.user.id) # current_user.notification_count = 0 # current_user.save() """ LIST OF NOTIFICATION ITEMS """ # user_notification_item = SubmittedToQATask.objects.filter(assigned_member=request.user, # status=1).order_by('-created_at', 'status', ) # if current_user.notification_count == 0: # user_notification_item = None context = {'tasks_list_of_tester': tasks_list_of_tester} return render(request, 'members/tester_all_task.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_tester]) def tester_task_details(request, task_id): if request.user.is_authenticated: # user_notification_item = Project.objects.filter(department_id=request.user.department.id, status=2) selected_task = get_object_or_404(SubmittedToQATask, id=task_id) actual_task = selected_task.task # actual task send by the developer or team member developer_of_actual_task = selected_task.task.assigned_member # developer or team member selected_task.tester_notified = True # as member visit detail page so he is notified selected_task.save() list_of_same_tasks = SubmittedToQATask.objects.filter(task_id=actual_task.id) # print(list_of_same_tasks, '-------.....') """ CHANGING THE NOTIFICATION COUNT TO ZERO as he see the notification """ # current_user = User.objects.get(id=request.user.id) # current_user.notification_count = 0 # current_user.save() """ LIST OF NOTIFICATION ITEMS """ # user_notification_item = SubmittedToQATask.objects.filter(assigned_member=request.user, # status=1).order_by('-created_at', 'status') # print('user_notification_item: -- ', user_notification_item) # if current_user.notification_count == 0: # user_notification_item = None # If member see details of the task then team_member_notified will be true and module's status will be 3 if selected_task.status != 4: if selected_task.status != 3: if selected_task.tester_notified: selected_task.status = 2 selected_task.save() context = {'selected_task': selected_task} if request.method == "POST": bug_suggestion = request.POST.get('bug_suggestion', '') if 'submit_bug' in request.POST: if bug_suggestion.strip() == '': messages.warning(request, 'You are submitting as "fix bug" but didn\'t tell any suggestion.') return render(request, 'members/tester_task_details.html', context) else: try: # print(bug_suggestion, 'bug_suggestion') selected_task.bug = bug_suggestion selected_task.has_bug = True selected_task.status = 3 selected_task.is_verified = True selected_task.verified_at = datetime.now() selected_task.save() actual_task.status = 5 # actual task need modification as has bug actual_task.save() # if task's status=3 then other copy of the same task # which is submitted before those task's status = 3. # for task in list_of_same_tasks: # task.status = 3 # task.save() # create new task history object task_history = TaskHistory() task_history.task = actual_task task_history.description = (model_to_dict(actual_task)) task_history.status = 'Need Modification' task_history.user = developer_of_actual_task task_history.save() # setting the notification count number as task is done and send to the developer again developer_of_actual_task.notification_count += 1 developer_of_actual_task.save() messages.success(request, f"{selected_task} is send back to developer to fix bug.") except Exception as e: print('Error at tester submit bug feedback', e) else: try: # print(bug_suggestion, 'bug_suggestion') if bug_suggestion != '': # otherwise get default value selected_task.bug = bug_suggestion selected_task.has_bug = False selected_task.status = 4 selected_task.is_verified = True selected_task.verified_at = datetime.now() selected_task.save() actual_task.status = 6 # actual task is now completed as no bug # actual_task.completed_at = datetime.now() actual_task.save() # if task is completed/ verified then other copy of the same task # which is submitted before those also will be completed/verified. # for task in list_of_same_tasks: # task.status = 4 # task.save() # create new task history object task_history = TaskHistory() task_history.task = actual_task task_history.description = (model_to_dict(actual_task)) task_history.status = 'Worked Done' task_history.user = developer_of_actual_task task_history.save() # setting the notification count number as task is done and send to the developer again developer_of_actual_task.notification_count += 1 developer_of_actual_task.save() # user_notification_item = messages.success(request, f"{selected_task} is send back to developer as verified.") return redirect('tester-completed-task') except Exception as e: print('Error at tester submit feedback', e) return render(request, 'members/tester_task_details.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_tester]) def tester_running_tasks(request): if request.user.is_authenticated: running_tasks_list_of_tester = SubmittedToQATask.objects.filter(assigned_member=request.user, status=2).order_by( '-created_at', 'status', ) running_tasks_count_of_tester = running_tasks_list_of_tester.count() # print('running_tasks_list_of_tester == ', running_tasks_list_of_tester) context = {'running_tasks_list_of_tester': running_tasks_list_of_tester, 'running_tasks_count_of_tester': running_tasks_count_of_tester} return render(request, 'members/tester_running_tasks.html', context) @login_required(login_url='login') @has_access(allowed_roles=[role_tester]) def tester_completed_tasks(request): if request.user.is_authenticated: completed_tasks_list_of_tester = SubmittedToQATask.objects.filter(assigned_member=request.user, status=4).order_by( '-created_at', 'status', ) completed_tasks_count_of_tester = completed_tasks_list_of_tester.count() # print('running_tasks_list_of_tester == ', completed_tasks_list_of_tester) context = {'running_tasks_list_of_tester': completed_tasks_list_of_tester, 'completed_tasks_count_of_tester': completed_tasks_count_of_tester} return render(request, 'members/tester_completed_tasks.html', context)
33,748
33,748
0.611325
3,859
33,748
5.019435
0.066079
0.021941
0.017192
0.024781
0.695922
0.621683
0.568973
0.535209
0.50382
0.45142
0
0.006777
0.304848
33,748
1
33,748
33,748
0.818883
0.992681
0
0.350453
0
0
0.088242
0.037811
0
0
0
0
0
1
0.039275
false
0.009063
0.02719
0
0.135952
0.006042
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
30aabb6e715d7a5d13208feab88d6580cccb8208
109
py
Python
icon_picker_widget/apps.py
mik0w/django-material-icon-widget
da5e584fabe52585bc564b1680163a9f9a53d271
[ "MIT" ]
null
null
null
icon_picker_widget/apps.py
mik0w/django-material-icon-widget
da5e584fabe52585bc564b1680163a9f9a53d271
[ "MIT" ]
null
null
null
icon_picker_widget/apps.py
mik0w/django-material-icon-widget
da5e584fabe52585bc564b1680163a9f9a53d271
[ "MIT" ]
1
2021-12-11T02:03:42.000Z
2021-12-11T02:03:42.000Z
from django.apps import AppConfig class IconPickerWidgetConfig(AppConfig): name = 'icon_picker_widget'
18.166667
40
0.798165
12
109
7.083333
0.916667
0
0
0
0
0
0
0
0
0
0
0
0.137615
109
5
41
21.8
0.904255
0
0
0
0
0
0.165138
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
30b7d79508a571d5e51377188c43de83a624e2c1
204
py
Python
aiida_basis/groups/set/__init__.py
zooks97/aiida-basis
cfc3f57c9e33eebacf3fe11922fc8851df1c3c47
[ "MIT" ]
null
null
null
aiida_basis/groups/set/__init__.py
zooks97/aiida-basis
cfc3f57c9e33eebacf3fe11922fc8851df1c3c47
[ "MIT" ]
2
2021-09-21T11:28:55.000Z
2021-09-21T12:13:48.000Z
aiida_basis/groups/set/__init__.py
zooks97/aiida-basis
cfc3f57c9e33eebacf3fe11922fc8851df1c3c47
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # pylint: disable=undefined-variable """Module with group plugins to represent basis sets.""" from .basis import * from .openmx import * __all__ = (basis.__all__, openmx.__all__)
25.5
56
0.710784
26
204
5.115385
0.730769
0
0
0
0
0
0
0
0
0
0
0.005714
0.142157
204
7
57
29.142857
0.754286
0.529412
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.666667
0
0.666667
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
30c77f9a07ab066631ee29ec3aa43383a8f5d36b
89
py
Python
QAQ/webansi/apps.py
Brave01/ang
767d964505297d41edb464020781ed312ffbd862
[ "MIT" ]
1
2019-09-19T04:53:22.000Z
2019-09-19T04:53:22.000Z
QAQ/webansi/apps.py
Brave01/ang
767d964505297d41edb464020781ed312ffbd862
[ "MIT" ]
null
null
null
QAQ/webansi/apps.py
Brave01/ang
767d964505297d41edb464020781ed312ffbd862
[ "MIT" ]
1
2021-12-28T04:26:02.000Z
2021-12-28T04:26:02.000Z
from django.apps import AppConfig class WebansiConfig(AppConfig): name = 'webansi'
14.833333
33
0.752809
10
89
6.7
0.9
0
0
0
0
0
0
0
0
0
0
0
0.168539
89
5
34
17.8
0.905405
0
0
0
0
0
0.078652
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
30dcf763fa923776ad4733238959db1f1ff8a769
137
py
Python
Exareme-Docker/src/exareme/exareme-tools/madis/src/lib/colorama/__init__.py
tchamabe1979/exareme
462983e4feec7808e1fd447d02901502588a8879
[ "MIT" ]
null
null
null
Exareme-Docker/src/exareme/exareme-tools/madis/src/lib/colorama/__init__.py
tchamabe1979/exareme
462983e4feec7808e1fd447d02901502588a8879
[ "MIT" ]
null
null
null
Exareme-Docker/src/exareme/exareme-tools/madis/src/lib/colorama/__init__.py
tchamabe1979/exareme
462983e4feec7808e1fd447d02901502588a8879
[ "MIT" ]
null
null
null
from .ansi import Fore, Back, Style from .ansitowin32 import AnsiToWin32 from .initialise import init, deinit, reinit VERSION = '0.2.4'
22.833333
44
0.766423
20
137
5.25
0.75
0
0
0
0
0
0
0
0
0
0
0.059829
0.145985
137
5
45
27.4
0.837607
0
0
0
0
0
0.036496
0
0
0
0
0
0
1
0
false
0
0.75
0
0.75
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
30e5f86fbd1df731385cdfeb3fab535be78c23a3
129
py
Python
configs/__init__.py
RichardoMrMu/repvgg-xgaze
c32e6bb3b9a53848cd407ce54f8b685390f293d9
[ "MIT" ]
null
null
null
configs/__init__.py
RichardoMrMu/repvgg-xgaze
c32e6bb3b9a53848cd407ce54f8b685390f293d9
[ "MIT" ]
null
null
null
configs/__init__.py
RichardoMrMu/repvgg-xgaze
c32e6bb3b9a53848cd407ce54f8b685390f293d9
[ "MIT" ]
1
2021-08-13T05:04:43.000Z
2021-08-13T05:04:43.000Z
# -*- coding: utf-8 -*- # @Time : 2021/4/27 10:21 # @Author : RichardoMu # @File : __init__.py.py # @Software: PyCharm
25.8
29
0.55814
17
129
4
0.941176
0
0
0
0
0
0
0
0
0
0
0.122449
0.24031
129
5
30
25.8
0.571429
0.891473
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
a505cebfb43cdebd7bfb087686052267236e0a23
104
py
Python
event/Event.py
nicoale777/IdentificacionDeOrdenes
ea3eec1062168436fe06cfb4900c7fa4fdb7fe59
[ "Apache-2.0" ]
1
2020-10-15T15:40:40.000Z
2020-10-15T15:40:40.000Z
event/Event.py
nicoale777/IdentificacionDeOrdenes
ea3eec1062168436fe06cfb4900c7fa4fdb7fe59
[ "Apache-2.0" ]
null
null
null
event/Event.py
nicoale777/IdentificacionDeOrdenes
ea3eec1062168436fe06cfb4900c7fa4fdb7fe59
[ "Apache-2.0" ]
1
2020-10-15T15:35:31.000Z
2020-10-15T15:35:31.000Z
class Event: def __init__ (self, name:str, time:int): self.name=name self.time=time
20.8
44
0.605769
15
104
3.933333
0.6
0.271186
0
0
0
0
0
0
0
0
0
0
0.278846
104
4
45
26
0.786667
0
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0
0
0.5
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
4
a505f7d9ace464adabd091f0f5d0a9440dc1890b
152
py
Python
python_program.py
akatsukioshiro/Modularized_Automations
c79320fba183a38879e1bde84a9a92b36b34b852
[ "MIT" ]
null
null
null
python_program.py
akatsukioshiro/Modularized_Automations
c79320fba183a38879e1bde84a9a92b36b34b852
[ "MIT" ]
null
null
null
python_program.py
akatsukioshiro/Modularized_Automations
c79320fba183a38879e1bde84a9a92b36b34b852
[ "MIT" ]
null
null
null
#!"D:\STORE\0-Admin\Desktop\Chatbot-Osiris bkp\python.exe" import sys import subprocess subprocess.call("start cmd /k echo "+sys.argv[1], shell=True)
38
61
0.743421
25
152
4.52
0.88
0
0
0
0
0
0
0
0
0
0
0.014493
0.092105
152
4
61
38
0.804348
0.375
0
0
0
0
0.195652
0
0
0
0
0
0
1
0
true
0
0.666667
0
0.666667
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
a50641a4cfc1c95b426a9a1fa73b163c9a89b45a
1,253
py
Python
Examples/test.py
DavidNaizheZhou/RFEM_Python_Client
a5f7790b67de3423907ce10c0aa513c0a1aca47b
[ "MIT" ]
null
null
null
Examples/test.py
DavidNaizheZhou/RFEM_Python_Client
a5f7790b67de3423907ce10c0aa513c0a1aca47b
[ "MIT" ]
null
null
null
Examples/test.py
DavidNaizheZhou/RFEM_Python_Client
a5f7790b67de3423907ce10c0aa513c0a1aca47b
[ "MIT" ]
null
null
null
import sys sys.path.append(".") sys.path.append("../RFEM") sys.path.append("../UnitTests") #print(sys.path) from RFEM.enums import * from RFEM.window import * from RFEM.dataTypes import * from RFEM.initModel import * from RFEM.BasicObjects.material import * from RFEM.BasicObjects.section import * from RFEM.BasicObjects.thickness import * from RFEM.BasicObjects.node import * from RFEM.BasicObjects.line import * from RFEM.BasicObjects.member import * from RFEM.BasicObjects.surface import * from RFEM.BasicObjects.solid import * from RFEM.BasicObjects.opening import * from RFEM.BasicObjects.lineSet import * from RFEM.BasicObjects.memberSet import * from RFEM.BasicObjects.surfaceSet import * from RFEM.BasicObjects.solidSet import * from RFEM.TypesForNodes.nodalSupport import * from RFEM.TypesForMembers.memberHinge import * from RFEM.LoadCasesAndCombinations.staticAnalysisSettings import * from RFEM.LoadCasesAndCombinations.loadCase import * from RFEM.Loads.nodalLoad import * from RFEM.Loads.memberLoad import * from RFEM.Loads.surfaceLoad import * #import pytest from UnitTests import test_loads #test_loads.test_free_polygon_load() #test_loads.test_imposed_nodal_deformation() test_loads.test_imposed_line_deformation() print('Fertig!')
30.560976
66
0.815642
159
1,253
6.345912
0.289308
0.190287
0.319128
0.334985
0
0
0
0
0
0
0
0
0.093376
1,253
41
67
30.560976
0.888204
0.084597
0
0
0
0
0.023601
0
0
0
0
0
0
1
0
true
0
0.83871
0
0.83871
0.032258
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
1
0
1
0
0
0
0
4
a5170809844296d4c2110a0a46e42fde5ad1fd27
76
py
Python
evaluator/RealTime/__init__.py
CryptoRichy/OctoBot
1ca5bd2ba4b8fc09859518fcb2a62f74a1435019
[ "Apache-2.0" ]
1
2018-11-26T16:43:36.000Z
2018-11-26T16:43:36.000Z
evaluator/RealTime/__init__.py
CryptoRichy/OctoBot
1ca5bd2ba4b8fc09859518fcb2a62f74a1435019
[ "Apache-2.0" ]
null
null
null
evaluator/RealTime/__init__.py
CryptoRichy/OctoBot
1ca5bd2ba4b8fc09859518fcb2a62f74a1435019
[ "Apache-2.0" ]
null
null
null
from .realtime_evaluator import * from tentacles.Evaluator.RealTime import *
38
42
0.842105
9
76
7
0.555556
0
0
0
0
0
0
0
0
0
0
0
0.092105
76
2
42
38
0.913043
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
eb6ebb076c0bd52dbd86e7455c9e74e3fa6af5bf
61
py
Python
test_votesmart.py
AliaElKattan/python-votesmart
bb9f47563195eaab04a91a4dded00c2a8f418f2c
[ "BSD-3-Clause" ]
50
2015-07-06T10:17:51.000Z
2021-06-25T16:53:01.000Z
test_votesmart.py
AliaElKattan/python-votesmart
bb9f47563195eaab04a91a4dded00c2a8f418f2c
[ "BSD-3-Clause" ]
6
2015-05-05T21:38:05.000Z
2018-05-29T14:02:38.000Z
test_votesmart.py
AliaElKattan/python-votesmart
bb9f47563195eaab04a91a4dded00c2a8f418f2c
[ "BSD-3-Clause" ]
26
2015-07-16T09:31:16.000Z
2022-01-10T07:04:47.000Z
import doctest doctest.testfile('README.rst', verbose=False)
20.333333
45
0.803279
8
61
6.125
0.875
0
0
0
0
0
0
0
0
0
0
0
0.065574
61
2
46
30.5
0.859649
0
0
0
0
0
0.163934
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
eb6fce4b1485538e38a0ec7ca12736d096728bb9
4,528
py
Python
gen_ips.py
62726164/netscan
5124457b3dbeb77a909716726f9c3c8005e3ae89
[ "0BSD" ]
27
2020-01-13T07:16:35.000Z
2022-02-10T03:37:51.000Z
gen_ips.py
62726164/netscan
5124457b3dbeb77a909716726f9c3c8005e3ae89
[ "0BSD" ]
null
null
null
gen_ips.py
62726164/netscan
5124457b3dbeb77a909716726f9c3c8005e3ae89
[ "0BSD" ]
4
2019-12-20T07:41:08.000Z
2021-08-17T12:02:56.000Z
""" gen_ips.py - Generate a list of IPs for a few common IPv4 CIDR prefixes. There are no range or sanity checks here. I assume the user understands what an octet is and what the limits are. This is very basic. There are much better programs for this. """ import sys import time USAGE = "usage: python gen_ips.py CIDR_Prefix\nCIDR_Prefix should be 8, 16, 19, 20, 21, 22, 23 or 24." def stroke8(octet1, fp): """ generate a /8 list of IPs""" for octet2 in xrange(256): for octet3 in xrange(256): for octet4 in xrange(256): print >> fp, octet1 + "." + str(octet2) + "." + str(octet3) + "." + str(octet4) def stroke16(octet1, octet2, fp): """ generate a /16 list of IPs""" for octet3 in xrange(256): for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + str(octet3) + "." + str(octet4) def stroke19(octet1, octet2, octet3, fp): """ generate a /19 list of IPs""" for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + octet3 + "." + str(octet4) x = 0 while x < 31: x = x + 1 octet3 = int(octet3) + 1 for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + str(octet3) + "." + str(octet4) def stroke20(octet1, octet2, octet3, fp): """ generate a /20 list of IPs""" for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + octet3 + "." + str(octet4) x = 0 while x < 15: x = x + 1 octet3 = int(octet3) + 1 for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + str(octet3) + "." + str(octet4) def stroke21(octet1, octet2, octet3, fp): """ generate a /21 list of IPs""" for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + octet3 + "." + str(octet4) x = 0 while x < 7: x = x + 1 octet3 = int(octet3) + 1 for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + str(octet3) + "." + str(octet4) def stroke22(octet1, octet2, octet3, fp): """ generate a /22 list of IPs""" for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + octet3 + "." + str(octet4) x = 0 while x < 3: x = x + 1 octet3 = int(octet3) + 1 for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + str(octet3) + "." + str(octet4) def stroke23(octet1, octet2, octet3, fp): """ generate a /23 list of IPs""" for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + octet3 + "." + str(octet4) octet3 = int(octet3) + 1 for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + str(octet3) + "." + str(octet4) def stroke24(octet1, octet2, octet3, fp): """ generate a /24 list of IPs""" for octet4 in xrange(256): print >> fp, octet1 + "." + octet2 + "." + octet3 + "." + str(octet4) # main if len(sys.argv) != 2: sys.exit(USAGE) FP = open('ips_%s.txt' %time.time(), 'w') if sys.argv[1] == '8': stroke8(raw_input("Enter the first octect: "), FP) elif sys.argv[1] == '16': stroke16(raw_input("Enter the first octect: "), raw_input("Enter the second octect: "), FP) elif sys.argv[1] == '19': stroke19(raw_input("Enter the first octect: "), raw_input("Enter the second octect: "), raw_input("Enter the third octect: "), FP) elif sys.argv[1] == '20': stroke20(raw_input("Enter the first octect: "), raw_input("Enter the second octect: "), raw_input("Enter the third octect: "), FP) elif sys.argv[1] == '21': stroke21(raw_input("Enter the first octect: "), raw_input("Enter the second octect: "), raw_input("Enter the third octect: "), FP) elif sys.argv[1] == '22': stroke22(raw_input("Enter the first octect: "), raw_input("Enter the second octect: "), raw_input("Enter the third octect: "), FP) elif sys.argv[1] == '23': stroke23(raw_input("Enter the first octect: "), raw_input("Enter the second octect: "), raw_input("Enter the third octect: "), FP) elif sys.argv[1] == '24': stroke24(raw_input("Enter the first octect: "), raw_input("Enter the second octect: "), raw_input("Enter the third octect: "), FP) else: print "%s is not a supported CIDR prefix." %sys.argv[1] FP.close()
35.100775
102
0.546599
610
4,528
4.014754
0.172131
0.068599
0.111474
0.137199
0.739077
0.739077
0.634545
0.634545
0.634545
0.634545
0
0.078554
0.291519
4,528
128
103
35.375
0.68485
0.000883
0
0.565217
1
0.01087
0.177677
0.006074
0
0
0
0
0
0
null
null
0
0.021739
null
null
0.152174
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
4
eb8504d523743d7728a8907cebcf87d23468590a
366
py
Python
src/include/falconn/ffht/ffht/__init__.py
1flei/FALCONN
abe6996fa7f7c2debbd04e41e2acb564f71f370f
[ "MIT" ]
1,068
2015-12-10T18:03:11.000Z
2022-03-29T09:05:38.000Z
src/include/falconn/ffht/ffht/__init__.py
1flei/FALCONN
abe6996fa7f7c2debbd04e41e2acb564f71f370f
[ "MIT" ]
108
2015-12-10T21:14:41.000Z
2022-03-15T17:51:17.000Z
src/include/falconn/ffht/ffht/__init__.py
1flei/FALCONN
abe6996fa7f7c2debbd04e41e2acb564f71f370f
[ "MIT" ]
224
2015-12-17T02:35:21.000Z
2022-03-29T09:05:40.000Z
"""Python wrapper for FFHT. This is a Python wrapper for [FFHT](https://github.com/FALCONN-LIB/FFHT). It exposes one function, `fht`, which performs the Fast Hadamard Transform on a given one-dimensional NumPy array. To the best of our knowledge, FFHT is currently the fastest open-source implementation of *any* Fourier-like transform. """ from _ffht import fht
30.5
73
0.770492
58
366
4.844828
0.741379
0.092527
0.113879
0.142349
0
0
0
0
0
0
0
0
0.144809
366
11
74
33.272727
0.897764
0.915301
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
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
1
0
1
0
0
4
eb876842bfc4be6b3a38b2520a644e3f5baf5ecc
46
py
Python
res/public/explorer.py
ccebrecos/py-telegram-bot
b8f47da07e706fad189baaf059e9889ff932e9da
[ "Apache-2.0" ]
2
2018-03-31T11:43:57.000Z
2021-03-11T19:07:27.000Z
res/public/explorer.py
ccebrecos/py-telegram-bot
b8f47da07e706fad189baaf059e9889ff932e9da
[ "Apache-2.0" ]
null
null
null
res/public/explorer.py
ccebrecos/py-telegram-bot
b8f47da07e706fad189baaf059e9889ff932e9da
[ "Apache-2.0" ]
1
2021-03-27T19:31:39.000Z
2021-03-27T19:31:39.000Z
EXPLORER = "https://testnet.smartbit.com.au/"
23
45
0.717391
6
46
5.5
1
0
0
0
0
0
0
0
0
0
0
0
0.065217
46
1
46
46
0.767442
0
0
0
0
0
0.695652
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
eb945d88c57ecac4798ddd5df64a2a174f7aeaf3
34,205
py
Python
scripts/iclr_2018/generate_plots.py
alcinos/dps
5467db1216e9f9089376d2c71f524ced2382e4f6
[ "Apache-2.0" ]
null
null
null
scripts/iclr_2018/generate_plots.py
alcinos/dps
5467db1216e9f9089376d2c71f524ced2382e4f6
[ "Apache-2.0" ]
null
null
null
scripts/iclr_2018/generate_plots.py
alcinos/dps
5467db1216e9f9089376d2c71f524ced2382e4f6
[ "Apache-2.0" ]
null
null
null
from cycler import cycler import os import argparse import numpy as np import matplotlib.pyplot as plt from dps.hyper import extract_data_from_job from dps.utils import ( process_path, Config, sha_cache, set_clear_cache, confidence_interval, standard_error ) cache_dir = process_path('/home/eric/.cache/dps_plots') plot_dir = './plots' single_op_paths = Config() single_op_paths['sum:dps'] = 'sample_efficiency/dps_new/sum/results.zip' single_op_paths['sum:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/sum/results.zip' single_op_paths['sum:cnn'] = 'sample_efficiency/cnn/sum/exp_cnn_sum_12hours_2017_10_21_00_54_52.zip' single_op_paths['sum:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/sum/results.zip' single_op_paths['sum:rnn_pure'] = 'sample_efficiency/rnn_pure/sum/results.zip' single_op_paths['sum:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/sum/results.zip' single_op_paths['prod:dps'] = 'sample_efficiency/dps_new/prod/results.zip' single_op_paths['prod:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/prod/results.zip' single_op_paths['prod:cnn'] = 'sample_efficiency/cnn/prod/exp_cnn_prod_12hours_2017_10_21_00_55_50.zip' single_op_paths['prod:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/prod/results.zip' single_op_paths['prod:rnn_pure'] = 'sample_efficiency/rnn_pure/prod/results.zip' single_op_paths['prod:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/prod/results.zip' single_op_paths['max:dps'] = 'sample_efficiency/dps_new/max/results.zip' single_op_paths['max:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/max/results.zip' single_op_paths['max:cnn'] = 'sample_efficiency/cnn/max/exp_cnn_max_12hours_2017_10_21_00_56_53.zip' single_op_paths['max:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/max/results.zip' single_op_paths['max:rnn_pure'] = 'sample_efficiency/rnn_pure/max/results.zip' single_op_paths['max:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/max/results.zip' single_op_paths['min:dps'] = 'sample_efficiency/dps_new/min/results.zip' single_op_paths['min:cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/min/results.zip' single_op_paths['min:cnn'] = 'sample_efficiency/cnn/min/exp_cnn_min_12hours_2017_10_21_00_57_32.zip' single_op_paths['min:cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/min/results.zip' single_op_paths['min:rnn_pure'] = 'sample_efficiency/rnn_pure/min/results.zip' single_op_paths['min:rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/min/results.zip' combined_paths = Config() combined_paths['dps'] = 'sample_efficiency/dps_new/combined/results.zip' combined_paths['cnn_pretrained'] = 'sample_efficiency/cnn_pretrained/combined/results.zip' combined_paths['cnn'] = 'sample_efficiency/cnn/combined/exp_cnn_all_2017_10_23_01_22_58.zip' combined_paths['cnn_pretrained_pure'] = 'sample_efficiency/cnn_pretrained_pure/combined/results.zip' combined_paths['rnn_pure'] = 'sample_efficiency/rnn_pure/combined/results.zip' combined_paths['rnn_pretrained_pure'] = 'sample_efficiency/rnn_pretrained_pure/combined/results.zip' parity_paths = Config() parity_paths['B:dps'] = 'curriculum_parity/dps_new/B/results.zip' parity_paths['B:cnn'] = 'curriculum_parity/cnn/A/exp_final_cnn_parity_A_2017_10_26_23_08_20.zip' parity_paths['B:cnn_pretrained'] = 'curriculum_parity/cnn_pretrained/B/results.zip' parity_paths['C:dps'] = 'curriculum_parity/dps_new/C/results.zip' parity_paths['C:cnn'] = 'curriculum_parity/cnn/B/exp_final_cnn_parity_B_2017_10_26_23_07_11.zip' parity_paths['C:cnn_pretrained'] = 'curriculum_parity/cnn_pretrained/C/results.zip' size_paths = Config() size_paths["A:dps"] = 'curriculum_size/dps_new/A/results.zip' size_paths["A:cnn"] = 'curriculum_size/cnn/A/results.zip' size_paths['A:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/A/results.zip' size_paths['A:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/A/results.zip' size_paths['A:rnn_pure'] = 'curriculum_size/rnn_pure/A/results.zip' size_paths['A:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/A/results.zip' size_paths["B:dps"] = 'curriculum_size/dps_new/B/results.zip' size_paths["B:cnn"] = 'curriculum_size/cnn/B/results.zip' size_paths['B:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/B/results.zip' size_paths['B:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/B/results.zip' size_paths['B:rnn_pure'] = 'curriculum_size/rnn_pure/B/results.zip' size_paths['B:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/B/results.zip' size_paths["C:dps"] = 'curriculum_size/dps_new/C/results.zip' size_paths["C:cnn"] = 'curriculum_size/cnn/C/results.zip' size_paths['C:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/C/results.zip' size_paths['C:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/C/results.zip' size_paths['C:rnn_pure'] = 'curriculum_size/rnn_pure/C/results.zip' size_paths['C:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/C/results.zip' size_paths["D:dps"] = 'curriculum_size/dps_new/D/results.zip' size_paths["D:cnn"] = 'curriculum_size/cnn/D/results.zip' size_paths['D:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/D/results.zip' size_paths['D:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/D/results.zip' size_paths['D:rnn_pure'] = 'curriculum_size/rnn_pure/D/results.zip' size_paths['D:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/D/results.zip' size_paths["E:dps"] = 'curriculum_size/dps_new/E/results.zip' size_paths["E:cnn"] = 'curriculum_size/cnn/E/results.zip' size_paths['E:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/E/results.zip' size_paths['E:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/E/results.zip' size_paths['E:rnn_pure'] = 'curriculum_size/rnn_pure/E/results.zip' size_paths['E:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/E/results.zip' size_paths["F:dps"] = 'curriculum_size/dps_new/F/results.zip' size_paths["F:cnn"] = 'curriculum_size/cnn/F/results.zip' size_paths['F:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/F/results.zip' size_paths['F:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/F/results.zip' size_paths['F:rnn_pure'] = 'curriculum_size/rnn_pure/F/results.zip' size_paths['F:rnn_pretrained_pure'] = 'curriculum_size/rnn_pretrained_pure/F/results.zip' size_paths['G:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/G/results.zip' size_paths['G:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/G/results.zip' size_paths['H:cnn_pretrained'] = 'curriculum_size/cnn_pretrained/H/results.zip' size_paths['G:cnn_pretrained_pure'] = 'curriculum_size/cnn_pretrained_pure/G/results.zip' op_paths = Config() op_paths['B:dps'] = 'curriculum_op/dps_new/B/results.zip' op_paths['B:cnn'] = 'curriculum_op/cnn/A/exp_final_cnn_op_A_2017_10_26_23_08_20.zip' op_paths['B:cnn_pretrained'] = 'curriculum_op/cnn_pretrained/B/results.zip' op_paths['C:dps'] = 'curriculum_op/dps_new/C/results.zip' op_paths['C:cnn'] = 'curriculum_op/cnn/B/exp_final_cnn_op_B_2017_10_26_23_07_11.zip' op_paths['C:cnn_pretrained'] = 'curriculum_op/cnn_pretrained/C/results.zip' ablation_paths = Config() ablation_paths['full_interface'] = 'sample_efficiency/dps/combined/results.zip' ablation_paths['no_modules'] = 'ablations/no_modules/results.zip' ablation_paths['no_transformations'] = 'ablations/no_transformations/results.zip' ablation_paths['no_classifiers'] = 'ablations/no_classifiers/results.zip' def std_dev(ys): y_upper = y_lower = [_y.std() for _y in ys] return y_upper, y_lower def ci95(ys): conf_int = [confidence_interval(_y.values, 0.95) for _y in ys] y = [_y.mean() for _y in ys] y_lower = y - np.array([ci[0] for ci in conf_int]) y_upper = np.array([ci[1] for ci in conf_int]) - y return y_upper, y_lower def std_err(ys): y_upper = y_lower = [standard_error(_y.values) for _y in ys] return y_upper, y_lower spread_measures = {func.__name__: func for func in [std_dev, ci95, std_err]} def test_01_loss(r): return 100 * r['test_01_loss'] @sha_cache(cache_dir) def _extract_cnn_data(f, n_controller_units, spread_measure, y_func, groupby='n_train'): flat = False if isinstance(n_controller_units, int): n_controller_units = [n_controller_units] flat = True if isinstance(groupby, str): groupby = [groupby] data = {} df = extract_data_from_job(f, ['n_controller_units', 'curriculum:-1:do_train'] + groupby) df.loc[df['curriculum:-1:do_train'] == False, 'curriculum:-1:n_train'] = 0 groups = df.groupby('n_controller_units') for i, (k, _df) in enumerate(groups): if k in n_controller_units: _groups = _df.groupby(groupby) values = [g for g in _groups] x = [v[0] for v in values] ys = [y_func(v[1]) for v in values] y = [_y.mean() for _y in ys] y_upper, y_lower = spread_measures[spread_measure](ys) data[k] = np.stack([x, y, y_upper, y_lower]) if flat: return next(iter(data.values())) return data @sha_cache(cache_dir) def _extract_rl_data(f, spread_measure, y_func): data = {} df = extract_data_from_job(f, 'n_train') df.loc[df['total_steps'] == 0, 'n_train'] = 0 groups = df.groupby('n_train') values = list(groups) x = [v[0] for v in values] ys = [y_func(v[1]) for v in values] y = [_y.mean() for _y in ys] y_upper, y_lower = spread_measures[spread_measure](ys) data = np.stack([x, y, y_upper, y_lower]) return data def gen_sample_efficiency_single_op(): fig, axes = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(10, 7)) fig.text(0.52, 0.01, '# Training Examples', ha='center', fontsize=12) fig.text(0.01, 0.51, '% Test Error', va='center', rotation='vertical', fontsize=12) cnn_n_train = [32, 128, 512] spread_measure = 'std_err' pp = [ dict(title='Sum', key='sum'), dict(title='Product', key='prod'), dict(title='Maximum', key='max'), dict(title='Minimum', key='min'), ] for i, (ax, p) in enumerate(zip(axes.flatten(), pp)): label_order = [] x, y, *yerr = _extract_rl_data(single_op_paths[p['key']]['dps'], spread_measure, test_01_loss) label = 'RL + Interface' ax.errorbar(x, y, yerr=yerr, label=label, ls='--') label_order.append(label) data = _extract_cnn_data( single_op_paths[p['key']]['cnn_pretrained'], cnn_n_train, spread_measure, test_01_loss, 'n_train') for k, v in data.items(): x, y, *yerr = v label = "CNN Pretrained - {} hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) label_order.append(label) data = _extract_cnn_data( single_op_paths[p['key']]['cnn_pretrained_pure'], cnn_n_train, spread_measure, test_01_loss, 'n_train') for k, v in data.items(): x, y, *yerr = v label = "CNN Pretrained Pure - {} hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) label_order.append(label) data = _extract_cnn_data( single_op_paths[p['key']]['rnn_pure'], 128, spread_measure, test_01_loss, 'n_train') x, y, *yerr = data label = "RNN - 128 hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) label_order.append(label) data = _extract_cnn_data( single_op_paths[p['key']]['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'n_train') x, y, *yerr = data label = "RNN Pretrained - 128 hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) label_order.append(label) ax.set_title(p['title']) ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) ax.set_xticks(x) legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())} ordered_handles = [legend_handles[l] for l in label_order] ax.legend(ordered_handles, label_order, loc='best', ncol=1) plt.subplots_adjust( left=0.07, bottom=0.08, right=0.98, top=0.95, wspace=0.05, hspace=0.15) fig.savefig(os.path.join(plot_dir, 'sample_efficiency.pdf')) return fig def gen_sample_efficiency_combined(): fig = plt.figure(figsize=(5, 3.5)) ax = plt.gca() cnn_n_train = [32, 128, 512] spread_measure = 'std_err' label_order = [] x, y, *yerr = _extract_rl_data(combined_paths['dps'], spread_measure, test_01_loss) label = 'RL + Interface' ax.errorbar(x, y, yerr=yerr, label=label, ls='--') label_order.append(label) data = _extract_cnn_data(combined_paths['cnn_pretrained'], cnn_n_train, spread_measure, test_01_loss, 'n_train') for k, v in data.items(): x, y, *yerr = v label = "CNN - {} hidden units".format(k) label_order.append(label) ax.errorbar(x, y, yerr=yerr, label=label) data = _extract_cnn_data( combined_paths['cnn_pretrained_pure'], cnn_n_train, spread_measure, test_01_loss, 'n_train') for k, v in data.items(): x, y, *yerr = v label = "CNN Pretrained Pure - {} hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) label_order.append(label) data = _extract_cnn_data( combined_paths['rnn_pure'], 128, spread_measure, test_01_loss, 'n_train') x, y, *yerr = data label = "RNN - 128 hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) label_order.append(label) data = _extract_cnn_data( combined_paths['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'n_train') x, y, *yerr = data label = "RNN Pretrained - 128 hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) label_order.append(label) ax.set_ylabel('% Test Error', fontsize=12) ax.set_xlabel('# Training Examples', fontsize=12) ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) ax.set_xticks(x) legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())} ordered_handles = [legend_handles[l] for l in label_order] ax.legend(ordered_handles, label_order, loc='best', ncol=1, fontsize=8) plt.subplots_adjust(left=0.16, bottom=0.15, right=0.97, top=0.96) fig.savefig(os.path.join(plot_dir, 'sample_efficiency_combined.pdf')) return fig def gen_super_sample_efficiency(): fig, _ = plt.subplots(2, 4, sharex=True, sharey=True, figsize=(10.7, 5.5)) fig.text(0.52, 0.01, '# Training Examples', ha='center', fontsize=12) fig.text(0.01, 0.51, '% Test Error', va='center', rotation='vertical', fontsize=12) shape = (2, 4) indi_axes = [ plt.subplot2grid(shape, (0, 0)), plt.subplot2grid(shape, (0, 1)), plt.subplot2grid(shape, (1, 0)), plt.subplot2grid(shape, (1, 1)) ] combined_ax = plt.subplot2grid(shape, (0, 2), colspan=2, rowspan=2) pp = [ dict(title='Sum', key='sum'), dict(title='Product', key='prod'), dict(title='Maximum', key='max'), dict(title='Minimum', key='min'), ] cnn_n_train = [32, 128, 512] spread_measure = 'std_err' for i, (ax, p) in enumerate(zip(indi_axes, pp)): x, y, *yerr = _extract_rl_data(single_op_paths[p['key']]['dps'], spread_measure, test_01_loss) label = 'RL + Interface' ax.errorbar(x, y, yerr=yerr, label=label, ls='--') cnn_sum_data = _extract_cnn_data(single_op_paths[p['key']]['cnn'], cnn_n_train, spread_measure, test_01_loss, 'n_train') for k, v in cnn_sum_data.items(): x, y, *yerr = v label = "CNN - {} hidden units".format(k) ax.errorbar(x, y, yerr=yerr, label=label) ax.set_title(p['title']) ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) # Combined combined_ax.set_title("Combined Task") combined_ax.tick_params(axis='both', labelsize=14) combined_ax.set_ylim((0.0, 100.0)) combined_ax.set_xscale('log', basex=2) label_order = [] x, y, *yerr = _extract_rl_data(combined_paths['dps'], spread_measure, test_01_loss) label = 'RL + Interface' combined_ax.errorbar(x, y, yerr=yerr, label=label, ls='--') label_order.append(label) cnn_all_data = _extract_cnn_data(combined_paths['cnn'], cnn_n_train, spread_measure, test_01_loss, 'n_train') for k, v in cnn_all_data.items(): x, y, *yerr = v label = "CNN - {} hidden units".format(k) label_order.append(label) combined_ax.errorbar(x, y, yerr=yerr, label=label) legend_handles = {l: h for h, l in zip(*combined_ax.get_legend_handles_labels())} ordered_handles = [legend_handles[l] for l in label_order] combined_ax.legend(ordered_handles, label_order, loc='best', ncol=1) plt.subplots_adjust( left=0.09, bottom=0.11, right=0.97, top=0.95, wspace=0.13, hspace=0.20) fig.savefig(os.path.join(plot_dir, 'sample_efficiency_super.pdf')) return fig def gen_size_curriculum(): fig, axes = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5)) spread_measure = 'std_err' fig.text(0.52, 0.01, '# Training Examples on Test Task', ha='center', fontsize=12) # ******************************************************************************** ax = axes[0] xticks = set() label_order = [] x, y, *yerr = _extract_rl_data(size_paths['A']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) xticks |= set(x) rl_colour = line.get_c() x, y, *yerr = _extract_rl_data(size_paths['D']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour) label_order.append(label) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['A']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) xticks |= set(x) cnn_colour = line.get_c() x, y, *yerr = _extract_cnn_data(size_paths['D']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour) label_order.append(label) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['A']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN Pretrained Pure - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) xticks |= set(x) cnn_pretrained_pure_colour = line.get_c() x, y, *yerr = _extract_cnn_data(size_paths['D']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN Pretrained Pure - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_pretrained_pure_colour) label_order.append(label) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['A']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'RNN Pure - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) xticks |= set(x) rnn_pure_colour = line.get_c() x, y, *yerr = _extract_cnn_data(size_paths['D']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'RNN Pure - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rnn_pure_colour) label_order.append(label) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['A']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'RNN Pretrained Pure - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) xticks |= set(x) rnn_pretrained_pure_colour = line.get_c() x, y, *yerr = _extract_cnn_data(size_paths['D']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'RNN Pretrained Pure - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rnn_pretrained_pure_colour) label_order.append(label) xticks |= set(x) if not args.paper: x, y, *yerr = _extract_cnn_data(size_paths['G']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - Alternate Curric 1' ax.errorbar(x, y, yerr=yerr, label=label, ls='-.', c=cnn_colour) label_order.append(label) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['H']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - Alternate Curric 2' ax.errorbar(x, y, yerr=yerr, label=label, ls=':', c=cnn_colour) label_order.append(label) xticks |= set(x) legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())} ordered_handles = [legend_handles[l] for l in label_order] ax.legend(ordered_handles, label_order, loc='best', ncol=1) ax.set_title('3x3, 2-3 digits') ax.set_ylabel('% Test Error', fontsize=12) ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('symlog', basex=2) ax.set_xticks(sorted(xticks)) # ******************************************************************************** ax = axes[1] xticks = set() x, y, *yerr = _extract_rl_data(size_paths['B']['dps'], spread_measure, test_01_loss) ax.errorbar(x, y, yerr=yerr, ls='-', c=rl_colour) xticks |= set(x) x, y, *yerr = _extract_rl_data(size_paths['E']['dps'], spread_measure, test_01_loss) ax.errorbar(x, y, yerr=yerr, ls='--', c=rl_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['B']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['E']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['B']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_pretrained_pure_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['E']['cnn_pretrained_pure'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_pretrained_pure_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['B']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='-', c=rnn_pure_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['E']['rnn_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='--', c=rnn_pure_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['B']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='-', c=rnn_pretrained_pure_colour) xticks |= set(x) x, y, *yerr = _extract_cnn_data(size_paths['E']['rnn_pretrained_pure'], 128, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='--', c=rnn_pretrained_pure_colour) xticks |= set(x) ax.set_title('3x3, 4 digits') ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('symlog', basex=2) ax.set_xticks(sorted(xticks)) # ******************************************************************************** # ax = axes[2] # xticks = set() # x, y, *yerr = _extract_rl_data(size_paths['C']['dps'], spread_measure, test_01_loss) # ax.errorbar(x, y, yerr=yerr, ls='-', c=rl_colour) # xticks |= set(x) # x, y, *yerr = _extract_rl_data(size_paths['F']['dps'], spread_measure, test_01_loss) # ax.errorbar(x, y, yerr=yerr, ls='--', c=rl_colour) # xticks |= set(x) # x, y, *yerr = _extract_cnn_data(size_paths['C']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') # ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_colour) # xticks |= set(x) # x, y, *yerr = _extract_cnn_data(size_paths['F']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') # ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_colour) # xticks |= set(x) # ax.set_title('3x3, 5 digits') # ax.tick_params(axis='both', labelsize=14) # ax.set_ylim((0.0, 100.0)) # ax.set_xscale('symlog', basex=2) # ax.set_xticks(sorted(xticks)) plt.subplots_adjust( left=0.09, bottom=0.11, right=0.97, top=0.95, wspace=0.13, hspace=0.20) fig.savefig(os.path.join(plot_dir, 'size_curriculum.pdf')) return fig def gen_parity_curriculum(): fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, figsize=(10, 5)) spread_measure = 'std_err' fig.text(0.52, 0.01, '# Training Examples on Test Task', ha='center', fontsize=12) ax.set_ylabel('% Test Error', fontsize=12) ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) label_order = [] x, y, *yerr = _extract_rl_data(parity_paths['B']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) rl_colour = line.get_c() x, y, *yerr = _extract_rl_data(parity_paths['C']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour) label_order.append(label) x, y, *yerr = _extract_cnn_data(parity_paths['B']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) cnn_colour = line.get_c() x, y, *yerr = _extract_cnn_data(parity_paths['C']['cnn_pretrained'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour) label_order.append(label) legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())} ordered_handles = [legend_handles[l] for l in label_order] ax.legend(ordered_handles, label_order, loc='best', ncol=1) ax.set_ylim((0.0, 100.0)) ax.set_xscale('symlog', basex=2) plt.subplots_adjust(left=0.09, bottom=0.11, right=0.97, top=0.95, wspace=0.13, hspace=0.20) fig.savefig(os.path.join(plot_dir, 'parity_curriculum.pdf')) return fig def gen_curric(): fig, axes = plt.subplots(1, 3, sharex=True, sharey=True, figsize=(10, 3.7)) spread_measure = 'std_err' fig.text(0.52, 0.01, '# Training Examples on Test Task', ha='center', fontsize=12) ax = axes[0] ax.set_title('3x3, 2-3 digits') ax.set_ylabel('% Test Error', fontsize=12) ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) label_order = [] x, y, *yerr = _extract_rl_data(size_paths['A']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) rl_colour = line.get_c() x, y, *yerr = _extract_rl_data(size_paths['C']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour) label_order.append(label) x, y, *yerr = _extract_cnn_data(size_paths['A']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) cnn_colour = line.get_c() x, y, *yerr = _extract_cnn_data(size_paths['C']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour) label_order.append(label) ax = axes[1] ax.set_title('3x3, 4 digits') ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) x, y, *yerr = _extract_rl_data(size_paths['B']['dps'], spread_measure, test_01_loss) ax.errorbar(x, y, yerr=yerr, ls='-', c=rl_colour) x, y, *yerr = _extract_rl_data(size_paths['F']['dps'], spread_measure, test_01_loss) ax.errorbar(x, y, yerr=yerr, ls='--', c=rl_colour) x, y, *yerr = _extract_cnn_data(size_paths['B']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='-', c=cnn_colour) x, y, *yerr = _extract_cnn_data(size_paths['F']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') ax.errorbar(x, y, yerr=yerr, ls='--', c=cnn_colour) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) ax = axes[2] ax.set_title('even -> odd') ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) label_order = [] x, y, *yerr = _extract_rl_data(parity_paths['A']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) rl_colour = line.get_c() x, y, *yerr = _extract_rl_data(parity_paths['C']['dps'], spread_measure, test_01_loss) label = 'RL + Interface - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=rl_colour) label_order.append(label) x, y, *yerr = _extract_cnn_data(parity_paths['A']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - With Curric' line, _, _ = ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) cnn_colour = line.get_c() x, y, *yerr = _extract_cnn_data(parity_paths['C']['cnn'], 512, spread_measure, test_01_loss, 'curriculum:-1:n_train') label = 'CNN - No Curric' ax.errorbar(x, y, yerr=yerr, label=label, ls='--', c=cnn_colour) label_order.append(label) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())} ordered_handles = [legend_handles[l] for l in label_order] ax.legend(ordered_handles, label_order, loc='best', ncol=1, fontsize=8) plt.subplots_adjust( left=0.08, bottom=0.15, right=0.98, top=0.91, wspace=0.13, hspace=0.20) fig.savefig(os.path.join(plot_dir, 'curriculum.pdf')) return fig def gen_ablations(): plt.figure(figsize=(5, 3.5)) ax = plt.gca() ax.set_ylabel('% Test Error', fontsize=12) ax.set_xlabel('# Training Examples', fontsize=12) ax.tick_params(axis='both', labelsize=14) ax.set_ylim((0.0, 100.0)) ax.set_xscale('log', basex=2) spread_measure = 'std_err' label_order = [] x, y, *yerr = _extract_rl_data(ablation_paths['full_interface'], spread_measure, lambda r: 100 * r['test_loss']) label = 'Full Interface' ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) x, y, *yerr = _extract_rl_data(ablation_paths['no_modules'], spread_measure, test_01_loss) label = 'No Modules' ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) x, y, *yerr = _extract_rl_data(ablation_paths['no_transformations'], spread_measure, test_01_loss) label = 'No Transformations' ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) x, y, *yerr = _extract_rl_data(ablation_paths['no_classifiers'], spread_measure, test_01_loss) label = 'No Classifiers' ax.errorbar(x, y, yerr=yerr, label=label, ls='-') label_order.append(label) legend_handles = {l: h for h, l in zip(*ax.get_legend_handles_labels())} ordered_handles = [legend_handles[l] for l in label_order] ax.legend(ordered_handles, label_order, loc='best', ncol=1, fontsize=8) plt.subplots_adjust(left=0.16, bottom=0.15, right=0.97, top=0.96) fig.savefig(os.path.join(plot_dir, 'ablations.pdf')) return fig if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("plots", nargs='+') parser.add_argument("--style", default="bmh") parser.add_argument("--no-block", action="store_true") parser.add_argument("--show", action="store_true") parser.add_argument("--clear-cache", action="store_true") parser.add_argument("--paper", action="store_true") args = parser.parse_args() plt.rc('lines', linewidth=1) color_cycle = ['tab:blue', 'tab:orange', 'tab:green', 'tab:brown'] os.makedirs(plot_dir, exist_ok=True) if args.clear_cache: set_clear_cache(True) with plt.style.context(args.style): plt.rc('axes', prop_cycle=(cycler('color', color_cycle))) funcs = { "single_op": gen_sample_efficiency_single_op, "combined": gen_sample_efficiency_combined, "super": gen_super_sample_efficiency, "size": gen_size_curriculum, "parity": gen_parity_curriculum, "curriculum": gen_curric, "ablations": gen_ablations, } for name, do_plot in funcs.items(): if name in args.plots: fig = do_plot() if args.show: plt.show(block=not args.no_block)
40.383707
135
0.673995
5,293
34,205
4.074438
0.054978
0.011314
0.033386
0.033386
0.867106
0.819021
0.764954
0.726607
0.620746
0.595243
0
0.029386
0.161321
34,205
846
136
40.431442
0.722383
0.033212
0
0.528642
0
0
0.258708
0.157361
0
0
0
0
0
1
0.021277
false
0
0.011457
0.001637
0.055646
0
0
0
0
null
0
0
0
1
1
1
1
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
4
ccdccac561d82e48af3b228ad740d0bc33b81dba
248
py
Python
services/__init__.py
ongzhixian/python-apps
11a0d0ce656a7e9d7bdff18dd29feaa2bb436ae6
[ "MIT" ]
null
null
null
services/__init__.py
ongzhixian/python-apps
11a0d0ce656a7e9d7bdff18dd29feaa2bb436ae6
[ "MIT" ]
null
null
null
services/__init__.py
ongzhixian/python-apps
11a0d0ce656a7e9d7bdff18dd29feaa2bb436ae6
[ "MIT" ]
null
null
null
################################################################################ # Define package composition ################################################################################ #__all__ = ["site", "url_dump", "palindrome", "phaser"]
41.333333
80
0.237903
9
248
6
1
0
0
0
0
0
0
0
0
0
0
0
0.052419
248
5
81
49.6
0.229787
0.322581
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
ccf2668370707c69d2224a2635f28aed842bd9be
260
py
Python
language/python/modules/inspect/inspect_module.py
bigfoolliu/liu_aistuff
aa661d37c05c257ee293285dd0868fb7e8227628
[ "MIT" ]
1
2019-11-25T07:23:42.000Z
2019-11-25T07:23:42.000Z
language/python/modules/inspect/inspect_module.py
bigfoolliu/liu_aistuff
aa661d37c05c257ee293285dd0868fb7e8227628
[ "MIT" ]
13
2020-01-07T16:09:47.000Z
2022-03-02T12:51:44.000Z
language/python/modules/inspect/inspect_module.py
bigfoolliu/liu_aistuff
aa661d37c05c257ee293285dd0868fb7e8227628
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ inspect模块 用于收集python对象的信息,可以获取类或函数的参数的信息,源码,解析堆栈,对对象进行类型检查等等 https://www.cnblogs.com/yaohong/p/8874154.html 主要作用: 1.对是否是模块、框架、函数进行类型检查 2.获取源码 3.获取类或者函数的参数信息 4.解析堆栈 """ import inspect
12.380952
50
0.734615
36
260
5.305556
0.972222
0
0
0
0
0
0
0
0
0
0
0.055794
0.103846
260
20
51
13
0.763949
0.873077
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
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
1
0
1
0
0
4
ccf89bb038f7544a20d01045c91c8cb4d8dbee96
13,370
py
Python
tests/test.py
OpenITI/oimdp
9cb0dfb298b90d85f08e248633369c0c3c494c65
[ "MIT" ]
1
2022-02-21T11:55:39.000Z
2022-02-21T11:55:39.000Z
tests/test.py
OpenITI/oimdp
9cb0dfb298b90d85f08e248633369c0c3c494c65
[ "MIT" ]
7
2022-02-05T09:04:20.000Z
2022-02-06T15:31:28.000Z
tests/test.py
OpenITI/oimdp
9cb0dfb298b90d85f08e248633369c0c3c494c65
[ "MIT" ]
1
2021-07-09T06:23:26.000Z
2021-07-09T06:23:26.000Z
import sys import os sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) import unittest import oimdp from oimdp.structures import Age, BioOrEvent, Date, DictionaryUnit, Document, DoxographicalItem, Editorial, Hemistich, Hukm, Isnad, Line, Matn, Milestone, MorphologicalPattern, NamedEntity, OpenTagAuto, OpenTagUser, PageNumber, Paragraph, Riwayat, RouteDist, RouteFrom, RouteOrDistance, RouteTowa, SectionHeader, TextPart, Verse class TestStringMethods(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestStringMethods, self).__init__(*args, **kwargs) root = os.path.dirname(__file__) filepath = os.path.join( root, "test.md" ) test_file = open(filepath, "r") self.text = test_file.read() test_file.close() self.parsed = oimdp.parse(self.text) def generic_check(self, datatype, location: int, type: str, property: str = ""): content = self.parsed.content[location] self.assertTrue(isinstance(content, datatype)) if (len(property) > 0): self.assertEqual(getattr(content, property), type) def test_magic(self): self.assertEqual(str(self.parsed.magic_value), "######OpenITI#") def test_meta(self): self.assertEqual(str(self.parsed.simple_metadata[1]), "000.SortField :: Shamela_0023833") self.assertEqual(str(self.parsed.simple_metadata[-1]), "999.MiscINFO :: NODATA") def test_document(self): self.assertTrue(isinstance(self.parsed, Document)) def test_page(self): self.assertTrue(isinstance(self.parsed.content[1].parts[1], PageNumber)) self.assertEqual(str(self.parsed.content[1].parts[1]), "Vol. 00, p. 000") def test_bio_or_event(self): def check(location: int, type: str): self.generic_check(BioOrEvent, location, type, "be_type") check(2, "man") self.assertEqual(str(self.parsed.content[3].parts[0]), " أبو عمرو ابن العلاء واسمه") check(8, "man") self.assertEqual(str(self.parsed.content[9].parts[0]), " أبو عمرو ابن العلاء واسمه") check(14, "wom") self.assertEqual(str(self.parsed.content[15].parts[0]), " 1729 - صمعة بنت أحمد بن محمد بن عبيد الله الرئيس النيسابورية من ولد عثمان بن") check(17, "wom") self.assertEqual(str(self.parsed.content[18].parts[0]), " 1729 - صمعة بنت أحمد بن محمد بن عبيد الله الرئيس النيسابورية من ولد عثمان بن") check(20, "ref") self.assertEqual(str(self.parsed.content[21].parts[0]), " [a cross-reference, for both men and women]") check(23, "ref") self.assertEqual(str(self.parsed.content[24].parts[0]), " [a cross-reference, for both men and women]") check(26, "names") self.assertEqual(str(self.parsed.content[27].parts[0]), " -وفيها ولد: (@)(@@) المحدث عفيف ") check(29, "names") self.assertEqual(str(self.parsed.content[30].parts[0]), " -وفيها ولد: (@)(@@) المحدث عفيف ") check(32, "events") check(34, "event") check(49, "man") def test_dictionary_unit(self): def check(location: int, type: str): self.generic_check(DictionaryUnit, location, type, "dic_type") check(36, "nis") check(38, "top") check(40, "lex") check(42, "bib") def test_doxographical(self): def check(location: int, type: str): self.generic_check(DoxographicalItem, location, type, "dox_type") check(44, "pos") check(46, "sec") def test_editorial(self): self.assertTrue(isinstance(self.parsed.content[48], Editorial)) def test_morphological(self): self.assertTrue(isinstance(self.parsed.content[50], MorphologicalPattern)) self.assertTrue(self.parsed.content[50].category, "onomastic") def test_paragraph(self): self.assertTrue(isinstance(self.parsed.content[51], Paragraph)) def test_line(self): self.assertTrue(isinstance(self.parsed.content[52], Line)) self.assertTrue(isinstance(self.parsed.content[53], Line)) ## Check line parts on 53 def test_milestone(self): self.assertTrue(isinstance(self.parsed.content[67], Line)) self.assertTrue(isinstance(self.parsed.content[67].parts[1], Milestone)) def test_named_entities(self): self.assertTrue(isinstance(self.parsed.content[53].parts[1], Date)) self.assertEqual(self.parsed.content[53].parts[1].date_type, "death") self.assertTrue(isinstance(self.parsed.content[68].parts[1], Date)) self.assertEqual(self.parsed.content[68].parts[1].date_type, "birth") self.assertEqual(self.parsed.content[68].parts[1].value, "597") self.assertTrue(isinstance(self.parsed.content[69].parts[1], Date)) self.assertEqual(self.parsed.content[69].parts[1].date_type, "other") self.assertEqual(self.parsed.content[69].parts[1].value, "597") self.assertTrue(isinstance(self.parsed.content[70].parts[1], Age)) self.assertEqual(self.parsed.content[70].parts[1].value, "059") self.assertTrue(isinstance(self.parsed.content[71].parts[1], NamedEntity)) self.assertEqual(self.parsed.content[71].parts[1].ne_type, "soc") self.assertEqual(self.parsed.content[71].parts[1].prefix, 0) self.assertEqual(self.parsed.content[71].parts[1].extent, 2) self.assertEqual(self.parsed.content[71].parts[1].text, 'معمر شيخ: ') self.assertEqual(self.parsed.content[71].parts[2].text, 'واسط.. 1"018: نزيل: ') self.assertTrue(isinstance(self.parsed.content[72].parts[1], NamedEntity)) self.assertEqual(self.parsed.content[72].parts[1].ne_type, "soc") self.assertEqual(self.parsed.content[72].parts[1].prefix, 1) self.assertEqual(self.parsed.content[72].parts[1].extent, 3) self.assertTrue(isinstance(self.parsed.content[73].parts[1], NamedEntity)) self.assertEqual(self.parsed.content[73].parts[1].ne_type, "top") self.assertEqual(self.parsed.content[73].parts[1].prefix, 0) self.assertEqual(self.parsed.content[73].parts[1].extent, 2) self.assertTrue(isinstance(self.parsed.content[74].parts[1], NamedEntity)) self.assertEqual(self.parsed.content[74].parts[1].ne_type, "top") self.assertEqual(self.parsed.content[74].parts[1].prefix, 1) self.assertEqual(self.parsed.content[74].parts[1].extent, 3) self.assertTrue(isinstance(self.parsed.content[75].parts[1], NamedEntity)) self.assertEqual(self.parsed.content[75].parts[1].ne_type, "per") self.assertEqual(self.parsed.content[75].parts[1].prefix, 0) self.assertEqual(self.parsed.content[75].parts[1].extent, 2) self.assertTrue(isinstance(self.parsed.content[76].parts[1], NamedEntity)) self.assertEqual(self.parsed.content[76].parts[1].ne_type, "per") self.assertEqual(self.parsed.content[76].parts[1].prefix, 1) self.assertEqual(self.parsed.content[76].parts[1].extent, 3) self.assertTrue(isinstance(self.parsed.content[77].parts[1], NamedEntity)) self.assertEqual(self.parsed.content[77].parts[1].ne_type, "src") self.assertEqual(self.parsed.content[77].parts[1].prefix, 0) self.assertEqual(self.parsed.content[77].parts[1].extent, 3) def test_opentags(self): self.assertTrue(isinstance(self.parsed.content[79].parts[1], OpenTagUser)) self.assertEqual(self.parsed.content[79].parts[1].user, "USER") self.assertEqual(self.parsed.content[79].parts[1].t_type, "CAT") self.assertEqual(self.parsed.content[79].parts[1].t_subtype, "SUBCAT") self.assertEqual(self.parsed.content[79].parts[1].t_subsubtype, "SUBSUBCAT") def test_opentagsauto(self): self.assertTrue(isinstance(self.parsed.content[81].parts[1], OpenTagAuto)) self.assertEqual(self.parsed.content[81].parts[1].resp, "RES") self.assertEqual(self.parsed.content[81].parts[1].t_type, "TYPE") self.assertEqual(self.parsed.content[81].parts[1].category, "Category") self.assertEqual(self.parsed.content[81].parts[1].review, "fr") def test_riwayat(self): self.assertTrue(isinstance(self.parsed.content[54], Riwayat)) self.assertTrue(isinstance(self.parsed.content[55], Line)) self.assertTrue(isinstance(self.parsed.content[55].parts[0], Isnad)) self.assertTrue(isinstance(self.parsed.content[55].parts[1], TextPart)) self.assertEqual(self.parsed.content[55].parts[1].orig, " this section contains isnād ") self.assertTrue(isinstance(self.parsed.content[55].parts[2], Matn)) self.assertTrue(isinstance(self.parsed.content[55].parts[3], TextPart)) self.assertEqual(self.parsed.content[55].parts[3].orig, " this section") self.assertTrue(isinstance(self.parsed.content[56], Line)) self.assertTrue(isinstance(self.parsed.content[56].parts[0], TextPart)) self.assertEqual(self.parsed.content[56].parts[0].orig, " contains matn ") self.assertTrue(isinstance(self.parsed.content[56].parts[1], Hukm)) self.assertTrue(isinstance(self.parsed.content[56].parts[2], TextPart)) self.assertEqual(self.parsed.content[56].parts[2].orig, " this section contains ḥukm .") def test_route_or_distance(self): self.assertTrue(isinstance(self.parsed.content[57], RouteOrDistance)) self.assertTrue(isinstance(self.parsed.content[57].parts[0], RouteFrom)) self.assertTrue(isinstance(self.parsed.content[57].parts[1], TextPart)) self.assertEqual(self.parsed.content[57].parts[1].orig, " toponym ") self.assertTrue(isinstance(self.parsed.content[57].parts[2], RouteTowa)) self.assertTrue(isinstance(self.parsed.content[57].parts[3], TextPart)) self.assertEqual(self.parsed.content[57].parts[3].orig, " toponym ") self.assertTrue(isinstance(self.parsed.content[57].parts[4], RouteDist)) self.assertTrue(isinstance(self.parsed.content[57].parts[5], TextPart)) self.assertEqual(self.parsed.content[57].parts[5].orig, " distance_as_recorded") def test_section_headers(self): self.assertTrue(isinstance(self.parsed.content[58], SectionHeader)) self.assertEqual(self.parsed.content[58].value, " ذكر سرد النسب الزكي من محمد صلى الله عليه وآله وسلم، إلى آدم عليه السلام") self.assertEqual(self.parsed.content[58].level, 1) self.assertTrue(isinstance(self.parsed.content[59], SectionHeader)) self.assertEqual(self.parsed.content[59].value, " (نهج ابن هشام في هذا الكتاب) :") self.assertEqual(self.parsed.content[59].level, 2) self.assertTrue(isinstance(self.parsed.content[60], SectionHeader)) self.assertEqual(self.parsed.content[60].value, " (نهج ابن هشام في هذا الكتاب) :") self.assertEqual(self.parsed.content[60].level, 3) self.assertTrue(isinstance(self.parsed.content[61], SectionHeader)) self.assertEqual(self.parsed.content[61].value, " (نهج ابن هشام في هذا الكتاب) :") self.assertEqual(self.parsed.content[61].level, 4) self.assertTrue(isinstance(self.parsed.content[62], SectionHeader)) self.assertEqual(self.parsed.content[62].value, " (نهج ابن هشام في هذا الكتاب) :") self.assertEqual(self.parsed.content[62].level, 5) def test_verse(self): self.assertTrue(isinstance(self.parsed.content[63], Verse)) self.assertTrue(isinstance(self.parsed.content[63].parts[0], TextPart)) self.assertEqual(self.parsed.content[63].parts[0].orig, " وجمع العرب تحت لواء الرسول محمد عليه الصلاة ") self.assertTrue(isinstance(self.parsed.content[63].parts[1], Hemistich)) self.assertEqual(self.parsed.content[63].parts[1].orig, "%~%") self.assertTrue(isinstance(self.parsed.content[63].parts[2], TextPart)) self.assertEqual(self.parsed.content[63].parts[2].orig, " والسلام، وما يضاف إلى ذلك من") self.assertTrue(isinstance(self.parsed.content[64], Verse)) self.assertTrue(isinstance(self.parsed.content[64].parts[0], TextPart)) self.assertEqual(self.parsed.content[64].parts[0].orig, " ") self.assertTrue(isinstance(self.parsed.content[64].parts[1], Hemistich)) self.assertEqual(self.parsed.content[64].parts[1].orig, "%~%") self.assertTrue(isinstance(self.parsed.content[64].parts[2], TextPart)) self.assertEqual(self.parsed.content[64].parts[2].orig, " وجمع العرب تحت لواء الرسول محمد عليه الصلاة والسلام، وما يضاف إلى ذلك من") self.assertTrue(isinstance(self.parsed.content[65], Verse)) self.assertTrue(isinstance(self.parsed.content[65].parts[1], Hemistich)) self.assertEqual(self.parsed.content[65].parts[1].orig, "%~%") self.assertTrue(isinstance(self.parsed.content[65].parts[0], TextPart)) self.assertEqual(self.parsed.content[65].parts[0].orig, " جمع العرب تحت لواء الرسول محمد عليه الصلاة والسلام، وما يضاف إلى ذلك من") # TODO: ADMINISTRATIVE REGIONS! if __name__ == "__main__": unittest.main()
50.643939
328
0.667838
1,719
13,370
5.150087
0.164631
0.149102
0.243872
0.175082
0.767311
0.764825
0.689823
0.537219
0.259008
0.180165
0
0.040084
0.178983
13,370
263
329
50.836502
0.766056
0.003889
0
0.052632
0
0
0.091483
0
0
0
0
0.003802
0.631579
1
0.114833
false
0
0.023923
0
0.143541
0
0
0
0
null
0
1
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
4
692e40a83ff38cf27e376a103fbca00be8f8d0df
76
py
Python
seasonedParser/exceptions.py
KevinMidboe/seasonMover
380c4a02f48679c0204ecf1a5807718b93f2ff19
[ "MIT" ]
null
null
null
seasonedParser/exceptions.py
KevinMidboe/seasonMover
380c4a02f48679c0204ecf1a5807718b93f2ff19
[ "MIT" ]
9
2017-09-29T11:35:37.000Z
2020-02-19T09:34:15.000Z
seasonedParser/exceptions.py
KevinMidboe/seasonedParser
380c4a02f48679c0204ecf1a5807718b93f2ff19
[ "MIT" ]
null
null
null
#!/usr/bin/env python3.6 class InsufficientNameError(Exception): pass
12.666667
39
0.736842
9
76
6.222222
1
0
0
0
0
0
0
0
0
0
0
0.030769
0.144737
76
5
40
15.2
0.830769
0.302632
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.5
0
0
0.5
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
1
0
0
0
0
0
4
694d0580c884b425cc7776054d3543b1c96ba389
1,367
py
Python
src/sima/workflow/blueprints/workflowrouting.py
SINTEF/simapy
650b8c2f15503dad98e2bfc0d0788509593822c7
[ "MIT" ]
null
null
null
src/sima/workflow/blueprints/workflowrouting.py
SINTEF/simapy
650b8c2f15503dad98e2bfc0d0788509593822c7
[ "MIT" ]
null
null
null
src/sima/workflow/blueprints/workflowrouting.py
SINTEF/simapy
650b8c2f15503dad98e2bfc0d0788509593822c7
[ "MIT" ]
null
null
null
# # Generated with WorkflowRoutingBlueprint from dmt.blueprint import Blueprint from dmt.dimension import Dimension from dmt.attribute import Attribute from dmt.enum_attribute import EnumAttribute from dmt.blueprint_attribute import BlueprintAttribute from sima.sima.blueprints.moao import MOAOBlueprint class WorkflowRoutingBlueprint(MOAOBlueprint): """""" def __init__(self, name="WorkflowRouting", package_path="sima/workflow", description=""): super().__init__(name,package_path,description) self.attributes.append(Attribute("name","string","",default="")) self.attributes.append(Attribute("description","string","",default="")) self.attributes.append(Attribute("_id","string","",default="")) self.attributes.append(BlueprintAttribute("scriptableValues","sima/sima/ScriptableValue","",True,Dimension("*"))) self.attributes.append(BlueprintAttribute("workflowSetInputs","sima/workflow/WorkflowSetItem","",True,Dimension("*"))) self.attributes.append(BlueprintAttribute("workflowInputVariations","sima/workflow/WorkflowInputVariationItem","",True,Dimension("*"))) self.attributes.append(BlueprintAttribute("inputs","sima/workflow/WorkflowLinkItem","",True,Dimension("*"))) self.attributes.append(BlueprintAttribute("outputs","sima/workflow/WorkflowLinkItem","",True,Dimension("*")))
62.136364
143
0.752012
127
1,367
7.992126
0.330709
0.110345
0.157635
0.187192
0.384236
0.283744
0
0
0
0
0
0
0.093636
1,367
22
144
62.136364
0.819209
0.02853
0
0
1
0
0.22138
0.134193
0
0
0
0
0
1
0.058824
false
0
0.352941
0
0.470588
0.529412
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
1
0
0
1
0
4
c632525ae113464408e447d8f5b00eef62e1b0cb
91
py
Python
backend/teaching/apps.py
cesko-digital/zacni-uc
281c56aec5509d5dd8bbbd60f054ffcd9156609e
[ "MIT" ]
4
2021-02-26T09:28:14.000Z
2021-07-08T19:21:57.000Z
backend/teaching/apps.py
cesko-digital/zacni-uc
281c56aec5509d5dd8bbbd60f054ffcd9156609e
[ "MIT" ]
35
2021-01-27T08:38:59.000Z
2021-12-13T19:42:38.000Z
backend/teaching/apps.py
cesko-digital/zacni-uc
281c56aec5509d5dd8bbbd60f054ffcd9156609e
[ "MIT" ]
5
2021-01-21T21:35:42.000Z
2022-01-06T10:07:58.000Z
from django.apps import AppConfig class TeachingConfig(AppConfig): name = "teaching"
15.166667
33
0.758242
10
91
6.9
0.9
0
0
0
0
0
0
0
0
0
0
0
0.164835
91
5
34
18.2
0.907895
0
0
0
0
0
0.087912
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
c641ff7d61a3df9db62deda7543004d7e7b824f2
42
py
Python
macihara/__init__.py
harasimowiczmaciek/test
0b6899f8944acdee3bdf45448847bde328a9a95f
[ "MIT" ]
null
null
null
macihara/__init__.py
harasimowiczmaciek/test
0b6899f8944acdee3bdf45448847bde328a9a95f
[ "MIT" ]
null
null
null
macihara/__init__.py
harasimowiczmaciek/test
0b6899f8944acdee3bdf45448847bde328a9a95f
[ "MIT" ]
null
null
null
from dodaj import dodaj name = "macihara"
14
23
0.761905
6
42
5.333333
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.166667
42
2
24
21
0.914286
0
0
0
0
0
0.190476
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
d67bad03c4372e1679128c5595a0c2419571273a
31
py
Python
software_testing/__init__.py
rafaelleinio/software-testing
0cb9e95b65675121360a0e47ad127666c6c5ae7d
[ "MIT" ]
1
2021-02-28T02:12:35.000Z
2021-02-28T02:12:35.000Z
software_testing/__init__.py
rafaelleinio/software-testing
0cb9e95b65675121360a0e47ad127666c6c5ae7d
[ "MIT" ]
null
null
null
software_testing/__init__.py
rafaelleinio/software-testing
0cb9e95b65675121360a0e47ad127666c6c5ae7d
[ "MIT" ]
null
null
null
"""Software testing module."""
15.5
30
0.677419
3
31
7
1
0
0
0
0
0
0
0
0
0
0
0
0.096774
31
1
31
31
0.75
0.774194
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
d69d3736a48dc1da2286126c41b8262985f53416
284
py
Python
declare_qtquick/typehint/prop_hint.py
likianta/declare-qtquick
93c2ce49d841ccdeb0272085c5f731139927f0d7
[ "MIT" ]
3
2021-11-02T03:45:27.000Z
2022-03-27T05:33:36.000Z
declare_qtquick/typehint/prop_hint.py
likianta/declare-qtquick
93c2ce49d841ccdeb0272085c5f731139927f0d7
[ "MIT" ]
null
null
null
declare_qtquick/typehint/prop_hint.py
likianta/declare-qtquick
93c2ce49d841ccdeb0272085c5f731139927f0d7
[ "MIT" ]
null
null
null
try: from typing import * if __name__ == '__main__': from declare_qtquick.properties.basic_properties import * from declare_qtquick.properties.group_properties import * from declare_qtquick.widgets.api import * except Exception as e: raise e
25.818182
65
0.697183
33
284
5.606061
0.575758
0.178378
0.291892
0.302703
0.367568
0
0
0
0
0
0
0
0.242958
284
10
66
28.4
0.860465
0
0
0
0
0
0.028169
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
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
1
0
1
0
0
0
0
4
d6a0b9394a9599ee65ea6f46e4b0027bfe0269e2
100
py
Python
telemetry/clients/__init__.py
trevorgrayson/telemetry
efeca1b2062f40a2557f2c030dc687f546f3c60b
[ "MIT" ]
3
2020-03-20T20:04:37.000Z
2021-08-23T20:11:10.000Z
telemetry/clients/__init__.py
trevorgrayson/telemetry
efeca1b2062f40a2557f2c030dc687f546f3c60b
[ "MIT" ]
2
2019-06-10T08:02:05.000Z
2019-06-10T08:02:22.000Z
telemetry/clients/__init__.py
trevorgrayson/telemetry
efeca1b2062f40a2557f2c030dc687f546f3c60b
[ "MIT" ]
null
null
null
from .default import Default from .slack import SlackTelemeter from .statsd_ import StatsdTelemeter
25
36
0.85
12
100
7
0.583333
0
0
0
0
0
0
0
0
0
0
0
0.12
100
3
37
33.333333
0.954545
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
d6bfdc10088c83f5f3776dca641e9cb46c672b8f
779
py
Python
verify/__init__.py
drsteve/PyForecastTools
b4179931945547a218555fc0e84e4142fa614059
[ "BSD-3-Clause" ]
27
2018-07-05T16:36:35.000Z
2022-03-12T09:14:52.000Z
verify/__init__.py
drsteve/PyForecastTools
b4179931945547a218555fc0e84e4142fa614059
[ "BSD-3-Clause" ]
12
2018-09-27T00:50:44.000Z
2021-09-16T00:15:41.000Z
verify/__init__.py
drsteve/PyForecastTools
b4179931945547a218555fc0e84e4142fa614059
[ "BSD-3-Clause" ]
9
2018-09-24T14:13:18.000Z
2022-03-12T09:14:55.000Z
"""Module containing verification and performance metrics With the exception of the ContingencyNxN and Contingency2x2 classes, the inputs for all metrics are assumed to be array-like and 1D. Bad values are assumed to be stored as NaN and these are excluded in metric calculations. With the exception of the ContingencyNxN and Contingency2x2 classes, the inputs for all metrics are assumed to be array-like and 1D. Bad values are assumed to be stored as NaN and these are excluded in metric calculations. Author: Steve Morley Institution: Los Alamos National Laboratory Contact: smorley@lanl.gov Los Alamos National Laboratory Copyright (c) 2017, Los Alamos National Security, LLC All rights reserved. """ from .metrics import * from .categorical import * from . import plot
32.458333
68
0.804878
118
779
5.313559
0.474576
0.063796
0.076555
0.089314
0.580542
0.580542
0.580542
0.580542
0.580542
0.580542
0
0.015244
0.157895
779
23
69
33.869565
0.940549
0.901155
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
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
1
0
1
0
0
4
d6ece4575cd8e67c2e39bfddb2190ecea876d0a7
179
py
Python
bot/database/connection.py
TupaBan-Dev/jdan734-bot
891238591477e81ab8bda3f29bb4bc10424f1588
[ "MIT" ]
null
null
null
bot/database/connection.py
TupaBan-Dev/jdan734-bot
891238591477e81ab8bda3f29bb4bc10424f1588
[ "MIT" ]
null
null
null
bot/database/connection.py
TupaBan-Dev/jdan734-bot
891238591477e81ab8bda3f29bb4bc10424f1588
[ "MIT" ]
null
null
null
from peewee_async import Manager from ..config import DB_PATH from .lib.async_sqlite import SqliteDatabase, onefor, get_count db = SqliteDatabase(DB_PATH) manager = Manager(db)
22.375
63
0.810056
26
179
5.384615
0.538462
0.085714
0
0
0
0
0
0
0
0
0
0
0.122905
179
8
64
22.375
0.89172
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.6
0
0.6
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
d6f763692b1fc19299d6aa76bdb399e3495058e3
65
py
Python
examples/Hello.py
dgisolfi/pycal
038d00439f1fa2b42c6476915b0a38ce41e5d25f
[ "MIT" ]
null
null
null
examples/Hello.py
dgisolfi/pycal
038d00439f1fa2b42c6476915b0a38ce41e5d25f
[ "MIT" ]
null
null
null
examples/Hello.py
dgisolfi/pycal
038d00439f1fa2b42c6476915b0a38ce41e5d25f
[ "MIT" ]
null
null
null
#!/usr/bin/env python Program := HelloWorld print('Hello World!')
21.666667
21
0.723077
9
65
5.222222
1
0
0
0
0
0
0
0
0
0
0
0
0.092308
65
3
22
21.666667
0.79661
0.307692
0
0
0
0
0.266667
0
0
0
0
0
0
0
null
null
0
0
null
null
0.5
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
1
0
4
ba3491df0b256f2bc2b0b8c7eb4e4a9ca0e7369f
2,503
py
Python
testsuite/filterwidth-reg/run.py
LongerVision/OpenShadingLanguage
30d2a4a089c5c9d521b27519329c205763dfe483
[ "BSD-3-Clause" ]
1,105
2015-01-02T20:47:19.000Z
2021-01-25T13:20:56.000Z
testsuite/filterwidth-reg/run.py
LongerVision/OpenShadingLanguage
30d2a4a089c5c9d521b27519329c205763dfe483
[ "BSD-3-Clause" ]
696
2015-01-07T23:42:08.000Z
2021-01-25T03:55:08.000Z
testsuite/filterwidth-reg/run.py
LongerVision/OpenShadingLanguage
30d2a4a089c5c9d521b27519329c205763dfe483
[ "BSD-3-Clause" ]
248
2015-01-05T13:41:28.000Z
2021-01-24T23:29:55.000Z
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_u_float -od uint8 -o op fw_u_float.tif "\ "-o mop mfw_u_float.tif") command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_u_point -od uint8 -o op fw_u_point.tif") command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_u_vector -od uint8 -o op fw_u_vector.tif") outputs.append ("fw_u_float.tif") outputs.append ("mfw_u_float.tif") outputs.append ("fw_u_point.tif") outputs.append ("fw_u_vector.tif") command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_v_float -od uint8 -o op fw_v_float.tif") command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_v_point -od uint8 -o op fw_v_point.tif") command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_v_vector -od uint8 -o op fw_v_vector.tif") outputs.append ("fw_v_float.tif") outputs.append ("fw_v_point.tif") outputs.append ("fw_v_vector.tif") command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_v_dvector -od uint8 -o op fw_v_dvector.tif "\ "-o dxop dx_fw_v_dvector.tif -o dyop dy_fw_v_dvector.tif "\ "-o mop m_fw_v_dvector.tif "\ "-o mdxop dx_m_fw_v_dvector.tif -o mdyop dy_m_fw_v_dvector.tif") outputs.append ("fw_v_dvector.tif") outputs.append ("dx_fw_v_dvector.tif") outputs.append ("dy_fw_v_dvector.tif") outputs.append ("m_fw_v_dvector.tif") outputs.append ("dx_m_fw_v_dvector.tif") outputs.append ("dy_m_fw_v_dvector.tif") command += testshade("--vary_udxdy --vary_vdxdy --vary_pdxdy -g 32 32 test_filterwidth_v_dfloat -od uint8 -o op fw_v_dfloat.tif "\ "-o dxop dx_fw_v_dfloat.tif -o dyop dy_fw_v_dfloat.tif "\ "-o mop m_fw_v_dfloat.tif "\ "-o mdxop dx_m_fw_v_dfloat.tif -o mdyop dy_m_fw_v_dfloat.tif") outputs.append ("fw_v_dfloat.tif") outputs.append ("dx_fw_v_dfloat.tif") outputs.append ("dy_fw_v_dfloat.tif") outputs.append ("m_fw_v_dfloat.tif") outputs.append ("dx_m_fw_v_dfloat.tif") outputs.append ("dy_m_fw_v_dfloat.tif") # expect a few LSB failures failthresh = 0.008 failpercent = 3
49.078431
132
0.718738
425
2,503
3.875294
0.155294
0.054645
0.184578
0.094718
0.857316
0.731633
0.547662
0.343048
0.343048
0.343048
0
0.021822
0.157811
2,503
50
133
50.06
0.759488
0.083899
0
0
0
0
0.639703
0.122868
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
1
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
ba7d6d87f70c0be3463e4fa9012b0b95a2fc5797
647
py
Python
src/hed_utils/support/os_type.py
Hrissimir/hed_utils
22e340f2f0637b999a67cf8ff201c044c93597a1
[ "MIT" ]
null
null
null
src/hed_utils/support/os_type.py
Hrissimir/hed_utils
22e340f2f0637b999a67cf8ff201c044c93597a1
[ "MIT" ]
1
2021-07-26T04:16:58.000Z
2021-07-26T04:16:58.000Z
src/hed_utils/support/os_type.py
Hrissimir/hed_utils
22e340f2f0637b999a67cf8ff201c044c93597a1
[ "MIT" ]
null
null
null
import platform WINDOWS = "Windows" LINUX = "Linux" MAC_OS = "MacOS" UNKNOWN = "Unknown" def is_64bit() -> bool: return ("64bit" in platform.architecture()) or ("64" in platform.uname().machine) def is_linux() -> bool: return "linux" in platform.uname().system.lower() def is_mac() -> bool: return platform.uname().system.lower() in ("darwin", "macosx", "macos") def is_windows() -> bool: return "windows" in platform.uname().system.lower() def get_current(): if is_linux(): return LINUX elif is_mac(): return MAC_OS elif is_windows(): return WINDOWS else: return UNKNOWN
19.029412
85
0.630603
83
647
4.795181
0.337349
0.050251
0.113065
0.180905
0.145729
0.145729
0
0
0
0
0
0.011928
0.222566
647
33
86
19.606061
0.779324
0
0
0
0
0
0.092736
0
0
0
0
0
0
1
0.227273
false
0
0.045455
0.181818
0.636364
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
1
1
0
0
4
ba9ee23615d667e6404868cd063640abffac57cc
452
py
Python
Learning/CodeWars/Python/7kyu_Birthday_I-Cake.py
aliasfoxkde/snippets
bb6dcc6597316ef9c88611f526935059451c3b5a
[ "MIT" ]
null
null
null
Learning/CodeWars/Python/7kyu_Birthday_I-Cake.py
aliasfoxkde/snippets
bb6dcc6597316ef9c88611f526935059451c3b5a
[ "MIT" ]
null
null
null
Learning/CodeWars/Python/7kyu_Birthday_I-Cake.py
aliasfoxkde/snippets
bb6dcc6597316ef9c88611f526935059451c3b5a
[ "MIT" ]
null
null
null
# See: https://www.codewars.com/kata/5805ed25c2799821cb000005 ''' # Long version: def cake(candles,debris): y = 0 for i, c in enumerate(debris): if i % 2 == 1: y += ord(c)-ord('a')+1 else: y += ord(c) if y > 0.7 * candles: return "Fire!" return "That was close!" ''' # Compact version def cake(candles,debris): return ['That was close!','Fire!'][candles<=sum(map(ord, debris))]
23.789474
70
0.54646
62
452
3.983871
0.564516
0.080972
0.11336
0.17004
0.218623
0
0
0
0
0
0
0.076923
0.280973
452
19
70
23.789474
0.683077
0.75885
0
0
0
0
0.196078
0
0
0
0
0
0
1
0.5
false
0
0
0.5
1
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
1
1
0
0
4
bac7b1973436eb367f30e6be9f61e7c0dfb10d18
113,265
py
Python
adsk/cam.py
DannoPeters/adsk
3b328ebbc8ea0292ccfa33327f93c978e10cf88d
[ "MIT" ]
1
2022-03-16T01:01:57.000Z
2022-03-16T01:01:57.000Z
adsk/cam.py
DannoPeters/adsk
3b328ebbc8ea0292ccfa33327f93c978e10cf88d
[ "MIT" ]
null
null
null
adsk/cam.py
DannoPeters/adsk
3b328ebbc8ea0292ccfa33327f93c978e10cf88d
[ "MIT" ]
null
null
null
# This file is automatically generated for code intellisense only. # It does not reflect the actual implementation. from __future__ import annotations from . import core from . import fusion class InspectionPointState(): """ Summarize state of measured inspection point. Compares the deviation from the nominal position, or the projected position (if using projection), to the contact position relative to the upper or lower tolerances. Further information can be found in the online help """ def __init__(self): pass WithinTolerance = 0 AboveTolerance = 1 BelowTolerance = 2 Unprojected = 3 class LibraryLocation(): """ List of locations representing folders in the library dialogs. """ def __init__(self): pass Local = 0 Cloud = 1 Network = 2 OnlineSamples = 3 External = 4 class MachineAxisTypes(): """ List of machine axis types for MachineAxis """ def __init__(self): pass LinearMachineAxisType = 0 RotaryMachineAxisType = 1 class MachinePartTypes(): """ List of part types for MachinePart """ def __init__(self): pass BasicMachinePartType = 0 AxisMachinePartType = 1 ToolAttachmentMachinePartType = 2 FixtureAttachmentMachinePartType = 3 class MachineTemplate(): """ List of the machine templates to create a machine from. """ def __init__(self): pass GenericLathe = 0 Generic3Axis = 1 Generic4Axis = 2 Generic5AxisHeadHead = 3 Generic5AxisHeadTable = 4 Generic5AxisTableTable = 5 class OperationStates(): """ The possible states of an operation """ def __init__(self): pass IsValidOperationState = 0 IsInvalidOperationState = 1 SuppressedOperationState = 2 NoToolpathOperationState = 3 class OperationStrategyTypes(): """ The valid options for the Strategy Type of an operation. """ def __init__(self): pass AdaptiveClearing2D = 0 Pocket2D = 1 Face = 2 Contour2D = 3 Slot = 4 Trace = 5 Thread = 6 Bore = 7 Circular = 8 Engrave = 9 AdaptiveClearing = 10 PocketClearing = 11 Parallel = 12 Contour = 13 Ramp = 14 Horizontal = 15 Pencil = 16 Scallop = 17 Spiral = 18 Radial = 19 MorphedSpiral = 20 Projection = 21 Drilling = 22 Jet2D = 23 TurningChamfer = 24 TurningFace = 25 TurningGroove = 26 TurningPart = 27 TurningProfile = 28 TurningProfileGroove = 29 TurningStockTransfer = 30 TurningThread = 31 SteepAndShallow = 32 Flow = 33 RotaryFinishing = 34 Chamfer2D = 35 Morph = 36 MultiAxisContour = 37 MultiAxisMorph = 38 RestFinishing = 39 Swarf = 40 SurfaceInspection = 41 ManualInspection = 42 ProbeWCS = 43 ProbeGeometry = 44 PartAlignment = 45 PathMeasure = 46 ManualMeasure = 47 class OperationTypes(): """ The valid options for the Operation Type of a Setup. """ def __init__(self): pass MillingOperation = 0 TurningOperation = 1 JetOperation = 2 AdditiveOperation = 3 class PostOutputUnitOptions(): """ List of the valid options for the outputUnit property on a PostProcessInput object . """ def __init__(self): pass DocumentUnitsOutput = 0 InchesOutput = 1 MillimetersOutput = 2 class SetupChangeEventType(): """ List of setup change event types. """ def __init__(self): pass Arbitrary = 0 PrintSettingSelection = 1 class SetupSheetFormats(): """ List of the formats to choose from when generating setup sheets """ def __init__(self): pass HTMLFormat = 0 ExcelFormat = 1 class CAMExportManager(core.Base): """ Export manager used to export the setup's models in one of the formats defined the the ExportOptions objects. The export is currently restricted to additive setups only and the availability of the export option and its settings depends on the chosen machine. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMExportManager: return CAMExportManager() def execute(self, exportOptions: CAMExportOptions) -> bool: """ Executes an export based on the export options """ return bool() def createFormlabsOptions(self) -> CAMFormlabsExportOptions: """ Creates a new Formlabs export option. """ return CAMFormlabsExportOptions() def create3MFOptions(self) -> CAM3MFExportOptions: """ Creates a new 3MF export option. """ return CAM3MFExportOptions() class CAMExportOptions(core.Base): """ Parent class for all ExportOptions objects giving access to the setup and file name used for the export. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMExportOptions: return CAMExportOptions() @property def fullFilename(self) -> str: """ The file we want to export to. Needs to contain a valid path, as no intermediate folders are created. """ return str() @fullFilename.setter def fullFilename(self, value: str): """ The file we want to export to. Needs to contain a valid path, as no intermediate folders are created. """ pass @property def exportObject(self) -> core.Base: """ The export object we want to export. Depending on the actual export option, this might be geometry, an operation or a setup. """ return core.Base() @exportObject.setter def exportObject(self, value: core.Base): """ The export object we want to export. Depending on the actual export option, this might be geometry, an operation or a setup. """ pass class CAMFolders(core.Base): """ Collection that provides access to the folders within an existing setup, folder or pattern. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMFolders: return CAMFolders() def item(self, index: int) -> CAMFolder: """ Function that returns the specified folder using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return CAMFolder() def itemByName(self, name: str) -> CAMFolder: """ Returns the folder with the specified name (as appears in the browser). name : The name (as it appears in the browser) of the folder. Returns the specified folder or null in the case where there is no folder with the specified name. """ return CAMFolder() def itemByOperationId(self, id: int) -> CAMFolder: """ Returns the folder with the specified operation id. id : The id of the folder. Returns the specified folder or null in the case where there is no folder with the specified operation id. """ return CAMFolder() @property def count(self) -> int: """ The number of items in the collection. """ return int() class CAMInspectionResults(core.Base): """ Collection that provides access to the Measures in a results folder. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMInspectionResults: return CAMInspectionResults() def item(self, index: int) -> CAMMeasure: """ Function that returns the specified measure using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return CAMMeasure() def itemByName(self, name: str) -> CAMMeasure: """ Returns the measure with the specified name (as appears in the browser). name : The name (as it appears in the browser) of the measure. Returns the specified measure or null in the case where there is no measure with the specified name. """ return CAMMeasure() @property def count(self) -> int: """ The number of measures in the collection. """ return int() class CAMLibraryManager(core.Base): """ CAMLibraryManager provides access to properties related to various libraries in the Fusion 360 Manufacture workspace, such as the post library and machine library. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMLibraryManager: return CAMLibraryManager() @property def fusion360PostFolder(self) -> str: """ Gets the absolute path to the folder containing Fusion 360 posts. Fusion 360 posts appear in the post library under the Fusion 360 tab. """ return str() @property def localPostFolder(self) -> str: """ Gets the absolute path to the folder containing local posts. Local posts appear in post library under the local tab. """ return str() @property def fusion360MachineFolder(self) -> str: """ Gets the absolute path to the folder containing Fusion 360 machines. Fusion 360 machines appear in the machine library under the Fusion 360 tab. """ return str() @property def localMachineFolder(self) -> str: """ Gets the absolute path to the folder containing local machines. Local Machines appear in machine library under the local tab. """ return str() @property def networkMachineFolder(self) -> str: """ Gets the absolute path to the folder containing network machines. Network machines appear in the machine library under the network tab. """ return str() class CAMManager(core.Base): """ This singleton object provides access to application-level events and properties that relate to the CAM (Manufacture) workspace in Fusion 360. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMManager: return CAMManager() @staticmethod def get() -> CAMManager: """ Access to the root CAMManager object. Return the root CAMManager object or null if it failed. """ return CAMManager() @property def libraryManager(self) -> CAMLibraryManager: """ CAMLibraryManager provides access to properties related to various libraries in the Fusion 360 Manufacture workspace, such as the post library and machine library. Return a CAMLibraryManager object or null if it failed. """ return CAMLibraryManager() @property def postEnginePath(self) -> str: """ Gets the absolute path to the post engine (post.exe) installed with Fusion 360. """ return str() @property def networkMachineIntegrationManager(self) -> NetworkMachineIntegrationManager: """ NetworkMachineIntegrationManager provides access to properties and events needed to integrate addins into the 'Find network machines' dialog, which enables users to add machine configurations representing machines on the network to their machine library. Return a NetworkMachineIntegrationManager object or null if it failed. """ return NetworkMachineIntegrationManager() class CAMMeasure(core.Base): """ Object that represents a Measure folder. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMMeasure: return CAMMeasure() @property def inspectionPathResults(self) -> InspectionPathResults: """ Access all the surface inspection results from a measure return a collection of surface inspection results from a measure or null if none found """ return InspectionPathResults() class CAMParameter(core.Base): """ Base class for representing parameter of an operation. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMParameter: return CAMParameter() @property def name(self) -> str: """ Gets the name (internal name) of the parameter. """ return str() @property def title(self) -> str: """ Returns the title of this parameter as seen in the user interface. This title is localized and can change based on the current language """ return str() @property def expression(self) -> str: """ Gets and sets the value expression of the parameter. """ return str() @expression.setter def expression(self, value: str): """ Gets and sets the value expression of the parameter. """ pass @property def isEnabled(self) -> bool: """ Gets if this parameter is enabled. Some parameters are enabled/disabled depending on the values set for other parameters. """ return bool() @property def error(self) -> str: """ Returns a message corresponding to any active error associated with the value of this parameter. """ return str() @property def warning(self) -> str: """ Returns a message corresponding to any active warning associated with the value of this parameter. """ return str() @property def isEditable(self) -> bool: """ Returns whether or not the parameter's expression or value can be modified. """ return bool() @property def value(self) -> ParameterValue: """ Returns an object that allows you to get and set the value associated with the parameter. Within CAM operations, floating point values (via FloatParameterValue) are returned and set using a standardized set of "internal" units, rather than using the document units. The units used depend on the type of parameter. For reference, the units used are: Length - centimeters (cm) Angle - radians (rad) Linear velocity - millimeters/minute (mm/min) Rotational velocity - revolutions per minute (rpm) Time - seconds (s) Weight - kilograms (kg) Power - Watts (W) Flow rate - liters/minute (l/min) Area - square centimeters (cm²) Volume - cubic centimeters (cm³) Temperature - degrees celsius (C) """ return ParameterValue() class CAMParameters(core.Base): """ Collection that provides access to the parameters of an existing operation. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMParameters: return CAMParameters() def item(self, index: int) -> CAMParameter: """ Function that returns the specified parameter using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return CAMParameter() def itemByName(self, internalName: str) -> CAMParameter: """ Returns the parameter of the specified id (internal name). internalName : The id (internal name) of the parameter. Returns the specified parameter or null in the case where there is no parameter with the specified id. """ return CAMParameter() @property def count(self) -> int: """ The number of items in the collection. """ return int() class CAMPatterns(core.Base): """ Collection that provides access to the patterns within an existing setup, folder or pattern. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMPatterns: return CAMPatterns() def item(self, index: int) -> CAMPattern: """ Function that returns the specified pattern using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return CAMPattern() def itemByName(self, name: str) -> CAMPattern: """ Returns the pattern with the specified name (as appears in the browser). name : The name (as it appears in the browser) of the pattern. Returns the specified pattern or null in the case where there is no pattern with the specified name. """ return CAMPattern() def itemByOperationId(self, id: int) -> CAMPattern: """ Returns the pattern with the specified operation id. id : The id of the pattern. Returns the specified pattern or null in the case where there is no pattern with the specified operation id. """ return CAMPattern() @property def count(self) -> int: """ The number of items in the collection. """ return int() class ChildOperationList(core.Base): """ Provides access to the collection of child operations, folders and patterns of an existing setup. """ def __init__(self): pass @staticmethod def cast(arg) -> ChildOperationList: return ChildOperationList() def item(self, index: int) -> core.Base: """ Returns the specified item using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return core.Base() def itemByName(self, name: str) -> core.Base: """ Returns the operation, folder or pattern with the specified name (the name seen in the browser). name : The name of the operation, folder or pattern as seen in the browser. Returns the specified item or null in the case where there is no item with the specified name. """ return core.Base() def itemByOperationId(self, id: int) -> core.Base: """ Returns the operation, folder or pattern with the specified operation id. id : The id of the operation, folder or pattern. Returns the specified item or null in the case where there is no item with the specified operation id. """ return core.Base() @property def count(self) -> int: """ Gets the number of objects in the collection. """ return int() class CreateMachineConfigurationsEventHandler(core.EventHandler): """ Event handler for the CreateMachineConfigurationsEvent. """ def __init__(self): pass @staticmethod def cast(arg) -> CreateMachineConfigurationsEventHandler: return CreateMachineConfigurationsEventHandler() def notify(self, eventArgs: CreateMachineConfigurationsEventArgs) -> None: """ The function called by Fusion 360 when the associated event is fired. eventArgs : Returns an object that provides access to additional information associated with the event. """ pass class GenerateToolpathFuture(core.Base): """ Used to check the state and get back the results of toolpath generation. """ def __init__(self): pass @staticmethod def cast(arg) -> GenerateToolpathFuture: return GenerateToolpathFuture() @property def numberOfOperations(self) -> int: """ Returns a number of operations need to be generated. """ return int() @property def numberOfCompleted(self) -> int: """ Returns a number of operations whose toolpath generation are completed. """ return int() @property def operations(self) -> Operations: """ Returns all operations that need to be generated. """ return Operations() @property def isGenerationCompleted(self) -> bool: """ Returns true if all operations are generated. """ return bool() class InspectionPathResult(core.Base): """ Class to represent measured results from an surface inspection path. """ def __init__(self): pass @staticmethod def cast(arg) -> InspectionPathResult: return InspectionPathResult() @property def pointResults(self) -> InspectionPointResults: """ return all the point results for the path. """ return InspectionPointResults() class InspectionPathResults(core.Base): """ collection of inspection paths results. """ def __init__(self): pass @staticmethod def cast(arg) -> InspectionPathResults: return InspectionPathResults() def item(self, index: int) -> InspectionPathResult: """ Function that returns the specified InspectionPathResult using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return InspectionPathResult() @property def count(self) -> int: """ The number of InspectionPathResult in the collection. """ return int() class InspectionPointResult(core.Base): """ Class to represent an inspection point's measured result. These are created as a result of probing a surface inspection path. For each point on the surface inspection path, the nominal position is the contact position on the CAD model. The measured 'contact point' is recorded when probing and a notional projected point can be calculated on the CAD model. The error is calculated as the deviation from the nominal over and above the tolerance. All values are in the Fusion's internal units which for positional and length values is CM. """ def __init__(self): pass @staticmethod def cast(arg) -> InspectionPointResult: return InspectionPointResult() @property def nominalPosition(self) -> core.Point3D: """ get the nominal position of the inspection point. """ return core.Point3D() @property def projectedPoint(self) -> core.Point3D: """ get the projected position of the measured point. """ return core.Point3D() @property def contact(self) -> core.Point3D: """ get the contact position of the inspection point. """ return core.Point3D() @property def offset(self) -> float: """ get offset associated with the inspection point. """ return float() @property def delta(self) -> core.Vector3D: """ get the deviation vector of the measured point from nominal. """ return core.Vector3D() @property def deviation(self) -> float: """ get the deviation of the measured point. """ return float() @property def error(self) -> float: """ get the error of the measured point adjusting by the allowable tolerance. """ return float() @property def state(self) -> InspectionPointState: """ Get the state of the result. """ return InspectionPointState() class InspectionPointResults(core.Base): """ collection of inspection point results """ def __init__(self): pass @staticmethod def cast(arg) -> InspectionPointResults: return InspectionPointResults() def item(self, index: int) -> InspectionPointResult: """ Function that returns the specified InspectionPointResult using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return InspectionPointResult() @property def count(self) -> int: """ The number of InspectionPointResult in the collection. """ return int() class Machine(core.Base): """ Object that represents a machine. """ def __init__(self): pass @staticmethod def cast(arg) -> Machine: return Machine() @staticmethod def createFromTemplate(machineTemplate: MachineTemplate) -> Machine: """ Creates a Machine from a template. machineTemplate : The template to act as a base for creating a machine from. Returns the newly created machine with a valid kinematics tree. """ return Machine() @staticmethod def createFromFile(location: LibraryLocation, filePath: str) -> Machine: """ Creates a Machine from a file. location : The location in the machine library. filePath : The path to a file to act as a base for creating a machine from. The path is relative to the library location given, unless library location is External, then the filePath is expected to be an absolute path. Returns the newly created machine with a valid kinematics tree. """ return Machine() def save(self, location: LibraryLocation, filePath: str) -> bool: """ Save the Machine to a file. Any subsequent edits will need to be saved again. location : The location in the machine library to save the machine to. filePath : The path of the file to save the machine as. The path is relative to the library location given, unless library location is External, then the filePath is expected to be an absolute path. .machine will be appended if no extension is given. Returns true if the machine was saved successfully, false otherwise. """ return bool() @property def vendor(self) -> str: """ Gets and sets the vendor name of the machine. """ return str() @vendor.setter def vendor(self, value: str): """ Gets and sets the vendor name of the machine. """ pass @property def model(self) -> str: """ Gets and sets the model name of the machine. """ return str() @model.setter def model(self, value: str): """ Gets and sets the model name of the machine. """ pass @property def description(self) -> str: """ Gets and sets the description of the machine. """ return str() @description.setter def description(self, value: str): """ Gets and sets the description of the machine. """ pass @property def id(self) -> str: """ Gets the unique identifier of the machine. Can be used for comparing machines within the document. """ return str() @property def capabilities(self) -> MachineCapabilities: """ Gets the capabilities of the machine. """ return MachineCapabilities() @property def kinematics(self) -> MachineKinematics: """ Gets the kinematics tree of the machine. """ return MachineKinematics() class MachineAxis(core.Base): """ Abstract base class representing a single machine axis. """ def __init__(self): pass @staticmethod def cast(arg) -> MachineAxis: return MachineAxis() @property def name(self) -> str: """ The name of this axis. """ return str() @name.setter def name(self, value: str): """ The name of this axis. """ pass @property def axisType(self) -> MachineAxisTypes: """ The type of axis. """ return MachineAxisTypes() @property def hasLimits(self) -> bool: """ Does this axis have a limited range of motion. """ return bool() @property def physicalMin(self) -> float: """ The minimum possible value for this axis (in mm/deg). Must be less than physicalMax. Set the value of this and physicalMax to 0 to remove axis limits. """ return float() @physicalMin.setter def physicalMin(self, value: float): """ The minimum possible value for this axis (in mm/deg). Must be less than physicalMax. Set the value of this and physicalMax to 0 to remove axis limits. """ pass @property def physicalMax(self) -> float: """ The maximum possible value for this axis (in mm/deg). Must be less than physicalMin. Set the value of this and physicalMin to 0 to remove axis limits. """ return float() @physicalMax.setter def physicalMax(self, value: float): """ The maximum possible value for this axis (in mm/deg). Must be less than physicalMin. Set the value of this and physicalMin to 0 to remove axis limits. """ pass @property def homePosition(self) -> float: """ Specifies the value (in mm/deg) that this axis returns to when the machine is homed. """ return float() @homePosition.setter def homePosition(self, value: float): """ Specifies the value (in mm/deg) that this axis returns to when the machine is homed. """ pass class MachineAxisInput(core.Base): """ Object that defines the properties required to create a machine axis object. """ def __init__(self): pass @staticmethod def cast(arg) -> MachineAxisInput: return MachineAxisInput() @property def axisType(self) -> MachineAxisTypes: """ The type of axis. This axis type determines which parameters of this object are valid to be accessed or modified. """ return MachineAxisTypes() @property def name(self) -> str: """ The user facing name of this axis. """ return str() @name.setter def name(self, value: str): """ The user facing name of this axis. """ pass @property def homePosition(self) -> float: """ Specifies the value (in mm/deg) that this axis returns to when the machine is homed. """ return float() @homePosition.setter def homePosition(self, value: float): """ Specifies the value (in mm/deg) that this axis returns to when the machine is homed. """ pass @property def physicalMin(self) -> float: """ The minimum possible value for this axis (in mm/deg). Set the value of this and physicalMax to 0 to create an unlimited axis. """ return float() @physicalMin.setter def physicalMin(self, value: float): """ The minimum possible value for this axis (in mm/deg). Set the value of this and physicalMax to 0 to create an unlimited axis. """ pass @property def physicalMax(self) -> float: """ The maximum possible value for this axis (in mm/deg). Set the value of this and physicalMin to 0 to create an unlimited axis. """ return float() @physicalMax.setter def physicalMax(self, value: float): """ The maximum possible value for this axis (in mm/deg). Set the value of this and physicalMin to 0 to create an unlimited axis. """ pass class MachineCapabilities(core.Base): """ Object that represents the capabilities of the machine. """ def __init__(self): pass @staticmethod def cast(arg) -> MachineCapabilities: return MachineCapabilities() @property def isMillingSupported(self) -> bool: """ Gets and sets if the machine is capable of subtractive milling. """ return bool() @isMillingSupported.setter def isMillingSupported(self, value: bool): """ Gets and sets if the machine is capable of subtractive milling. """ pass @property def isTurningSupported(self) -> bool: """ Gets and sets if the machine is capable of subtractive turning. """ return bool() @isTurningSupported.setter def isTurningSupported(self, value: bool): """ Gets and sets if the machine is capable of subtractive turning. """ pass @property def isCuttingSupported(self) -> bool: """ Gets and sets if the machine is capable of subtractive cutting. """ return bool() @isCuttingSupported.setter def isCuttingSupported(self, value: bool): """ Gets and sets if the machine is capable of subtractive cutting. """ pass class MachineDescription(core.Base): """ A description of a machine used to preview machines in the 'Find network machines' dialog """ def __init__(self): pass @staticmethod def cast(arg) -> MachineDescription: return MachineDescription() @staticmethod def create(vendor: str, model: str, ipAddress: str) -> MachineDescription: """ Creates a new MachineDescription. vendor : The machine vendor. model : The machine model. ipAddress : The machine's ipv4 ip address. Returns the newly created MachineDescription object, and allocates a unique id for the object, or null if the creation failed. """ return MachineDescription() @property def id(self) -> int: """ Gets this MachineDescription's unique id. This id can be used to match MachineDescription objects provided during the SearchNetworkMachinesEvent with those requested to create machine configurations for during the CreateMachineConfigurations event. """ return int() @property def vendor(self) -> str: """ Gets and sets the vendor name of the machine. """ return str() @vendor.setter def vendor(self, value: str): """ Gets and sets the vendor name of the machine. """ pass @property def model(self) -> str: """ Gets and sets the model name of the machine. """ return str() @model.setter def model(self, value: str): """ Gets and sets the model name of the machine. """ pass @property def ipAddress(self) -> str: """ Gets and sets the ip address of the machine. """ return str() @ipAddress.setter def ipAddress(self, value: str): """ Gets and sets the ip address of the machine. """ pass @property def control(self) -> str: """ Gets and sets the controller name of the machine. Controller info is not displayed if not set. """ return str() @control.setter def control(self, value: str): """ Gets and sets the controller name of the machine. Controller info is not displayed if not set. """ pass @property def iconPath(self) -> str: """ Gets and sets the absolute path to the 128x128 png image of the machine. A default image is used if not set. """ return str() @iconPath.setter def iconPath(self, value: str): """ Gets and sets the absolute path to the 128x128 png image of the machine. A default image is used if not set. """ pass @property def serial(self) -> str: """ Gets and sets the serial number of the machine. A serial number is not displayed if not set. """ return str() @serial.setter def serial(self, value: str): """ Gets and sets the serial number of the machine. A serial number is not displayed if not set. """ pass class MachineKinematics(core.Base): """ Object that represents the kinematics tree in the machine. """ def __init__(self): pass @staticmethod def cast(arg) -> MachineKinematics: return MachineKinematics() @property def parts(self) -> MachineParts: """ Get the root parts collection. """ return MachineParts() class MachinePart(core.Base): """ Object representing some part of a machine, such as the static base of the machine, an axis, or the attachment points for tools and fixtures. """ def __init__(self): pass @staticmethod def cast(arg) -> MachinePart: return MachinePart() def deleteMe(self) -> None: """ Delete this part and its children from the kinematics tree. """ pass @property def children(self) -> MachineParts: """ Get the collection of child parts. """ return MachineParts() @property def parent(self) -> MachinePart: """ Get or set the parent of this part. Setting the parent will add this part to the end of the parent's children collection. Setting the parent will throw an error if the new parent is this part or a child this part. """ return MachinePart() @parent.setter def parent(self, value: MachinePart): """ Get or set the parent of this part. Setting the parent will add this part to the end of the parent's children collection. Setting the parent will throw an error if the new parent is this part or a child this part. """ pass @property def partType(self) -> MachinePartTypes: """ Get the type of this part. """ return MachinePartTypes() @property def id(self) -> str: """ Get the internal ID of the part. This is unique with respect to other MachineParts in the Machine. """ return str() @property def axis(self) -> MachineAxis: """ Get the axis object for this part used to reference this part for other operations. Only valid when partType is Axis, otherwise returns null """ return MachineAxis() class MachinePartInput(core.Base): """ Object representing the set of inputs required to create a new MachinePart. Set an MachineAxisInput object on this object's axisInput parameter to create a new MachineAxis with this part. """ def __init__(self): pass @staticmethod def cast(arg) -> MachinePartInput: return MachinePartInput() def createAxisInput(self, axisType: MachineAxisTypes) -> MachineAxisInput: """ Create a new MachineAxisInput object to be used to create a new MachineAxis. Set this object on to an axis type MachinePartInput to create a new MachineAxis with that part. axisType : The type of MachineAxisInput to create. Returns a LinearMachineAxisInput or RotaryMachineAxisInput, or null if the creation failed. """ return MachineAxisInput() @property def id(self) -> str: """ Get or set the internal ID of the part, used to reference this part for other operations. This ID can be any string. This must be unique with respect to other MachineParts in the Machine. """ return str() @id.setter def id(self, value: str): """ Get or set the internal ID of the part, used to reference this part for other operations. This ID can be any string. This must be unique with respect to other MachineParts in the Machine. """ pass @property def partType(self) -> MachinePartTypes: """ Get the type of part this input will create. """ return MachinePartTypes() @property def axisInput(self) -> MachineAxisInput: """ Get or Set an axis input object to create a new MachineAxis with this part. Only valid when partType is Axis. """ return MachineAxisInput() @axisInput.setter def axisInput(self, value: MachineAxisInput): """ Get or Set an axis input object to create a new MachineAxis with this part. Only valid when partType is Axis. """ pass class MachineParts(core.Base): """ Object that represents a collection of machine parts. These parts are the children of another part or the collection of base parts from MachineKinematics """ def __init__(self): pass @staticmethod def cast(arg) -> MachineParts: return MachineParts() def add(self, partInput: MachinePartInput) -> MachinePart: """ Add a new part to this collection. The part's parent will be set to the the owner of this collection, or null if this is the root parts collection. If the passed MachinePartInput has a MachineAxisInput a new MachineAxis will be created. partInput : Part input object used to create the new MachinePart. Returns the newly creted MachinePart or null if creation failed. """ return MachinePart() def createPartInput(self, partType: MachinePartTypes) -> MachinePartInput: """ Create a new MachinePartInput. partType : The type of part to create. When this parameter is Axis, you must set a value for axisInput. Returns the new MachinePartInput or null if creation failed. """ return MachinePartInput() def item(self, index: int) -> MachinePart: """ Get the part at index in this collection. index : The index of the part. The MachinePart at index. """ return MachinePart() def itemById(self, id: str) -> MachinePart: """ Get the part with the given ID. id : The ID for the part to get. Returns the MachinePart with the given ID, or null if the given ID does not match any part in the collection. """ return MachinePart() @property def count(self) -> int: """ Get the number of parts in this collection. """ return int() class MachiningTime(core.Base): """ Object returned when using the getMachiningTime method from the CAM class. Use the properties on this object to get the machining time results. """ def __init__(self): pass @staticmethod def cast(arg) -> MachiningTime: return MachiningTime() @property def feedDistance(self) -> float: """ Gets the feed distance in centimeters. """ return float() @property def totalFeedTime(self) -> float: """ Get the total feed time in seconds. """ return float() @property def rapidDistance(self) -> float: """ Gets the calculated rapid distance in centimeters. """ return float() @property def totalRapidTime(self) -> float: """ Gets the total rapid feed time in seconds. """ return float() @property def toolChangeCount(self) -> int: """ Gets the number of tool changes. """ return int() @property def totalToolChangeTime(self) -> float: """ Gets the total tool change time in seconds. """ return float() @property def machiningTime(self) -> float: """ Gets the machining time in seconds. """ return float() class NetworkMachineIntegrationInput(core.Base): """ An input object required to register an addin for use in the 'Find network machines' dialog. This input object defines properties of an addin and allows an addin to customize its appearence in the 'Find network machines' dialog. """ def __init__(self): pass @staticmethod def cast(arg) -> NetworkMachineIntegrationInput: return NetworkMachineIntegrationInput() @staticmethod def create(displayName: str, description: str) -> NetworkMachineIntegrationInput: """ displayName : The name that will be presented to the user in the 'Find network machines' dialog. description : A description of the addin which appears as a tooltip alongside the display name. Returns true if the addin was successfully registered. """ return NetworkMachineIntegrationInput() @property def displayName(self) -> str: """ Gets and sets the display name of the addin that appears in the 'vendor' dropdown in the 'Find network machines' dialog. """ return str() @displayName.setter def displayName(self, value: str): """ Gets and sets the display name of the addin that appears in the 'vendor' dropdown in the 'Find network machines' dialog. """ pass @property def description(self) -> str: """ Gets and sets the description of the addin """ return str() @description.setter def description(self, value: str): """ Gets and sets the description of the addin """ pass class NetworkMachineIntegrationManager(core.Base): """ NetworkMachineManager provides access to properties and events needed to integrate addins into the 'Find network machines' dialog, which enables users to add machine configurations representing machines on the network to their machine library. """ def __init__(self): pass @staticmethod def cast(arg) -> NetworkMachineIntegrationManager: return NetworkMachineIntegrationManager() def registerNetworkMachineIntegration(self, networkMachineIntegrationInput: NetworkMachineIntegrationInput) -> bool: """ Registers an addin for use in the 'Find network machines' dialog. This dialog will fire the SearchNetworkMachinesEvent and CreateMachineConfigurationsEvent, which the addin must handle. See SearchNetworkMachinesEvent and CreateMachineConfigurationsEvent for details. networkMachineIntegrationInput : An object defining properties of an addin, also allowing an addin to customize its appearence in the 'Find network machines' dialog. """ return bool() @property def searchNetworkMachinesEvent(self) -> SearchNetworkMachinesEvent: """ This event is fired from the 'Find network machines' dialog when the corresponding addin is selected from the vendor dropdown, or when 'search all vendors' is selected. This event will allow the addin to initiate an enumeration of machines on the network, and populate the 'Find network machines' dialog with descriptions of each machine found. See SearchNetworkMachinesEvent for details. """ return SearchNetworkMachinesEvent() @property def createMachineConfigurationsEvent(self) -> CreateMachineConfigurationsEvent: """ This event is fired from the 'Find network machines' dialog when MachineDescription(s) previously provided during the handling of the SearchNetworkMachines event are selected to add to the user's Machine Library. This event will allow the addins to create machine configurations corresponding to the selected MachineDescription objects. See CreateMachineConfigurationsEvent for details. """ return CreateMachineConfigurationsEvent() class OperationBase(core.Base): """ Base class object representing all operations, folders, patterns and setups. """ def __init__(self): pass @staticmethod def cast(arg) -> OperationBase: return OperationBase() @property def name(self) -> str: """ Gets and sets the name of the operation as seen in the browser. This name is unique as compared to the names of all other operations in the document. """ return str() @name.setter def name(self, value: str): """ Gets and sets the name of the operation as seen in the browser. This name is unique as compared to the names of all other operations in the document. """ pass @property def isProtected(self) -> bool: """ Gets and sets the "protected" property value of the operation. Gets/sets true if the operation is protected. """ return bool() @isProtected.setter def isProtected(self, value: bool): """ Gets and sets the "protected" property value of the operation. Gets/sets true if the operation is protected. """ pass @property def isOptional(self) -> bool: """ Gets and sets the "Optional" property value of the operation. Gets/sets true if the operation is optional. """ return bool() @isOptional.setter def isOptional(self, value: bool): """ Gets and sets the "Optional" property value of the operation. Gets/sets true if the operation is optional. """ pass @property def isSuppressed(self) -> bool: """ Gets and sets the "Suppressed" property value of the operation. Gets/sets true if the operation is suppressed. """ return bool() @isSuppressed.setter def isSuppressed(self, value: bool): """ Gets and sets the "Suppressed" property value of the operation. Gets/sets true if the operation is suppressed. """ pass @property def parentSetup(self) -> Setup: """ Gets the Setup this operation belongs to. """ return Setup() @property def isSelected(self) -> bool: """ Gets if this operation is selected in the 'Setups' browser. """ return bool() @property def notes(self) -> str: """ Gets and sets the notes of the operation. """ return str() @notes.setter def notes(self, value: str): """ Gets and sets the notes of the operation. """ pass @property def operationId(self) -> int: """ Returns the id of the operation. This id is unique as compared to the ids of all other operations in the document. This id will not change when changing the order or parent of the operation. This id will remain valid when the document is saved and reloaded. """ return int() @property def parameters(self) -> CAMParameters: """ Gets the CAMParameters collection for this operation. """ return CAMParameters() @property def attributes(self) -> core.Attributes: """ Returns the collection of attributes associated with this object. """ return core.Attributes() class Operations(core.Base): """ Collection that provides access to the individual operations within an existing setup, folder or pattern. """ def __init__(self): pass @staticmethod def cast(arg) -> Operations: return Operations() def item(self, index: int) -> Operation: """ Function that returns the specified operation using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return Operation() def itemByName(self, name: str) -> Operation: """ Returns the operation with the specified name (as appears in the browser). name : The name (as it appears in the browser) of the operation. Returns the specified operation or null in the case where there is no operation with the specified name. """ return Operation() def itemByOperationId(self, id: int) -> Operation: """ Returns the operation with the specified operation id. id : The id of the operation. Returns the specified operation or null in the case where there is no operation with the specified operation id. """ return Operation() @property def count(self) -> int: """ The number of items in the collection. """ return int() class ParameterValue(core.Base): """ Base class for representing the value of a parameter. Subclasses implement value handling for available parameter types. """ def __init__(self): pass @staticmethod def cast(arg) -> ParameterValue: return ParameterValue() @property def parent(self) -> core.Base: """ Get the parameter object that the value is associated with. """ return core.Base() class PostProcessInput(core.Base): """ This class defines the properties that pertain to the settings and options required for posting a toolpath to generate a CNC file. A PostProcessInput object is a required parameter for the postProcessAll() and postProcess() methods on the CAM class. """ def __init__(self): pass @staticmethod def cast(arg) -> PostProcessInput: return PostProcessInput() @staticmethod def create(programName: str, postConfiguration: str, outputFolder: str, outputUnits: PostOutputUnitOptions) -> PostProcessInput: """ Creates a new PostProcessInput object to be used as an input argument by the postProcess() and postProcessAll() methods on the CAM class for posting toolpaths and generating CNC files. programName : The program name or number. If the post configuration specifies the parameter programNameIsInteger = true, then the program name must be a number. postConfiguration : The full filename (including the path) to the post configuration file (.cps) The post config file can be stored in any path but for convenience you can use the genericPostFolder or the personalPostFolder property on the CAM class to specify the path if your .cps file is stored in either of those locations. You must add a forward slash (this works for Mac or Windows) to the path defined by these folder properties before the filename (e.g. postConfiguration = cam.genericPostFolder + '/' + 'fanuc.cps') outputFolder : The path for the existing output folder where the .cnc files will be located. This method will create the specified output folder if it does not already exist. It is not necessary to add a slash to the end of the outputFolder path. You should use forward slashes in your path definition if you want your script to run on both Mac and Windows. outputUnits : The units option for the cnc output. Valid options are DocumentUnitsOutput, InchesOutput or MillimetersOutput Returns the newly created PostProcessInput object or null if the creation failed. """ return PostProcessInput() @property def programName(self) -> str: """ Gets and sets the program name or number. If the post configuration specifies the parameter programNameIsInteger = true, then the program name must be a number. """ return str() @programName.setter def programName(self, value: str): """ Gets and sets the program name or number. If the post configuration specifies the parameter programNameIsInteger = true, then the program name must be a number. """ pass @property def programComment(self) -> str: """ Gets and sets the program comment. The default value for this property is an empty string (""). """ return str() @programComment.setter def programComment(self, value: str): """ Gets and sets the program comment. The default value for this property is an empty string (""). """ pass @property def postConfiguration(self) -> str: """ Gets and sets the full filename (including the path) for the post configuration file (.cps) """ return str() @postConfiguration.setter def postConfiguration(self, value: str): """ Gets and sets the full filename (including the path) for the post configuration file (.cps) """ pass @property def outputFolder(self) -> str: """ Gets and sets the path for the output folder where the .cnc files will be located. """ return str() @outputFolder.setter def outputFolder(self, value: str): """ Gets and sets the path for the output folder where the .cnc files will be located. """ pass @property def outputUnits(self) -> PostOutputUnitOptions: """ Gets and sets the units option for the cnc output. Valid options are DocumentUnitsOutput, InchesOutput or MillimetersOutput """ return PostOutputUnitOptions() @outputUnits.setter def outputUnits(self, value: PostOutputUnitOptions): """ Gets and sets the units option for the cnc output. Valid options are DocumentUnitsOutput, InchesOutput or MillimetersOutput """ pass @property def isOpenInEditor(self) -> bool: """ Gets and sets the option if opening the cnc file with the editor after it is created. The default value for this property is true. """ return bool() @isOpenInEditor.setter def isOpenInEditor(self, value: bool): """ Gets and sets the option if opening the cnc file with the editor after it is created. The default value for this property is true. """ pass @property def areToolChangesMinimized(self) -> bool: """ Gets and sets that operations may be reordered between setups to minimize the number of tool changes. Operations within each setup will still be executed in the programmed order. This is commonly used for tombstone machining where you have multiple setups. The default value for this property is false. """ return bool() @areToolChangesMinimized.setter def areToolChangesMinimized(self, value: bool): """ Gets and sets that operations may be reordered between setups to minimize the number of tool changes. Operations within each setup will still be executed in the programmed order. This is commonly used for tombstone machining where you have multiple setups. The default value for this property is false. """ pass @property def postProperties(self) -> core.NamedValues: """ Gets and sets the list of post properties. Each property has a string name and a ValueInput object. The default value for this is an empty NamedValues. """ return core.NamedValues() @postProperties.setter def postProperties(self, value: core.NamedValues): """ Gets and sets the list of post properties. Each property has a string name and a ValueInput object. The default value for this is an empty NamedValues. """ pass @property def machine(self) -> Machine: """ Gets and sets the machine used for post processing. It will override the machines associated with the operations or setup when posting. The default value for this property is null. """ return Machine() @machine.setter def machine(self, value: Machine): """ Gets and sets the machine used for post processing. It will override the machines associated with the operations or setup when posting. The default value for this property is null. """ pass class SandvikIntegration(core.Base): """ This singleton object provides access to application-level events and properties that relate to the CAM (Manufacture) workspace in Fusion 360. """ def __init__(self): pass @staticmethod def cast(arg) -> SandvikIntegration: return SandvikIntegration() @staticmethod def get() -> SandvikIntegration: """ Access to the root CAMGlobal object. Return the root SandvikIntegration object or null if it failed. """ return SandvikIntegration() def getStockMaterialId(self, setup: Setup) -> str: """ Get the stock material id specified for the Setup. setup : The Setup object to get the stock material id for. The ID of the stock material set for the Setup. """ return str() def setStockMaterialId(self, setup: Setup, id: str) -> bool: """ Set the stock material id for the Setup. setup : The Setup object to set the stock material id for. Returns true if successful. """ return bool() def getStockMaterialText(self, setup: Setup) -> str: """ Get the stock material id specified for the Setup. setup : The Setup object to get the stock material id for. The ID of the stock material set for the Setup. """ return str() def setStockMaterialText(self, setup: Setup, text: str) -> bool: """ Set the stock material text for the Setup. This will be displayed in the user interface. setup : The Setup object to set the stock material text for. Returns true if successful. """ return bool() @property def preIntegrationEvent(self) -> SandvikPreIntegrationEvent: """ This event will be fired just before an operation/setup dialog (create/edit) is presented. This will allow the addin to indicate which, if any, of the integration actions should be shown, as well as details of the presentation. See SandvikPreIntegrationEventArgs for details. """ return SandvikPreIntegrationEvent() @property def integrationEvent(self) -> SandvikIntegrationEvent: """ An integration event will be fired when any of the buttons related to the integration is pressed. The event arguments will provide information about which button was pressed, and will provide contextual information, such as the object active at the time. """ return SandvikIntegrationEvent() @property def settings(self) -> str: """ Provides a mechanism to store and retrieve user-specific information as a hidden system preference. """ return str() @settings.setter def settings(self, value: str): """ Provides a mechanism to store and retrieve user-specific information as a hidden system preference. """ pass class SandvikIntegrationEventHandler(core.EventHandler): """ Event handler for the SandvikIntegrationEvent event. """ def __init__(self): pass @staticmethod def cast(arg) -> SandvikIntegrationEventHandler: return SandvikIntegrationEventHandler() def notify(self, eventArgs: SandvikIntegrationEventArgs) -> None: """ The function called by CAM when the associated event is fired. eventArgs : Returns an object that provides access to additional information associated with the event. """ pass class SandvikPreIntegrationEventHandler(core.EventHandler): """ Event handler for the SandvikPreIntegrationEvent event. """ def __init__(self): pass @staticmethod def cast(arg) -> SandvikPreIntegrationEventHandler: return SandvikPreIntegrationEventHandler() def notify(self, eventArgs: SandvikPreIntegrationEventArgs) -> None: """ The function called by CAM when the associated event is fired. eventArgs : Returns an object that provides access to additional information associated with the event. """ pass class SearchNetworkMachinesEventHandler(core.EventHandler): """ Event handler for the SearchNetworkMachinesEvent event. """ def __init__(self): pass @staticmethod def cast(arg) -> SearchNetworkMachinesEventHandler: return SearchNetworkMachinesEventHandler() def notify(self, eventArgs: SearchNetworkMachinesEventArgs) -> None: """ The function called by Fusion 360 when the associated event is fired. eventArgs : An object that provides access to additional information associated with the event. """ pass class SetupChangeEventHandler(core.EventHandler): """ The SetupChangeEventHandler is a client implemented class that can be added as a handler to a SetupChangeEvent. """ def __init__(self): pass @staticmethod def cast(arg) -> SetupChangeEventHandler: return SetupChangeEventHandler() def notify(self, eventArgs: SetupChangeEventArgs) -> None: """ The function called by CAM when the associated event is fired. eventArgs : Returns an object that provides access to additional information associated with the event. """ pass class SetupEventHandler(core.EventHandler): """ The SetupEventHandler is a client implemented class that can be added as a handler to a SetupEvent. """ def __init__(self): pass @staticmethod def cast(arg) -> SetupEventHandler: return SetupEventHandler() def notify(self, eventArgs: SetupEventArgs) -> None: """ The function called by CAM when the associated event is fired. eventArgs : Returns an object that provides access to additional information associated with the event. """ pass class Setups(core.Base): """ Collection that provides access to all of the existing setups in a document. """ def __init__(self): pass @staticmethod def cast(arg) -> Setups: return Setups() def item(self, index: int) -> Setup: """ Function that returns the specified setup using an index into the collection. index : The index of the item within the collection to return. The first item in the collection has an index of 0. Returns the specified item or null if an invalid index was specified. """ return Setup() def itemByName(self, name: str) -> Setup: """ Returns the setup with the specified name. name : The name (as it appears in the browser) of the operation. Returns the specified setup or null in the case where there is no setup with the specified name. """ return Setup() def itemByOperationId(self, id: int) -> Setup: """ Returns the setup with the specified operation id. id : The id of the operation. Returns the specified setup or null in the case where there is no setup with the specified operation id. """ return Setup() @property def count(self) -> int: """ The number of setups in the collection. """ return int() class BooleanParameterValue(ParameterValue): """ A parameter value that is a boolean. """ def __init__(self): pass @staticmethod def cast(arg) -> BooleanParameterValue: return BooleanParameterValue() @property def value(self) -> bool: """ Get or set the value of the parameter. """ return bool() @value.setter def value(self, value: bool): """ Get or set the value of the parameter. """ pass class CadObjectParameterValue(ParameterValue): """ A parameter value that is a CadObject. """ def __init__(self): pass @staticmethod def cast(arg) -> CadObjectParameterValue: return CadObjectParameterValue() class CAM(core.Product): """ Object that represents the CAM environment of a Fusion document. """ def __init__(self): pass @staticmethod def cast(arg) -> CAM: return CAM() def export3MFForDefaultAdditiveSetup(self, filepath: str, addSimulationInfo: bool, simPostProcess: bool, simSplitSurrogates: bool, simKeepThickeningStructure: bool) -> bool: """ Exports the default additive setup's models into a 3mf file. The 3mf also contains machine and support information. True on success, false on errors or wrong setup type """ return bool() def generateToolpath(self, operations: core.Base) -> GenerateToolpathFuture: """ Generates/Regenerates all of the toolpaths (including those nested in sub-folders or patterns) for the specified objects. operations : An Operation, Setup, Folder or Pattern object for which to generate the toolpath/s for. You can also specify a collection of any combination of these object types. Return GenerateToolpathFuture that includes the status of toolpath generation. """ return GenerateToolpathFuture() def generateAllToolpaths(self, skipValid: bool) -> GenerateToolpathFuture: """ Generates/Regenerates all toolpaths (includes those nested in sub-folders or patterns) in the document. skipValid : Option to skip valid toolpaths and only regenerate invalid toolpaths. Return GenerateToolpathFuture that includes the status of toolpath generation. """ return GenerateToolpathFuture() def clearToolpath(self, operations: core.Base) -> bool: """ Clears all of the toolpaths (including those nested in sub-folders or patterns) for the specified objects. operations : An Operation, Setup, Folder or Pattern object for which to clear the toolpath/s for. You can also specify a collection of any combination of these object types. Return true if successful. """ return bool() def clearAllToolpaths(self) -> bool: """ Clears all the toolpaths (includes those nested in sub-folders or patterns) in the document Return true if successful. """ return bool() def checkToolpath(self, operations: core.Base) -> bool: """ Checks if toolpath operations (including those nested in sub-folders or patterns) are valid for the specified objects. operations : An Operation, Setup, Folder or Pattern object for which to check the toolpath/s of. You can also specify a collection of any combination of these object types. Returns true if the toolpath operations are valid """ return bool() def checkAllToolpaths(self) -> bool: """ Checks if all the toolpath operations (includes those nested in sub-folders or patterns) in the document are valid Returns true if the all toolpath operations are valid """ return bool() def postProcess(self, operations: core.Base, input: PostProcessInput) -> bool: """ Post all of the toolpaths (including those nested in sub-folders or patterns) for the specified objects. If post processing fails, an error message can be retrieved from the error log explaining the reason for the failure. operations : An Operation, Setup, Folder or Pattern object for which to post the toolpath/s of. You can also specify a collection of any combination of these object types. input : The PostProcessInput object that defines the post options and parameters. Returns true if successful """ return bool() def postProcessAll(self, input: PostProcessInput) -> bool: """ Post all of the toolpaths (includes those nested in sub-folders or patterns) in the document. If post processing fails, an error message can be retrieved from the error log explaining the reason for the failure. input : The PostProcessInput object that defines the post options and parameters. Returns true if successful. """ return bool() def generateSetupSheet(self, operations: core.Base, format: SetupSheetFormats, folder: str, openDocument: bool) -> bool: """ Generate the setup sheets for the specified objects operations : An Operation, Setup, Folder or Pattern object for which to generate the setup sheet/s for. You can also specify a collection of any combination of these object types. format : The document format for the setup sheet. Valid options are HTMLFormat and ExcelFormat. Limitation: "ExcelFormat" can be used in windows OS only. folder : The destination folder to locate the setup sheet documents in. openDocument : An option to allow to open the document instantly after the generation. By default, the document is opened. Returns true if successful """ return bool() def generateAllSetupSheets(self, format: SetupSheetFormats, folder: str, openDocument: bool) -> bool: """ Generates all of the setup sheets for all of the operations in the document format : The document format for the setup sheet. Valid options are HTMLFormat and ExcelFormat. Limitation: "ExcelFormat" can be used in windows OS only. folder : The destination folder to locate the setup sheet documents in. openDocument : An option to allow to open the document instantly after the generation. By default, the document is opened. Returns true if successful """ return bool() def getMachiningTime(self, operations: core.Base, feedScale: float, rapidFeed: float, toolChangeTime: float) -> MachiningTime: """ Get the machining time for the specified objects. operations : An Operation, Setup, Folder or Pattern object for which to get the machining time for. You can also specify a collection of any combination of these object types. feedScale : The feed scale value (%) to use. rapidFeed : The rapid feed rate in centimeters per second. toolChangeTime : The tool change time in seconds. Returns a MachiningTime object that has properties holding the calculation results. """ return MachiningTime() @property def setups(self) -> Setups: """ Returns the Setups collection that provides access to existing setups """ return Setups() @property def allOperations(self) -> core.ObjectCollection: """ Gets a collection containing all of the operations in the document. This includes all operations nested in folders and patterns. """ return core.ObjectCollection() @property def genericPostFolder(self) -> str: """ Gets the installed post folder. """ return str() @property def personalPostFolder(self) -> str: """ Gets the personal post folder. """ return str() @property def temporaryFolder(self) -> str: """ Gets the folder for temporary files. """ return str() @property def customGraphicsGroups(self) -> fusion.CustomGraphicsGroups: """ Returns the customGraphicsGroups object associated with the CAM product. """ return fusion.CustomGraphicsGroups() @property def designRootOccurrence(self) -> fusion.Occurrence: """ Returns the occurrence that references the design root component in CAM product. """ return fusion.Occurrence() @property def flatPatternOccurrences(self) -> fusion.OccurrenceList: """ Returns a read only list of flat pattern occurrences in CAM product. """ return fusion.OccurrenceList() @property def allMachines(self) -> core.ObjectCollection: """ Gets a collection containing all of the machines in the document. """ return core.ObjectCollection() @property def setupCreated(self) -> SetupEvent: """ The SetupCreated event fires when a new setup was created. """ return SetupEvent() @property def setupDestroying(self) -> SetupEvent: """ The setupDestroying event fires before a setup will be destroyed. """ return SetupEvent() @property def setupChanged(self) -> SetupChangeEvent: """ The SetupChanged event fires when a setup was modified. """ return SetupChangeEvent() @property def setupActivating(self) -> SetupEvent: """ The SetupActivating event fires before a setup will be activated. """ return SetupEvent() @property def setupActivated(self) -> SetupEvent: """ The SetupActivated event fires when a setup was activated. """ return SetupEvent() @property def setupDeactivating(self) -> SetupEvent: """ The SetupDeactivating event fires before a setup will be deactivated. """ return SetupEvent() @property def setupDeactivated(self) -> SetupEvent: """ The SetupDeactivated event fires when a setup was deactivated. """ return SetupEvent() @property def exportManager(self) -> CAMExportManager: """ Returns the API-only Export Manager instance """ return CAMExportManager() @property def inspectionResults(self) -> CAMInspectionResults: """ Returns the results collection that provides access to existing measures then pathMeasures and manualMeasures """ return CAMInspectionResults() class CAM3MFExportOptions(CAMExportOptions): """ 3MF export option. Available with all additive machines except Formlabs. Expects a setup as its export object. """ def __init__(self): pass @staticmethod def cast(arg) -> CAM3MFExportOptions: return CAM3MFExportOptions() @property def areSupportsIncluded(self) -> bool: """ Flag toggling if support information should be included in the exported file. Includes both support structures marked as open or closed support as well as meta data used in Netfabb. This option might not be available for all machine types. The default value is false. """ return bool() @areSupportsIncluded.setter def areSupportsIncluded(self, value: bool): """ Flag toggling if support information should be included in the exported file. Includes both support structures marked as open or closed support as well as meta data used in Netfabb. This option might not be available for all machine types. The default value is false. """ pass @property def isMachineInformationIncluded(self) -> bool: """ Flag toggling if machine information should be included in the exported file. The machine information is only compatible with Netfabb. This option might not be available for all machine types. The default value is false. """ return bool() @isMachineInformationIncluded.setter def isMachineInformationIncluded(self, value: bool): """ Flag toggling if machine information should be included in the exported file. The machine information is only compatible with Netfabb. This option might not be available for all machine types. The default value is false. """ pass @property def isProcessSimulationDataIncluded(self) -> bool: """ Flag toggling if simulation information should be included in the exported file. This option might not be available for all machine types. The default value is false. """ return bool() @isProcessSimulationDataIncluded.setter def isProcessSimulationDataIncluded(self, value: bool): """ Flag toggling if simulation information should be included in the exported file. This option might not be available for all machine types. The default value is false. """ pass @property def isSimulationPostProcessingIncluded(self) -> bool: """ Flag toggling if post processing of the simulation should be included. This option might not be available for all machine types. The default value is false. """ return bool() @isSimulationPostProcessingIncluded.setter def isSimulationPostProcessingIncluded(self, value: bool): """ Flag toggling if post processing of the simulation should be included. This option might not be available for all machine types. The default value is false. """ pass @property def areSimulationSurrogatesSplit(self) -> bool: """ Flag toggling if surrogate supports used in the simulation should be split. This option might not be available for all machine types. The default value is false. """ return bool() @areSimulationSurrogatesSplit.setter def areSimulationSurrogatesSplit(self, value: bool): """ Flag toggling if surrogate supports used in the simulation should be split. This option might not be available for all machine types. The default value is false. """ pass @property def areSimulationThickeningStructuresKept(self) -> bool: """ Flag toggling if thickening structures used for simulation should be kept. This option might not be available for all machine types. The default value is false. """ return bool() @areSimulationThickeningStructuresKept.setter def areSimulationThickeningStructuresKept(self, value: bool): """ Flag toggling if thickening structures used for simulation should be kept. This option might not be available for all machine types. The default value is false. """ pass class CAMFolder(OperationBase): """ Object that represents a folder in an existing Setup, Folder or Pattern. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMFolder: return CAMFolder() def createFromTemplate(self, templateFilePath: str) -> core.ObjectCollection: """ Create and add operations, folders or patterns from the specified template file to the end of this folder. templateFilePath : The full path to the template file. Returns the collection containing all of the operations, folders and patterns created from the template file. """ return core.ObjectCollection() @property def isActive(self) -> bool: """ Gets if this folder is active. """ return bool() @property def operations(self) -> Operations: """ Returns the Operations collection that provides access to existing individual operations in this folder. """ return Operations() @property def folders(self) -> CAMFolders: """ Returns the Folders collection that provides access to existing folders in this folder. """ return CAMFolders() @property def patterns(self) -> CAMPatterns: """ Returns the Patterns collection that provides access to existing patterns in this folder. """ return CAMPatterns() @property def children(self) -> ChildOperationList: """ Returns a collection containing all of the immediate (top level) child operations, folders and patterns in this folder in the order they appear in the browser. """ return ChildOperationList() @property def parent(self) -> core.Base: """ Returns the parent Setup, Folder or Pattern for this Folder. """ return core.Base() @property def allOperations(self) -> core.ObjectCollection: """ Gets a collection containing all of the operations in this folder. This includes all operations nested in folders and patterns. """ return core.ObjectCollection() class CAMFormlabsExportOptions(CAMExportOptions): """ Formlabs export option. Available only with Formlabs machines. Expects a setup as its export object. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMFormlabsExportOptions: return CAMFormlabsExportOptions() @property def areSupportsIncluded(self) -> bool: """ Flag toggling if supports should be included in the exported file. The flag is only evaluated if the user has bought the extension. The default value is false. """ return bool() @areSupportsIncluded.setter def areSupportsIncluded(self, value: bool): """ Flag toggling if supports should be included in the exported file. The flag is only evaluated if the user has bought the extension. The default value is false. """ pass class ChoiceParameterValue(ParameterValue): """ A parameter value that is a list of choices. """ def __init__(self): pass @staticmethod def cast(arg) -> ChoiceParameterValue: return ChoiceParameterValue() def getChoices(self) -> tuple[bool, list[str], list[str]]: """ Method that returns the list of available choices. names : An array of the names of the choices. These coincide with the array of possible values returned by the values argument. values : An array of the possible values. These coincide with the array of names returned by the names argument. Returns true if the call was successful. """ return (bool(), [str()], [str()]) @property def value(self) -> str: """ Get or set the value of the parameter. This value will correspond to one of the available values of the parameter. """ return str() @value.setter def value(self, value: str): """ Get or set the value of the parameter. This value will correspond to one of the available values of the parameter. """ pass class CreateMachineConfigurationsEvent(core.Event): """ This event is fired from the 'Find network machines' dialog when MachineDescription(s) previously provided during the handling of the SearchNetworkMachines event are selected to add to the user's Machine Library. This event will allow the addins to create machine configurations corresponding to the selected MachineDescription objects. Handlers of this event should create machine configurations corresponding to each MachineDescription present in the 'machineDescriptions' property in the CreateMachineConfigurationsEventArgs and set them on the 'machines' property of the event args. See CreateMachineConfigurationsEventArgs for details. Note that this event is raised on a background thread. """ def __init__(self): pass @staticmethod def cast(arg) -> CreateMachineConfigurationsEvent: return CreateMachineConfigurationsEvent() def add(self, handler: CreateMachineConfigurationsEventHandler) -> bool: """ Add a handler to be notified when the CreateMachineConfigurationsEvent occurs. handler : The handler object to be called when this event is fired. Returns true if the addition of the handler was successful. """ return bool() def remove(self, handler: CreateMachineConfigurationsEventHandler) -> bool: """ Removes a handler from the CreateMachineConfigurationsEvent. handler : The handler object to be removed from the event. Returns true if removal of the handler was successful. """ return bool() class CreateMachineConfigurationsEventArgs(core.EventArgs): """ This EventArgs object will be sent with the CreateMachineConfigurationsEvent. """ def __init__(self): pass @staticmethod def cast(arg) -> CreateMachineConfigurationsEventArgs: return CreateMachineConfigurationsEventArgs() @property def machineDescriptions(self) -> list[MachineDescription]: """ Gets the collection of MachineDescription objects for which machine configurations must be created. These MachineDescription(s) will be a subset of those previously provided by the addin's SearchNetworkMachinesEventHandler. Returns a list of MachineDescription objects which is a subset of the list that was previously set by this addin on the 'machineDescriptions' property of the SearchNetworkMachinesEventArgs. """ return [MachineDescription()] @property def machines(self) -> list[Machine]: """ Gets and sets the list of Machine objects. Machines should be created corresponding to each of the MachineDescription objects provided in the machineDescriptions property. Machines can be created using adsk.cam.Machine.createFromTemplate or adsk.cam.Machine.createFromFile. """ return [Machine()] @machines.setter def machines(self, value: list[Machine]): """ Gets and sets the list of Machine objects. Machines should be created corresponding to each of the MachineDescription objects provided in the machineDescriptions property. Machines can be created using adsk.cam.Machine.createFromTemplate or adsk.cam.Machine.createFromFile. """ pass class FloatParameterValue(ParameterValue): """ A parameter value that is a floating point value. """ def __init__(self): pass @staticmethod def cast(arg) -> FloatParameterValue: return FloatParameterValue() @property def value(self) -> float: """ Get or set the value of the parameter. """ return float() @value.setter def value(self, value: float): """ Get or set the value of the parameter. """ pass class IntegerParameterValue(ParameterValue): """ A parameter value that is an integer. """ def __init__(self): pass @staticmethod def cast(arg) -> IntegerParameterValue: return IntegerParameterValue() @property def value(self) -> int: """ Get or set the value of the parameter. """ return int() @value.setter def value(self, value: int): """ Get or set the value of the parameter. """ pass class LinearMachineAxis(MachineAxis): """ Object that represents an axis with linear motion (e.g. X, Y, and Z). """ def __init__(self): pass @staticmethod def cast(arg) -> LinearMachineAxis: return LinearMachineAxis() @property def direction(self) -> core.Vector3D: """ The unit vector that represents the direction along which the axis will move. """ return core.Vector3D() @direction.setter def direction(self, value: core.Vector3D): """ The unit vector that represents the direction along which the axis will move. """ pass class LinearMachineAxisInput(MachineAxisInput): """ Object that defines the properties required to create a new linear machine axis object. """ def __init__(self): pass @staticmethod def cast(arg) -> LinearMachineAxisInput: return LinearMachineAxisInput() @property def direction(self) -> core.Vector3D: """ The unit vector that represents the direction along which the linear axis will move. This vector is in the machine's coordinate system (e.g. the X axis is always (1,0,0)). """ return core.Vector3D() @direction.setter def direction(self, value: core.Vector3D): """ The unit vector that represents the direction along which the linear axis will move. This vector is in the machine's coordinate system (e.g. the X axis is always (1,0,0)). """ pass class Operation(OperationBase): """ Object that represents an operation in an existing Setup, Folder or Pattern. """ def __init__(self): pass @staticmethod def cast(arg) -> Operation: return Operation() @property def strategyType(self) -> OperationStrategyTypes: """ Gets the strategy type for this operation. """ return OperationStrategyTypes() @property def isToolpathValid(self) -> bool: """ Gets if the toolpath for this operation is currently valid. (has not become invalidated by model changes). """ return bool() @property def isGenerating(self) -> bool: """ Gets if the toolpath is in the process of generating. """ return bool() @property def hasWarning(self) -> bool: """ Gets if problems were encountered when generating the toolpath for this operation. """ return bool() @property def parent(self) -> core.Base: """ Returns the parent Setup, Folder or Pattern for this operation. """ return core.Base() @property def hasToolpath(self) -> bool: """ Gets if a toolpath currently exists (has been generated) for this operation. """ return bool() @property def operationState(self) -> OperationStates: """ Gets the current state of this operation. """ return OperationStates() @property def generatingProgress(self) -> str: """ Gets the toolpath generation progress value for this operation. """ return str() @property def toolJson(self) -> str: """ Get or set the tool in JSON format for this operation. Adds tool to the document. """ return str() @toolJson.setter def toolJson(self, value: str): """ Get or set the tool in JSON format for this operation. Adds tool to the document. """ pass @property def toolPresetId(self) -> str: """ Get or set the id of the tool preset to be used. Must be valid for the applied tool. """ return str() @toolPresetId.setter def toolPresetId(self, value: str): """ Get or set the id of the tool preset to be used. Must be valid for the applied tool. """ pass class RotaryMachineAxis(MachineAxis): """ Object that represents an axis with rotary motion (e.g. A, B, and C). """ def __init__(self): pass @staticmethod def cast(arg) -> RotaryMachineAxis: return RotaryMachineAxis() @property def rotationAxis(self) -> core.InfiniteLine3D: """ The infinite line that defines the direction and location of the axis of rotation. """ return core.InfiniteLine3D() @rotationAxis.setter def rotationAxis(self, value: core.InfiniteLine3D): """ The infinite line that defines the direction and location of the axis of rotation. """ pass class RotaryMachineAxisInput(MachineAxisInput): """ Object that defines the properties required to create a new rotary machine axis object. """ def __init__(self): pass @staticmethod def cast(arg) -> RotaryMachineAxisInput: return RotaryMachineAxisInput() @property def rotationAxis(self) -> core.InfiniteLine3D: """ The infinite line that defines the direction and location of the axis of rotation. This direction is in the machine's coordinate system (e.g. an A axis would typically use (1,0,0) for the direction), and follows the right-hand rule. """ return core.InfiniteLine3D() @rotationAxis.setter def rotationAxis(self, value: core.InfiniteLine3D): """ The infinite line that defines the direction and location of the axis of rotation. This direction is in the machine's coordinate system (e.g. an A axis would typically use (1,0,0) for the direction), and follows the right-hand rule. """ pass class SandvikIntegrationEvent(core.Event): """ """ def __init__(self): pass @staticmethod def cast(arg) -> SandvikIntegrationEvent: return SandvikIntegrationEvent() def add(self, handler: SandvikIntegrationEventHandler) -> bool: """ Add a handler to be notified when the SandvikIntegrationEvent occurs. handler : The handler object to be called when this event is fired. Returns true if the addition of the handler was successful. """ return bool() def remove(self, handler: SandvikIntegrationEventHandler) -> bool: """ Removes a handler from the SandvikIntegrationEvent. handler : The handler object to be removed from the event. Returns true if removal of the handler was successful. """ return bool() class SandvikIntegrationEventArgs(core.EventArgs): """ This EventArgs object will be sent with the SandvikIntegrationEvent. """ def __init__(self): pass @staticmethod def cast(arg) -> SandvikIntegrationEventArgs: return SandvikIntegrationEventArgs() @property def action(self) -> str: """ The action to be performed -- by convention with Sandvik. Actions include: "selectAssembly" "getToolRecommendation" "getCuttingData" "setMaterial" """ return str() @property def contextObject(self) -> OperationBase: """ Provides access to the object that is being edited or created. """ return OperationBase() class SandvikPreIntegrationEvent(core.Event): """ """ def __init__(self): pass @staticmethod def cast(arg) -> SandvikPreIntegrationEvent: return SandvikPreIntegrationEvent() def add(self, handler: SandvikPreIntegrationEventHandler) -> bool: """ Add a handler to be notified when the SandvikPreIntegrationEvent occurs. handler : The handler object to be called when this event is fired. Returns true if the addition of the handler was successful. """ return bool() def remove(self, handler: SandvikPreIntegrationEventHandler) -> bool: """ Removes a handler from the SandvikPreIntegrationEvent. handler : The handler object to be removed from the event. Returns true if removal of the handler was successful. """ return bool() class SandvikPreIntegrationEventArgs(core.EventArgs): """ This EventArgs object will be sent with the SandvikPreIntegrationEvent. """ def __init__(self): pass @staticmethod def cast(arg) -> SandvikPreIntegrationEventArgs: return SandvikPreIntegrationEventArgs() @property def contextObject(self) -> OperationBase: """ Provides access to the object that is being edited or created. """ return OperationBase() @property def showSetMaterial(self) -> bool: """ Initially false, this should be set to true to enable the display of the "Set Material" action on the Setup create/edit dialog. """ return bool() @showSetMaterial.setter def showSetMaterial(self, value: bool): """ Initially false, this should be set to true to enable the display of the "Set Material" action on the Setup create/edit dialog. """ pass @property def showSelectToolAssembly(self) -> bool: """ Initially false, this should be set to true to enable the display of the "Select Tool Assembly" action on the Operation create/edit dialog. """ return bool() @showSelectToolAssembly.setter def showSelectToolAssembly(self, value: bool): """ Initially false, this should be set to true to enable the display of the "Select Tool Assembly" action on the Operation create/edit dialog. """ pass @property def showGetToolRecommendation(self) -> bool: """ Initially false, this should be set to true to enable the display of the "Get Tool Recommendation" action on the Operation create/edit dialog. """ return bool() @showGetToolRecommendation.setter def showGetToolRecommendation(self, value: bool): """ Initially false, this should be set to true to enable the display of the "Get Tool Recommendation" action on the Operation create/edit dialog. """ pass @property def showGetCuttingData(self) -> bool: """ Initially false, this should be set to true to enable the display of the "Get Cutting Data" action on the Operation create/edit dialog. """ return bool() @showGetCuttingData.setter def showGetCuttingData(self, value: bool): """ Initially false, this should be set to true to enable the display of the "Get Cutting Data" action on the Operation create/edit dialog. """ pass class SearchNetworkMachinesEvent(core.Event): """ This event is fired from the 'Find network machines' dialog when the corresponding addin is selected from the vendor dropdown, or when 'search all vendors' is selected. This event will allow the addin to initiate an enumeration of machines on the network. MachineDescription objects should be created for each machine found, and an list of those MachineDescription objects should be set on the 'machineDescriptions' property of the SearchNetworkMachinesEventArgs. Nothing should be set to signify no machines found. See SearchNetworkMachinesEventArgs and MachineDescription for details. Note that this event is raised on a background thread. """ def __init__(self): pass @staticmethod def cast(arg) -> SearchNetworkMachinesEvent: return SearchNetworkMachinesEvent() def add(self, handler: SearchNetworkMachinesEventHandler) -> bool: """ Add a handler to be notified when the SearchNetworkMachinesEvent occurs. handler : The handler object to be called when this event is fired. Returns true if the addition of the handler was successful. """ return bool() def remove(self, handler: SearchNetworkMachinesEventHandler) -> bool: """ Removes a handler from the SearchNetworkMachinesEvent. handler : The handler object to be removed from the event. Returns true if removal of the handler was successful. """ return bool() class SearchNetworkMachinesEventArgs(core.EventArgs): """ This EventArgs object will be sent with the SearchNetworkMachinesEvent. """ def __init__(self): pass @staticmethod def cast(arg) -> SearchNetworkMachinesEventArgs: return SearchNetworkMachinesEventArgs() @property def machineDescriptions(self) -> list[MachineDescription]: """ Gets and sets a list of MachineDescription objects representing machines found on the network. Do not set anything to signify no machine found. """ return [MachineDescription()] @machineDescriptions.setter def machineDescriptions(self, value: list[MachineDescription]): """ Gets and sets a list of MachineDescription objects representing machines found on the network. Do not set anything to signify no machine found. """ pass class Setup(OperationBase): """ Object that represents an existing Setup. """ def __init__(self): pass @staticmethod def cast(arg) -> Setup: return Setup() def createFromTemplate(self, templateFilePath: str) -> core.ObjectCollection: """ Create and add operations, folders or patterns from the specified template file to the end of this setup. templateFilePath : The full path to the template file. Returns the collection containing all of the operations, folders and patterns created from the template file. """ return core.ObjectCollection() @property def operationType(self) -> OperationTypes: """ Gets the Operation Type. It can be MillingOperation, TurningOperation, JetOperation or AdditiveOperation. """ return OperationTypes() @property def isActive(self) -> bool: """ Gets if this setup is active. """ return bool() @property def operations(self) -> Operations: """ Returns the Operations collection that provides access to existing operations in this setup. """ return Operations() @property def folders(self) -> CAMFolders: """ Returns the Folders collection that provides access to existing folders in this setup. """ return CAMFolders() @property def patterns(self) -> CAMPatterns: """ Returns the Patterns collection that provides access to existing patterns in this setup. """ return CAMPatterns() @property def children(self) -> ChildOperationList: """ Returns a collection containing all of the immediate (top level) child operations, folders and patterns in this setup in the order they appear in the browser. """ return ChildOperationList() @property def allOperations(self) -> core.ObjectCollection: """ Gets a collection containing all of the operations in this setup. This includes all operations nested in folders and patterns. """ return core.ObjectCollection() @property def models(self) -> core.ObjectCollection: """ Gets and sets the bodies associated with the setup. Passing in an empty ObjectCollection will remove all current bodies. Valid input is MeshBody and/or BRepBody objects. """ return core.ObjectCollection() @models.setter def models(self, value: core.ObjectCollection): """ Gets and sets the bodies associated with the setup. Passing in an empty ObjectCollection will remove all current bodies. Valid input is MeshBody and/or BRepBody objects. """ pass @property def fixtures(self) -> core.ObjectCollection: """ Gets the fixtures associated with the setup. """ return core.ObjectCollection() @property def stockSolids(self) -> core.ObjectCollection: """ Gets the stock solids associated with the setup. """ return core.ObjectCollection() @property def machine(self) -> Machine: """ Gets the Machine associated with the setup. """ return Machine() class SetupChangeEvent(core.Event): """ A SetupChangeEvent represents a setup related change event. It is used for SetupChanged notifications. """ def __init__(self): pass @staticmethod def cast(arg) -> SetupChangeEvent: return SetupChangeEvent() def add(self, handler: SetupChangeEventHandler) -> bool: """ Add a handler to be notified when the file event occurs. handler : The handler object to be called when this event is fired. Returns true if the addition of the handler was successful. """ return bool() def remove(self, handler: SetupChangeEventHandler) -> bool: """ Removes a handler from the event. handler : The handler object to be removed from the event. Returns true if removal of the handler was successful. """ return bool() class SetupChangeEventArgs(core.EventArgs): """ The SetupChangeEventArgs provides information associated with a change event of a setup. """ def __init__(self): pass @staticmethod def cast(arg) -> SetupChangeEventArgs: return SetupChangeEventArgs() @property def setup(self) -> Setup: """ Provides access to the setup. Can be null in the case where the event is fired before the setup has been created or after it has been deleted. """ return Setup() @property def info(self) -> str: """ Provides access to an information string. The optional string may contain additional information about the change. """ return str() @property def type(self) -> SetupChangeEventType: """ The type specifies the actual change. """ return SetupChangeEventType() class SetupEvent(core.Event): """ A SetupEvent represents a setup related event. For example, SetupCreated or SetupDestroying. """ def __init__(self): pass @staticmethod def cast(arg) -> SetupEvent: return SetupEvent() def add(self, handler: SetupEventHandler) -> bool: """ Add a handler to be notified when the file event occurs. handler : The handler object to be called when this event is fired. Returns true if the addition of the handler was successful. """ return bool() def remove(self, handler: SetupEventHandler) -> bool: """ Removes a handler from the event. handler : The handler object to be removed from the event. Returns true if removal of the handler was successful. """ return bool() class SetupEventArgs(core.EventArgs): """ The SetupEventArgs provides information associated with a setup event. """ def __init__(self): pass @staticmethod def cast(arg) -> SetupEventArgs: return SetupEventArgs() @property def setup(self) -> Setup: """ Provides access to the setup. Can be null in the case where the event is fired before the setup has been created or after it has been deleted. """ return Setup() class StringParameterValue(ParameterValue): """ A parameter value that is a string. """ def __init__(self): pass @staticmethod def cast(arg) -> StringParameterValue: return StringParameterValue() @property def value(self) -> str: """ Get or set the value of the parameter. """ return str() @value.setter def value(self, value: str): """ Get or set the value of the parameter. """ pass class CadMultiPointOnSurfaceParameterValue(CadObjectParameterValue): """ A parameter value that is a CadMultiPointOnSurface. """ def __init__(self): pass @staticmethod def cast(arg) -> CadMultiPointOnSurfaceParameterValue: return CadMultiPointOnSurfaceParameterValue() @property def values(self) -> list[core.Point3D]: """ Get/Set the values of the parameter as a vector of Point3D positions. Points are in CM units. Points are in model coordinates. """ return [core.Point3D()] @values.setter def values(self, value: list[core.Point3D]): """ Get/Set the values of the parameter as a vector of Point3D positions. Points are in CM units. Points are in model coordinates. """ pass class CAMPattern(CAMFolder): """ Object that represents a pattern in an existing Setup, Folder or Pattern. """ def __init__(self): pass @staticmethod def cast(arg) -> CAMPattern: return CAMPattern()
34.979926
191
0.637637
12,802
113,265
5.615841
0.085299
0.028918
0.012393
0.0169
0.600732
0.562578
0.532812
0.505327
0.478121
0.453112
0
0.00321
0.293074
113,265
3,237
192
34.990732
0.89468
0.482735
0
0.617787
1
0
0
0
0
0
0
0
0
1
0.32926
false
0.106585
0.002037
0.047522
0.665988
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
1
0
0
1
0
0
4
baca6e003cff493aabead3bb6fe20157f71121aa
629
py
Python
stable_baselines3/common/envs/__init__.py
martinwimpff/stable-baselines3-hmlf
6ffa947760f8c42a09f9ae42aa7485c608efc42d
[ "MIT" ]
null
null
null
stable_baselines3/common/envs/__init__.py
martinwimpff/stable-baselines3-hmlf
6ffa947760f8c42a09f9ae42aa7485c608efc42d
[ "MIT" ]
null
null
null
stable_baselines3/common/envs/__init__.py
martinwimpff/stable-baselines3-hmlf
6ffa947760f8c42a09f9ae42aa7485c608efc42d
[ "MIT" ]
null
null
null
from stable_baselines3.common.envs.bit_flipping_env import BitFlippingEnv from stable_baselines3.common.envs.dummy_env import DummyEnv from stable_baselines3.common.envs.dummy_hybrid import DummyHybrid from stable_baselines3.common.envs.identity_env import ( FakeImageEnv, IdentityEnv, IdentityEnvBox, IdentityEnvMultiBinary, IdentityEnvMultiDiscrete, ) from stable_baselines3.common.envs.multi_input_envs import SimpleMultiObsEnv from stable_baselines3.common.envs.wrap_environment import wrap_environment from stable_baselines3.common.envs.wrapper import OneHotWrapper, SequenceWrapper, SimpleHybridWrapper
44.928571
101
0.863275
71
629
7.422535
0.408451
0.132827
0.265655
0.345351
0.417457
0.132827
0
0
0
0
0
0.012216
0.08903
629
13
102
48.384615
0.907504
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.538462
0
0.538462
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
1
0
1
0
0
0
0
4
240d9e58c18ab9952a7c1601d98f9d97c0eebdd4
124
py
Python
savu/plugins/driver/cpu_plugin_tools.py
elainehoml/Savu
e4772704606f71d6803d832084e10faa585e7358
[ "Apache-2.0" ]
39
2015-03-30T14:03:42.000Z
2022-03-16T16:50:33.000Z
savu/plugins/driver/cpu_plugin_tools.py
elainehoml/Savu
e4772704606f71d6803d832084e10faa585e7358
[ "Apache-2.0" ]
670
2015-02-11T11:08:09.000Z
2022-03-21T09:27:57.000Z
savu/plugins/driver/cpu_plugin_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 CpuPluginTools(PluginTools): """The driver for Cpu plugins."""
24.8
49
0.774194
15
124
6.333333
0.866667
0
0
0
0
0
0
0
0
0
0
0
0.129032
124
4
50
31
0.87963
0.217742
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.5
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
240e921bed934739b7633a27bda7278bcbbdb8eb
693
py
Python
work_calendar_ru/data/holidays.py
SLRover/work-calendar-ru
623b03713c4fed20790cecfe7cc1e09ab7e313ca
[ "MIT" ]
3
2019-10-22T11:33:54.000Z
2021-08-19T07:45:58.000Z
work_calendar_ru/data/holidays.py
SLRover/work-calendar-ru
623b03713c4fed20790cecfe7cc1e09ab7e313ca
[ "MIT" ]
4
2019-10-25T14:25:40.000Z
2019-11-07T20:44:39.000Z
work_calendar_ru/data/holidays.py
SLRover/work-calendar-ru
623b03713c4fed20790cecfe7cc1e09ab7e313ca
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import datetime holidays = [ datetime.date(2020, 1, 1), datetime.date(2020, 1, 2), datetime.date(2020, 1, 3), datetime.date(2020, 1, 4), datetime.date(2020, 1, 5), datetime.date(2020, 1, 6), datetime.date(2020, 1, 7), datetime.date(2020, 1, 8), datetime.date(2020, 2, 24), datetime.date(2020, 3, 9), datetime.date(2020, 5, 1), datetime.date(2020, 5, 4), datetime.date(2020, 5, 5), datetime.date(2020, 5, 11), datetime.date(2020, 6, 12), datetime.date(2020, 11, 4) ] short_days = [ datetime.date(2020, 4, 30), datetime.date(2020, 5, 8), datetime.date(2020, 6, 11), datetime.date(2020, 11, 3), datetime.date(2020, 12, 31) ] work_weekends = []
38.5
114
0.637807
115
693
3.826087
0.217391
0.572727
0.763636
0.309091
0
0
0
0
0
0
0
0.232877
0.157287
693
17
115
40.764706
0.520548
0.030303
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.083333
0
0.083333
0
0
0
0
null
1
1
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
4
032cf2eac3d111c1d25491470d096d0f3396d7aa
198
py
Python
app/meetings/api/serializers.py
kaizumaki/owaranai-meter
aa4703f84116c9d6bac558f301de2389c9175fdf
[ "MIT" ]
5
2021-02-04T14:16:12.000Z
2021-02-19T12:36:50.000Z
app/meetings/api/serializers.py
kaizumaki/owaranai-meter
aa4703f84116c9d6bac558f301de2389c9175fdf
[ "MIT" ]
27
2021-02-11T04:49:39.000Z
2021-08-22T07:34:39.000Z
app/meetings/api/serializers.py
kaizumaki/owaranai-meter
aa4703f84116c9d6bac558f301de2389c9175fdf
[ "MIT" ]
6
2021-02-04T14:16:28.000Z
2021-02-27T07:14:38.000Z
from rest_framework import serializers from meetings.models import Meeting class MeetingSerializer(serializers.ModelSerializer): class Meta: model = Meeting fields = "__all__"
22
53
0.747475
20
198
7.15
0.75
0
0
0
0
0
0
0
0
0
0
0
0.20202
198
8
54
24.75
0.905063
0
0
0
0
0
0.035354
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.666667
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
032d82918fc429670cd57eb1409ac1a5ba94da1f
893
py
Python
samples.py
AIshutin/magic-rpg
140f4d313ea316e033c09aa9b11394a64aea9555
[ "Apache-2.0" ]
null
null
null
samples.py
AIshutin/magic-rpg
140f4d313ea316e033c09aa9b11394a64aea9555
[ "Apache-2.0" ]
null
null
null
samples.py
AIshutin/magic-rpg
140f4d313ea316e033c09aa9b11394a64aea9555
[ "Apache-2.0" ]
null
null
null
from techs import Technologie as Tech biodescr = "Often child is like his parents. At least child's appearence is similiar to his ancestors. It's working with all around: plants, animals and races. You can track down ancestors of the creature to predict it's properties. You can breed creatures for creating new that you look for. Genome - is something that stores information about these properties. When creatures breed it's genomes mix in new ways. It can be used for farming and in military goals as a way to create war beasts/warriors. Also it's important to save best genome samples and breed them with each outher. After a few generations the result will improve it's ancestors." print(biodescr.count(' '), len(biodescr)) genome = Tech(name='Genome&Selection', description=biodescr, level=3) "A knight can touch metall in a special glow and his shell will be made from same metall. "
111.625
648
0.786114
152
893
4.618421
0.638158
0.021368
0
0
0
0
0
0
0
0
0
0.001335
0.161254
893
8
649
111.625
0.935915
0
0
0
0
0.2
0.828859
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
0.2
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
1
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
034036b58991f8e9d78576ffa8134722eb90902c
4,440
py
Python
graphs_trees/bst/bst_solution.py
stephank007/python_challenges
dfd8d18c03a06735f6e4e02b0660007fe2d02f07
[ "Apache-2.0" ]
null
null
null
graphs_trees/bst/bst_solution.py
stephank007/python_challenges
dfd8d18c03a06735f6e4e02b0660007fe2d02f07
[ "Apache-2.0" ]
null
null
null
graphs_trees/bst/bst_solution.py
stephank007/python_challenges
dfd8d18c03a06735f6e4e02b0660007fe2d02f07
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Solution Notebook # ## Problem: Implement a binary search tree with an insert method. # # * [Constraints](#Constraints) # * [Test Cases](#Test-Cases) # * [Algorithm](#Algorithm) # * [Code](#Code) # * [Unit Test](#Unit-Test) # ## Constraints # # * Can we insert None values? # * No # * Can we assume we are working with valid integers? # * Yes # * Can we assume all left descendents <= n < all right descendents? # * Yes # * Do we have to keep track of the parent nodes? # * This is optional # * Can we assume this fits in memory? # * Yes # ## Test Cases # # ### Insert # # Insert will be tested through the following traversal: # # ### In-Order Traversal # # * 5, 2, 8, 1, 3 -> 1, 2, 3, 5, 8 # * 1, 2, 3, 4, 5 -> 1, 2, 3, 4, 5 # # If the `root` input is `None`, return a tree with the only element being the new root node. # # You do not have to code the in-order traversal, it is part of the unit test. # ## Algorithm # # ### Insert # # * If the root is None, return Node(data) # * If the data is <= the current node's data # * If the current node's left child is None, set it to Node(data) # * Else, recursively call insert on the left child # * Else # * If the current node's right child is None, set it to Node(data) # * Else, recursively call insert on the right child # # Complexity: # # * Time: O(h), where h is the height of the tree # * In a balanced tree, the height is O(log(n)) # * In the worst case we have a linked list structure with O(n) # * Space: O(m), where m is the recursion depth, or O(1) if using an iterative approach # ## Code # In[1]: get_ipython().run_cell_magic('writefile', 'bst.py', "class Node(object):\n\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n self.parent = None\n\n def __repr__(self):\n return str(self.data)\n\n\nclass Bst(object):\n\n def __init__(self, root=None):\n self.root = root\n\n def insert(self, data):\n if data is None:\n raise TypeError('data cannot be None')\n if self.root is None:\n self.root = Node(data)\n return self.root\n else:\n return self._insert(self.root, data)\n\n def _insert(self, node, data):\n if node is None:\n return Node(data)\n if data <= node.data:\n if node.left is None:\n node.left = self._insert(node.left, data)\n node.left.parent = node\n return node.left\n else:\n return self._insert(node.left, data)\n else:\n if node.right is None:\n node.right = self._insert(node.right, data)\n node.right.parent = node\n return node.right\n else:\n return self._insert(node.right, data)") # In[2]: get_ipython().run_line_magic('run', 'bst.py') # ## Unit Test # In[3]: get_ipython().run_line_magic('run', 'dfs.py') # In[4]: get_ipython().run_line_magic('run', '../utils/results.py') # In[5]: get_ipython().run_cell_magic('writefile', 'test_bst.py', "import unittest\n\n\nclass TestTree(unittest.TestCase):\n\n def __init__(self, *args, **kwargs):\n super(TestTree, self).__init__()\n self.results = Results()\n\n def test_tree_one(self):\n bst = Bst()\n bst.insert(5)\n bst.insert(2)\n bst.insert(8)\n bst.insert(1)\n bst.insert(3)\n in_order_traversal(bst.root, self.results.add_result)\n self.assertEqual(str(self.results), '[1, 2, 3, 5, 8]')\n self.results.clear_results()\n\n def test_tree_two(self):\n bst = Bst()\n bst.insert(1)\n bst.insert(2)\n bst.insert(3)\n bst.insert(4)\n bst.insert(5)\n in_order_traversal(bst.root, self.results.add_result)\n self.assertEqual(str(self.results), '[1, 2, 3, 4, 5]')\n\n print('Success: test_tree')\n\n\ndef main():\n test = TestTree()\n test.test_tree_one()\n test.test_tree_two()\n\n\nif __name__ == '__main__':\n main()") # In[6]: get_ipython().run_line_magic('run', '-i test_bst.py')
43.529412
1,262
0.60045
700
4,440
3.708571
0.242857
0.010015
0.038521
0.026194
0.359399
0.276579
0.163328
0.102465
0.102465
0.102465
0
0.014432
0.250901
4,440
101
1,263
43.960396
0.766085
0.393694
0
0
0
0.333333
0.875433
0.183775
0
0
0
0
0.166667
1
0
true
0
0.166667
0
0.166667
0.166667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
036df1466e36ebb6d8218aab2d10c0618e39a382
92,360
py
Python
freee/freee.py
datagrid-okada/python-freee-api
d023267a5442cf0e8f30f7ceab076d74c65cf5ce
[ "MIT" ]
2
2021-02-22T17:06:01.000Z
2022-03-18T07:05:24.000Z
freee/freee.py
datagrid-okada/python-freee-api
d023267a5442cf0e8f30f7ceab076d74c65cf5ce
[ "MIT" ]
null
null
null
freee/freee.py
datagrid-okada/python-freee-api
d023267a5442cf0e8f30f7ceab076d74c65cf5ce
[ "MIT" ]
null
null
null
import requests import json import urllib.parse import time class Freee(): def __init__(self, client_id, client_secret, company_id, token_filename): self.client_id = client_id self.client_secret = client_secret self.token_filename = token_filename self.redirect_uri = 'urn:ietf:wg:oauth:2.0:oob' self.authorize_api_url = 'https://accounts.secure.freee.co.jp/public_api/token' self.account_endpoint = "https://api.freee.co.jp/api/1/" self.hr_endpoint = "https://api.freee.co.jp/hr/api/v1/" self.company_id = company_id # =========================================== # 認証系 # =========================================== def save_tokens(self, token_dict): f = open(self.token_filename, "w") json.dump(token_dict, f, ensure_ascii=False, indent=4, sort_keys=True, separators=(',', ': ')) def read_tokens(self): with open(self.token_filename) as f: return json.load(f) def get_access_token(self, authorization_code): params = { 'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': authorization_code, 'redirect_uri': self.redirect_uri } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } res = requests.post(self.authorize_api_url, params=params, headers=headers) if res.ok: self.save_tokens(res.json()) else: print("client_id, client_secret, authorization_codeのいずれかに不備がある可能性があります。再度認証コードを取得してください") raise res.raise_for_status() def set_tokens(self, token_dict): self.access_token = token_dict["access_token"] self.access_token_expired_at = token_dict["created_at"] + token_dict["expires_in"] self.refresh_token = token_dict["refresh_token"] def run_refresh_token(self): params = { "grant_type": "refresh_token", "client_id": self.client_id, "client_secret": self.client_secret, "refresh_token": self.refresh_token } res = requests.post(self.authorize_api_url, data=params) if res.ok: token_dict = res.json() self.set_tokens(token_dict) self.save_tokens(token_dict) else: print("client_id, client_secret, refresh_tokenのいずれかに不備がある可能性があります") raise res.raise_for_status() # =========================================== # リクエスト系 # =========================================== def confirm_expired(self): return True if time.time() - self.access_token_expired_at >= 0 else False def send_request(self, request_method, url, payload): if self.confirm_expired(): self.run_refresh_token() if request_method == "get": headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + self.access_token } res = requests.get(url, headers=headers, params=payload) if res.ok: return res.json() else: raise res.raise_for_status() elif request_method == "put": headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + self.access_token } res = requests.put(url, headers=headers, data=json.dumps(payload)) if res.ok: return res.json() else: raise res.raise_for_status() elif request_method == "delete": headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + self.access_token } res = requests.delete(url, headers=headers, data=json.dumps(payload)) if res.ok: return res else: raise res.raise_for_status() # =========================================== # 会計freee API # =========================================== # =========================================== # Account items(勘定科目) # =========================================== def get_account_item(self, account_item_id, **payload): """指定した勘定科目の詳細を取得 指定した勘定科目の詳細を取得する Args: account_item_id (int): 勘定科目ID company_id (int): 事務所ID Returns: dict: like below { "account_item": { "id": 1, "name": "ソフトウェア", "company_id": 1, "tax_code": 1, "account_category_id": 1, "shortcut": "SOFUTO", "shortcut_num": "123", "corresponding_type_expense": 5, "corresponding_type_income": 2, "searchable": 2, "accumulated_dep_account_item_name": "減価償却累計額", "items": [ { "name": "住民税", "id": 1 } ], "partners": [ { "name": "test", "id": 1 } ], "available": true } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["account_items", str(account_item_id)])) return self.send_request(request_method, url, payload) def get_account_items(self, **payload): """ 勘定科目一覧の取得 指定した事業所の勘定科目一覧を取得する Args: company_id (int): 事務所ID base_date (str, optional): 基準日:指定した場合、勘定科目に紐づく税区分(default_tax_code)が、基準日の税率に基づいて返ります。 Returns: dict: like below { "account_items": [ { "id": 1, "name": "ソフトウェア", "default_tax_id": 34, "default_tax_code": 34, "categories": [ "資産" ], "available": true } ] } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, "account_items") return self.send_request(request_method, url, payload) # =========================================== # Banks (連携サービス) # =========================================== # =========================================== # Companies(事務所) # =========================================== def get_companies(self, **payload): """事業所一覧の取得 事業所一覧の取得 Args: No parameters Returns: dict: like below { "account_item": { "id": 1, "name": "ソフトウェア", "company_id": 1, "tax_code": 1, "account_category_id": 1, "shortcut": "SOFUTO", "shortcut_num": "123", "corresponding_type_expense": 5, "corresponding_type_income": 2, "searchable": 2, "accumulated_dep_account_item_name": "減価償却累計額", "items": [ { "name": "住民税", "id": 1 } ], "partners": [ { "name": "test", "id": 1 } ], "available": true } } Notes: 定義 role admin : 管理者 simple_accounting : 一般 self_only : 取引登録のみ read_only : 閲覧のみ """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, "companies") return self.send_request(request_method, url, payload) def get_company(self, company_id, **payload): """事業所の詳細情報の取得 ユーザが所属する事業所の詳細を取得する Args: id (int): 事業所ID details (bool): 取得情報に勘定科目・税区分コード・税区分・品目・取引先・部門・メモタグ・口座の一覧を含める. Available values : true account_items (bool): 取得情報に勘定科目一覧を含める. Available values : true taxes (bool): 取得情報に税区分コード・税区分一覧を含める. Available values : true items (bool): 取得情報に品目一覧を含める. Available values : true partners (bool): 取得情報に取引先一覧を含める. Available values : true sections (bool): 取得情報に部門一覧を含める. Available values : true tags (bool): 取得情報にメモタグ一覧を含める. Available values : true walletables (bool): 取得情報に口座一覧を含める. Available values : true Returns: dict: like below { "company": { "id": 1, "display_name": "freee事務所", "tax_at_source_calc_type": 0, "corporate_number": "1234567890123", "txn_number_format": "not_used", "default_wallet_account_id": 1, "private_settlement": true, "minus_format": 0, "role": "admin", "phone1": "03-1234-xxxx", "zipcode": "000-0000", "prefecture_code": 4, "street_name1": "XX区YY1−1−1", "street_name2": "ビル1F", "invoice_layout": 0, "invoice_style": 0, "amount_fraction": 0, "industry_class": "agriculture_forestry_fisheries_ore", "industry_code": "transport_delivery", "workflow_setting": "disabled", "use_partner_code": true } } Notes: 定義 role admin : 管理者 simple_accounting : 一般 self_only : 取引登録のみ read_only : 閲覧のみ """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["companies", str(company_id)])) return self.send_request(request_method, url, payload) # =========================================== # Deals(取引(収入/支出)) # =========================================== def get_deals(self, **payload): """取引一覧(収入/支出)の取得 指定した事業所の取引一覧(収入/支出)を取得する Args: company_id (int): 事務所ID partner_id (int, optional): 取引先ID account_item_id (int, optional): 勘定科目ID partner_code (str, optional): 取引先コード status (str, optional): 決済状況 (未決済: unsettled, 完了: settled) type (str, optional): 収支区分 (収入: income, 支出: expense) start_issue_date (string, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_issue_date (str, optional): 発生日で絞込:終了日(yyyy-mm-dd) start_due_date (str, optional): 支払期日で絞込:開始日(yyyy-mm-dd) end_due_date (str, optional): 支払期日で絞込:終了日(yyyy-mm-dd) start_renew_date (str, optional): +更新日で絞込:開始日(yyyy-mm-dd) end_renew_date (str, optional): +更新日で絞込:終了日(yyyy-mm-dd) offset (int, optional): 取得レコードのオフセット (デフォルト: 0) limit (int, optional): 取得レコードの件数 (デフォルト: 20, 最大: 100) registered_from (str, optional): 取引登録元アプリで絞込(me: 本APIを叩くアプリ自身から登録した取引のみ) accruals (str, optional): 取引の債権債務行の表示(without: 表示しない(デフォルト), with: 表示する) Returns: dict: like below { "deals": [ { "id": 101, "company_id": 1, "issue_date": "2013-01-01", "due_date": "2013-02-28", "amount": 5250, "due_amount": 0, "type": "expense", "partner_id": 201, "ref_number": "123-456", "status": "settled", "details": [ { "id": 11, "account_item_id": 803, "tax_id": 14, "tax_code": 2, "tag_ids": [ 1, 2, 3 ], "amount": 5250, "vat": 250, "description": "備考", "entry_side": "debit" } ], "renews": [ { "id": 11, "update_date": "2014-01-01", "renew_target_id": 12, "renew_target_type": "detail", "details": [ { "tax_code": 1, "tag_ids": [ 1 ], "amount": 108000, "account_item_id": 1, "vat": 8000, "id": 1, "entry_side": "debit" } ] } ], "payments": [ { "id": 202, "date": "2013-01-28", "from_walletable_type": "bank_account", "from_walletable_id": 103, "amount": 5250 } ] } ], "meta": { "total_count": 100 } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, "deals") return self.send_request(request_method, url, payload) def get_deal(self, deal_id, **payload): """取引(収入/支出)の取得 指定した事業所の取引(収入/支出)を取得する Args: deal_id (int): 取引ID company_id (int): 事務所ID accruals(str, optional): 取引の債権債務行の表示(without: 表示しない(デフォルト), with: 表示する) Returns: dict: like below { "deal": { "id": 101, "company_id": 1, "issue_date": "2013-01-01", "due_date": "2013-02-28", "amount": 5250, "due_amount": 0, "type": "expense", "partner_id": 201, "ref_number": "123-456", "status": "settled", "details": [ { "id": 11, "account_item_id": 803, "tax_id": 14, "tax_code": 2, "tag_ids": [ 1, 2, 3 ], "amount": 5250, "vat": 250, "description": "備考", "entry_side": "debit" } ], "renews": [ { "id": 11, "update_date": "2014-01-01", "renew_target_id": 12, "renew_target_type": "detail", "details": [ { "tax_code": 1, "tag_ids": [ 1 ], "amount": 108000, "account_item_id": 1, "vat": 8000, "id": 1, "entry_side": "debit" } ] } ], "payments": [ { "id": 202, "date": "2013-01-28", "from_walletable_type": "bank_account", "from_walletable_id": 103, "amount": 5250 } ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["deals", str(deal_id)])) return self.send_request(request_method, url, payload) # =========================================== # Expense application line templates(経費科目) # =========================================== def get_expense_application_line_templates(self, **payload): """経費科目一覧の取得 指定した事業所の経費科目一覧を取得する Args: offset (int): 取得レコードのオフセット (デフォルト: 0) limit (int): 取得レコードの件数 (デフォルト: 20, 最大: 100) Returns: dict: like below { "expense_application_line_templates": [ { "id": 1, "name": "交通費", "account_item_name": "旅費交通費", "tax_name": "課対仕入", "description": "電車、バス、飛行機などの交通費", "line_description": "移動区間" } ] } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, "expense_application_line_templates") return self.send_request(request_method, url, payload) # =========================================== # Journals (仕訳帳) # =========================================== def get_request_downloading_journals(self, **payload): """ダウンロード要求 ユーザが所属する事業所の仕訳帳のダウンロードをリクエストします 生成されるファイルに関しては、ヘルプページをご参照ください Args: download_type (str): ダウンロード形式. Available values : csv, pdf, yayoi, generic company_id (int): 事業所ID visible_tags (array[string], optional): 補助科目やコメントとして出力する項目. Available values : partner, item, tag, section, description, wallet_txn_description, all start_date (str, optional): 取得開始日 (yyyy-mm-dd) end_date (str, optional): 取得終了日 (yyyy-mm-dd) Note: 定義 download_type csv pdf yayoi (csv alias) generic visible_tags : 指定しない場合は従来の仕様の仕訳帳が出力されます partner : 取引先タグ item : 品目タグ tag : メモタグ section : 部門タグ description : 備考欄 wallet_txn_description : 明細の備考欄 all : 指定された場合は上記の設定をすべて有効として扱います id : 受け付けID Returns: dict: like below { "journals": { "id": 1, "messages": ":id でリクエストを受け付けました。", "company_id": 1, "download_type": "csv", "start_date": "2017-05-01", "end_date": "2017-05-31", "visible_tags": [ "all" ], "status_url": "https://api.freee.co.jp/api/1/journals/reports/4/status" } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, "journals") return self.send_request(request_method, url, payload) def get_downloading_journals_status(self, id, **payload): """ステータス確認 ダウンロードリクエストのステータスを確認する *このAPIは無料プランのアカウントではご利用になれません Args: company_id (int): 事業所ID id (int): 受付ID visible_tags (array[string], optional): 補助科目やコメントとして出力する項目. Available values : partner, item, tag, section, description, wallet_txn_description, all start_date (str, optional): 取得開始日 (yyyy-mm-dd) end_date (str, optional): 取得終了日 (yyyy-mm-dd) Note: 定義 enqueued : 実行待ち working : 実行中 uploaded : 準備完了 id : 受け付けID Returns: dict: like below { "journals": { "id": 1, "company_id": 1, "download_type": "csv", "status": "csv", "start_date": "2017-05-01", "end_date": "2017-05-31", "visible_tags": [ "all" ], "download_url": "https://api.freee.co.jp/api/1/journals/reports/1/download" } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["journals", "reports", id, "status"])) return self.send_request(request_method, url, payload) def get_download_journals(self, id, **payload): """ダウンロード実行 ダウンロードを実行する *このAPIは無料プランのアカウントではご利用になれません *レスポンスを直接returnしているので注意 Args: company_id (int): 事業所ID id (int): 受付ID Note: 定義 id : 受け付けID Returns: None """ url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["journals", "reports", id, "download"])) if self.confirm_expired(): token_dict = self.run_refresh_token() self.save_tokens(token_dict) headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + self.access_token } res = requests.get(url, headers=headers, params=payload) if res.ok: return res else: raise res.raise_for_status() # =========================================== # ManualJournals (振替伝票) # =========================================== def get_manual_journals(self, **payload): """振替伝票一覧の取得 指定した事業所の振替伝票一覧を取得する Args: company_id (int): 事業所ID start_issue_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_issue_date (str, optional): 発生日で絞込:終了日(yyyy-mm-dd) entry_side (str, optional): 貸借で絞込 (貸方: credit, 借方: debit). Available values : credit, debit account_item_id (int, optional): 勘定科目IDで絞込 min_amount (int, optional): 金額で絞込:下限 max_amount (int, optional): 金額で絞込:上限 partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択の貸借行を絞り込めます) partner_code (str, optional): 取引先コードで絞込 item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択の貸借行を絞り込めます) section_id (int, optional): 部門IDで絞込(0を指定すると、部門が未選択の貸借行を絞り込めます) segment_1_tag_id (int, optional): セグメント1IDで絞り込み(0を指定すると、セグメント1が未選択の貸借行を絞り込めます) segment_2_tag_id (int, optional): セグメント2IDで絞り込み(0を指定すると、セグメント2が未選択の貸借行を絞り込めます) segment_3_tag_id (int, optional): セグメント3IDで絞り込み(0を指定すると、セグメント3が未選択の貸借行を絞り込めます) comment_status (str, optional): コメント状態で絞込(自分宛のコメント: posted_with_mention, 自分宛のコメント-未解決: raised_with_mention, 自分宛のコメント-解決済: resolved_with_mention, コメントあり: posted, 未解決: raised, 解決済: resolved, コメントなし: none)Available values : posted_with_mention, raised_with_mention, resolved_with_mention, posted, raised, resolved, none comment_important (bool, optional): 重要コメント付きの振替伝票を絞込 adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without).Available values : only, without txn_number (str, optional): 仕訳番号で絞込(事業所の仕訳番号形式が有効な場合のみ) offset (int, optional): 取得レコードのオフセット (デフォルト: 0) limit (int, optional): 取得レコードの件数 (デフォルト: 20, 最大: 500) Note: 定義 issue_date : 発生日 adjustment : 決算整理仕訳フラグ(true: 決算整理仕訳, false: 日常仕訳) txn_number : 仕訳番号 details : 振替伝票の貸借行 entry_side : 貸借区分 credit : 貸方 debit : 借方 amount : 金額 注意点 振替伝票は売掛・買掛レポートには反映されません。債権・債務データの登録は取引(Deals)をお使いください。 事業所の仕訳番号形式が有効な場合のみ、レスポンスで仕訳番号(txn_number)を返します。 セグメントタグ情報は法人向けのプロフェッショナルプラン以上で利用可能です。利用可能なセグメントの数は、法人向けのプロフェッショナルプランの場合は1つ、エンタープライズプランの場合は3つです。 partner_codeを利用するには、事業所の設定から取引先コードの利用を有効にする必要があります。またpartner_codeとpartner_idは同時に指定することはできません。 Returns: dict: like below { "manual_journals": [ { "id": 1, "company_id": 1, "issue_date": "2018-01-01", "adjustment": false, "details": [ { "id": 1, "entry_side": "credit", "account_item_id": 1, "tax_code": 1, "tag_ids": [ 1 ], "tag_names": [ "メモタグ" ], "segment_1_tag_id": 1, "segment_1_tag_name": 0, "segment_2_tag_id": 1, "segment_2_tag_name": 0, "segment_3_tag_id": 1, "segment_3_tag_name": 0, "amount": 108000, "vat": 8000, "description": "備考" } ] } ] } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, "manual_journals") return self.send_request(request_method, url, payload) def get_manual_journal(self, id, **payload): """振替伝票の取得 指定した事業所の振替伝票を取得する Args: company_id (int): 事業所ID id (int): 振替伝票ID Note: 定義 issue_date : 発生日 adjustment : 決算整理仕訳フラグ(true: 決算整理仕訳, false: 日常仕訳) txn_number : 仕訳番号 details : 振替伝票の貸借行 entry_side : 貸借区分 credit : 貸方 debit : 借方 amount : 金額 注意点 振替伝票は売掛・買掛レポートには反映されません。債権・債務データの登録は取引(Deals)をお使いください。 事業所の仕訳番号形式が有効な場合のみ、レスポンスで仕訳番号(txn_number)を返します。 セグメントタグ情報は法人向けのプロフェッショナルプラン以上で利用可能です。利用可能なセグメントの数は、法人向けのプロフェッショナルプランの場合は1つ、エンタープライズプランの場合は3つです。 Returns: dict: like below { "manual_journal": { "id": 1, "company_id": 1, "issue_date": "2018-01-01", "adjustment": false, "details": [ { "id": 1, "entry_side": "credit", "account_item_id": 1, "tax_code": 1, "tag_ids": [ 1 ], "tag_names": [ "メモタグ" ], "segment_1_tag_id": 1, "segment_1_tag_name": 0, "segment_2_tag_id": 1, "segment_2_tag_name": 0, "segment_3_tag_id": 1, "segment_3_tag_name": 0, "amount": 108000, "vat": 8000, "description": "備考" } ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["manual_journals", id])) return self.send_request(request_method, url, payload) # =========================================== # Trial balance (試算表) # =========================================== def get_reports_trial_bs(self, **payload): """貸借対照表の取得 指定した事業所の貸借対照表を取得する Args: company_id (int): 事業所ID fiscal_year (int, optional): 会計年度 start_month (int, optional): 発生月で絞込:開始会計月(mm) end_month (int, optional): 発生月で絞込:終了会計月(mm) start_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_date (str, optional) 発生日で絞込:終了日(yyyy-mm-dd) account_item_display_type (str, optional): 勘定科目の表示(勘定科目: account_item, 決算書表示:group). Available values : account_item, group breakdown_display_type (str, optional): 内訳の表示(取引先: partner, 品目: item, 勘定科目: account_item) ※勘定科目はaccount_item_display_typeが「group」の時のみ指定できます. Available values : partner, item, account_item partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択で絞り込めます) partner_code (str, optional): 取引先コードで絞込(事業所設定で取引先コードの利用を有効にしている場合のみ利用可能です) item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択で絞り込めます) adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without). Available values : only, without Note: 定義 created_at : 作成日時 account_item_name : 勘定科目名 hierarchy_level: 階層レベル parent_account_item_name: 親の勘定科目名 opening_balance : 期首残高 debit_amount : 借方金額 credit_amount: 貸方金額 closing_balance : 期末残高 composition_ratio : 構成比 注意点 会計年度が指定されない場合、現在の会計年度がデフォルトとなります。 絞り込み条件の日付と、月または年度は同時に指定することはできません。 Returns: dict: like below { "trial_bs": { "company_id": 1, "fiscal_year": 2019, "start_month": 1, "end_month": 12, "start_date": "2019-01-01", "end_date": "2019-12-31", "account_item_display_type": "account_item", "breakdown_display_type": "partner", "partner_id": 1, "partner_code": "code001", "item_id": 1, "adjustment": "only", "created_at": "2018-09-10T13:47:24.000+09:00", "balances": [ { "account_item_id": 192, "account_item_name": "現金", "partners": [ { "id": 22, "name": "freee", "opening_balance": 0, "debit_amount": 0, "credit_amount": 2592, "closing_balance": -25920, "composition_ratio": 0.85 } ], "items": [ { "id": 1, "name": "源泉所得税", "opening_balance": 0, "debit_amount": 0, "credit_amount": 2592, "closing_balance": -25920, "composition_ratio": 0.85 } ], "account_category_id": 8, "account_category_name": "流動資産", "total_line": true, "hierarchy_level": 3, "parent_account_category_id": 19, "parent_account_category_name": "他流動資産", "opening_balance": 0, "debit_amount": 0, "credit_amount": 2592, "closing_balance": -25920, "composition_ratio": 0.85 } ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["reports", "trial_bs"])) return self.send_request(request_method, url, payload) def get_reports_trial_bs_two_years(self, **payload): """貸借対照表(前年比較)の取得 指定した事業所の貸借対照表(前年比較)を取得する Args: company_id (int): 事業所ID fiscal_year (int, optional): 会計年度 start_month (int, optional): 発生月で絞込:開始会計月(mm) end_month (int, optional): 発生月で絞込:終了会計月(mm) start_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_date (str, optional) 発生日で絞込:終了日(yyyy-mm-dd) account_item_display_type (str, optional): 勘定科目の表示(勘定科目: account_item, 決算書表示:group). Available values : account_item, group breakdown_display_type (str, optional): 内訳の表示(取引先: partner, 品目: item, 勘定科目: account_item) ※勘定科目はaccount_item_display_typeが「group」の時のみ指定できます. Available values : partner, item, account_item partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択で絞り込めます) partner_code (str, optional): 取引先コードで絞込(事業所設定で取引先コードの利用を有効にしている場合のみ利用可能です) item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択で絞り込めます) adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without). Available values : only, without Note: 定義 created_at : 作成日時 account_item_name : 勘定科目名 hierarchy_level: 階層レベル parent_account_item_name: 親の勘定科目名 last_year_closing_balance: 前年度期末残高 closing_balance : 期末残高 注意点 会計年度が指定されない場合、現在の会計年度がデフォルトとなります。 絞り込み条件の日付と、月または年度は同時に指定することはできません。 Returns: dict: like below { "trial_bs_two_years" : { "company_id" : 1, "fiscal_year" : 2017, "created_at" : "2018-05-01 12:00:50" "balances" : [{ "account_item_id" : 1000, "account_item_name" : "現金", "hierarchy_level" : 2, "parent_account_item_id" : 100; "parent_account_item_name" : "流動資産", "last_year_closing_balance" : 25000, "closing_balance" : 100000, "year_on_year" : 0.85 }, ... ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["reports", "trial_bs_two_years"])) return self.send_request(request_method, url, payload) def get_reports_trial_bs_three_years(self, **payload): """貸借対照表(3期間比較)の取得 指定した事業所の貸借対照表(3期間比較)を取得する Args: company_id (int): 事業所ID fiscal_year (int, optional): 会計年度 start_month (int, optional): 発生月で絞込:開始会計月(mm) end_month (int, optional): 発生月で絞込:終了会計月(mm) start_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_date (str, optional) 発生日で絞込:終了日(yyyy-mm-dd) account_item_display_type (str, optional): 勘定科目の表示(勘定科目: account_item, 決算書表示:group). Available values : account_item, group breakdown_display_type (str, optional): 内訳の表示(取引先: partner, 品目: item, 勘定科目: account_item) ※勘定科目はaccount_item_display_typeが「group」の時のみ指定できます. Available values : partner, item, account_item partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択で絞り込めます) partner_code (str, optional): 取引先コードで絞込(事業所設定で取引先コードの利用を有効にしている場合のみ利用可能です) item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択で絞り込めます) adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without). Available values : only, without Note: 定義 created_at : 作成日時 account_item_name : 勘定科目名 hierarchy_level: 階層レベル parent_account_item_name: 親の勘定科目名 closing_balance : 期末残高 two_years_before_closing_balance: 前々年度期末残高 last_year_closing_balance: 前年度期末残高 year_on_year : 前年比 注意点 会計年度が指定されない場合、現在の会計年度がデフォルトとなります。 絞り込み条件の日付と、月または年度は同時に指定することはできません。 Returns: dict: like below { "trial_bs_three_years" : { "company_id" : 1, "fiscal_year" : 2017, "created_at" : "2018-05-01 12:00:50" "balances" : [{ "account_item_id" : 1000, "account_item_name" : "現金", "hierarchy_level" : 2, "parent_account_item_id" : 100; "parent_account_item_name" : "流動資産", "two_year_before_closing_balance" : 50000, "last_year_closing_balance" : 25000, "closing_balance" : 100000, "year_on_year" : 0.85 }, ... ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["reports", "trial_bs_three_years"])) return self.send_request(request_method, url, payload) def get_reports_trial_pl(self, **payload): """損益計算書の取得 指定した事業所の損益計算書(前年比較)を取得する Args: company_id (int): 事業所ID fiscal_year (int, optional): 会計年度 start_month (int, optional): 発生月で絞込:開始会計月(mm) end_month (int, optional): 発生月で絞込:終了会計月(mm) start_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_date (str, optional) 発生日で絞込:終了日(yyyy-mm-dd) account_item_display_type (str, optional): 勘定科目の表示(勘定科目: account_item, 決算書表示:group). Available values : account_item, group breakdown_display_type (str, optional): 内訳の表示(取引先: partner, 品目: item, 勘定科目: account_item) ※勘定科目はaccount_item_display_typeが「group」の時のみ指定できます. Available values : partner, item, account_item partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択で絞り込めます) partner_code (str, optional): 取引先コードで絞込(事業所設定で取引先コードの利用を有効にしている場合のみ利用可能です) item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択で絞り込めます) section_id (int, optional): 部門IDで絞込(0を指定すると、部門が未選択で絞り込めます) adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without). Available values : only, without cost_allocation (str, optional): 配賦仕訳で絞込(配賦仕訳のみ:only,配賦仕訳以外:without)Available values : only, not_include Note: 定義 created_at : 作成日時 account_item_name : 勘定科目名 hierarchy_level: 階層レベル parent_account_item_name: 親の勘定科目名 opening_balance : 期首残高 debit_amount : 借方金額 credit_amount: 貸方金額 closing_balance : 期末残高 composition_ratio : 構成比 注意点 会計年度が指定されない場合、現在の会計年度がデフォルトとなります。 絞り込み条件の日付と、月または年度は同時に指定することはできません。 Returns: dict: like below { "trial_pl" : { "company_id" : 1, "fiscal_year" : 2017, "breakdown_display_type" : "partner", "created_at" : "2018-05-01 12:00:50" "balances" : [{ "account_item_id" : 1500, "account_item_name" : "売上高", "hierarchy_level" : 2, "parent_account_item_id" : 100; "parent_account_item_name" : "営業収益", "opening_balance" : 100000, "debit_amount" : 50000, "credit_amount" : 20000, "closing_balance" : 130000, "composition_ratio" : 0.25 "partners" : [{ "id" : 123, "name" : "freee", "long_name" : "freee株式会社", "opening_balance" : 100000, "debit_amount" : 50000, "credit_amount" : 20000, "closing_balance" : 130000, "composition_ratio" : 0.25 }, ... ] }, ... ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["reports", "trial_pl"])) return self.send_request(request_method, url, payload) def get_reports_trial_pl_two_years(self, **payload): """損益計算書(前年比較)の取得 指定した事業所の損益計算書(前年比較)を取得する Args: company_id (int): 事業所ID fiscal_year (int, optional): 会計年度 start_month (int, optional): 発生月で絞込:開始会計月(mm) end_month (int, optional): 発生月で絞込:終了会計月(mm) start_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_date (str, optional) 発生日で絞込:終了日(yyyy-mm-dd) account_item_display_type (str, optional): 勘定科目の表示(勘定科目: account_item, 決算書表示:group). Available values : account_item, group breakdown_display_type (str, optional): 内訳の表示(取引先: partner, 品目: item, 勘定科目: account_item) ※勘定科目はaccount_item_display_typeが「group」の時のみ指定できます. Available values : partner, item, account_item partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択で絞り込めます) partner_code (str, optional): 取引先コードで絞込(事業所設定で取引先コードの利用を有効にしている場合のみ利用可能です) item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択で絞り込めます) section_id (int, optional): 部門IDで絞込(0を指定すると、部門が未選択で絞り込めます) adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without). Available values : only, without cost_allocation (str, optional): 配賦仕訳で絞込(配賦仕訳のみ:only,配賦仕訳以外:without)Available values : only, not_include Note: 定義 created_at : 作成日時 account_item_name : 勘定科目名 hierarchy_level: 階層レベル parent_account_item_name: 親の勘定科目名 last_year_closing_balance: 前年度期末残高 closing_balance : 期末残高 year_on_year : 前年比 注意点 会計年度が指定されない場合、現在の会計年度がデフォルトとなります。 絞り込み条件の日付と、月または年度は同時に指定することはできません。 Returns: dict: like below { "trial_pl_two_years" : { "company_id" : 1, "fiscal_year" : 2017, "created_at" : "2018-05-01 12:00:50" "balances" : [{ "account_item_id" : 1500, "account_item_name" : "売上高", "hierarchy_level" : 2, "parent_account_item_id" : 100; "parent_account_item_name" : "営業収益", "last_year_closing_balance" : 25000, "closing_balance" : 100000, "year_on_year" : 0.85 }, ... ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["reports", "trial_pl_two_years"])) return self.send_request(request_method, url, payload) def get_reports_trial_pl_three_years(self, **payload): """損益計算書(前年比較)の取得 指定した事業所の損益計算書(3期間比較)を取得する Args: company_id (int): 事業所ID fiscal_year (int, optional): 会計年度 start_month (int, optional): 発生月で絞込:開始会計月(mm) end_month (int, optional): 発生月で絞込:終了会計月(mm) start_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_date (str, optional) 発生日で絞込:終了日(yyyy-mm-dd) account_item_display_type (str, optional): 勘定科目の表示(勘定科目: account_item, 決算書表示:group). Available values : account_item, group breakdown_display_type (str, optional): 内訳の表示(取引先: partner, 品目: item, 勘定科目: account_item) ※勘定科目はaccount_item_display_typeが「group」の時のみ指定できます. Available values : partner, item, account_item partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択で絞り込めます) partner_code (str, optional): 取引先コードで絞込(事業所設定で取引先コードの利用を有効にしている場合のみ利用可能です) item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択で絞り込めます) section_id (int, optional): 部門IDで絞込(0を指定すると、部門が未選択で絞り込めます) adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without). Available values : only, without cost_allocation (str, optional): 配賦仕訳で絞込(配賦仕訳のみ:only,配賦仕訳以外:without)Available values : only, not_include Note: 定義 created_at : 作成日時 account_item_name : 勘定科目名 hierarchy_level: 階層レベル parent_account_item_name: 親の勘定科目名 two_years_before_closing_balance: 前々年度期末残高 last_year_closing_balance: 前年度期末残高 closing_balance : 期末残高 year_on_year : 前年比 注意点 会計年度が指定されない場合、現在の会計年度がデフォルトとなります。 絞り込み条件の日付と、月または年度は同時に指定することはできません。 Returns: dict: like below { "trial_pl_three_years" : { "company_id" : 1, "fiscal_year" : 2017, "created_at" : "2018-05-01 12:00:50" "balances" : [{ "account_item_id" : 1500, "account_item_name" : "売上高", "hierarchy_level" : 2, "parent_account_item_id" : 100; "parent_account_item_name" : "営業収益", "two_year_before_closing_balance" : 50000, "last_year_closing_balance" : 25000, "closing_balance" : 100000, "year_on_year" : 0.85 }, ... ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["reports", "trial_pl_three_years"])) return self.send_request(request_method, url, payload) def get_reports_trial_pl_sections(self, **payload): """損益計算書(部門比較)の取得 指定した事業所の損益計算書(部門比較)を取得する Args: company_id (int): 事業所ID section_ids (str): 出力する部門の指定(半角数字のidを半角カンマ区切りスペースなしで指定してください) fiscal_year (int, optional): 会計年度 start_month (int, optional): 発生月で絞込:開始会計月(mm) end_month (int, optional): 発生月で絞込:終了会計月(mm) start_date (str, optional): 発生日で絞込:開始日(yyyy-mm-dd) end_date (str, optional) 発生日で絞込:終了日(yyyy-mm-dd) account_item_display_type (str, optional): 勘定科目の表示(勘定科目: account_item, 決算書表示:group). Available values : account_item, group breakdown_display_type (str, optional): 内訳の表示(取引先: partner, 品目: item, 勘定科目: account_item) ※勘定科目はaccount_item_display_typeが「group」の時のみ指定できます. Available values : partner, item, account_item partner_id (int, optional): 取引先IDで絞込(0を指定すると、取引先が未選択で絞り込めます) partner_code (str, optional): 取引先コードで絞込(事業所設定で取引先コードの利用を有効にしている場合のみ利用可能です) item_id (int, optional): 品目IDで絞込(0を指定すると、品目が未選択で絞り込めます) section_id (int, optional): 部門IDで絞込(0を指定すると、部門が未選択で絞り込めます) adjustment (str, optional): 決算整理仕訳で絞込(決算整理仕訳のみ: only, 決算整理仕訳以外: without). Available values : only, without cost_allocation (str, optional): 配賦仕訳で絞込(配賦仕訳のみ:only,配賦仕訳以外:without)Available values : only, not_include Note: 定義 created_at : 作成日時 account_item_name : 勘定科目名 hierarchy_level: 階層レベル parent_account_item_name: 親の勘定科目名 closing_balance : 期末残高 注意点 個人向けのプレミアムプラン、法人向けのビジネスプラン以上で利用可能なAPIです。対象外のプランでは401エラーを返却します。 会計年度が指定されない場合、現在の会計年度がデフォルトとなります。 絞り込み条件の日付と、月または年度は同時に指定することはできません。 Returns: dict: like below { "trial_pl_sections" : { "company_id" : 1, "section_ids" : "1,2,3", "fiscal_year" : 2017, "created_at" : "2018-05-01 12:00:50" "balances" : [{ "account_item_id" : 1500, "account_item_name" : "売上高", "hierarchy_level" : 2, "parent_account_item_id" : 100; "parent_account_item_name" : "営業収益", "closing_balance" : 1000000, "sections" : [{ "id": 1 "name": "営業部", "closing_balance" : 100000 }, { "id": 2 "name": "広報部", "closing_balance" : 200000 }, { "id": 3 "name": "人事部", "closing_balance" : 300000 }, ... ] }, ... ] } } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["reports", "trial_pl_sections"])) return self.send_request(request_method, url, payload) # =========================================== # Walletables (口座) # =========================================== def get_walletables(self, **payload): """口座一覧の取得 指定した事業所の口座一覧を取得する Args: company_id (int): 事業所ID with_balance (boool): 残高情報を含める Note: 定義 type bank_account : 銀行口座 credit_card : クレジットカード wallet : その他の決済口座 walletable_balance : 登録残高 last_balance : 同期残高 Returns: dict: like below { "walletables": [ { "id": 1, "name": "freee銀行", "bank_id": 3, "type": "bank_account", "last_balance": 1565583, "walletable_balance": 1340261 } ] } """ request_method = "get" url = urllib.parse.urljoin(self.account_endpoint, ("/").join(["walletables"])) return self.send_request(request_method, url, payload) # =========================================== # 人事労務freee API # =========================================== # =========================================== # タイムレコーダー(打刻)(タイムレコーダー(打刻)機能の操作) # =========================================== def get_time_clocks(self, employee_id, **payload): """打刻情報の一覧取得 指定した従業員・期間の打刻情報を返します。 デフォルトでは従業員の当月の打刻開始日から当日までの値が返ります。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID from_date(int, optional): 取得する打刻期間の開始日(YYYY-MM-DD)(例:2018-08-01)(デフォルト: 当月の打刻開始日) to_date(int, optional): 取得する打刻期間の終了日(YYYY-MM-DD)(例:2018-08-31)(デフォルト: 当日) per (int, optional): 一度に返すアイテム数。上限は100個で、指定なしで先頭から25個のアイテム取得。 page (int, optional): ページネーションにおけるページ番号であり、指定なしで1番 Returns: dict: like below { "employee_time_clocks": [ { "id": 0, "date": "string", "type": "string", "datetime": "2019-10-14T05:23:47.261Z", "original_datetime": "2019-10-14T05:23:47.261Z", "note": "string" } ] } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "time_clocks"])) return self.send_request(request_method, url, payload) def get_time_clock(self, employee_id, time_clock_id, **payload): """打刻情報の詳細取得 指定した従業員・指定した打刻の詳細情報を返します。 打刻情報の一覧取得APIにて取得した打刻IDを利用することができます。 Args: employee_id (str): 従業員ID time_clock_id (str): 打刻情報ID company_id (int): 事務所ID Returns: dict: like below { "employee_time_clock": { "id": 0, "date": "string", "type": "string", "datetime": "2019-10-14T05:28:58.011Z", "original_datetime": "2019-10-14T05:28:58.011Z", "note": "string" } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "time_clocks", time_clock_id])) return self.send_request(request_method, url, payload) def get_time_clock_available_types(self, employee_id, **payload): """打刻可能種別の取得 指定した従業員・日付の打刻可能種別と打刻基準日を返します。 例: すでに出勤した状態だと、休憩開始、退勤が配列で返ります。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID date (date, optional): 対象日(YYYY-MM-DD)(例:2018-08-01)(デフォルト:当日) Returns: dict: like below """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "time_clocks/available_types"])) return self.send_request(request_method, url, payload) # =========================================== # ログインユーザー(ログインユーザーの取得) # =========================================== def get_login_user(self, **payload): """ログインユーザーの取得 このリクエストの認可セッションにおけるログインユーザの情報を返します。人事労務freeeでは一人のログインユーザを複数の事業所に関連付けられるため、このユーザと関連のあるすべての事業所の情報をリストで返します。他のAPIのパラメータとして company_id が求められる場合は、このAPIで取得した company_id を使用します。 Args: No parameters Returns: dict: like below { "id": 0, "companies": [ { "id": 0, "name": "string", "role": "string", "external_cid": "string", "employee_id": 0, "display_name": "string" } ] } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, "users/me") return self.send_request(request_method, url, payload) # =========================================== # 給与明細(給与明細の操作) # =========================================== def get_salaries_employee_payroll_statements(self, **payload): """給与明細情報を取得 指定した事業所に所属する従業員の給与明細をリストで返します。 指定した年月に支払いのある給与明細が返されます。 Args: company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 per (int, optional): 一度に返すアイテム数。上限は100個で、指定なしで先頭から25個のアイテム取得。 page (int, optional): ページネーションにおけるページ番号であり、指定なしで1番 Returns: dict: like below { "employee_payroll_statements": [ { "id": 0, "company_id": 0, "employee_id": 0, "employee_name": "string", "employee_display_name": "string", "employee_num": "string", "pay_date": "string", "start_date": "string", "closing_date": "string", "variable_pay_start_date": "string", "variable_pay_closing_date": "string", "fixed": true, "calc_status": "string", "calculated_at": "2019-10-12T14:15:27.217Z", "pay_calc_type": "string", "basic_pay_amount": "string", "work_days": "string", "normal_work_time": "string", "normal_work_days": "string", "work_mins_by_paid_holiday": "string", "num_paid_holidays": "string", "is_board_member": true, "total_attendance_deduction_amount": "string", "total_allowance_amount": "string", "total_deduction_amount": "string", "net_payment_amount": "string", "gross_payment_amount": "string", "total_worked_days_count": "string", "total_taxable_payment_amount": "string", "total_expense_amount": "string", "total_transfer_amount": "string", "total_annual_payment_amount": "string", "payments": [ { "name": "string", "amount": "string" } ], "deductions": [ { "name": "string", "amount": "string" } ], "attendances": [ { "name": "string", "time": "string", "amount": "string" } ], "overtime_pays": [ { "name": "string", "time": "string", "amount": "string" } ], "remark": "string" } ] } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, "salaries/employee_payroll_statements") return self.send_request(request_method, url, payload) def get_salaries_employee_payroll_statement(self, employee_id, **payload): """特定の従業員の給与明細情報を取得 指定した従業員ID、年月の給与明細を返します。 指定した年月に支払いのある給与明細が返されます。 Args: employee_id (str): 従業員ID company_id (int): 事務所ID year (int): 対象年 month (int): 対象月 per (int, optional): 一度に返すアイテム数。上限は100個で、指定なしで先頭から25個のアイテム取得。 page (int, optional): ページネーションにおけるページ番号であり、指定なしで1番 Returns: dict: like below { "employee_payroll_statement": { "id": 0, "company_id": 0, "employee_id": 0, "employee_name": "string", "employee_display_name": "string", "employee_num": "string", "pay_date": "string", "start_date": "string", "closing_date": "string", "variable_pay_start_date": "string", "variable_pay_closing_date": "string", "fixed": true, "calc_status": "string", "calculated_at": "2019-10-12T14:21:53.194Z", "pay_calc_type": "string", "basic_pay_amount": "string", "work_days": "string", "normal_work_time": "string", "normal_work_days": "string", "work_mins_by_paid_holiday": "string", "num_paid_holidays": "string", "is_board_member": true, "total_attendance_deduction_amount": "string", "total_allowance_amount": "string", "total_deduction_amount": "string", "net_payment_amount": "string", "gross_payment_amount": "string", "total_worked_days_count": "string", "total_taxable_payment_amount": "string", "total_expense_amount": "string", "total_transfer_amount": "string", "total_annual_payment_amount": "string", "payments": [ { "name": "string", "amount": "string" } ], "deductions": [ { "name": "string", "amount": "string" } ], "attendances": [ { "name": "string", "time": "string", "amount": "string" } ], "overtime_pays": [ { "name": "string", "time": "string", "amount": "string" } ], "remark": "string" } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["salaries/employee_payroll_statements", str(employee_id)])) return self.send_request(request_method, url, payload) # =========================================== # 勤怠(勤怠の操作) # =========================================== def delete_work_record(self, employee_id, date, payload): """勤怠情報削除 指定した従業員の勤怠情報を削除します。 Args: employee_id (str): 従業員ID date (str): 指定日 like 2019-09-01 payload (dict): Request params Request params: { "company_id": 0 } Returns: """ request_method = "delete" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", str(employee_id), "work_records", date])) return self.send_request(request_method, url, payload) def get_work_record(self, employee_id, date, **payload): """勤怠情報取得 指定した従業員・日付の勤怠情報を返します。 Args: employee_id (str): 従業員ID date (str): 指定日 like 2019-09-01 company_id (int): 事務所ID Returns: dict: like below { "break_records": [ { "clock_in_at": "2019-10-12T15:19:35.625Z", "clock_out_at": "2019-10-12T15:19:35.625Z" } ], "clock_in_at": "2019-10-12T15:19:35.625Z", "clock_out_at": "2019-10-12T15:19:35.625Z", "date": "2019-10-12T15:19:35.625Z", "day_pattern": "string", "schedule_pattern": "string", "early_leaving_mins": 0, "is_absence": false, "is_editable": true, "lateness_mins": 0, "normal_work_clock_in_at": "2019-10-12T15:19:35.625Z", "normal_work_clock_out_at": "2019-10-12T15:19:35.625Z", "normal_work_mins": 0, "normal_work_mins_by_paid_holiday": 0, "note": "string", "paid_holiday": 0.5, "use_attendance_deduction": true, "use_default_work_pattern": true, "total_overtime_work_mins": 0, "total_holiday_work_mins": 0, "total_latenight_work_mins": 0 } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", str(employee_id), "work_records", date])) return self.send_request(request_method, url, payload) def put_work_record(self, employee_id, date, payload): """勤怠情報更新 指定した従業員の勤怠情報を更新します。 Args: employee_id (str): 従業員ID date (str): 指定日 like 2019-09-01 payload (dict): Request params Request params: 出勤日について出退勤時刻および休憩時間を更新する場合は以下のようなパラメータをリクエストします。 { "work_record": { "company_id": 1, "break_records": [ { "clock_in_at": "2017-05-25T12:00:00.000+09:00", "clock_out_at": "2017-05-25T13:00:00.000+09:00" } ], "clock_in_at": "2017-05-25T09:10:00.000+09:00", "clock_out_at": "2017-05-25T18:20:00.000+09:00" } } 勤務パターンや既定の所定労働時間を変更する場合は use_default_work_pattern に false を指定するとともに、各設定を上書きするパラメータをリクエストします。 { "work_record": { "company_id": 1, "break_records": [ { "clock_in_at": "2017-05-25T12:00:00.000+09:00", "clock_out_at": "2017-05-25T13:00:00.000+09:00" } ], "clock_in_at": "2017-05-25T09:10:00.000+09:00", "clock_out_at": "2017-05-25T18:20:00.000+09:00", "day_pattern": "normal_day", "normal_work_clock_in_at": "2017-05-25T01100:00.000+09:00", "normal_work_clock_out_at": "2017-12-20T20:00:00.000+09:00", "normal_work_mins": 0, "use_default_work_pattern": false } } 欠勤を付ける場合は company_idとis_absence 以外のパラメータは必要ありません。 { "work_record": { "company_id": 1, "is_absence": true } } Returns: dict: like below { "break_records": [ { "clock_in_at": "2019-10-27T12:52:52.524Z", "clock_out_at": "2019-10-27T12:52:52.524Z" } ], "clock_in_at": "2019-10-27T12:52:52.524Z", "clock_out_at": "2019-10-27T12:52:52.524Z", "date": "2019-10-27T12:52:52.524Z", "day_pattern": "string", "schedule_pattern": "string", "early_leaving_mins": 0, "is_absence": false, "is_editable": true, "lateness_mins": 0, "normal_work_clock_in_at": "2019-10-27T12:52:52.524Z", "normal_work_clock_out_at": "2019-10-27T12:52:52.524Z", "normal_work_mins": 0, "normal_work_mins_by_paid_holiday": 0, "note": "string", "paid_holiday": 0.5, "use_attendance_deduction": true, "use_default_work_pattern": true, "total_overtime_work_mins": 0, "total_holiday_work_mins": 0, "total_latenight_work_mins": 0 } """ request_method = "put" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", str(employee_id), "work_records", date])) return self.send_request(request_method, url, payload) # =========================================== # 勤怠情報サマリ(勤怠情報の月次サマリの操作) # =========================================== def get_work_record_summaries(self, employee_id, year, month, **payload): """勤怠情報月次サマリの取得 指定した従業員、月の勤怠情報のサマリを返します。work_recordsオプションにtrueを指定することで、明細となる日次の勤怠情報もあわせて返却します。 Args: employee_id (str): 従業員ID year (int): 指定年 month (int): 指定月 company_id (int): 事務所ID work_records (str, optional): サマリ情報に日次の勤怠情報を含める(true/false)(デフォルト: false) Returns: dict: like below { "year": 0, "month": 0, "start_date": "string", "end_date": "string", "work_days": 0, "total_work_mins": 0, "total_normal_work_mins": 0, "total_excess_statutory_work_mins": 0, "total_overtime_except_normal_work_mins": 0, "total_overtime_within_normal_work_mins": 0, "total_holiday_work_mins": 0, "total_latenight_work_mins": 0, "num_absences": 0, "num_paid_holidays": 0, "num_paid_holidays_left": 0, "num_substitute_holidays_used": 0, "num_compensatory_holidays_used": 0, "num_special_holidays_used": 0, "total_lateness_and_early_leaving_mins": 0, "work_records": [ { "break_records": [ { "clock_in_at": "2019-10-12T15:06:06.666Z", "clock_out_at": "2019-10-12T15:06:06.666Z" } ], "clock_in_at": "2019-10-12T15:06:06.666Z", "clock_out_at": "2019-10-12T15:06:06.666Z", "date": "2019-10-12T15:06:06.666Z", "day_pattern": "string", "schedule_pattern": "string", "early_leaving_mins": 0, "is_absence": false, "is_editable": true, "lateness_mins": 0, "normal_work_clock_in_at": "2019-10-12T15:06:06.666Z", "normal_work_clock_out_at": "2019-10-12T15:06:06.666Z", "normal_work_mins": 0, "normal_work_mins_by_paid_holiday": 0, "note": "string", "paid_holiday": 0.5, "use_attendance_deduction": true, "use_default_work_pattern": true, "total_overtime_work_mins": 0, "total_holiday_work_mins": 0, "total_latenight_work_mins": 0 } ] } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", str(employee_id), "work_record_summaries", str(year), str(month)])) return self.send_request(request_method, url, payload) # =========================================== # 従業員情報(従業員の操作) # =========================================== def get_all_employees(self, company_id, **payload): """従業員情報を取得 指定した事業所に所属する退職者も含めた従業員をリストで返します。 Args: company_id (int): 事務所ID per (int, optional): 一度に返すアイテム数。上限は100個で、指定なしで先頭から25個のアイテム取得。 page (int, optional): ページネーションにおけるページ番号であり、指定なしで1番 Returns: dict: like below [{ "id": 0, "num": "string", "display_name": "string", "entry_date": "2019-10-12T14:05:59.702Z", "retire_date": "2019-10-12T14:05:59.702Z", "user_id": 0, "email": "string" }] """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["companies", str(company_id), "employees"])) return self.send_request(request_method, url, payload) def get_employees_at_designated_date(self, **payload): """従業員情報を取得 指定した事業所、指定年月に所属する従業員をリストで返します。 Args: company_id (int): 事務所ID year (int): 対象年 month (int): 対象月 per (int, optional): 一度に返すアイテム数。上限は100個で、指定なしで先頭から25個のアイテム取得。 page (int, optional): ページネーションにおけるページ番号であり、指定なしで1番 Returns: dict: like below { "employees": [ { "id": 0, "company_id": 0, "num": "string", "display_name": "string", "base_pension_num": "string", "employment_insurance_reference_number": "string", "birth_date": "string", "entry_date": "string", "retire_date": "string", "user_id": 0, "profile_rule": { "id": 0, "company_id": 0, "employee_id": 0, "last_name": "string", "first_name": "string", "last_name_kana": "string", "first_name_kana": "string", "zipcode1": "string", "zipcode2": "string", "pref": "string", "address": "string", "address_kana": "string", "phone1": "string", "phone2": "string", "phone3": "string", "residential_zipcode1": "string", "residential_zipcode2": "string", "residential_pref": "string", "residential_address": "string", "residential_address_kana": "string", "employment_type": "string", "title": "string", "gender": 0, "married": true, "is_working_student": true, "widow_type": "string", "disability_type": "string" }, "health_insurance_rule": { "id": 0, "company_id": 0, "employee_id": 0, "entried": true, "reference_num": "string", "standard_monthly_remuneration": 0 }, "welfare_pension_insurance_rule": { "id": 0, "company_id": 0, "employee_id": 0, "entried": true, "reference_num": "string", "standard_monthly_remuneration": 0 }, "dependent_rules": [ { "id": 0, "company_id": 0, "employee_id": 0, "last_name": "string", "first_name": "string", "last_name_kana": "string", "first_name_kana": "string", "gender": 0, "relationship": "string", "birth_date": "string", "residence_type": "string", "zipcode1": "string", "zipcode2": "string", "pref": "string", "address": "string", "address_kana": "string", "base_pension_num": "string", "income": 0, "annual_revenue": 0, "disability_type": "string", "occupation": "string", "annual_remittance_amount": 0, "social_insurance_and_tax_dependent": "string" } ], "bank_account_rule": { "id": 0, "company_id": 0, "employee_id": 0, "bank_name": "string", "bank_name_kana": "string", "bank_code": "string", "branch_name": "string", "branch_name_kana": "string", "branch_code": "string", "account_number": "string", "account_name": "string", "account_type": "string" }, "basic_pay_rule": { "id": 0, "company_id": 0, "employee_id": 0, "pay_calc_type": "string", "pay_amount": 0 } } ], "total_count": 0 } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, "employees") return self.send_request(request_method, url, payload) def get_employee(self, employee_id, **payload): """特定の従業員情報を取得 指定したIDの従業員を返します。 Args: id: 従業員ID company_id (int): 事務所ID year (int): 対象年 month (int): 対象月 Returns: dict: like below { "employee": { "id": 0, "company_id": 0, "num": "string", "display_name": "string", "base_pension_num": "string", "employment_insurance_reference_number": "string", "birth_date": "string", "entry_date": "string", "retire_date": "string", "user_id": 0, "profile_rule": { "id": 0, "company_id": 0, "employee_id": 0, "last_name": "string", "first_name": "string", "last_name_kana": "string", "first_name_kana": "string", "zipcode1": "string", "zipcode2": "string", "pref": "string", "address": "string", "address_kana": "string", "phone1": "string", "phone2": "string", "phone3": "string", "residential_zipcode1": "string", "residential_zipcode2": "string", "residential_pref": "string", "residential_address": "string", "residential_address_kana": "string", "employment_type": "string", "title": "string", "gender": 0, "married": true, "is_working_student": true, "widow_type": "string", "disability_type": "string" }, "health_insurance_rule": { "id": 0, "company_id": 0, "employee_id": 0, "entried": true, "reference_num": "string", "standard_monthly_remuneration": 0 }, "welfare_pension_insurance_rule": { "id": 0, "company_id": 0, "employee_id": 0, "entried": true, "reference_num": "string", "standard_monthly_remuneration": 0 }, "dependent_rules": [ { "id": 0, "company_id": 0, "employee_id": 0, "last_name": "string", "first_name": "string", "last_name_kana": "string", "first_name_kana": "string", "gender": 0, "relationship": "string", "birth_date": "string", "residence_type": "string", "zipcode1": "string", "zipcode2": "string", "pref": "string", "address": "string", "address_kana": "string", "base_pension_num": "string", "income": 0, "annual_revenue": 0, "disability_type": "string", "occupation": "string", "annual_remittance_amount": 0, "social_insurance_and_tax_dependent": "string" } ], "bank_account_rule": { "id": 0, "company_id": 0, "employee_id": 0, "bank_name": "string", "bank_name_kana": "string", "bank_code": "string", "branch_name": "string", "branch_name_kana": "string", "branch_code": "string", "account_number": "string", "account_name": "string", "account_type": "string" }, "basic_pay_rule": { "id": 0, "company_id": 0, "employee_id": 0, "pay_calc_type": "string", "pay_amount": 0 } } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", str(employee_id)])) return self.send_request(request_method, url, payload) # =========================================== # 従業員の基本給(従業員の基本給の操作) # =========================================== def get_basic_pay_rule(self, employee_id, **payload): """従業員の基本給の取得 指定した従業員・日付の基本給情報を返します。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 Returns: dict: like below { "employee_basic_pay_rule": { "id": 0, "company_id": 0, "employee_id": 0, "pay_calc_type": "string", "pay_amount": 0 } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "basic_pay_rule"])) return self.send_request(request_method, url, payload) # =========================================== # 従取得業員の銀行口座(従業員の銀行口座の操作) # =========================================== def get_bank_account_rule(self, employee_id, **payload): """銀行口座の取得 指定した従業員・日付の銀行口座情報を返します。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 Returns: dict: like below { "employee_bank_account_rule": { "id": 0, "company_id": 0, "employee_id": 0, "bank_name": "string", "bank_name_kana": "string", "bank_code": "string", "branch_name": "string", "branch_name_kana": "string", "branch_code": "string", "account_number": "string", "account_name": "string", "account_type": "string" } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "bank_account_rule"])) return self.send_request(request_method, url, payload) # =========================================== # 従業員の健康保険(従業員の健康保険の操作) # =========================================== def get_health_insurance_rule(self, employee_id, **payload): """健康保険情報を返します。 指定した従業員・日付の健康保険情報を返します。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 Returns: dict: like below { "employee_health_insurance_rule": { "id": 0, "company_id": 0, "employee_id": 0, "entried": true, "reference_num": "string", "standard_monthly_remuneration": 0 } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "health_insurance_rule"])) return self.send_request(request_method, url, payload) # =========================================== # 従業員の厚生年金保険(従業員の厚生年金保険の操作) # =========================================== def get_welfare_pension_insurance_rule(self, employee_id, **payload): """厚生年金保険情報を返します。 指定した従業員・日付の厚生年金保険情報を返します。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 Returns: dict: like below { "employee_welfare_pension_insurance_rule": { "id": 0, "company_id": 0, "employee_id": 0, "entried": true, "reference_num": "string", "standard_monthly_remuneration": 0 } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "welfare_pension_insurance_rule"])) return self.send_request(request_method, url, payload) # =========================================== # 従業員の姓名・住所など(従業員の姓名・住所などの操作) # =========================================== def get_profile_rule(self, employee_id, **payload): """従業員の姓名などの情報を返します。 指定した従業員・日付の姓名などの情報を返します。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 Returns: { "employee_profile_rule": { "id": 0, "company_id": 0, "employee_id": 0, "last_name": "string", "first_name": "string", "last_name_kana": "string", "first_name_kana": "string", "zipcode1": "string", "zipcode2": "string", "pref": "string", "address": "string", "address_kana": "string", "phone1": "string", "phone2": "string", "phone3": "string", "residential_zipcode1": "string", "residential_zipcode2": "string", "residential_pref": "string", "residential_address": "string", "residential_address_kana": "string", "employment_type": "string", "title": "string", "gender": 0, "married": true, "is_working_student": true, "widow_type": "string", "disability_type": "string" } } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "profile_rule"])) return self.send_request(request_method, url, payload) # =========================================== # 従業員の扶養親族(従業員の扶養親族の操作) # =========================================== def get_dependent_rules(self, employee_id, **payload): """従業員の扶養親族情報を返します。 指定した従業員・日付の扶養親族情報を返します。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 Returns: dict: like below """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["employees", employee_id, "dependent_rules"])) return self.send_request(request_method, url, payload) # =========================================== # 所属(所属の操作) # =========================================== def get_employee_group_memberships(self, **payload): """所属一覽の取得 指定した事業所の指定日付時点における所属情報をリストで返します。 Args: company_id (int): 事務所ID base_date (str): 指定日 per (int, optional): 一度に返すアイテム数。上限は100個で、指定なしで先頭から25個のアイテム取得。 page (int, optional): ページネーションにおけるページ番号であり、指定なしで1番 Returns: dict: like below { "employee_group_memberships": [ { "id": 0, "num": "string", "display_name": "string", "entry_date": "string", "retire_date": "string", "user_id": 0, "login_email": "string", "group_memberships": [ { "start_date": "string", "end_date": "string", "group_id": 0, "group_code": "string", "group_name": "string", "level": 0, "position_id": 0, "position_code": "string", "position_name": "string", "parent_group_id": 0, "parent_group_code": "string", "parent_group_name": "string" } ] } ], "total_count": 0 } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, "employee_group_memberships") return self.send_request(request_method, url, payload) # =========================================== # 賞与明細(賞与明細の操作) # =========================================== def get_bonuses_employee_payroll_statements(self, **payload): """賞与明細一覽の取得 指定した従業員・日付の扶養親族情報を返します。 指定した年月に支払いのある賞与明細が返されます。 Args: company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 per (int, optional): 一度に返すアイテム数。上限は100個で、指定なしで先頭から25個のアイテム取得。 page (int, optional): ページネーションにおけるページ番号であり、指定なしで1番 Returns: dict: like below { "employee_payroll_statements": [ { "id": 0, "company_id": 0, "employee_id": 0, "employee_name": "string", "employee_display_name": "string", "employee_num": "string", "closing_date": "string", "pay_date": "string", "fixed": true, "calc_status": "string", "calculated_at": "2019-10-14T06:10:27.766Z", "bonus_amount": "string", "total_allowance_amount": "string", "total_deduction_amount": "string", "net_payment_amount": "string", "gross_payment_amount": "string", "total_taxable_payment_amount": "string", "allowances": [ { "name": "string", "amount": "string" } ], "deductions": [ { "name": "string", "amount": "string" } ], "remark": "string" } ], "total_count": 0 } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, "bonuses/employee_payroll_statements") return self.send_request(request_method, url, payload) def get_bonuses_employee_payroll_statement(self, employee_id, **payload): """ある従業員の賞与明細を取得 指定した従業員ID、年月の賞与明細を返します。 指定した年月に支払いのある賞与明細が返されます。 Args: employee_id (int): 従業員ID company_id (int): 事務所ID year(int): 対象年 month(int): 対象月 Returns: dict: like below { "employee_payroll_statement": { "id": 0, "company_id": 0, "employee_id": 0, "employee_name": "string", "employee_display_name": "string", "employee_num": "string", "closing_date": "string", "pay_date": "string", "fixed": true, "calc_status": "string", "calculated_at": "2019-10-14T06:20:36.831Z", "bonus_amount": "string", "total_allowance_amount": "string", "total_deduction_amount": "string", "net_payment_amount": "string", "gross_payment_amount": "string", "total_taxable_payment_amount": "string", "allowances": [ { "name": "string", "amount": "string" } ], "deductions": [ { "name": "string", "amount": "string" } ], "remark": "string" } """ request_method = "get" url = urllib.parse.urljoin(self.hr_endpoint, ("/").join(["bonuses/employee_payroll_statements", employee_id])) return self.send_request(request_method, url, payload)
36.049961
328
0.456063
7,682
92,360
5.230409
0.114293
0.025734
0.016725
0.024042
0.76884
0.741264
0.726605
0.713091
0.696989
0.680762
0
0.034861
0.415483
92,360
2,561
329
36.064037
0.708776
0.665829
0
0.468401
0
0
0.11345
0.028998
0
0
0
0
0
1
0.185874
false
0
0.01487
0.003717
0.379182
0.007435
0
0
0
null
0
0
0
0
1
1
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
0370175c9a05ccfcc6d32c5c429c7ad04293878f
170
py
Python
setup.py
alexmagwe/Nia_IoT
7120db494a17d0c11cb6e0a95113819d9a0f0665
[ "Apache-2.0" ]
null
null
null
setup.py
alexmagwe/Nia_IoT
7120db494a17d0c11cb6e0a95113819d9a0f0665
[ "Apache-2.0" ]
null
null
null
setup.py
alexmagwe/Nia_IoT
7120db494a17d0c11cb6e0a95113819d9a0f0665
[ "Apache-2.0" ]
null
null
null
from nia import create_app app = create_app() if __name__=='__main__': app.run(debug=True, host="192.68.1.104", port = 8090) #app.run(debug=True, port = 5000)
18.888889
57
0.664706
28
170
3.678571
0.678571
0.174757
0.213592
0.291262
0
0
0
0
0
0
0
0.120567
0.170588
170
8
58
21.25
0.609929
0.188235
0
0
0
0
0.145985
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0
1
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
ceecf7db7cb872f030b9df6b31173e298b681a3f
700
py
Python
decorated_example.py
linrong/flask-server
5f0896c6ccedb6b172b9af7e1018600e38a2df43
[ "MIT" ]
null
null
null
decorated_example.py
linrong/flask-server
5f0896c6ccedb6b172b9af7e1018600e38a2df43
[ "MIT" ]
1
2019-09-06T10:06:47.000Z
2019-09-10T07:18:47.000Z
decorated_example.py
linrong/flask-server
5f0896c6ccedb6b172b9af7e1018600e38a2df43
[ "MIT" ]
null
null
null
print('装饰器') class C(): get_password_callback = None def get_password(self, f): print('1') self.get_password_callback = f return f def prints(self): if self.get_password_callback: self.get_password_callback() else: print(0) c = C() c.prints() # 输出 0 @c.get_password # 输出 1 def b(): print(2) c.prints() # 输出 2 # 输出 # 0 # 1 # 2 print('装饰器调用顺序') def a(f): print(1) return f def b(f): print(2) return f def c(f): print(3) return f @a @b @c def d(): print(4) # 实际调用运行顺序为 # d = a(b(c(d))) # 没有调用d()时 # 输出为 3 2 1 # 调用d() d() # 输出为 4 # Python装饰器的代码执行顺序(https://www.jianshu.com/p/a58d6f71b1ce)
13.461538
58
0.551429
113
700
3.327434
0.327434
0.175532
0.202128
0.183511
0
0
0
0
0
0
0
0.046559
0.294286
700
52
58
13.461538
0.714575
0.195714
0
0.235294
0
0
0.020036
0
0
0
0
0
0
1
0.205882
false
0.176471
0
0
0.382353
0.352941
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
4
3000bad65263a7207d59af90982469aeb53e09fd
153
py
Python
src/__init__.py
JoyXujingyan0830/A-unified-model-for-zero-shot-musical-source-separation-transcription-and-synthesis
a99c3e2eb7ca0a56b3545307aa0f6b51685ed4e6
[ "MIT" ]
15
2021-08-13T08:46:36.000Z
2022-03-26T15:18:08.000Z
src/__init__.py
JoyXujingyan0830/A-unified-model-for-zero-shot-musical-source-separation-transcription-and-synthesis
a99c3e2eb7ca0a56b3545307aa0f6b51685ed4e6
[ "MIT" ]
4
2021-09-09T08:03:17.000Z
2022-01-13T05:21:41.000Z
src/__init__.py
JoyXujingyan0830/A-unified-model-for-zero-shot-musical-source-separation-transcription-and-synthesis
a99c3e2eb7ca0a56b3545307aa0f6b51685ed4e6
[ "MIT" ]
5
2021-08-13T15:17:19.000Z
2022-03-18T08:56:21.000Z
import sys import os pkg_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(pkg_path) import conf, utils, dataset, models, inference
15.3
53
0.764706
24
153
4.625
0.583333
0.126126
0
0
0
0
0
0
0
0
0
0
0.124183
153
9
54
17
0.828358
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.6
0
0.6
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
301cfd420f974d547948e95e08537ddd6957c48f
129
py
Python
Mundo 1/ex021 Tocando musica.py
AbelRapha/Python-Exercicios-CeV
17e7055c982c8a1224992602ece50bae8eeee365
[ "MIT" ]
null
null
null
Mundo 1/ex021 Tocando musica.py
AbelRapha/Python-Exercicios-CeV
17e7055c982c8a1224992602ece50bae8eeee365
[ "MIT" ]
null
null
null
Mundo 1/ex021 Tocando musica.py
AbelRapha/Python-Exercicios-CeV
17e7055c982c8a1224992602ece50bae8eeee365
[ "MIT" ]
null
null
null
from pygame import mixer mixer.init() mixer.music.load('ex021.mp3') mixer.music.play() input('CURTE O SOM!') mixer.music.pause()
18.428571
29
0.736434
21
129
4.52381
0.714286
0.315789
0
0
0
0
0
0
0
0
0
0.033898
0.085271
129
6
30
21.5
0.771186
0
0
0
0
0
0.162791
0
0
0
0
0
0
1
0
true
0
0.166667
0
0.166667
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
302c04fb72edfa1bfad6cb70cc4c36aa3c833e95
185
py
Python
src/winnow/models/manufacturing_spec.py
opendesk/schema
9c6d8483abbfeb5e3bd225b2916c212e2c21872b
[ "Unlicense" ]
3
2016-04-05T16:51:27.000Z
2016-08-30T20:56:25.000Z
src/winnow/models/manufacturing_spec.py
opendesk/schema
9c6d8483abbfeb5e3bd225b2916c212e2c21872b
[ "Unlicense" ]
null
null
null
src/winnow/models/manufacturing_spec.py
opendesk/schema
9c6d8483abbfeb5e3bd225b2916c212e2c21872b
[ "Unlicense" ]
1
2019-08-14T16:51:56.000Z
2019-08-14T16:51:56.000Z
import winnow from winnow.models.base import WinnowVersion class WinnowManufacturingSpecfifcation(WinnowVersion): @property def id(self): return self.kwargs[u"uuid"]
18.5
54
0.751351
20
185
6.95
0.8
0
0
0
0
0
0
0
0
0
0
0
0.172973
185
10
55
18.5
0.908497
0
0
0
0
0
0.021505
0
0
0
0
0
0
1
0.166667
false
0
0.333333
0.166667
0.833333
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
1
1
1
0
0
4
3042a34ae0d343e1586063fc3ae0b2e967962e80
167
py
Python
backend/database/models/multimedia.py
AlexanderBerardino/police-data-trust
587fe2bc1e7f048e2308d89803abb20f4e619aab
[ "MIT" ]
16
2021-03-02T21:32:52.000Z
2022-03-15T23:13:06.000Z
backend/database/models/multimedia.py
AlexanderBerardino/police-data-trust
587fe2bc1e7f048e2308d89803abb20f4e619aab
[ "MIT" ]
173
2021-03-03T01:35:36.000Z
2022-03-30T03:17:58.000Z
backend/database/models/multimedia.py
AlexanderBerardino/police-data-trust
587fe2bc1e7f048e2308d89803abb20f4e619aab
[ "MIT" ]
36
2021-03-03T00:27:20.000Z
2022-03-29T23:07:57.000Z
from .. import db class Multimedia(db.Model): id = db.Column(db.Integer, primary_key=True) incident_id = db.Column(db.Integer, db.ForeignKey("incident.id"))
23.857143
69
0.706587
25
167
4.64
0.56
0.068966
0.172414
0.206897
0.327586
0
0
0
0
0
0
0
0.143713
167
6
70
27.833333
0.811189
0
0
0
0
0
0.065868
0
0
0
0
0
0
1
0
false
0
0.25
0
1
0
1
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
1
0
0
4
3046f2fef99b36b5a184497321ae300310ef2275
142
py
Python
gupiao/get_data.py
zhangyage/Python-oldboy
a95c1b465929e2be641e425fcb5e15b366800831
[ "Apache-2.0" ]
1
2020-06-04T08:44:09.000Z
2020-06-04T08:44:09.000Z
gupiao/get_data.py
zhangyage/Python-oldboy
a95c1b465929e2be641e425fcb5e15b366800831
[ "Apache-2.0" ]
null
null
null
gupiao/get_data.py
zhangyage/Python-oldboy
a95c1b465929e2be641e425fcb5e15b366800831
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- from models.model import Gu_info gupiao = Gu_info() print gupiao.Selectdate(gname='振华股份')
20.285714
37
0.676056
21
142
4.47619
0.857143
0.12766
0
0
0
0
0
0
0
0
0
0.008333
0.15493
142
7
37
20.285714
0.775
0.288732
0
0
0
0
0.042553
0
0
0
0
0
0
0
null
null
0
0.333333
null
null
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
1
0
0
0
1
0
0
0
0
4
06294771e65359eba5598c6ca296372323cded5c
1,024
py
Python
tests/example.py
PixelwarStudio/PyPlant
95c8ed1fd382fad9164edea4204a62648eeb0d65
[ "MIT" ]
null
null
null
tests/example.py
PixelwarStudio/PyPlant
95c8ed1fd382fad9164edea4204a62648eeb0d65
[ "MIT" ]
null
null
null
tests/example.py
PixelwarStudio/PyPlant
95c8ed1fd382fad9164edea4204a62648eeb0d65
[ "MIT" ]
null
null
null
from plant.lsystem import LSystem, Var, Const # Variables # Algae class A(Var): def replace(self): return (A(), B()) class B(Var): def replace(self): return (A(),) # Fractal binary tree class Zero(Var): def replace(self): return (One(), SqrBracketOpen(), Zero(), SqrBracketClose(), Zero()) def __str__(self): return "0" class One(Var): def replace(self): return (One(),)*2 def __str__(self): return "1" # Koch snowflake class F(Var): def replace(self): return (F(), Plus(), F(), Minus(), Minus(), F(), Plus(), F()) # Constants class SqrBracketOpen(Const): def __str__(self): return "[" class SqrBracketClose(Const): def __str__(self): return "]" class Plus(Const): def __str__(self): return "+" class Minus(Const): def __str__(self): return "-" # LSystems algae = lambda : LSystem((A(),)) fractal_binary_tree = lambda : LSystem((Zero(),)) koch_snowflake = lambda : LSystem((F(),))
19.320755
75
0.585938
122
1,024
4.696721
0.278689
0.191972
0.104712
0.167539
0.387435
0.310646
0
0
0
0
0
0.003891
0.24707
1,024
53
76
19.320755
0.7393
0.067383
0
0.314286
0
0
0.006322
0
0
0
0
0
0
1
0.314286
false
0
0.028571
0.314286
0.914286
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
1
1
0
0
4
0633de797cf5fe879781520885e8f87b766fc674
96
py
Python
e2e/test-helpers/clear-password-file.py
Mattlk13/go-strong-auth-plugin
dec7800c0a84771080a712194eb615c571385449
[ "Apache-2.0" ]
5
2016-03-11T14:43:08.000Z
2017-08-02T13:49:19.000Z
e2e/test-helpers/clear-password-file.py
Mattlk13/go-strong-auth-plugin
dec7800c0a84771080a712194eb615c571385449
[ "Apache-2.0" ]
3
2016-10-12T03:34:17.000Z
2017-06-27T15:47:14.000Z
e2e/test-helpers/clear-password-file.py
Mattlk13/go-strong-auth-plugin
dec7800c0a84771080a712194eb615c571385449
[ "Apache-2.0" ]
1
2017-02-28T00:56:04.000Z
2017-02-28T00:56:04.000Z
#!/usr/bin/python3 with open("/etc/go/passwd", "w") as passwordFile: passwordFile.write('')
24
49
0.666667
13
96
4.923077
0.923077
0
0
0
0
0
0
0
0
0
0
0.011765
0.114583
96
4
50
24
0.741176
0.177083
0
0
0
0
0.189873
0
0
0
0
0
0
1
0
true
1
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
1
0
0
0
0
0
4
0641b6a99dbff532a1700abcb472d179cf6f6b64
384
py
Python
tests/test_ringbuf.py
kevinkk525/micropython_wlan_link
0d7d9a6716a90ef4dbf4199985be79e9715f990f
[ "MIT" ]
1
2021-03-24T16:45:29.000Z
2021-03-24T16:45:29.000Z
tests/test_ringbuf.py
kevinkk525/micropython_wlan_link
0d7d9a6716a90ef4dbf4199985be79e9715f990f
[ "MIT" ]
null
null
null
tests/test_ringbuf.py
kevinkk525/micropython_wlan_link
0d7d9a6716a90ef4dbf4199985be79e9715f990f
[ "MIT" ]
null
null
null
# Author: Kevin Köck # Copyright Kevin Köck 2021 Released under the MIT license # Created on 2021-03-14 __updated__ = "2021-03-14" __version__ = "0.1" from wlan_link_libs.ringbuf import Ringbuf r = Ringbuf(15) print(r._free()) m = b"0123456789" print(r.append(m)) print(r.append(m)) print(r._buf) print(r.get(5)) print(r.append(m)) print(r._buf) print(r.append(m)) print(r.get())
18.285714
58
0.713542
69
384
3.782609
0.507246
0.206897
0.183908
0.199234
0.314176
0.314176
0.214559
0.214559
0.214559
0
0
0.103858
0.122396
384
20
59
19.2
0.670623
0.252604
0
0.428571
0
0
0.08156
0
0
0
0
0
0
1
0
false
0
0.071429
0
0.071429
0.642857
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
4
06495ccbead0c98e9f3ad8021e77e4e00ba42a24
208
py
Python
notifications_delivery/clients/__init__.py
quis/notifications-delivery
be4c8dae870757d24edddf8253b6c2cbf2791bdc
[ "MIT" ]
1
2016-01-11T20:16:44.000Z
2016-01-11T20:16:44.000Z
notifications_delivery/clients/__init__.py
quis/notifications-delivery
be4c8dae870757d24edddf8253b6c2cbf2791bdc
[ "MIT" ]
2
2016-02-09T10:44:28.000Z
2016-02-10T16:38:11.000Z
notifications_delivery/clients/__init__.py
quis/notifications-delivery
be4c8dae870757d24edddf8253b6c2cbf2791bdc
[ "MIT" ]
3
2016-07-14T10:15:28.000Z
2021-04-10T20:03:22.000Z
class ClientException(Exception): ''' Base Exceptions for sending notifications that fail ''' pass class Client(object): ''' Base client for sending notifications. ''' pass
14.857143
55
0.634615
20
208
6.6
0.65
0.151515
0.348485
0
0
0
0
0
0
0
0
0
0.274038
208
13
56
16
0.874172
0.432692
0
0.5
0
0
0
0
0
0
0
0
0
1
0
true
0.5
0
0
0.5
0
1
0
0
null
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
1
0
0
0
0
0
4
064affb599571d4f9ec8f7d66969e733da78f9fc
47
py
Python
AWS_Test/src/__init__.py
tuggegese/CodingWDB
429532ca91854535b3dc867f4a7f8cb685ada342
[ "MIT" ]
1
2021-11-10T02:18:20.000Z
2021-11-10T02:18:20.000Z
AWS_Test/src/__init__.py
tuggegese/CodingWDB
429532ca91854535b3dc867f4a7f8cb685ada342
[ "MIT" ]
2
2021-11-10T02:25:05.000Z
2022-02-07T14:35:35.000Z
AWS_Test/src/__init__.py
tuggegese/CodingWDB
429532ca91854535b3dc867f4a7f8cb685ada342
[ "MIT" ]
1
2021-11-10T02:31:49.000Z
2021-11-10T02:31:49.000Z
from flask import Flask api = Flask(__name__)
11.75
23
0.765957
7
47
4.571429
0.714286
0
0
0
0
0
0
0
0
0
0
0
0.170213
47
3
24
15.666667
0.820513
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
06573be104f45d1fa937a966d69ff356434946d2
133,206
py
Python
cogs/utility.py
bubby932/RecNetBotV2
ed846791584ed344d55357e0989eb241ee6f13b0
[ "MIT" ]
5
2021-07-16T21:12:14.000Z
2022-03-12T18:59:47.000Z
cogs/utility.py
bubby932/RecNetBotV2
ed846791584ed344d55357e0989eb241ee6f13b0
[ "MIT" ]
1
2021-12-02T06:43:55.000Z
2021-12-02T06:43:55.000Z
cogs/utility.py
bubby932/RecNetBotV2
ed846791584ed344d55357e0989eb241ee6f13b0
[ "MIT" ]
8
2021-08-08T21:35:42.000Z
2022-02-18T20:21:48.000Z
import functions import httpx import requests import discord import operator import random import asyncio from datetime import date from discord.ext import owoify from discord.ext import commands from discord.ext import menus from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType def convert_platform_mask(i): chk_tuple = ('Steam', 'Oculus', 'PlayStation', 'Xbox', 'HeadlessBot', 'iOS', 'Android') output = [] pos = 0 while i: if i & 1: output.append(chk_tuple[pos]) pos += 1 i >>= 1 return output async def cheers_worker(isbn, account_id): limits = httpx.Limits(max_keepalive_connections=10, max_connections=100) async with httpx.AsyncClient(limits=limits) as client: for a, b in enumerate(isbn): response = await client.get(f"https://api.rec.net/api/images/v1/{b}/cheers") cheers = response.json() if account_id in cheers: global self_cheers self_cheers += 1 if self_cheers == 1: global latest_self_cheered latest_self_cheered = httpx.get(f"https://api.rec.net/api/images/v4/{b}").json() print(self_cheers) async def main(account_id, photos): global self_cheers global latest_self_cheered self_cheers = 0 latest_self_cheered = "" photo_list = [] for image in photos: if image['CheerCount'] > 0: photo_list.append(image['Id']) tasks = [] ids = [] for a, b in enumerate(photo_list): ids.append(b) if len(ids) > len(photo_list) / 200: tasks.append(cheers_worker(ids, account_id)) ids = [] tasks.append(cheers_worker(ids, account_id)) await asyncio.gather(*tasks) print("return") return [self_cheers, latest_self_cheered] class Utility(commands.Cog): def __init__(self, client): self.client = client self.session_message = {} self.buttons = { "default": { "bio": [ [ Button(style=ButtonStyle.red, label="Owoify"), Button(style=ButtonStyle.red, label="Check Cringe Rating") ], ], "rinfo": [ [ Button(style=ButtonStyle.red, label="Roles"), Button(style=ButtonStyle.red, label="Rooms by Creator") ] ], "stats": [ [ Button(style=ButtonStyle.red, label="Self-Cheers"), Button(style=ButtonStyle.red, label="Bookmarked") ] ], "profile": [ [ Button(style=ButtonStyle.red, label="Stats") ] ], "creatorstats": [ [ Button(style=ButtonStyle.red, label="Profile") ] ], "roomsby": [ [ Button(style=ButtonStyle.red, label="Profile") ] ], "pfp": [ [ Button(style=ButtonStyle.red, label="Profile") ] ], "banner": [ [ Button(style=ButtonStyle.red, label="Profile") ] ], "junior": [ [ Button(style=ButtonStyle.red, label="Profile") ] ], "date": [ [ Button(style=ButtonStyle.red, label="Profile") ] ], "nickname": [ [ Button(style=ButtonStyle.red, label="Profile") ] ] }, "disabled": { "bio": [ [ Button(style=ButtonStyle.red, label="Owoify", disabled=True), Button(style=ButtonStyle.red, label="Check Cringe Rating", disabled=True) ] ], "rinfo": [ [ Button(style=ButtonStyle.red, label="Roles", disabled=True), Button(style=ButtonStyle.red, label="Rooms by Creator", disabled=True) ] ], "stats": [ [ Button(style=ButtonStyle.red, label="Self-Cheers", disabled=True), Button(style=ButtonStyle.red, label="Bookmarked", disabled=True) ] ], "profile": [ [ Button(style=ButtonStyle.red, label="Stats", disabled=True) ] ], "creatorstats": [ [ Button(style=ButtonStyle.red, label="Profile", disabled=True) ] ], "roomsby": [ [ Button(style=ButtonStyle.red, label="Profile", disabled=True) ] ], "pfp": [ [ Button(style=ButtonStyle.red, label="Profile", disabled=True) ] ], "banner": [ [ Button(style=ButtonStyle.red, label="Profile", disabled=True) ] ], "junior": [ [ Button(style=ButtonStyle.red, label="Profile", disabled=True) ] ], "date": [ [ Button(style=ButtonStyle.red, label="Profile", disabled=True) ] ], "nickname": [ [ Button(style=ButtonStyle.red, label="Profile", disabled=True) ] ] } } self.session_message = {} DiscordComponents(client) # UTILITY COMMANDS """ Cringe bio check is here just to make my life easier. yayayayayayayayayayay """ # CMD-CRINGEBIOCHECK @commands.command(aliases=["cbc"]) @commands.check(functions.beta_tester) async def cringebiocheck(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: bio = functions.get_bio(account['account_id']) pfp = functions.id_to_pfp(account['account_id'], True) print(f"{ctx.command} > {account['account_id']}, {account['username']}, {bio}, {pfp}") embed = functions.default_embed() embed.add_field(name=f"{account['username']}'s bio:", value=f"```{bio}```") flags = "" cringe_check_list = functions.load("cringe_word_list.json") cringe_score = 0 cringe_rating_dict = { 0: "Not cringe!", 1: "A little cringe!", 2: "Cringe!", 3: "Very cringe!", 4: "Yikes..!", 5: "Radically cringe!", 6: "Super cringe!", 7: "Mega cringe!", 8: "Ultra cringe!", 9: "THE CRINGIEST!", 10: "All hope for humanity has been lost!" } if bio: split_bio = bio.split(" ") for word in split_bio: for flag in cringe_check_list: if flag.casefold() in word.casefold(): cringe_score += 1 flags += f"`{flag}`, " if cringe_score > len(cringe_rating_dict) - 1: cringe_rating = cringe_rating_dict[len(cringe_rating_dict) - 1] else: cringe_rating = cringe_rating_dict[cringe_score] embed.add_field(name="Cringe score", value=f"`{cringe_score}` ({cringe_rating})", inline=False) if flags: embed.add_field(name="Flags", value=f"||{flags}||\nThis command is just for fun, and not meant to shame anybody!", inline=False) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) """ if cringe_score >= 5: bios = functions.load("cringe_bios.json") i = 0 for item in bios: if str(item[0]) == str(account['account_id']): bios.pop(i) break i += 1 bios.append([account['account_id'], bio]) functions.save("cringe_bios.json", bios) """ else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @cringebiocheck.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-OWOIFY @commands.command(aliases=["owo"]) @commands.check(functions.beta_tester) async def owoify(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: bio = functions.get_bio(account['account_id']) pfp = functions.id_to_pfp(account['account_id'], True) print(f"{ctx.command} > {account['account_id']}, {account['username']}, {bio}, {pfp}") embed = functions.default_embed() embed.add_field(name=f"{account['username']}'s owofied bio:", value=f"```{owoify.owoify(bio)}```") embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @owoify.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error @commands.command() @commands.check(functions.beta_tester) async def rectnet(self, ctx): cheers = functions.cheers_in_room() await ctx.send( f"<@{ctx.author.id}>\n**Cheers:** `{cheers['cheers']}`\n**Images taken:** `{cheers['image_count']}`\n\n**On frontpage: ** `{cheers['frontpage_count']}` (top 100)") # CMD-PLATFORMS @commands.command(aliases=["pf", "platform", "device", "devices"]) async def platforms(self, ctx, username): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(username) if account: platform_icons = { "Steam": "<:Steam:841761616193257474>", "Oculus": "<:Oculus:841761615682469890>", "PlayStation": "<:PlayStation:841761615514697800>", "Xbox": "<:Xbox:841761617129242674>", "iOS": "<:iOS:841761614734688297>", "Android": "<:android:870734160585703424>" } platform_str = "`Unknown!`" platforms = account['platforms'] if platforms: platform_str = "" platform_list = convert_platform_mask(platforms) for platform in platform_list: platform_str += f"{platform_icons[platform]} `{platform}`, " platform_str = platform_str[:-2] embed = discord.Embed( title=f"@{account['username']}'s platform(s)!", description=platform_str + "\n*Note: This might be inaccurate!*", colour=discord.Colour.orange() ) embed = functions.embed_footer(ctx, embed) embed.set_author(name=f"{account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'])) await ctx.send(embed=embed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{username}` doesn't exist!") await ctx.send(embed=embed) @platforms.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-LEVEL @commands.command(aliases=["lvl"]) async def level(self, ctx, username): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(username) if account: prog = functions.id_to_progression(account['account_id']) if not prog: embed = functions.error_msg(ctx, f"Couldn't fetch `@{username}`'s level!") return await ctx.send(embed=embed) embed = discord.Embed( title=f"@{account['username']}'s level!", description=f"Level: `{prog['Level']}`\nXP: `{prog['XP']}`", colour=discord.Colour.orange() ) embed = functions.embed_footer(ctx, embed) embed.set_author(name=f"{account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'])) await ctx.send(embed=embed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{username}` doesn't exist!") await ctx.send(embed=embed) @level.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-ROLES @commands.command() async def roles(self, ctx, room): functions.log(ctx.guild.name, ctx.author, ctx.command) response = functions.get_room_json(room) if response: room_data = response roles_data = room_data['Roles'] role_stats = { "255": 0, "30": 0, "20": 0, "10": 0 } i = 0 users = [] user_bulk = "https://accounts.rec.net/account/bulk?" for user in roles_data: user_bulk += F"&id={user['AccountId']}" role_stats[str(user['Role'])] += 1 i += 1 if i >= 100: print("Over hunna!") i = 0 response = requests.get(user_bulk) users = users + response.json() user_bulk = "https://accounts.rec.net/account/bulk?" if user_bulk != "https://accounts.rec.net/account/bulk?": print("left overs!") response = requests.get(user_bulk) users = users + response.json() users = sorted(users, key=lambda k: k['displayName']) i = 0 msg = "" for user in users: role_dict = { 255: "**Owner**", 30: "`Co-Owner`", 20: "*Moderator*", 10: "Host" } role = "UNKNOWN" for roled in roles_data: if roled['AccountId'] == user['accountId']: role = role_dict[roled['Role']] msg += f"[{user['displayName']}](https://rec.net/user/{user['username']}): {role}\n" if len(msg) > 1800: embed = discord.Embed( title=f"Users with a role in ^{room_data['Name']}", colour=discord.Colour.orange(), description=msg ) embed = functions.embed_footer(ctx, embed) await ctx.send(embed=embed) msg = "" if msg: embed = discord.Embed( title=f"Users with a role in ^{room_data['Name']}", colour=discord.Colour.orange(), description=msg ) embed = functions.embed_footer(ctx, embed) await ctx.send(embed=embed) embed = discord.Embed( title=f"Conclusion ({room_data['Name']})", description=f"**Users with a role:** `{len(roles_data)}`\nCo-Owners: `{role_stats['30']}`\nModerators: `{role_stats['20']}`\nHosts: `{role_stats['10']}`", colour=discord.Colour.orange(), url=f"https://rec.net/room/{room_data['Name']}", ) embed.set_thumbnail(url=f"https://img.rec.net/{room_data['ImageName']}?width=480") embed = functions.embed_footer(ctx, embed) return await ctx.send(embed=embed) else: room_embed = functions.error_msg(ctx, f"Room `^{room}` doesn't exist!") functions.embed_footer(ctx, room_embed) return await ctx.send(embed=room_embed) @roles.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a room!") await ctx.send(embed=embed) else: raise error # CMD-SELFCHEERS @commands.command(aliases=["selfc"]) async def selfcheers(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) author = f"<@{ctx.author.id}>" self_cheers = 0 latest_self_cheered = "" print("check account") # REMOVETHIS account = functions.check_account_existence_and_return(profile) if account: print("embed") # REMOVETHIS embed = discord.Embed( title=f"<a:spinning:804022054822346823> Getting @{account['username']}'s self cheered posts...", description="This shouldn't take too long.", colour=discord.Colour.orange() ) print("send embed loading") # REMOVETHIS functions.embed_footer(ctx, embed) loading = await ctx.send(embed=embed) photos = httpx.get(f"https://api.rec.net/api/images/v4/player/{account['account_id']}?take=10000000").json() # ye self_cheer_data = await main(account['account_id'], photos) self_cheers = self_cheer_data[0] latest_self_cheer = self_cheer_data[1] print(f"returned: {self_cheers}") pfp = functions.id_to_pfp(account['account_id']) if self_cheers: percentage = round(self_cheers / len(photos) * 100, 2) result_string = f"Self cheered: `{self_cheers}`\n*That's `{percentage}%` of their posts!*\n\n[Latest self cheered post](https://rec.net/image/{latest_self_cheer['Id']})" embed = discord.Embed( title=f"@{account['username']}'s self cheered posts!", description=result_string, colour=discord.Colour.orange() ) embed.set_author(name=f"{account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) embed.set_image(url=f"https://img.rec.net/{latest_self_cheer['ImageName']}?width=720") else: result_string = f"No self cheers, `@{account['username']}` is pure! <:CheerSport:803244185447956490>" embed = functions.error_msg(ctx, result_string) embed.set_author(name=f"{account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) embed.set_thumbnail(url=pfp) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) try: await loading.delete() pfp = functions.id_to_pfp(account['account_id'], True) embed.set_author(name=f"{account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) embed.set_thumbnail(url=pfp) except: pass functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(author, embed=embed) @selfcheers.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-INFRONTPAGE @commands.command(aliases=['IFP', 'BL', 'BLACKLISTED']) @commands.check(functions.beta_tester) async def infrontpage(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session account = functions.check_account_existence_and_return(profile) if account: latest_comment = "" blacklisted = True post_ = None frontpage = requests.get("https://api.rec.net/api/images/v3/feed/global?take=500").json() count = 1 for post in frontpage: count += 1 if post['PlayerId'] == account['account_id']: blacklisted = False post_ = post break if blacklisted: title_string = f"@{account['username']} is not in frontpage!" description = f"No `@{account['username']}`'s post was found in [RecNet](https://rec.net)'s frontpage!" else: response = requests.get(f"https://api.rec.net/api/images/v1/{post['Id']}/comments") if response.ok: comments = response.json() if comments: latest_comment = {"user": functions.id_to_username(comments[-1]['PlayerId']), "comment": comments[-1]['Comment']} else: latest_comment = "" else: latest_comment = "" title_string = f"@{account['username']} is in frontpage!" description = f"Their [post](https://rec.net/image/{post['Id']}) appears in `#{count - 1}`.\n<:CheerGeneral:803244099510861885> `{post['CheerCount']}` 💬 `{post['CommentCount']}`" embed = discord.Embed( colour=discord.Colour.orange(), title=title_string, description=description ) if latest_comment: embed.add_field(name="Latest Comment", value=f"[`@{latest_comment['user']}`](https://rec.net/user/{latest_comment['user']}): {latest_comment['comment']}", inline=False) if not blacklisted: embed.set_image(url=f"https://img.rec.net/{post['ImageName']}?width=720") pfp = functions.id_to_pfp(account['account_id']) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if not blacklisted: await ctx.send(embed=embed, components=[ Button(style=ButtonStyle.URL, label="Post", url=f"https://rec.net/image/{post['Id']}")]) else: await ctx.send(embed=embed) @infrontpage.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-BIO @commands.command() @commands.check(functions.beta_tester) async def bio(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session account = functions.check_account_existence_and_return(profile) if account: bio = functions.get_bio(account['account_id']) pfp = functions.id_to_pfp(account['account_id'], True) print(f"{ctx.command} > {account['account_id']}, {account['username']}, {bio}, {pfp}") embed = functions.default_embed() embed.add_field(name=f"{account['username']}'s bio:", value=f"```{bio}```") embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function m = await ctx.send( embed=embed, components=self.buttons['default']['bio'] ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit(components=self.buttons['disabled']['bio']) if res.component.label == "Check Cringe Rating": await m.edit( components=self.buttons['disabled']['bio'] ) await self.cringebiocheck(ctx, profile) elif res.component.label == "Owoify": await m.edit( components=self.buttons['disabled']['bio'] ) await self.owoify(ctx, profile) @bio.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-PFP @commands.command() @commands.check(functions.beta_tester) async def pfp(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session success = False account = functions.check_account_existence_and_return(profile) if account: pfp = functions.id_to_pfp(account['account_id'], False) link = functions.id_to_pfp(account['account_id'], False, False) print(f"{ctx.command} > {account['account_id']}, {account['username']}, {pfp}") embed = discord.Embed( colour=discord.Colour.orange(), description=f"[{account['username']}'s profile picture](https://rec.net/image/{link})" ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) embed.set_image(url=pfp) success = True else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if success: m = await ctx.send( embed=embed, components=[ [ Button(style=ButtonStyle.URL, label="Post", url=f"https://rec.net/image/{link}"), Button(style=ButtonStyle.URL, label="Direct Link", url=f"https://img.rec.net/{link}"), self.buttons['default']['pfp'][0][0] ] ] ) else: return await ctx.send( embed=embed ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit( components=[ [ Button(style=ButtonStyle.URL, label="Post", url=f"https://rec.net/image/{link}"), Button(style=ButtonStyle.URL, label="Direct Link", url=f"https://img.rec.net/{link}"), self.buttons['disabled']['pfp'][0][0] ] ] ) if res.component.label == "Profile": await m.edit( components=[ [ Button(style=ButtonStyle.URL, label="Post", url=f"https://rec.net/image/{link}"), Button(style=ButtonStyle.URL, label="Direct Link", url=f"https://img.rec.net/{link}"), self.buttons['disabled']['pfp'][0][0] ] ] ) await self.profile(ctx, profile) @pfp.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-TOPSUBSCRIBED @commands.command(aliases=['ts']) @commands.check(functions.beta_tester) async def topsubscribed(self, ctx, username=None): functions.log(ctx.guild.name, ctx.author, ctx.command) leaderboard_take = 10 account = None if username: account = functions.check_account_existence_and_return(username) if account: leaderboard_take = 10000 response = requests.get(f"https://clubs.rec.net/subscription/top/creators?take={leaderboard_take}") if response.ok: top_creators = response.json() else: return await ctx.send(f"Error {response.status_code} while requesting top creators!") print(top_creators) creators = {} embed = discord.Embed( title="Subscriber leaderboard", colour=discord.Colour.orange(), url="https://rec.net/top/creators" ) bulk = "https://accounts.rec.net/account/bulk?" count = 0 for user in top_creators: count += 1 if count > 10: break creators[str(user['accountId'])] = {"username": None, "display_name": None, "subscribers": user['subscriberCount']} bulk += f"&id={user['accountId']}" print(creators) response = requests.get(bulk) if response.ok: creator_account_data = response.json() else: return await ctx.send(f"Error {response.status_code} while requesting creator data!") for user in creator_account_data: creators[str(user['accountId'])]['display_name'] = user['displayName'] creators[str(user['accountId'])]['username'] = user['username'] highlighted_in_list = False index = 0 for user in top_creators: # Makes sure everyone's in the right order index += 1 if index > 10: break rank = f"{index}." display_name = creators[str(user['accountId'])]['display_name'] if index == 1: embed.set_thumbnail(url=functions.id_to_pfp(user['accountId'])) rank = "🥇" elif index == 2: rank = "🥈" elif index == 3: rank = "🥉" if account and account['account_id'] == user['accountId']: embed.add_field(name=f"{rank} {display_name} 🔎", value=f"`{creators[str(user['accountId'])]['subscribers']:,}`\n[Profile](https://rec.net/user/{creators[str(user['accountId'])]['username']})", inline=False) highlighted_in_list = True else: embed.add_field(name=f"{rank} {display_name}", value=f"`{creators[str(user['accountId'])]['subscribers']:,}`\n[Profile](https://rec.net/user/{creators[str(user['accountId'])]['username']})", inline=False) if account and not highlighted_in_list: found = False index = 0 for user in top_creators: index += 1 if user['accountId'] == account['account_id']: embed.add_field(name=f"{index}. {account['display_name']} 🔎", value=f"`{user['subscriberCount']:,}`\n[Profile](https://rec.net/user/{account['username']})", inline=False) found = True break if not found: embed.add_field(name=f"User @{username} doesn't appear on the leaderboards!", value="`.ts <username>`", inline=False) else: embed.add_field(name="Check someone's placement by including in their username!", value="`.ts <username>`", inline=False) embed.add_field(name="This leaderboard is based on subscribers!", value="For a more accurate *creator* leaderboard, do `.tc`!", inline=False) embed = functions.embed_footer(ctx, embed) await ctx.send(embed=embed) # CMD-TOPCREATORS @commands.command(aliases=['tc']) @commands.check(functions.beta_tester) async def topcreators(self, ctx): functions.log(ctx.guild.name, ctx.author, ctx.command) leaderboard_take = 100 response = requests.get(f"https://clubs.rec.net/subscription/top/creators?take={leaderboard_take}") if response.ok: top_creators = response.json() else: return await ctx.send(f"Error {response.status_code} while requesting top creators!") print(top_creators) creators = [] embed = discord.Embed( title="Creator leaderboard", colour=discord.Colour.orange() ) bulk = "https://accounts.rec.net/account/bulk?" creator_score = 0 for user in top_creators: account_rooms = functions.id_to_rooms(user['accountId']) if account_rooms: room_count = 0 cheers = 0 favorites = 0 visitors = 0 visits = 0 creator_score = 0 for room in account_rooms: cheers += room['Stats']['CheerCount'] favorites += room['Stats']['FavoriteCount'] visitors += room['Stats']['VisitorCount'] visits += room['Stats']['VisitCount'] temp_room_stats_sum = room['Stats']['CheerCount'] + room['Stats']['FavoriteCount'] + room['Stats'][ 'VisitorCount'] + room['Stats']['VisitCount'] room_count += 1 creator_score += round((temp_room_stats_sum + room_count * 1000) / 5) creators.append({"account_id": user['accountId'], "username": None, "display_name": None, "subscribers": user['subscriberCount'], "creator_score": creator_score}) bulk += f"&id={user['accountId']}" print(creators) response = requests.get(bulk) if response.ok: creator_account_data = response.json() else: return await ctx.send(f"Error {response.status_code} while requesting creator data!") for user in creator_account_data: index = 0 for creator in creators: if creator['account_id'] == user['accountId']: creator['display_name'] = user['displayName'] creator['username'] = user['username'] break index += 1 def sort_by_score(list_): return list_['creator_score'] creators.sort(reverse=True, key=sort_by_score) index = 0 for user in creators: index += 1 if index > 10: break rank = f"{index}." display_name = user['display_name'] if index == 1: embed.set_thumbnail(url=functions.id_to_pfp(user['account_id'])) rank = "🥇" elif index == 2: rank = "🥈" elif index == 3: rank = "🥉" embed.add_field(name=f"{rank} {display_name}", value=f"`{user['creator_score']:,}`\n[Profile](https://rec.net/user/{user['username']})", inline=False) embed.add_field(name="Based on my creator score algorithm!", value="Calculated with total room statistics!\n||`(cheers + favorites + visits + visitors + room count * 1,000) / 5`||\nFor the official leaderboard, do `.ts`.", inline=False) embed = functions.embed_footer(ctx, embed) await ctx.send(embed=embed) # CMD-BANNER @commands.command() @commands.check(functions.beta_tester) async def banner(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session success = False account = functions.check_account_existence_and_return(profile) if account: banner = functions.id_to_banner(account['account_id'], True) link = functions.id_to_banner(account['account_id'], False) print(f"{ctx.command} > {account['account_id']}, {account['username']}, {banner}") if not banner: embed = discord.Embed( colour=discord.Colour.orange(), description=f"{account['username']}'s banner" ) banner = "https://cdn.rec.net/static/banners/default_player.png" # replace with default banner else: embed = discord.Embed( colour=discord.Colour.orange(), description=f"[{account['username']}'s banner](https://rec.net/image/{link})" ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'])) embed.set_image(url=banner) success = True else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if success: m = await ctx.send( embed=embed, components=[ [ Button(style=ButtonStyle.URL, label="Post", url=f"https://rec.net/image/{link}"), Button(style=ButtonStyle.URL, label="Direct Link", url=f"https://img.rec.net/{link}"), self.buttons['default']['banner'][0][0] ] ] ) else: return await ctx.send( embed=embed ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit( components=[ [ Button(style=ButtonStyle.URL, label="Post", url=f"https://rec.net/image/{link}"), Button(style=ButtonStyle.URL, label="Direct Link", url=f"https://img.rec.net/{link}"), self.buttons['disabled']['banner'][0][0] ] ] ) if res.component.label == "Profile": await m.edit( components=[ [ Button(style=ButtonStyle.URL, label="Post", url=f"https://rec.net/image/{link}"), Button(style=ButtonStyle.URL, label="Direct Link", url=f"https://img.rec.net/{link}"), self.buttons['disabled']['banner'][0][0] ] ] ) await self.profile(ctx, profile) @banner.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-PROFILE @commands.command(aliases=['p']) @commands.check(functions.beta_tester) async def profile(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session account = functions.check_account_existence_and_return(profile) if account: pfp = functions.id_to_pfp(account['account_id'], False) bio = functions.get_bio(account['account_id']) jr_status = "🧔 Adult account!" if account['junior']: jr_status = "🍼 Junior account!" embed = discord.Embed( colour=discord.Colour.orange(), description=f"**{account['display_name']}** | *@{account['username']}*\n🏅 Level: `{functions.id_to_progression(account['account_id'])['Level']}`\n```{bio}```\n{jr_status}\n📆 Joined `{functions.months[account['created_at'][5:7]]} {account['created_at'][8:10]}. {account['created_at'][0:4]}`" ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) embed.set_image(url=pfp) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function msg = "" if not account['is_username']: msg = f"`@{profile}` doesn't exist, this was the closest hit." m = await ctx.send( msg, embed=embed, components=[ Button(style=ButtonStyle.URL, label="Profile", url=f"https://rec.net/user/{account['username']}"), self.buttons['default']['profile'][0]] ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit(components=[ Button(style=ButtonStyle.URL, label="Profile", url=f"https://rec.net/user/{account['username']}"), self.buttons['disabled']['profile'][0]]) if res.component.label == "Stats": await m.edit( components=[ Button(style=ButtonStyle.URL, label="Profile", url=f"https://rec.net/user/{account['username']}"), self.buttons['disabled']['profile'][0]] ) await self.stats(ctx, profile) @profile.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-OLDER @commands.command() @commands.check(functions.beta_tester) async def older(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) success = False account = functions.check_account_existence_and_return(profile) if account: older = 100 - ((account['account_id'] / 30000000) * 100) created_at = account['created_at'] embed = discord.Embed( colour=discord.Colour.orange(), description=f"This account is older than `{round(older, 2)}%` of other accounts.\n*Creation date:* `{created_at[8:10]}. {functions.months[created_at[5:7]]} {created_at[0:4]}`" ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) success = True else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function return await ctx.send(embed=embed) @older.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-JUNIOR @commands.command(aliases=['jr']) @commands.check(functions.beta_tester) async def junior(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session success = False account = functions.check_account_existence_and_return(profile) if account: is_junior = functions.id_to_is_junior(account['account_id']) print(f"{ctx.command} > {account['account_id']}, {account['username']}, {is_junior}") if is_junior: title = f"{account['username']} is a junior! 🧒" else: title = f"{account['username']} is not junior! 🧔" embed = discord.Embed( colour=discord.Colour.orange(), title=title ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) success = True else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if success: m = await ctx.send( embed=embed, components=self.buttons['default']['junior'] ) else: return await ctx.send( embed=embed ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit( components=self.buttons['disabled']['junior'] ) if res.component.label == "Profile": await m.edit( components=self.buttons['disabled']['junior'] ) await self.profile(ctx, profile) @junior.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-DATE @commands.command(aliases=['createdat']) @commands.check(functions.beta_tester) async def date(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session success = False account = functions.check_account_existence_and_return(profile) if account: created_at = str(functions.id_to_creation_date(account['account_id'])) today = str(date.today()) d0 = date(int(created_at[0:4]), int(created_at[5:7]), int(created_at[8:10])) d1 = date(int(today[0:4]), int(today[5:7]), int(today[8:10])) delta = d1 - d0 print(f"{ctx.command} > {account['account_id']}, {account['username']}, {created_at}") embed = discord.Embed( colour=discord.Colour.orange(), title=f"{account['username']}'s account was created at", description=f"📆 `{created_at[8:10]}. {functions.months[created_at[5:7]]} {created_at[0:4]}` | `{delta.days}` days ago\n⏰ `{created_at[11:16]} UTC`" ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) success = True else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if success: m = await ctx.send( embed=embed, components=self.buttons['default']['date'] ) else: return await ctx.send( embed=embed ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit( components=self.buttons['disabled']['date'] ) if res.component.label == "Profile": await m.edit( components=self.buttons['disabled']['date'] ) await self.profile(ctx, profile) @date.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-NICKNAME @commands.command(aliases=['displayname']) @commands.check(functions.beta_tester) async def nickname(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session success = False account = functions.check_account_existence_and_return(profile) if account: display_name = functions.id_to_display_name(account['account_id']) print(f"{ctx.command} > {account['account_id']}, {account['username']}, {display_name}") embed = discord.Embed( colour=discord.Colour.orange(), title=f"{account['username']}'s display name is", description=f"`{display_name}`" ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) success = True else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if success: m = await ctx.send( embed=embed, components=self.buttons['default']['nickname'] ) else: return await ctx.send( embed=embed ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit( components=self.buttons['disabled']['nickname'] ) if res.component.label == "Profile": await m.edit( components=self.buttons['disabled']['nickname'] ) await self.profile(ctx, profile) @nickname.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-LATEST @commands.command(aliases=['newest']) @commands.check(functions.beta_tester) async def latest(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: latest = functions.id_to_latest_photo(account['account_id']) if latest: embed = functions.image_embed(latest) else: print(f"{ctx.command} > {account['account_id']}, {account['username']}, Latest not found!") embed = functions.error_msg(ctx, f"User `{account['username']}` hasn't shared any pictures!") return await ctx.send(embed=embed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Latest from `@{account['username']}`", embed=embed) @latest.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-OLDEST @commands.command() @commands.check(functions.beta_tester) async def oldest(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: oldest = functions.id_to_oldest_photo(account['account_id']) if oldest: embed = functions.image_embed(oldest) else: print(f"{ctx.command} > {account['account_id']}, {account['username']}, Oldest not found!") embed = functions.error_msg(ctx, f"User `{account['username']}` hasn't shared any pictures!") return await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Oldest from `@{account['username']}`", embed=embed) @oldest.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-OLDESTFEED @commands.command(aliases=['oldestappearance']) @commands.check(functions.beta_tester) async def oldestfeed(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: oldestfeed = functions.id_to_oldest_feed(account['account_id']) if oldestfeed: embed = functions.image_embed(oldestfeed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Oldest feed from `@{account['username']}`", embed=embed) @oldestfeed.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-LATESTFEED @commands.command(aliases=['appearance']) @commands.check(functions.beta_tester) async def latestfeed(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: latestfeed = functions.id_to_latest_feed(account['account_id']) if latestfeed: embed = functions.image_embed(latestfeed) else: print(f"{ctx.command} > {account['account_id']}, {account['username']}, latestfeed not found!") embed = functions.error_msg(ctx, f"User `{account['username']}` isn't tagged in any post!") return await ctx.send(embed=embed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Latest feed from `@{account['username']}`", embed=embed) @latestfeed.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-CHEERS @commands.command() @commands.check(functions.beta_tester) async def cheers(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: cheer_data = functions.id_to_cheer_stats(account['account_id']) if cheer_data['total_cheers'] > 0: most_cheered_post_text = f"\n<:CheerSport:803244185447956490> [Most Cheered Post:](https://rec.net/image/{cheer_data['most_cheered']['Id']}) (<:CheerGeneral:803244099510861885> `{cheer_data['most_cheered']['CheerCount']}`)" else: most_cheered_post_text = "" embed = discord.Embed( colour=discord.Colour.orange(), title=f"{account['username']}'s cheer statistics", description=f"<:CheerGeneral:803244099510861885> Total Cheers: `{cheer_data['total_cheers']}`{most_cheered_post_text}" ) print("set image") embed.set_image(url=f"https://img.rec.net/{cheer_data['most_cheered']['ImageName']}?width=720") embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @cheers.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-COMMENTS @commands.command() @commands.check(functions.beta_tester) async def comments(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: comment_data = functions.id_to_comment_stats(account['account_id']) if comment_data['total_comments'] > 0: most_commented_post_text = f"\n<:CheerSport:803244185447956490> [Most Commented Post:](https://rec.net/image/{comment_data['most_commented']['Id']}) (💬 `{comment_data['most_commented']['CommentCount']}`)" else: most_commented_post_text = "" embed = discord.Embed( colour=discord.Colour.orange(), title=f"{account['username']}'s comment statistics", description=f"💬 Total Comments: `{comment_data['total_comments']}`{most_commented_post_text}" ) print("set image") embed.set_image(url=f"https://img.rec.net/{comment_data['most_commented']['ImageName']}?width=720") embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @comments.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-PHOTOSTATS @commands.command() @commands.check(functions.beta_tester) async def photostats(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: photos = functions.id_to_photos(account['account_id']) total_pictures = len(photos) all_cheers = functions.id_to_all_cheers(account['account_id']) pictures_cheered = total_pictures - all_cheers.count(0) all_comments = functions.id_to_all_comments(account['account_id']) pictures_commented = total_pictures - all_comments.count(0) embed = discord.Embed( colour=discord.Colour.orange(), title=f"{account['username']} has shared {total_pictures:,} pictures!", description=f"<:CheerGeneral:803244099510861885> `{pictures_cheered:,}` of them are cheered!\n💬 `{pictures_commented:,}` of them have been commented!" ) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=functions.id_to_pfp(account['account_id'], True)) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @photostats.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-STATS @commands.command() @commands.check(functions.beta_tester) async def stats(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session account = functions.check_account_existence_and_return(profile) successful = False if account: photos = functions.id_to_photos(account['account_id']) feed = functions.id_to_feed(account['account_id']) total_pictures = len(photos) total_feed = len(feed) if not total_pictures: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture!") return await ctx.send(embed=embed) all_cheers = functions.id_to_all_cheers(account['account_id']) pictures_cheered = total_pictures - all_cheers.count(0) cheer_data = functions.id_to_cheer_stats(account['account_id']) all_comments = functions.id_to_all_comments(account['account_id']) pictures_commented = total_pictures - all_comments.count(0) comment_data = functions.id_to_comment_stats(account['account_id']) embed = discord.Embed( colour=discord.Colour.orange(), title=f"RecNet Statistics for {account['username']}!", description=f"Pictures shared: `{total_pictures:,}`\nPictures tagged in: `{total_feed:,}`" ) # embed.add_field(name="Pictures shared", value=f"`{total_pictures}`\n", inline=True) # embed.add_field(name="Pictures tagged in", value=f"`{total_feed}`\n", inline=True) # embed.add_field(name="‎⠀", value=f"‎⠀", inline=False) if pictures_cheered: embed.add_field(name="CHEER STATISTICS", value=f"Total Cheers: <:CheerGeneral:803244099510861885> `{cheer_data['total_cheers']:,}`\nUser's posts cheered: `{pictures_cheered:,}`\n[**Most cheered post**](https://rec.net/image/{cheer_data['most_cheered']['Id']})\n<:CheerGeneral:803244099510861885> `{cheer_data['most_cheered']['CheerCount']:,}` 💬 `{cheer_data['most_cheered']['CommentCount']:,}`", inline=True) if pictures_commented: embed.add_field(name="COMMENT STATISTICS", value=f"Total Comments: 💬 `{comment_data['total_comments']:,}`\nUser's posts commented: `{pictures_commented:,}`\n[**Most commented post**](https://rec.net/image/{comment_data['most_commented']['Id']})\n<:CheerGeneral:803244099510861885> `{comment_data['most_commented']['CheerCount']:,}` 💬 `{comment_data['most_commented']['CommentCount']:,}`\n\n", inline=True) oldest_text = "" oldest = photos[-1] print(oldest) if oldest: oldest_text = f"[First post](https://rec.net/image/{oldest['Id']})\n" latest_text = "" latest = photos[0] print(latest) if latest: latest_text = f"[Latest post](https://rec.net/image/{latest['Id']})\n" oldestfeed_text = "" oldestfeed = feed[-1] print(oldestfeed) if oldestfeed: oldestfeed_text = f"[First appearance](https://rec.net/image/{oldestfeed['Id']})\n" latestfeed_text = "" latestfeed = feed[0] print(latestfeed) if latestfeed: latestfeed_text = f"[Latest appearance](https://rec.net/image/{latestfeed['Id']})" embed.add_field(name="OTHER POSTS", value=f"{oldest_text}{latest_text}{oldestfeed_text}{latestfeed_text}", inline=False) pfp = functions.id_to_pfp(account['account_id'], True) embed.set_thumbnail(url=pfp) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) successful = True else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if successful: m = await ctx.send( embed=embed, components=self.buttons['default']['stats'] ) else: return await ctx.send(embed=embed) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit(components=self.buttons['disabled']['stats']) if res.component.label == "Self-Cheers": await m.edit( components=self.buttons['disabled']['stats'] ) await self.selfcheers(ctx, profile) elif res.component.label == "Bookmarked": await m.edit( components=self.buttons['disabled']['stats'] ) await self.bookmarked(ctx, profile) @stats.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-ROOM @commands.command(aliases=["rinfo", "roominfo"]) @commands.check(functions.beta_tester) async def room(self, ctx, room_name): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session author = f"<@{ctx.author.id}>" embed = discord.Embed( description=f"<a:spinning:804022054822346823> Getting statistics for the room `^{room_name}`...", colour=discord.Colour.orange() ) functions.embed_footer(ctx, embed) loading = await ctx.send(embed=embed) print("Get room json") successful = False try: room_embed = functions.room_embed(room_name, False, ctx) functions.embed_footer(ctx, room_embed) m = await ctx.send( author, embed=room_embed, components=self.buttons['default']['rinfo'] ) successful = True await loading.delete() except: await loading.delete() room_embed = functions.error_msg(ctx, f"Room `^{room_name}` doesn't exist or is private!") functions.embed_footer(ctx, room_embed) return await ctx.send(embed=room_embed) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit(components=self.buttons['disabled']['rinfo']) if res.component.label == "Roles": await m.edit( components=self.buttons['disabled']['rinfo'] ) await self.roles(ctx, room_name) elif res.component.label == "Rooms by Creator": await m.edit( components=self.buttons['disabled']['rinfo'] ) await self.roomsby(ctx, functions.id_to_username(functions.get_room_json(room_name)['CreatorAccountId'])) @room.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a room!") await ctx.send(embed=embed) else: raise error # CMD-APICHECK @commands.command(aliases=['apicheck', "ac"]) @commands.check(functions.beta_tester) async def apistatus(self, ctx): functions.log(ctx.guild.name, ctx.author, ctx.command) author = f"<@{ctx.author.id}>" embed = discord.Embed( description="<a:loading:794930501597003786> Calling API to check its status...", colour=discord.Colour.orange() ) functions.embed_footer(ctx, embed) loading = await ctx.send(embed=embed) embed = discord.Embed( title="API call results!", colour=discord.Colour.orange() ) # Rooms try: api = requests.get("https://rooms.rec.net/rooms?name=paintball", timeout=10) if api.ok: embed.add_field(name="Room API call", value="`✅ Successful!`", inline=False) else: embed.add_field(name="Room API call", value="`❌ Failure.`", inline=False) except: embed.add_field(name="Room API call", value="`❌ Failure.`", inline=False) # Accounts try: api = requests.get("https://accounts.rec.net/account?username=coach", timeout=10) if api.ok: embed.add_field(name="Account API call", value="`✅ Successful!`", inline=False) else: embed.add_field(name="Account API call", value="`❌ Failure.`", inline=False) except: embed.add_field(name="Account API call", value="`❌ Failure.`", inline=False) # Images try: api = requests.get("https://api.rec.net/api/images/v3/feed/global?take=5", timeout=10) if api.ok: embed.add_field(name="Image API call", value="`✅ Successful!`", inline=False) else: embed.add_field(name="Image API call", value="`❌ Failure.`", inline=False) except: embed.add_field(name="Image API call", value="`❌ Failure.`", inline=False) # Events try: api = requests.get("https://api.rec.net/api/playerevents/v1?take=5", timeout=10) if api.ok: embed.add_field(name="Event API call", value="`✅ Successful!`", inline=False) else: embed.add_field(name="Event API call", value="`❌ Failure.`", inline=False) except: embed.add_field(name="Event API call", value="`❌ Failure.`", inline=False) await loading.delete() functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(author, embed=embed) # CMD-SHORTCUTS @commands.command(aliases=['sc']) @commands.check(functions.beta_tester) async def shortcuts(self, ctx, username=None): functions.log(ctx.guild.name, ctx.author, ctx.command) author = f"<@{ctx.author.id}>" embed = discord.Embed( title="Shortcuts for RecNet", colour=discord.Colour.orange() ) embed.add_field(name="Rec.net", value="[Link](https://rec.net/)", inline=True) embed.add_field(name="Rooms", value="[Link](https://rec.net/room/browse)", inline=True) embed.add_field(name="Events", value="[Link](https://rec.net/event/browse)", inline=True) if not username: embed.add_field(name="LINKS TO YOUR PROFILE", value="If nothing shows up below this, you didn't enter your username. `.shortcuts <username>`", inline=False) embed.set_footer(text="Shortcuts for -") else: old_username = username try: username = functions.check_account_existence_and_return(username)["username"] embed.add_field(name="LINKS TO YOUR PROFILE", value=f"Account: `@{username}`", inline=False) except: embed.add_field(name="LINKS TO YOUR PROFILE", value=f"Account: `@{old_username}`", inline=False) embed.add_field(name="Profile", value=f"[Link](https://rec.net/user/{username})", inline=True) embed.add_field(name="Photos", value=f"[Link](https://rec.net/user/{username}/photos)", inline=True) embed.add_field(name="Rooms", value=f"[Link](https://rec.net/user/{username}/rooms)", inline=True) embed.add_field(name="Events", value=f"[Link](https://rec.net/user/{username}/events)", inline=True) embed.add_field(name="Settings", value=f"[Link](https://rec.net/user/{username}/settings)", inline=True) embed.add_field(name="Friends", value=f"[Link](https://rec.net/user/{username}/friends)", inline=True) embed.add_field(name="Subscribers", value=f"[Link](https://rec.net/user/{username}/subscribers)", inline=True) embed.add_field(name="Subscriptions", value=f"[Link](https://rec.net/user/{username}/subscriptions)", inline=True) embed.add_field(name="Seller stats", value="[Link](https://rec.net/seller-stats)", inline=True) embed.set_footer(text=f"Shortcuts for @{username}") functions.embed_footer(ctx, embed) await ctx.send(author, embed=embed) # CMD-PLACEMENT @commands.command() @commands.check(functions.beta_tester) async def placement(self, ctx, room): functions.log(ctx.guild.name, ctx.author, ctx.command) room_json = functions.get_room_json(room) if room_json: placement = functions.get_room_placement(room) if not placement: placement = "<1000" embed = discord.Embed( title=f"{room_json['Name']}'s placement on hot", description=f"🔥 `#{placement}`", url=f"https://rec.net/room/{room_json['Name']}", colour=discord.Colour.orange() ) embed.set_thumbnail(url=f"https://img.rec.net/{room_json['ImageName']}?width=720") else: embed = functions.error_msg(ctx, f"Room `{room}` doesn't exist!") functions.embed_footer(ctx, embed) await ctx.send(embed=embed) @placement.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a room!") await ctx.send(embed=embed) else: pass # CMD-FEATURED @commands.command() @commands.check(functions.beta_tester) async def featured(self, ctx): functions.log(ctx.guild.name, ctx.author, ctx.command) author = f"<@{ctx.author.id}>" featured_rooms = functions.get_featured_rooms() featured_reset = requests.get("https://rooms.rec.net/featuredrooms/current").json()["EndAt"] today = str(date.today()) d0 = date(int(featured_reset[0:4]), int(featured_reset[5:7]), int(featured_reset[8:10])) d1 = date(int(today[0:4]), int(today[5:7]), int(today[8:10])) delta = d0 - d1 embed = discord.Embed( colour=discord.Colour.orange(), description="<a:spinning:804022054822346823> Getting featured rooms and their statistics..." ) functions.embed_footer(ctx, embed) loading = await ctx.send(embed=embed) embed = discord.Embed( colour=discord.Colour.orange(), title="Featured rooms", description=f"Next rotation: `{delta.days}` days" ) count = 0 for room in featured_rooms: count += 1 embed.add_field( name=f"{count}. ^{room['RoomName']}", value=f"[🔗 RecNet link](https://rec.net/room/{room['RoomName']})\nHot placement: `#{functions.get_room_placement(room['RoomName'])}`", inline=False ) functions.embed_footer(ctx, embed) await loading.delete() await ctx.send(embed=embed) # CMD-TAKENINBY @commands.command(aliases=['ti', 'tib', 'takeninby']) @commands.check(functions.beta_tester) async def takenin(self, ctx, room, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) room_data = functions.get_room_json(room) if room_data: # if room exists account = functions.check_account_existence_and_return(profile) if account: # if account exists photos = functions.id_to_photos(account['account_id']) if photos: # if user has posted anything images = [] for post in photos: if post['RoomId'] == room_data['RoomId']: images.append(post) if images: pages = menus.MenuPages(source=ImageMenu(range(1, len(images) + 1), images), clear_reactions_after=True) await pages.start(ctx) else: # not found embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture in `^{room_data['Name']}`!") await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture!") await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") await ctx.send(embed=embed) else: # room doesn't exist embed = functions.error_msg(ctx, f"Room `^{room}` doesn't exist!") await ctx.send(embed=embed) @takenin.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a room and an user! Usage: `.takenin <room> <user>`") await ctx.send(embed=embed) else: pass # CMD-TAKENOFBY @commands.command(aliases=['to', 'tob', 'takenofby']) @commands.check(functions.beta_tester) async def takenof(self, ctx, of_user, by_user): functions.log(ctx.guild.name, ctx.author, ctx.command) of_user_account = functions.check_account_existence_and_return(of_user) by_user_account = functions.check_account_existence_and_return(by_user) if of_user_account and by_user_account: # if both exist of_user_feed = functions.id_to_feed(of_user_account['account_id']) if of_user_feed: # if user appears anywhere images = [] for post in of_user_feed: if by_user_account['account_id'] == post['PlayerId']: images.append(post) if images: pages = menus.MenuPages(source=ImageMenu(range(1, len(images) + 1), images), clear_reactions_after=True) await pages.start(ctx) else: # not found embed = functions.error_msg(ctx, f"Couldn't find any picture taken by `@{by_user_account['username']}`, that features `@{of_user_account['username']}`") await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{of_user_account['username']}` isn't tagged in any post!") await ctx.send(embed=embed) else: # either doesn't exist embed = functions.error_msg(ctx, f"Either `@{of_user}` or `@{by_user}` don't exist!") await ctx.send(embed=embed) @takenof.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in 2 users! Usage: `.takenof <of_user> <by_user>`") await ctx.send(embed=embed) else: pass # CMD-TAKENOFIN @commands.command(aliases=['toi']) @commands.check(functions.beta_tester) async def takenofin(self, ctx, of_user, room): functions.log(ctx.guild.name, ctx.author, ctx.command) of_user_account = functions.check_account_existence_and_return(of_user) room_data = functions.get_room_json(room) if of_user_account: # if both exist if room_data: of_user_feed = functions.id_to_feed(of_user_account['account_id']) if of_user_feed: # if user appears anywhere images = [] for post in of_user_feed: if room_data['RoomId'] == post['RoomId']: images.append(post) if images: pages = menus.MenuPages(source=ImageMenu(range(1, len(images) + 1), images), clear_reactions_after=True) await pages.start(ctx) else: # not found embed = functions.error_msg(ctx, f"Couldn't find any picture taken of `@{of_user_account['username']}` in `^{room_data['Name']}`!") await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"Room `^{room}` doesn't exist!") await ctx.send(embed=embed) else: # either doesn't exist embed = functions.error_msg(ctx, f"User `@{of_user}` doesn't exist!") await ctx.send(embed=embed) @takenofin.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an user and a room! Usage: `.takenofin <user> <room>`") await ctx.send(embed=embed) else: pass # CMD-TOGETHER @commands.command() @commands.check(functions.beta_tester) async def together(self, ctx, user1, user2): functions.log(ctx.guild.name, ctx.author, ctx.command) user1_account = functions.check_account_existence_and_return(user1) user2_account = functions.check_account_existence_and_return(user2) if user1_account and user2_account: # if both exist user1_feed = functions.id_to_feed(user1_account['account_id']) if user1_feed: # if user appears anywhere images = functions.together(user1_account['account_id'], user2_account['account_id']) if images: pages = menus.MenuPages(source=ImageMenu(range(1, len(images) + 1), images), clear_reactions_after=True) await pages.start(ctx) else: # not found embed = functions.error_msg(ctx, f"Couldn't find any post that features both `@{user1_account['username']}` and `@{user2_account['username']}`!") return await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"Couldn't find any post that features both `@{user1_account['username']}` and `@{user2_account['username']}`!") return await ctx.send(embed=embed) else: # either doesn't exist embed = functions.error_msg(ctx, f"Either `@{user1}` or `@{user2}` don't exist!") return await ctx.send(embed=embed) @together.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in 2 users! Usage: `.together <user1> <user2>`") await ctx.send(embed=embed) else: pass # CMD-SORTBY @commands.command() @commands.check(functions.beta_tester) async def sortby(self, ctx, profile, mode): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: photos = functions.id_to_photos(account['account_id']) if photos: mode = mode.lower() reverse_sort = True if mode == "cheers": mode = lambda i: i["CheerCount"] reverse_sort = True elif mode == "comments": mode = lambda i: i["CommentCount"] reverse_sort = True elif mode == "oldest": mode = lambda i: i["CreatedAt"] reverse_sort = False elif mode == "latest": mode = lambda i: i["CreatedAt"] reverse_sort = True else: mode = None if mode: images = sorted(photos, key=mode, reverse=reverse_sort) pages = menus.MenuPages(source=ImageMenu(range(1, len(images) + 1), images), clear_reactions_after=True) await pages.start(ctx) else: embed = functions.error_msg(ctx, "Invalid mode! Modes are `cheers`, `comments`, `latest`, `oldest`") else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture!") return await ctx.send(embed=embed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @sortby.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username and mode! \nUsage: `.sortby <user> <latest|oldest|cheers|comments>`") await ctx.send(embed=embed) else: raise error # CMD-ROOMSBY @commands.command() @commands.check(functions.beta_tester) async def roomsby(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session account = functions.check_account_existence_and_return(profile) success = False if account: account_rooms = functions.id_to_rooms(account['account_id']) if account_rooms: embed = discord.Embed( colour=discord.Colour.orange(), title=f"@{account['username']}'s (max) 10 latest rooms" ) count = 0 for room in account_rooms: count += 1 embed.add_field(name=f"{count}. ^{room['Name']}", value=f"**Description:** ```{room['Description']}```\n**Statistics**\n<:CheerGeneral:803244099510861885> `{room['Stats']['CheerCount']:,}` *(CHEERS)*\n⭐ `{room['Stats']['FavoriteCount']:,}` *(FAVORITES)*\n👤 `{room['Stats']['VisitorCount']:,}` *(VISITORS)*\n👥 `{room['Stats']['VisitCount']:,}` *(ROOM VISITS)*", inline=False) if count == 10: break pfp = functions.id_to_pfp(account['account_id'], True) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) success = True else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single room!") return await ctx.send(embed=embed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if success: m = await ctx.send( embed=embed, components=self.buttons['default']['roomsby'] ) else: return await ctx.send( embed=embed ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit(components=self.buttons['disabled']['roomsby']) if res.component.label == "Profile": await m.edit( components=self.buttons['disabled']['roomsby'] ) await self.profile(ctx, profile) @roomsby.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-CREATORSTATS @commands.command(aliases=['cs']) @commands.check(functions.beta_tester) async def creatorstats(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) m_session = random.randint(0, 999999) self.session_message[ctx.author.id] = m_session account = functions.check_account_existence_and_return(profile) success = False if account: account_rooms = functions.id_to_rooms(account['account_id']) if account_rooms: best_room = {} worst_room = {} room_count = 0 cheers = 0 favorites = 0 visitors = 0 visits = 0 creator_score = 0 for room in account_rooms: cheers += room['Stats']['CheerCount'] favorites += room['Stats']['FavoriteCount'] visitors += room['Stats']['VisitorCount'] visits += room['Stats']['VisitCount'] room_count += 1 temp_room_stats_sum = room['Stats']['CheerCount'] + room['Stats']['FavoriteCount'] + room['Stats'][ 'VisitorCount'] + room['Stats']['VisitCount'] creator_score += round((temp_room_stats_sum + room_count * 1000) / 5) if room_count == 1: best_room = room best_room['RoomStatsSum'] = temp_room_stats_sum worst_room = room worst_room['RoomStatsSum'] = temp_room_stats_sum else: # print(f"BestRoom {best_room['Name']}: {best_room['RoomStatsSum']} vs {room['Name']}: {temp_room_stats_sum}") # print(f"WorstRoom {worst_room['Name']}: {worst_room['RoomStatsSum']} vs {room['Name']}: {temp_room_stats_sum}") if best_room['RoomStatsSum'] < temp_room_stats_sum: best_room = room best_room['RoomStatsSum'] = temp_room_stats_sum elif worst_room['RoomStatsSum'] > temp_room_stats_sum: worst_room = room worst_room['RoomStatsSum'] = temp_room_stats_sum embed = discord.Embed( colour=discord.Colour.orange(), title=f"@{account['username']}'s creator statistics", description=f"Rooms published: `{room_count}`\nCreator Score: `{creator_score:,}`" ) embed.add_field( name="Total Room Statistics", value=f"<:CheerGeneral:803244099510861885> `{cheers:,}` *(CHEERS)*\n⭐ `{favorites:,}` *(FAVORITES)*\n👤 `{visitors:,}` *(VISITORS)*\n👥 `{visits:,}` *(VISITS)*", inline=False ) embed.add_field( name="Best Room", value=f"🚪 [^{best_room['Name']}](https://rec.net/room/{best_room['Name']})", inline=True ) embed.add_field( name="Worst Room", value=f"🚪 [^{worst_room['Name']}](https://rec.net/room/{worst_room['Name']})", inline=True ) pfp = functions.id_to_pfp(account['account_id'], True) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) success = True else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single room!") return await ctx.send(embed=embed) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function if success: m = await ctx.send( embed=embed, components=self.buttons['default']['roomsby'] ) else: return await ctx.send( embed=embed ) def check(res): return ctx.author == res.user and res.channel == ctx.channel and self.session_message[ ctx.author.id] == m_session try: res = await self.client.wait_for("button_click", check=check, timeout=30) await res.respond(type=6) except: return await m.edit(components=self.buttons['disabled']['roomsby']) if res.component.label == "Profile": await m.edit( components=self.buttons['disabled']['roomsby'] ) await self.profile(ctx, profile) @roomsby.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-BOOKMARKED @commands.command(aliases=["bookmark", "favorites", "favorite"]) @commands.check(functions.beta_tester) async def bookmarked(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) author = f"<@{ctx.author.id}>" account = functions.check_account_existence_and_return(profile) if account: embed = discord.Embed( colour=discord.Colour.orange(), description=f"<a:spinning:804022054822346823> Looking for `@{account['username']}`'s bookmarked posts..." ) functions.embed_footer(ctx, embed) loading = await ctx.send(embed=embed) embed = discord.Embed( colour=discord.Colour.orange(), title=f"@{account['username']}'s bookmarked photos 📌", ) photos = functions.id_to_photos(account['account_id']) print(f"photos: {bool(photos)}") found_bookmarked = False if photos: comment_count = len(functions.id_to_all_comments(account['account_id'])) if comment_count > 0: count = 0 for photo in photos: if photo['CommentCount'] > 0: print(f"comments over 0 - {photo['Id']}") comments = functions.get_photo_comments(photo['Id']) for comment in comments: if comment['PlayerId'] == account['account_id'] and "bookmark" in comment[ 'Comment'].lower(): print("BOOKMARKED!!!") found_bookmarked = True count += 1 if count > 25: break embed.add_field(name=f"{count}. \"{comment['Comment'].replace('bookmark', '')}\"", value=f"https://rec.net/image/{comment['SavedImageId']}", inline=False) pfp = functions.id_to_pfp(account['account_id'], True) embed.set_author(name=f"🔗 {account['username']}'s profile", url=f"https://rec.net/user/{account['username']}", icon_url=pfp) else: # account doesn't exist embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) functions.embed_footer(ctx, embed) # get default footer from function await loading.delete() if not found_bookmarked: embed.add_field(name="None!", value="You can bookmark your own posts by commenting\n`bookmark <text>`\non a post of yours! The text you type in is there just to remind you of what the bookmarked image is, however, it's not necessary.", inline=False) await ctx.send(f"{author}\n**Bookmarked:** `{count}/25`", embed=embed) @bookmarked.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-LATESTINBY @commands.command(aliases=["latestin"]) @commands.check(functions.beta_tester) async def latestinby(self, ctx, room, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: total_photos = len(functions.id_to_photos(account['account_id'])) if total_photos: print("get photos in") # REMOVEME photosin = functions.id_to_photos_in(account['account_id'], room) if photosin: print("latestin") # REMOVEME latestin = photosin[0] embed = functions.image_embed(latestin) else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture in `^{room}`!") else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture!") return await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) print("send") # REMOVEME functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Latest by `@{account['username']}`, in `^{room}`", embed=embed) @latestinby.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a room and an user! Usage: `.latestinby <room> <user>`") await ctx.send(embed=embed) else: raise error # CMD-OLDESTINBY @commands.command(aliases=["oldestin"]) @commands.check(functions.beta_tester) async def oldestinby(self, ctx, room, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) account = functions.check_account_existence_and_return(profile) if account: total_photos = len(functions.id_to_photos(account['account_id'])) if total_photos: print("get photos in") # REMOVEME photosin = functions.id_to_photos_in(account['account_id'], room) if photosin: print("oldestin") # REMOVEME oldestin = photosin[len(photosin) - 1] embed = functions.image_embed(oldestin) else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture in `^{room}`!") return await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{account['username']}` hasn't shared a single picture!") return await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{profile}` doesn't exist!") return await ctx.send(embed=embed) print("send") # REMOVEME functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Oldest by `@{account['username']}`, in `^{room}`", embed=embed) @oldestinby.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a room and an user! Usage: `.oldestinby <room> <user>`") await ctx.send(embed=embed) else: pass # CMD-LATESTWITH @commands.command() @commands.check(functions.beta_tester) async def latestwith(self, ctx, user1, user2): functions.log(ctx.guild.name, ctx.author, ctx.command) user1_account = functions.check_account_existence_and_return(user1) user2_account = functions.check_account_existence_and_return(user2) if user1_account and user2_account: user1_feed = len(functions.id_to_feed(user1_account['account_id'])) if user1_feed: print("get photos with") # REMOVEME photoswith = functions.together(user1_account['account_id'], user2_account['account_id']) if photoswith: print("latestwith") # REMOVEME latestwith = photoswith[0] embed = functions.image_embed(latestwith) else: embed = functions.error_msg(ctx, f"Couldn't find any post that features both `@{user1_account['username']}` and `@{user2_account['username']}`!") else: embed = functions.error_msg(ctx, f"Couldn't find any post that features both `@{user1_account['username']}` and `@{user2_account['username']}`!") else: embed = functions.error_msg(ctx, f"Either `@{user1}` or `@{user2}` don't exist!") print("send") # REMOVEME functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Latest with both `@{user1_account['username']}` and `@{user2_account['username']}`", embed=embed) @latestwith.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in two users! Usage: `.latestwith <user1> <user2>`") await ctx.send(embed=embed) else: pass # CMD-OLDESTWITH @commands.command() @commands.check(functions.beta_tester) async def oldestwith(self, ctx, user1, user2): functions.log(ctx.guild.name, ctx.author, ctx.command) user1_account = functions.check_account_existence_and_return(user1) user2_account = functions.check_account_existence_and_return(user2) if user1_account and user2_account: user1_feed = len(functions.id_to_feed(user1_account['account_id'])) if user1_feed: print("get photos with") # REMOVEME photoswith = functions.together(user1_account['account_id'], user2_account['account_id']) if photoswith: print("oldestwith") # REMOVEME oldestwith = photoswith[len(photoswith) - 1] embed = functions.image_embed(oldestwith) else: embed = functions.error_msg(ctx, f"Couldn't find any post that features both `@{user1_account['username']}` and `@{user2_account['username']}`!") else: embed = functions.error_msg(ctx, f"Couldn't find any post that features both `@{user1_account['username']}` and `@{user2_account['username']}`!") else: embed = functions.error_msg(ctx, f"Either `@{user1}` or `@{user2}` don't exist!") print("send") # REMOVEME functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(f"Oldest with both `@{user1_account['username']}` and `@{user2_account['username']}`", embed=embed) @oldestwith.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in two users! Usage: `.oldestwith <user1> <user2>`") await ctx.send(embed=embed) else: pass # CMD-ANNIVERSARY @commands.command() @commands.check(functions.beta_tester) async def anniversary(self, ctx, profile): functions.log(ctx.guild.name, ctx.author, ctx.command) await ctx.send("trol") @anniversary.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-FRONTPAGE @commands.command() @commands.check(functions.beta_tester) async def frontpage(self, ctx): images = requests.get("https://api.rec.net/api/images/v3/feed/global?take=51").json() pages = menus.MenuPages(source=ImageMenu(range(1, 51), images), clear_reactions_after=True) await pages.start(ctx) # CMD-FEED @commands.command() @commands.check(functions.beta_tester) async def feed(self, ctx, username): account = functions.check_account_existence_and_return(username) if account: images = requests.get( f"https://api.rec.net/api/images/v3/feed/player/{account['account_id']}?take=9999999").json() if images: pages = menus.MenuPages(source=ImageMenu(range(1, len(images) + 1), images), clear_reactions_after=True) await pages.start(ctx) else: embed = functions.error_msg(ctx, f"User `@{username}` isn't tagged in a single picture!") await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{username}` doesn't exist!") await ctx.send(embed=embed) @feed.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-PHOTOS @commands.command() @commands.check(functions.beta_tester) async def photos(self, ctx, username): account = functions.check_account_existence_and_return(username) if account: images = requests.get( f"https://api.rec.net/api/images/v4/player/{account['account_id']}?take=9999999").json() if images: pages = menus.MenuPages(source=ImageMenu(range(1, len(images) + 1), images), clear_reactions_after=True) await pages.start(ctx) else: embed = functions.error_msg(ctx, f"User `@{username}` hasn't shared a single picture!") await ctx.send(embed=embed) else: embed = functions.error_msg(ctx, f"User `@{username}` doesn't exist!") await ctx.send(embed=embed) @photos.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: pass # CMD-EVENTSEARCH @commands.command(aliases=["es"]) @commands.check(functions.beta_tester) async def eventsearch(self, ctx, word): functions.log(ctx.guild.name, ctx.author, ctx.command) keyword = str(word) if len(keyword) < 2: embed = functions.error_msg(ctx, "Keyword must be at least 2 characters long!") await ctx.send(embed=embed) else: embed = discord.Embed( colour=discord.Colour.orange(), title=f"Events found with keyword \"{keyword}\"", description="*Max. 15*" ) events_found = functions.event_search(keyword) if not events_found: embed = functions.error_msg(ctx, f"No events found with the keyword `{word}`!") return await ctx.send(embed=embed) room_bulk = "https://rooms.rec.net/rooms/bulk?" acc_bulk = "https://accounts.rec.net/account/bulk?" for event in events_found: room_bulk += f"&id={event['RoomId']}" acc_bulk += f"&id={event['CreatorPlayerId']}" rooms = requests.get(room_bulk).json() accs = requests.get(acc_bulk).json() for event in events_found: if not " " + word in event['Name'].casefold(): continue if len(embed.fields) >= 15: break embed = functions.event_embed_field(embed, event, rooms, accs) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @eventsearch.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a word to search!") await ctx.send(embed=embed) else: raise error # CMD-EVENTSBY @commands.command(aliases=["eb"]) @commands.check(functions.beta_tester) async def eventsby(self, ctx, user): functions.log(ctx.guild.name, ctx.author, ctx.command) username = str(user) account = functions.check_account_existence_and_return(username) if not account: embed = functions.error_msg(ctx, f"User `@{username}` doesn't exist!") return await ctx.send(embed=embed) events_found = functions.events_by(None, account['account_id']) if not events_found: embed = functions.error_msg(ctx, f"No events found that were made by `@{account['username']}`!") return await ctx.send(embed=embed) embed = discord.Embed( colour=discord.Colour.orange(), title=f"Events made by @{account['username']}", description=f"\nTotal Count: `{len(events_found)}`\n*Max. 15 displayed*" ) room_bulk = "https://rooms.rec.net/rooms/bulk?" acc_bulk = "https://accounts.rec.net/account/bulk?" for event in events_found: room_bulk += f"&id={event['RoomId']}" acc_bulk += f"&id={event['CreatorPlayerId']}" rooms = requests.get(room_bulk).json() accs = requests.get(acc_bulk).json() for event in events_found: if len(embed.fields) >= 15: break embed = functions.event_embed_field(embed, event, rooms, accs) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send( embed=embed, components=[ Button(style=ButtonStyle.URL, label="User Events", url=f"https://rec.net/user/{account['username']}/events") ] ) @eventsby.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username!") await ctx.send(embed=embed) else: raise error # CMD-EVENTSIN @commands.command(aliases=["ebi"]) @commands.check(functions.beta_tester) async def eventsbyin(self, ctx, user, room): functions.log(ctx.guild.name, ctx.author, ctx.command) username = str(user) account = functions.check_account_existence_and_return(username) if not account: embed = functions.error_msg(ctx, f"User `@{username}` doesn't exist!") return await ctx.send(embed=embed) room_data = functions.get_room_json(room) if not room_data: embed = functions.error_msg(ctx, f"Room `^{room}` doesn't exist or is private!") return await ctx.send(embed=embed) events_found = functions.events_by(None, account['account_id']) if not events_found: embed = functions.error_msg(ctx, f"No events found that were made by `@{account['username']}` in `^{room_data['Name']}`!") return await ctx.send(embed=embed) events_in_room = [] for event in events_found: if event['RoomId'] != room_data['RoomId']: continue events_in_room.append(event) embed = discord.Embed( colour=discord.Colour.orange(), title=f"Events made by @{account['username']} in ^{room_data['Name']}", description=f"Total Count: `{len(events_in_room)}`\n*Max. 15 displayed*" ) room_bulk = "https://rooms.rec.net/rooms/bulk?" acc_bulk = "https://accounts.rec.net/account/bulk?" for event in events_found: room_bulk += f"&id={event['RoomId']}" acc_bulk += f"&id={event['CreatorPlayerId']}" rooms = requests.get(room_bulk).json() accs = requests.get(acc_bulk).json() for event in events_in_room: if len(embed.fields) >= 15: break embed = functions.event_embed_field(embed, event, rooms, accs) functions.embed_footer(ctx, embed) # get default footer from function if not embed.fields: embed = functions.error_msg(ctx, f"No events found made by `@{account['username']}` in `^{room_data['Name']}`!") return await ctx.send(embed=embed) await ctx.send( embed=embed, components=[ Button(style=ButtonStyle.URL, label="User Events", url=f"https://rec.net/user/{account['username']}/events") ] ) @eventsbyin.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in an username and room!\nExample: `.eventsbyin <username> <room>`") await ctx.send(embed=embed) else: raise error # CMD-EVENTSIN @commands.command(aliases=["ei"]) @commands.check(functions.beta_tester) async def eventsin(self, ctx, room): functions.log(ctx.guild.name, ctx.author, ctx.command) room = str(room) events_found = functions.events_in(room) if not events_found: embed = functions.error_msg(ctx, f"No events found that were made by `^{room}`!") return await ctx.send(embed=embed) embed = discord.Embed( colour=discord.Colour.orange(), title=f"Events made in ^{room}", description=f"\nTotal Count: `{len(events_found)}`\n*Max. 15 displayed*" ) room_bulk = "https://rooms.rec.net/rooms/bulk?" acc_bulk = "https://accounts.rec.net/account/bulk?" for event in events_found: room_bulk += f"&id={event['RoomId']}" acc_bulk += f"&id={event['CreatorPlayerId']}" rooms = requests.get(room_bulk).json() accs = requests.get(acc_bulk).json() for event in events_found: if len(embed.fields) >= 15: break embed = functions.event_embed_field(embed, event, rooms, accs) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send( embed=embed, components=[ Button(style=ButtonStyle.URL, label="Room Events", url=f"https://rec.net/room/{room}/events") ] ) @eventsin.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) if isinstance(error, commands.MissingRequiredArgument): embed = functions.error_msg(ctx, "Please include in a room!") await ctx.send(embed=embed) else: raise error # CMD-LATESTEVENTS @commands.command(aliases=["le"]) @commands.check(functions.beta_tester) async def latestevents(self, ctx): functions.log(ctx.guild.name, ctx.author, ctx.command) embed = discord.Embed( colour=discord.Colour.orange(), title=f"Latest events made", description="*Max. 15*" ) events_found = functions.latest_events() if not events_found: embed = functions.error_msg(ctx, f"No events were found!") return await ctx.send(embed=embed) room_bulk = "https://rooms.rec.net/rooms/bulk?" acc_bulk = "https://accounts.rec.net/account/bulk?" for event in events_found: room_bulk += f"&id={event['RoomId']}" acc_bulk += f"&id={event['CreatorPlayerId']}" rooms = requests.get(room_bulk).json() accs = requests.get(acc_bulk).json() for event in events_found: if len(embed.fields) >= 15: break embed = functions.event_embed_field(embed, event, rooms, accs) functions.embed_footer(ctx, embed) # get default footer from function await ctx.send(embed=embed) @latestevents.error async def clear_error(self, ctx, error): await functions.report_error(ctx, error, self.client.get_channel(functions.error_channel)) raise error class ImageMenu(menus.ListPageSource): def __init__(self, data, images): super().__init__(data, per_page=1) self.images = images async def format_page(self, menu, entries): offset = menu.current_page * self.per_page post = self.images[offset] tagged = functions.get_tagged_accounts_string(post) self_cheer_string = "" cheers = requests.get(f"https://api.rec.net/api/images/v1/{post['Id']}/cheers").json() if post['PlayerId'] in cheers: self_cheer_string = "\n*SELF CHEERED!*" room_name = functions.id_to_room_name(post['RoomId']) embed = discord.Embed( colour=discord.Colour.orange(), title=f"🔗 Post #{offset + 1}", description=f"🚪 [`^{room_name}`](https://rec.net/room/{room_name})\n<:CheerGeneral:803244099510861885> `{post['CheerCount']}` 💬 `{post['CommentCount']}`{self_cheer_string}\n📆 `{post['CreatedAt'][:10]}` ⏰ `{post['CreatedAt'][11:16]} UTC`\n{tagged}\n", url=f"https://rec.net/image/{post['Id']}" ) comments = "" if post['CommentCount']: comment_json = requests.get(f"https://api.rec.net/api/images/v1/{post['Id']}/comments").json() bulk = "https://accounts.rec.net/account/bulk?" comment_section = {} comments = "💬 **Comments:**\n\n" for comment in comment_json: # commentor = functions.id_to_username(comment['PlayerId']) bulk += f"&id={comment['PlayerId']}" comment_section[comment['PlayerId']] = comment['Comment'] bulk_account_call = requests.get(bulk).json() old_count = 0 count = 0 for account in bulk_account_call: # comments += f"👤 [`@{account['username']}`](https://rec.net/user/{account['username']})\n💬 `{comment_json[count]['Comment']}` \n\n" comments += f"[`@{account['username']}`](https://rec.net/user/{account['username']})\n`{comment_section[account['accountId']]}`\n\n" count += 1 if len(comments) < 800: embed.add_field(name="⠀", value=comments, inline=True) comments = "" old_count = count if count > old_count: embed.add_field(name="⠀", value=comments, inline=True) poster_username = functions.id_to_username(post['PlayerId']) embed.set_author(name=f"🔗 {poster_username}'s profile", url=f"https://rec.net/user/{poster_username}", icon_url=functions.id_to_pfp(post['PlayerId'], True)) embed.set_image(url=f"http://img.rec.net/{post['ImageName']}?width=720") return embed def setup(client): client.add_cog(Utility(client))
42.368321
386
0.562445
14,672
133,206
4.991276
0.044166
0.024579
0.029004
0.036446
0.795308
0.770688
0.74903
0.704596
0.675251
0.638642
0
0.011181
0.313815
133,206
3,143
387
42.381801
0.789145
0.025825
0
0.656832
0
0.013975
0.198347
0.047096
0
0
0
0
0
1
0.006211
false
0.009317
0.004658
0.004658
0.046972
0.017469
0
0
0
null
0
0
0
0
1
1
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
0673a92d95ea2282616aadf5305567396ddcb0cb
187
py
Python
Project-Directory/app1/models.py
RonBulaon/AlumniChecker
e18ec1e6458fbff6c272e7c7fe11e6d36564f1ae
[ "Apache-2.0" ]
null
null
null
Project-Directory/app1/models.py
RonBulaon/AlumniChecker
e18ec1e6458fbff6c272e7c7fe11e6d36564f1ae
[ "Apache-2.0" ]
null
null
null
Project-Directory/app1/models.py
RonBulaon/AlumniChecker
e18ec1e6458fbff6c272e7c7fe11e6d36564f1ae
[ "Apache-2.0" ]
null
null
null
from django.db import models class SiteWide(models.Model): sitename = models.CharField(max_length=255, default='ChangeMe') def __str__(self): return self.sitename
18.7
67
0.700535
23
187
5.478261
0.826087
0
0
0
0
0
0
0
0
0
0
0.020134
0.203209
187
9
68
20.777778
0.825503
0
0
0
0
0
0.043243
0
0
0
0
0
0
1
0.2
false
0
0.2
0.2
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
4
06b32dc987541cf3d24b54ec981bec5268b4d104
31
py
Python
manage/__init__.py
everyvoter/everyvoter
65d9b8bdf9b5c64057135c279f6e03b6c207e0fa
[ "MIT" ]
5
2019-07-01T17:50:44.000Z
2022-02-20T02:44:42.000Z
manage/__init__.py
everyvoter/everyvoter
65d9b8bdf9b5c64057135c279f6e03b6c207e0fa
[ "MIT" ]
3
2020-06-05T21:44:33.000Z
2021-06-10T21:39:26.000Z
manage/__init__.py
everyvoter/everyvoter
65d9b8bdf9b5c64057135c279f6e03b6c207e0fa
[ "MIT" ]
1
2021-12-09T06:32:40.000Z
2021-12-09T06:32:40.000Z
"""Admin app for EveryVoter"""
15.5
30
0.677419
4
31
5.25
1
0
0
0
0
0
0
0
0
0
0
0
0.129032
31
1
31
31
0.777778
0.774194
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
ebf8736b62ff9788469fa7d06d59eef34d849b6a
248
py
Python
src/resources/entities/colorchanger.py
n0remac/Acute-Alligators-2021-Summer-Code-Jam
addedb95daec0224631c6a62e07718c9c4afd2b6
[ "MIT" ]
null
null
null
src/resources/entities/colorchanger.py
n0remac/Acute-Alligators-2021-Summer-Code-Jam
addedb95daec0224631c6a62e07718c9c4afd2b6
[ "MIT" ]
36
2021-07-11T20:14:29.000Z
2021-07-17T14:04:40.000Z
src/resources/entities/colorchanger.py
n0remac/Acute-Alligators-2021-Summer-Code-Jam
addedb95daec0224631c6a62e07718c9c4afd2b6
[ "MIT" ]
1
2021-07-17T17:08:24.000Z
2021-07-17T17:08:24.000Z
from .abstractdungeonentity import AbstractDungeonEntity class ColorChanger(AbstractDungeonEntity): """Dungeon Items that change players color if captured""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
27.555556
61
0.733871
24
248
7.25
0.791667
0.114943
0
0
0
0
0
0
0
0
0
0
0.157258
248
8
62
31
0.832536
0.205645
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0
0.75
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
4
23193b52f8ac6394560b3a00e5242fc9f127ffd5
177
py
Python
CONFIG.py
BRadTone/tf-conv-net
252d2397401533d7cee5dffa8ee6acf5c1f20372
[ "MIT" ]
null
null
null
CONFIG.py
BRadTone/tf-conv-net
252d2397401533d7cee5dffa8ee6acf5c1f20372
[ "MIT" ]
null
null
null
CONFIG.py
BRadTone/tf-conv-net
252d2397401533d7cee5dffa8ee6acf5c1f20372
[ "MIT" ]
null
null
null
class CONFIG: DATAST_DIR_PATH = './dataset/' DOWNLOADED_FILE_NAME= 'cifar-10-batches.tar.gz' DATASET_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
35.4
75
0.706215
27
177
4.444444
0.814815
0.116667
0
0
0
0
0
0
0
0
0
0.025806
0.124294
177
4
76
44.25
0.748387
0
0
0
0
0.25
0.497175
0.129944
0
0
0
0
0
1
0
false
0
0
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
4
233baeb4e4d42e6947dbd72972041b0b8fa7d793
164
py
Python
test/sort/test_merge.py
dmvieira/algs
bf88d026ecf7210f0a1d601b36d7fc82364bd46f
[ "Apache-2.0" ]
null
null
null
test/sort/test_merge.py
dmvieira/algs
bf88d026ecf7210f0a1d601b36d7fc82364bd46f
[ "Apache-2.0" ]
null
null
null
test/sort/test_merge.py
dmvieira/algs
bf88d026ecf7210f0a1d601b36d7fc82364bd46f
[ "Apache-2.0" ]
null
null
null
import unittest from test.sort import CommonSort from src.sort.merge import MergeSort class TestMergeSort(unittest.TestCase, CommonSort): sort_alg = MergeSort
23.428571
51
0.817073
21
164
6.333333
0.619048
0
0
0
0
0
0
0
0
0
0
0
0.128049
164
7
52
23.428571
0.93007
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.6
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
234bc4ae26e8cc810af1697ab377fce9d2825af9
179
py
Python
make_hash.py
fostroll/modelsrv0
0debc1d64734aafd5d4286397f9db530c7dd8719
[ "CC0-1.0" ]
null
null
null
make_hash.py
fostroll/modelsrv0
0debc1d64734aafd5d4286397f9db530c7dd8719
[ "CC0-1.0" ]
null
null
null
make_hash.py
fostroll/modelsrv0
0debc1d64734aafd5d4286397f9db530c7dd8719
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/python from passlib.context import CryptContext import sys pwd_context = CryptContext(schemes='sha512_crypt', deprecated='auto') print(pwd_context.hash(sys.argv[1]))
22.375
69
0.787709
25
179
5.52
0.76
0.144928
0
0
0
0
0
0
0
0
0
0.024242
0.078212
179
7
70
25.571429
0.812121
0.089385
0
0
0
0
0.098765
0
0
0
0
0
0
1
0
false
0.25
0.5
0
0.5
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
1
1
0
0
0
0
4
88d3eff9343b9e6714223023cfaecdf8ed8afe98
120
py
Python
src/fewie/evaluation/classifiers/__init__.py
DFKI-NLP/fewie
a47d2a02bc51cf951fc294de43bdb7557bc574b4
[ "MIT" ]
null
null
null
src/fewie/evaluation/classifiers/__init__.py
DFKI-NLP/fewie
a47d2a02bc51cf951fc294de43bdb7557bc574b4
[ "MIT" ]
null
null
null
src/fewie/evaluation/classifiers/__init__.py
DFKI-NLP/fewie
a47d2a02bc51cf951fc294de43bdb7557bc574b4
[ "MIT" ]
null
null
null
from .logistic_regression import LogisticRegression CLASSIFIER_NAME_MAP = {"logistic_regression": LogisticRegression}
24
65
0.858333
11
120
9
0.727273
0.363636
0
0
0
0
0
0
0
0
0
0
0.083333
120
4
66
30
0.9
0
0
0
0
0
0.158333
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
88e8392d0e1d4691c7435f0d1e7f9e58efc847f6
2,273
py
Python
tests/test_elm_codeshift.py
PChambino/elm-doc
08cce96e9c36db208a4ba9eb08a9faf9f3acba19
[ "BSD-3-Clause" ]
29
2017-02-01T11:58:44.000Z
2021-05-21T15:18:33.000Z
tests/test_elm_codeshift.py
PChambino/elm-doc
08cce96e9c36db208a4ba9eb08a9faf9f3acba19
[ "BSD-3-Clause" ]
143
2017-07-26T17:34:44.000Z
2022-03-01T18:01:43.000Z
tests/test_elm_codeshift.py
PChambino/elm-doc
08cce96e9c36db208a4ba9eb08a9faf9f3acba19
[ "BSD-3-Clause" ]
7
2018-03-09T10:04:45.000Z
2021-10-19T19:17:40.000Z
from elm_doc import elm_codeshift def test_elm_codeshift_strips_ports_from_single_line_port_module_declaration(): source = 'port module Main exposing (main)' actual = elm_codeshift.strip_ports_from_string(source) expected = 'module Main exposing (main)' assert actual == expected def test_elm_codeshift_strips_ports_from_multiline_port_module_declaration(): source = '''{-| doc comment before module -} port module Main exposing {-| multiline comment -} ( main, -- inline comment init, ) ''' actual = elm_codeshift.strip_ports_from_string(source) expected = '''{-| doc comment before module -} module Main exposing {-| multiline comment -} ( main, -- inline comment init, ) ''' assert actual == expected def test_elm_codeshift_strips_ports_from_single_line_port_function_declaration(): source = 'port cmd : String -> Cmd ()' actual = elm_codeshift.strip_ports_from_string(source) expected = '''cmd : String -> Cmd () cmd a0 = Cmd.none ''' assert actual == expected def test_elm_codeshift_strips_ports_from_multiline_port_function_declaration(): source = ''' -- all arguments on the next line port cmd : String -> Cmd () {-| last argument on the next line -} port cmd : String -> Cmd () -- suddenly, an unrelated function func : () {- first and last argument on the next line -} port sub : Sub () port sub1 : Sub () {-| with interspersed comments -} port cmd : String -- Inline comment -> Foo {- Single line comment -} -> Foo {-| Single line doc comment -} -> Foo {-| Multi line comment -} -> Cmd () ''' actual = elm_codeshift.strip_ports_from_string(source) expected = ''' -- all arguments on the next line cmd : String -> Cmd () cmd a0 = Cmd.none {-| last argument on the next line -} cmd : String -> Cmd () cmd a0 = Cmd.none -- suddenly, an unrelated function func : () {- first and last argument on the next line -} sub : Sub () sub = Sub.none sub1 : Sub () sub1 = Sub.none {-| with interspersed comments -} cmd : String -- Inline comment -> Foo {- Single line comment -} -> Foo {-| Single line doc comment -} -> Foo {-| Multi line comment -} -> Cmd () cmd a0 a1 a2 a3 = Cmd.none ''' assert actual == expected
19.10084
81
0.66476
289
2,273
5.034602
0.186851
0.074227
0.049485
0.053608
0.761512
0.742955
0.718213
0.690722
0.650859
0.50378
0
0.005621
0.217334
2,273
118
82
19.262712
0.812254
0
0
0.74
0
0
0.615486
0
0
0
0
0
0.04
1
0.04
false
0
0.01
0
0.05
0
0
0
0
null
0
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
88e9c7c4071183c4b46c454ff9a36b007223affd
24
py
Python
lib/__init__.py
facelessuser/ThemeTweaker
3f01e6bd3229ef4aeaeed3aafb9ee2628070364b
[ "MIT" ]
18
2015-02-13T21:13:22.000Z
2020-09-28T19:37:48.000Z
lib/__init__.py
facelessuser/ThemeTweaker
3f01e6bd3229ef4aeaeed3aafb9ee2628070364b
[ "MIT" ]
8
2015-07-08T18:45:45.000Z
2021-09-05T22:57:57.000Z
lib/__init__.py
facelessuser/ThemeTweaker
3f01e6bd3229ef4aeaeed3aafb9ee2628070364b
[ "MIT" ]
5
2017-02-10T04:18:32.000Z
2017-11-20T04:54:06.000Z
"""ThemeTweaker lib."""
12
23
0.625
2
24
7.5
1
0
0
0
0
0
0
0
0
0
0
0
0.083333
24
1
24
24
0.681818
0.708333
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
88eaec2505f8aca328dfee9872a07518b623439d
25
py
Python
templates/function.py
Tsitko/drawyourbot
87ce611a6aaba0dbcd02332edecf1dfe79dcae03
[ "MIT" ]
22
2021-04-22T08:00:08.000Z
2021-08-11T00:30:30.000Z
templates/function.py
Tsitko/drawyourbot
87ce611a6aaba0dbcd02332edecf1dfe79dcae03
[ "MIT" ]
null
null
null
templates/function.py
Tsitko/drawyourbot
87ce611a6aaba0dbcd02332edecf1dfe79dcae03
[ "MIT" ]
4
2021-08-10T08:36:12.000Z
2022-03-27T15:21:30.000Z
%block_name%(bot, update)
25
25
0.76
4
25
4.5
1
0
0
0
0
0
0
0
0
0
0
0
0.04
25
1
25
25
0.75
0
0
0
0
0
0
0
0
0
0
0
0
0
null
null
0
0
null
null
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
4
88ef8e40685d9b2058020a689ca9f40439d5d37e
194
py
Python
backend/backend/permissions/__init__.py
ProjetoALES/ales-website
9dc5b460f5e780a1221d0ed5071043f088082395
[ "MIT" ]
null
null
null
backend/backend/permissions/__init__.py
ProjetoALES/ales-website
9dc5b460f5e780a1221d0ed5071043f088082395
[ "MIT" ]
19
2020-02-25T05:29:39.000Z
2021-09-22T18:38:26.000Z
backend/backend/permissions/__init__.py
ProjetoALES/ales-website
9dc5b460f5e780a1221d0ed5071043f088082395
[ "MIT" ]
null
null
null
from .token import HasValidToken from .http import ( IsGetRequest, IsPostRequest, IsPutPatchRequest, IsReadyOnlyRequest, IsDeleteRequest, ) from .ownership import OwnsObject
19.4
33
0.752577
16
194
9.125
0.75
0
0
0
0
0
0
0
0
0
0
0
0.195876
194
9
34
21.555556
0.935897
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.333333
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
88f8c179b37b4eeec9bc125f331709eb2d0236e3
52
py
Python
xbee/helpers/dispatch/__init__.py
harp00/python-xbee
2de03ae5a4de19e3654b15772b2af46866abcb40
[ "MIT" ]
65
2015-12-06T02:38:28.000Z
2017-09-05T16:46:07.000Z
xbee/helpers/dispatch/__init__.py
harp00/python-xbee
2de03ae5a4de19e3654b15772b2af46866abcb40
[ "MIT" ]
44
2015-10-23T15:33:54.000Z
2017-09-01T06:39:50.000Z
xbee/helpers/dispatch/__init__.py
harp00/python-xbee
2de03ae5a4de19e3654b15772b2af46866abcb40
[ "MIT" ]
43
2015-12-15T02:52:21.000Z
2017-06-24T17:14:53.000Z
from xbee.helpers.dispatch.dispatch import Dispatch
26
51
0.865385
7
52
6.428571
0.714286
0
0
0
0
0
0
0
0
0
0
0
0.076923
52
1
52
52
0.9375
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4