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
8186967767101fb35051d8aa2f45b3fbbdd6498c
595
py
Python
upylab/upylab_4.6.py
piousteph/mooc_python
b7446c8a8317e2ae5e87a9ce27fd107f20333765
[ "MIT" ]
null
null
null
upylab/upylab_4.6.py
piousteph/mooc_python
b7446c8a8317e2ae5e87a9ce27fd107f20333765
[ "MIT" ]
null
null
null
upylab/upylab_4.6.py
piousteph/mooc_python
b7446c8a8317e2ae5e87a9ce27fd107f20333765
[ "MIT" ]
null
null
null
import random def alea_dice(s): random.seed(s) d1 = random.randint(1, 6) d2 = random.randint(1, 6) d3 = random.randint(1, 6) res = False if d1 == 4 and d2 == 2 and d3 == 1: res = True elif d1 == 4 and d2 == 1 and d3 == 2: res = True elif d1 == 2 and d2 == 4 and d3 == 1: res = True elif d1 == 2 and d2 == 1 and d3 == 4: res = True elif d1 == 1 and d2 == 4 and d3 == 2: res = True elif d1 == 1 and d2 == 2 and d3 == 4: res = True else: res = False return res print(alea_dice(1))
20.517241
41
0.478992
101
595
2.80198
0.237624
0.106007
0.194346
0.229682
0.522968
0.399293
0.399293
0
0
0
0
0.127424
0.393277
595
28
42
21.25
0.65651
0
0
0.347826
0
0
0
0
0
0
0
0
0
1
0.043478
false
0
0.043478
0
0.130435
0.043478
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
818a54a6f34281622ebba63ffad0f4d0293acee0
3,918
py
Python
ProjectSystem/login/views.py
matthew9602/Project-Management-System
ba74de0bfd4785a46fbe8b332d8bff1e4eb980a9
[ "MIT" ]
1
2021-04-01T17:30:58.000Z
2021-04-01T17:30:58.000Z
ProjectSystem/login/views.py
MatthewTsan/Project-Management-System
ba74de0bfd4785a46fbe8b332d8bff1e4eb980a9
[ "MIT" ]
null
null
null
ProjectSystem/login/views.py
MatthewTsan/Project-Management-System
ba74de0bfd4785a46fbe8b332d8bff1e4eb980a9
[ "MIT" ]
null
null
null
from django.shortcuts import render from django.http.response import HttpResponse, HttpResponseRedirect import MySQLdb from login import forms # Create your views here. def index(request): if 'username' in request.POST or 'userpassword' in request.POST or 'username' in request.GET and 'userpassword' in request.GET: print 'do check' return check(request) username = request.COOKIES.get('username','') if username: print 'username:' + username position = checkPostion(username) return render(request,"login/login.html",{"username":username,"position":position}) else: return render(request,"login/login.html") def check(request): if request.method == "POST": print 'getPost' if 'username' in request.POST and 'userpassword' in request.POST: username = request.POST['username'] userpassword = request.POST['userpassword'] # form = forms.LoginForm(request) # username = form.username # userpassword = form.userpassword # print 'get name:' + username # print 'get passwd:' + userpassword if request.method == "GET": print 'Method GET' if 'username' in request.GET and 'userpassword' in request.GET: username = request.GET['username'] userpassword = request.GET['userpassword'] if not username or not userpassword: print 'username:' + username print 'userpasswd:' + userpassword print "please input username or password" return render(request,'login/login.html',{'string':'please input username or password'}) print 'username:' + username print 'userpasswd:' + userpassword conn = MySQLdb.Connect(host = 'localhost', user = 'root', passwd = '07n0604', port = 3306, db = 'projectsystem') cursor = conn.cursor() sql = "SELECT * FROM user" cursor.execute(sql) print sql rs = cursor.fetchall() print rs user_success = False for raw in rs: print raw if raw[1] == username: if raw[2] == userpassword: user_success = True if raw[3] == '0': #return render(request, "admin_bookinfo\\book_info.html") response = HttpResponseRedirect('/teacher/project/list/') response.set_cookie('username', username, 3600) return response if raw[3] == '1': response = HttpResponseRedirect('/student/project/list/') response.set_cookie('username', username, 3600) return response print user_success if not user_success: return render(request, "login/login.html", {'string':"name or password error"}) def logout(request): response = HttpResponseRedirect('/login/') response.delete_cookie('username') return response def about(request): username = request.COOKIES.get('username','') if username: print 'username:' + username position = checkPostion(username) return render(request,"login/about.html",{"username":username,"position":position}) else: return render(request,"login/about.html") def checkPostion(username): sql = "select Position from user where Name = '" + username + "'" conn = MySQLdb.connect(host = 'localhost', user = 'root', passwd = '07n0604', port = 3306, db = 'projectsystem') cursor = conn.cursor() cursor.execute('SET NAMES UTF8') cursor.execute(sql) rs = cursor.fetchall() print 'sql = ' + sql print rs cursor.close() conn.close() return rs[0][0]
35.297297
131
0.580909
393
3,918
5.768448
0.236641
0.03176
0.058668
0.06352
0.497574
0.430525
0.375827
0.34142
0.34142
0.299956
0
0.013694
0.310362
3,918
110
132
35.618182
0.825315
0.068402
0
0.393258
0
0
0.185612
0.012081
0
0
0
0
0
0
null
null
0.157303
0.044944
null
null
0.179775
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
818c049f1649768bb25c79a6e8fbbdd73f556c0f
19,643
py
Python
tests/unit/test_access_check.py
anshubansal2000/cloudmapper
86340a345b33b1dd3d3d67cd9914cbc039b4647f
[ "BSD-3-Clause" ]
5,021
2018-02-20T14:27:33.000Z
2022-03-31T23:40:48.000Z
tests/unit/test_access_check.py
sajathajk/cloudmapper
dd5aa06138bfbaca80f41f880c1709efa10c03c5
[ "BSD-3-Clause" ]
724
2018-02-20T15:51:01.000Z
2022-03-24T20:40:23.000Z
tests/unit/test_access_check.py
sajathajk/cloudmapper
dd5aa06138bfbaca80f41f880c1709efa10c03c5
[ "BSD-3-Clause" ]
792
2018-02-20T16:21:43.000Z
2022-03-30T13:14:17.000Z
import argparse import unittest import json from nose.tools import assert_equal, assert_true, assert_false from shared.common import parse_arguments from commands.access_check import ( replace_principal_variables, Principal, get_privilege_statements, get_allowed_privileges, access_check_command, ) class TestAccessCheck(unittest.TestCase): def test_replace_principal_variables(self): principal = Principal( "AssumedRole", [{"Key": "project", "Value": "prod"}, {"Key": "color", "Value": "blue"}], username="role", userid="", ) assert_equal(replace_principal_variables("*", principal), "*") # Ensure replacement works assert_equal( replace_principal_variables( "arn:aws:sns:*:*:${aws:PrincipalTag/project}", principal ), "arn:aws:sns:*:*:prod", ) # Ensure case insensitive replacement works assert_equal( replace_principal_variables( "arn:aws:sns:*:*:${aws:principaltag/project}", principal ), "arn:aws:sns:*:*:prod", ) # Ensure we don't replace unknown variables assert_equal( replace_principal_variables( "arn:aws:sns:*:*:${aws:principaltag/app}", principal ), "arn:aws:sns:*:*:${aws:principaltag/app}", ) # Ensure multiple replacements works assert_equal( replace_principal_variables( "arn:aws:sns:*:*:${aws:PrincipalTag/project}-${aws:PrincipalTag/color}", principal, ), "arn:aws:sns:*:*:prod-blue", ) def test_get_privilege_statements(self): principal = Principal( "AssumedRole", [{"Key": "project", "Value": "prod"}, {"Key": "color", "Value": "blue"}], username="role", userid="", ) policy_doc = """ { "Statement": [ { "Action": "s3:GetObject", "Effect": "Allow", "Resource": "*" }, { "Sid": "AllowSNSAccessBasedOnArnMatching", "Effect": "Allow", "Action": [ "sns:Publish" ], "Resource": [ "arn:aws:sns:*:*:${aws:PrincipalTag/project}-*" ] } ], "Version": "2012-10-17" }""" policy_doc = json.loads(policy_doc) # Ensure this works at all privilege_matches = [ { "privilege_prefix": "s3", "privilege_name": "GetObject", "resource_type": "object", } ] assert_true( len( get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test", ) ) > 0 ) # Ensure it doesn't return anything when we check for a privilege we don't have (s3:PutObject) privilege_matches = [ { "privilege_prefix": "s3", "privilege_name": "PutObject", "resource_type": "object", } ] assert_true( len( get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test", ) ) == 0 ) # Check the SNS privilege privilege_matches = [ { "privilege_prefix": "sns", "privilege_name": "Publish", "resource_type": "topic", } ] assert_true( len( get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test", ) ) > 0 ) # Check it against a specific resource assert_true( len( get_privilege_statements( policy_doc, privilege_matches, "arn:aws:sns:*:*:prod-*", principal, policy_identifier="unit_test", ) ) > 0 ) # Ensure we get zero when we use a different resource assert_true( len( get_privilege_statements( policy_doc, privilege_matches, "arn:aws:sns:*:*:dev-*", principal, policy_identifier="unit_test", ) ) == 0 ) def test_get_allowed_privileges(self): principal = Principal( "AssumedRole", [{"Key": "project", "Value": "prod"}, {"Key": "color", "Value": "blue"}], username="role", userid="", ) policy_doc = """ { "Statement": [ { "Action": "s3:GetObject", "Effect": "Allow", "Resource": "*" }, { "Sid": "AllowSNSAccessBasedOnArnMatching", "Effect": "Allow", "Action": [ "sns:Publish" ], "Resource": [ "arn:aws:sns:*:*:${aws:PrincipalTag/project}-*" ] } ], "Version": "2012-10-17" }""" policy_doc = json.loads(policy_doc) privilege_matches = [ { "privilege_prefix": "s3", "privilege_name": "GetObject", "resource_type": "object", } ] stmts = get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test" ) # Ensure we have allowed statements when there is no boundary assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) > 0) # Ensure we have allowed statements when the boundary matches what was allowed assert_true(len(get_allowed_privileges(privilege_matches, stmts, stmts)) > 0) policy_doc = """ { "Statement": [ { "Action": "*", "Effect": "Deny", "Resource": "*" } ], "Version": "2012-10-17" }""" policy_doc = json.loads(policy_doc) boundary = get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test" ) # Ensure nothing is allowed when the boundary denies all assert_true( len(get_allowed_privileges(privilege_matches, stmts, boundary)) == 0 ) def test_conditions_on_principal_tags(self): # Example from https://aws.amazon.com/blogs/security/working-backward-from-iam-policies-and-principal-tags-to-standardized-names-and-tags-for-your-aws-resources/ principal = Principal( "AssumedRole", [ {"Key": "project", "Value": "web"}, {"Key": "access-team", "Value": "eng"}, {"Key": "cost-center", "Value": "987654"}, ], username="role", userid="", ) policy_doc = """ { "Statement": [ { "Effect": "Allow", "Action": "s3:ListAllMyBuckets", "Resource": "*", "Condition": { "StringEquals": { "aws:PrincipalTag/project": "web" } } } ], "Version": "2012-10-17" }""" policy_doc = json.loads(policy_doc) # Ensure this works at all privilege_matches = [ { "privilege_prefix": "s3", "privilege_name": "ListAllMyBuckets", "resource_type": "object", } ] stmts = get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test" ) assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) > 0) principal = Principal( "AssumedRole", [ {"Key": "project", "Value": "database"}, {"Key": "access-team", "Value": "eng"}, {"Key": "cost-center", "Value": "987654"}, ], username="role", userid="", ) stmts = get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test" ) assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) == 0) # def test_conditions_on_resource_tags_ec2(self): # # TODO # # Example from https://aws.amazon.com/blogs/security/working-backward-from-iam-policies-and-principal-tags-to-standardized-names-and-tags-for-your-aws-resources/ # principal = Principal( # "AssumedRole", # [{"Key": "access-project", "Value": "peg"}, {"Key": "access-team", "Value": "eng"}, {"Key": "cost-center", "Value": "987654"}], # username="role", # userid="", # ) # policy_doc = """{ # "Action":[ # "ec2:StartInstances", # "ec2:StopInstances" # ], # "Resource":[ # "arn:aws:ec2:*:*:instance/*" # ], # "Effect":"Allow", # "Condition":{ # "StringEquals":{ # "ec2:ResourceTag/access-project":"web" # } # } # }""" # policy_doc = json.loads(policy_doc) # # Ensure this works at all # privilege_matches = [ # { # "privilege_prefix": "ec2", # "privilege_name": "StopInstances", # "resource_type": "instance", # } # ] # stmts = get_privilege_statements(policy_doc, privilege_matches, "*", principal) # # TODO Need to get resource info # print("get_privilege_statements: {}".format(stmts)) # assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) > 0) # def test_conditions_on_resource_and_principal_tags_ec2(self): # # TODO # # Example from https://aws.amazon.com/blogs/security/working-backward-from-iam-policies-and-principal-tags-to-standardized-names-and-tags-for-your-aws-resources/ # principal = Principal( # "AssumedRole", # [{"Key": "access-project", "Value": "peg"}, {"Key": "access-team", "Value": "eng"}, {"Key": "cost-center", "Value": "987654"}], # username="role", # userid="", # ) # policy_doc = """{ # "Action":[ # "ec2:StartInstances", # "ec2:StopInstances" # ], # "Resource":[ # "arn:aws:ec2:*:*:instance/*" # ], # "Effect":"Allow", # "Condition":{ # "StringEquals":{ # "ec2:ResourceTag/access-project":"${aws:PrincipalTag/access-project}" # } # } # }""" # policy_doc = json.loads(policy_doc) # # Ensure this works at all # privilege_matches = [ # { # "privilege_prefix": "ec2", # "privilege_name": "StopInstances", # "resource_type": "instance", # } # ] # stmts = get_privilege_statements(policy_doc, privilege_matches, "*", principal) # # TODO Need to get resource info # print("get_privilege_statements: {}".format(stmts)) # assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) > 0) # def test_conditions_on_resource_and_principal_tags_rds(self): # # TODO # # Example from https://aws.amazon.com/blogs/security/working-backward-from-iam-policies-and-principal-tags-to-standardized-names-and-tags-for-your-aws-resources/ # principal = Principal( # "AssumedRole", # [{"Key": "access-project", "Value": "peg"}, {"Key": "access-team", "Value": "eng"}, {"Key": "cost-center", "Value": "987654"}], # username="role", # userid="", # ) # policy_doc = """{ # "Version": "2012-10-17", # "Statement": [ # { # "Effect": "Allow", # "Action": "rds:DescribeDBInstances", # "Resource": "*" # }, # { # "Effect": "Allow", # "Action": [ # "rds:RebootDBInstance", # "rds:StartDBInstance", # "rds:StopDBInstance" # ], # "Resource": "*", # "Condition": { # "StringEquals": { # "aws:PrincipalTag/CostCenter": "0735", # "rds:db-tag/Project": "DataAnalytics" # } # } # } # ] # }""" # policy_doc = json.loads(policy_doc) # # Ensure this works at all # privilege_matches = [ # { # "privilege_prefix": "ec2", # "privilege_name": "StopInstances", # "resource_type": "instance", # } # ] # stmts = get_privilege_statements(policy_doc, privilege_matches, "*", principal) # # TODO Need to get resource info # print("get_privilege_statements: {}".format(stmts)) # assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) > 0) def test_conditions_on_resource_and_principal_tags_complex_secrets(self): principal = Principal( "AssumedRole", [ {"Key": "access-project", "Value": "peg"}, {"Key": "access-team", "Value": "eng"}, {"Key": "cost-center", "Value": "987654"}, ], username="role", userid="", ) policy_doc = """ { "Version": "2012-10-17", "Statement": [ { "Sid": "AllActionsSecretsManagerSameProjectSameTeam", "Effect": "Allow", "Action": "secretsmanager:*", "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/access-project": "${aws:PrincipalTag/access-project}", "aws:ResourceTag/access-team": "${aws:PrincipalTag/access-team}", "aws:ResourceTag/cost-center": "${aws:PrincipalTag/cost-center}" }, "ForAllValues:StringEquals": { "aws:TagKeys": [ "access-project", "access-team", "cost-center", "Name", "OwnedBy" ] }, "StringEqualsIfExists": { "aws:RequestTag/access-project": "${aws:PrincipalTag/access-project}", "aws:RequestTag/access-team": "${aws:PrincipalTag/access-team}", "aws:RequestTag/cost-center": "${aws:PrincipalTag/cost-center}" } } }, { "Sid": "AllResourcesSecretsManagerNoTags", "Effect": "Allow", "Action": [ "secretsmanager:GetRandomPassword", "secretsmanager:ListSecrets" ], "Resource": "*" }, { "Sid": "ReadSecretsManagerSameTeam", "Effect": "Allow", "Action": [ "secretsmanager:Describe*", "secretsmanager:Get*", "secretsmanager:List*" ], "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/access-team": "${aws:PrincipalTag/access-team}" } } }, { "Sid": "DenyUntagSecretsManagerReservedTags", "Effect": "Deny", "Action": "secretsmanager:UntagResource", "Resource": "*", "Condition": { "StringLike": { "aws:TagKeys": "access-*" } } }, { "Sid": "DenyPermissionsManagement", "Effect": "Deny", "Action": "secretsmanager:*Policy", "Resource": "*" } ] }""" policy_doc = json.loads(policy_doc) # Ensure this works at all privilege_matches = [ { "privilege_prefix": "secretsmanager", "privilege_name": "ListSecrets", "resource_type": "secret", } ] stmts = get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test" ) assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) > 0) # Ensure the Deny in the policy works privilege_matches = [ { "privilege_prefix": "secretsmanager", "privilege_name": "PutResourcePolicy", "resource_type": "secret", } ] stmts = get_privilege_statements( policy_doc, privilege_matches, "*", principal, policy_identifier="unit_test" ) assert_true(len(get_allowed_privileges(privilege_matches, stmts, None)) == 0) # TODO Testing these conditions requires getting resource tags # for stmt in stmts: # for m in stmt["matching_statements"]: # print(m) # exit(-1) # assert_true( # len(get_privilege_statements(policy_doc, privilege_matches, "*", principal)) # > 0 # ) def test_access_check(self): # This test calls the access_check command across the demo data, # thereby excersising much of its code # TODO This parsing code should not be here parser = argparse.ArgumentParser() parser.add_argument( "--resource_arn", help="The resource to be looked at, such as arn:aws:s3:::mybucket", required=True, ) parser.add_argument( "--privilege", help="The privilege in question (ex. s3:GetObject)" ) args, accounts, config = parse_arguments( [ "--accounts", "demo", "--config", "config.json.demo", "--resource_arn", "arn:aws:sns:*:*:prod-*", ], parser, ) access_check_command(accounts, config, args) # TODO Have that function return results that can be tested
33.29322
171
0.465764
1,501
19,643
5.910726
0.154564
0.039563
0.049594
0.028855
0.72757
0.708408
0.673016
0.634468
0.623422
0.611249
0
0.01095
0.404928
19,643
589
172
33.349745
0.748054
0.289212
0
0.532828
0
0
0.410247
0.103486
0
0
0
0.001698
0.045455
1
0.015152
false
0.002525
0.015152
0
0.032828
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
81abfb7e9b0aef6328aa3098436c36ead87af117
1,320
py
Python
test_jd_airmass.py
jacob975/TATIRP
2d81fa280e039aa931c6f8456632a23ef123282a
[ "MIT" ]
null
null
null
test_jd_airmass.py
jacob975/TATIRP
2d81fa280e039aa931c6f8456632a23ef123282a
[ "MIT" ]
4
2017-08-22T03:15:22.000Z
2017-12-19T17:55:31.000Z
test_jd_airmass.py
jacob975/TATIRP
2d81fa280e039aa931c6f8456632a23ef123282a
[ "MIT" ]
null
null
null
#!/usr/bin/python ''' Program: This is a program for converting Julian date(JD) to Heliocentric Julian date(HJD), Barycentric Julian date(BJD), and air mass. Then add these infos into the header of images. Usage: test_jd_airmass.py [image name] Editor: Jacob975 20180709 ################################# update log 20180709 version alpha 1 1. The code works ''' import os from astropy.io import fits as pyfits import numpy as np import time from sys import argv from reduction_lib import header_editor #-------------------------------------------- # main code if __name__ == "__main__": # Measure time start_time = time.time() #---------------------------------------- # Load argv if len(argv) != 2: print "Error!Wrong numbers of arguments" print "Usage: test_jd.py [image name]" exit() name_image = argv[1] #--------------------------------------- # Load header header = pyfits.getheader(argv[1]) # Test class-style functions stu = header_editor(header) print "hjd = {0}, bjd = {1}, air mass = {2}".format(stu.hjd(), stu.bjd(), stu.air_mass()) #--------------------------------------- # Measure time elapsed_time = time.time() - start_time print "Exiting Main Program, spending ", elapsed_time, "seconds."
29.333333
131
0.564394
161
1,320
4.503106
0.521739
0.044138
0.030345
0
0
0
0
0
0
0
0
0.025544
0.199242
1,320
44
132
30
0.66036
0.199242
0
0
0
0
0.213235
0
0
0
0
0
0
0
null
null
0
0.333333
null
null
0.222222
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
2
81be42f8fbae066abea4f58b315bc711b1d61dbd
109
py
Python
pycaro/__init__.py
anteverse/pycaro
dbf6dfb152246cc3a1756145c9b060213a638382
[ "MIT" ]
null
null
null
pycaro/__init__.py
anteverse/pycaro
dbf6dfb152246cc3a1756145c9b060213a638382
[ "MIT" ]
null
null
null
pycaro/__init__.py
anteverse/pycaro
dbf6dfb152246cc3a1756145c9b060213a638382
[ "MIT" ]
null
null
null
from pycaro.api.validate import ModuleChecker __all__ = [ "ModuleChecker" ] __version__ = "0.0.1.dev1"
13.625
45
0.715596
13
109
5.384615
0.846154
0
0
0
0
0
0
0
0
0
0
0.043956
0.165138
109
7
46
15.571429
0.725275
0
0
0
0
0
0.211009
0
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
81c5e019eda3f875954e946507564673d89ef584
253
py
Python
scratchpad/tornado/tornado_io.py
cnb0/katcp-python
35c860bc17ee6404cc59a14f7d1b8ac1fae4b73c
[ "BSD-3-Clause" ]
8
2015-02-25T20:13:54.000Z
2019-09-12T06:12:07.000Z
scratchpad/tornado/tornado_io.py
cnb0/katcp-python
35c860bc17ee6404cc59a14f7d1b8ac1fae4b73c
[ "BSD-3-Clause" ]
67
2015-01-12T09:58:36.000Z
2021-05-12T14:23:26.000Z
scratchpad/tornado/tornado_io.py
cnb0/katcp-python
35c860bc17ee6404cc59a14f7d1b8ac1fae4b73c
[ "BSD-3-Clause" ]
15
2015-04-28T13:18:28.000Z
2021-01-19T16:16:33.000Z
# Copyright 2014 National Research Foundation (South African Radio Astronomy Observatory) # BSD license - see LICENSE for details from __future__ import absolute_import, division, print_function import logging import mock from katcp.server import *
23
89
0.818182
32
253
6.28125
0.8125
0
0
0
0
0
0
0
0
0
0
0.018519
0.146245
253
10
90
25.3
0.912037
0.494071
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0.25
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
2
81cf1c5502f4d3c2e04f1cf2db9eab299671e610
1,706
py
Python
allauth/socialaccount/providers/wzlapp/test.py
manesourabh/django-allauth
230acc0fcd262fb182ac35227d8ee661277f6ceb
[ "MIT" ]
null
null
null
allauth/socialaccount/providers/wzlapp/test.py
manesourabh/django-allauth
230acc0fcd262fb182ac35227d8ee661277f6ceb
[ "MIT" ]
null
null
null
allauth/socialaccount/providers/wzlapp/test.py
manesourabh/django-allauth
230acc0fcd262fb182ac35227d8ee661277f6ceb
[ "MIT" ]
null
null
null
from allauth.socialaccount.tests import OAuth2TestsMixin from allauth.tests import MockedResponse, TestCase from .provider import WzlappProvider class SlackOAuth2Tests(OAuth2TestsMixin, TestCase): provider_id = WzlappProvider.id def get_mocked_response(self): return MockedResponse(200, """{ "ok": true, "user": { "name": "Sonny Whether", "id": "U0G9QF9C6", "email": "sonny@captain-fabian.com", "image_24": "https://secure.gravatar.com/avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg?s=24&d=https%3A%2F%2Fdev.slack.com%2Fimg%2Favatars%2Fava_0010-24.v1441146555.png", "image_32": "https://secure.gravatar.com/avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg?s=32&d=https%3A%2F%2Fdev.slack.com%2Fimg%2Favatars%2Fava_0010-32.v1441146555.png", "image_48": "https://secure.gravatar.com/avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg?s=48&d=https%3A%2F%2Fdev.slack.com%2Fimg%2Favatars%2Fava_0010-48.v1441146555.png", "image_72": "https://secure.gravatar.com/avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg?s=72&d=https%3A%2F%2Fdev.slack.com%2Fimg%2Favatars%2Fava_0010-72.v1441146555.png", "image_192": "https://secure.gravatar.com/avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg?s=192&d=https%3A%2F%2Fdev.slack.com%2Fimg%2Favatars%2Fava_0010-192.v1443724322.png", "image_512": "https://secure.gravatar.com/avatar/e3b51ca72dee4ef87916ae2b9240df50.jpg?s=512&d=https%3A%2F%2Fdev.slack.com%2Fimg%2Favatars%2Fava_0010-512.v1443724322.png" }, "team": { "id": "T0G9PQBBK", "name": "Captain Fabian's Naval Supply" } }""") # noqa
58.827586
182
0.69578
205
1,706
5.717073
0.302439
0.056314
0.09727
0.112628
0.56314
0.56314
0.56314
0.56314
0.235495
0.235495
0
0.196653
0.159437
1,706
28
183
60.928571
0.620642
0.002345
0
0
0
0.25
0.813529
0.015882
0
0
0
0
0
1
0.041667
false
0
0.125
0.041667
0.291667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
81dc4b43c453b3571df0c52404eed5ac9ba41a62
13,783
py
Python
intrinsic/cluster.py
seenu-andi-rajendran/plagcomps
98e82cfb871f73bbd8f4ab1452c2b27a95beee83
[ "MIT" ]
2
2015-01-18T06:20:27.000Z
2021-03-19T21:19:16.000Z
intrinsic/cluster.py
NoahCarnahan/plagcomps
98e82cfb871f73bbd8f4ab1452c2b27a95beee83
[ "MIT" ]
null
null
null
intrinsic/cluster.py
NoahCarnahan/plagcomps
98e82cfb871f73bbd8f4ab1452c2b27a95beee83
[ "MIT" ]
2
2015-11-19T12:52:14.000Z
2016-11-11T17:00:50.000Z
import hmm from kmedians import KMedians import outlier_detection import classify #from plagcomps.intrinsic import outlier_detection from numpy import array, matrix, random from scipy.cluster.vq import kmeans2, whiten from scipy.spatial.distance import pdist from scipy.cluster.hierarchy import linkage, fcluster from collections import Counter def cluster(method, k, items, **kwargs): if method == "kmeans": return _kmeans(items, k) elif method == "agglom": return _agglom(items, k) elif method == "hmm": return _hmm(items, k) elif method == "median_simple": return _median_simple(items) elif method == "median_kmeans": return _median_kmeans(items, k) elif method == "outlier": return outlier_detection.density_based(items, **kwargs) elif method == "kmedians": return _kmedians(items, k) elif method == "nn_confidences": return _nn_confidences(items) elif method == "combine_confidences": return _combine_confidences(items, **kwargs) else: raise ValueError("Invalid cluster method. Acceptable values are 'kmeans', 'agglom', or 'hmm'.") def _kmedians(stylo_vectors, k): features = array(stylo_vectors) clusterer = KMedians(k) clusterer.fit(features) return clusterer.get_confidences() def _kmeans(stylo_vectors, k): ''' Given a list of stylo_vectors, where each element is itself a list ('vector'), return our confidence that each vector is in the plagiarism cluster where the i_th element in the returned list represents the confidence assigned to the i_th input vector Uses k-means clustering to do so TODO allow for more parameters to be passed to the <kmeans2> function ''' feature_mat = array(stylo_vectors) # Normalizes by column normalized_features = whiten(feature_mat) # Initialize <k> clusters to be points in input vectors centroids, assigned_clusters = kmeans2(normalized_features, k, minit = 'points') # Get confidences # Special case when there is only one atom if len(stylo_vectors) == 1: return [0] # We are 0% confident that the atom is plagiarized. if k == 2: confidences = [] plag_cluster = Counter(assigned_clusters).most_common()[-1][0] #plag_cluster is the smallest cluster not_plag_cluster = 1 if plag_cluster == 0 else 0 for feat_vec in normalized_features: if plag_cluster < len(centroids) and plag_cluster >= 0: distance_from_plag = float(pdist(matrix([centroids[plag_cluster], feat_vec]))) distance_from_notplag = float(pdist(matrix([centroids[not_plag_cluster], feat_vec]))) if distance_from_notplag + distance_from_plag > 0: conf = distance_from_notplag / (distance_from_notplag + distance_from_plag) else: conf = 0 confidences.append(conf) else: confidences.append(0) else: # TODO: Develop a notion of confidence when k != 2 non_plag_cluster = Counter(assigned_clusters).most_common()[0][0] max_dist = 0 max_dist_vec = normalized_features[0] for i in xrange(len(assigned_clusters)): if assigned_clusters[i] == non_plag_cluster: dist = float(pdist(matrix([centroids[non_plag_cluster], normalized_features[i]]))) if dist > max_dist: max_dist_vec = normalized_features[i] max_dist = dist avg_centroid_dist = 0 sum_dist = 0 centroid_distance = {} for center in centroids: sum_dist += float(pdist(matrix([center, centroids[non_plag_cluster]]))) avg_centroid_dist = float(sum_dist/len(centroids)) confidences = [] for i in xrange(len(assigned_clusters)): try: if assigned_clusters[i] != non_plag_cluster: distance_from_max = float(pdist(matrix([max_dist_vec, normalized_features[i]]))) centroid_distance = float(pdist(matrix([centroids[assigned_clusters[i]], centroids[non_plag_cluster]]))) conf = (1-(float(1/(max_dist/distance_from_max))))*float(centroid_distance/avg_centroid_dist) confidences.append(conf) else: confidences.append(0) except: confidences.append(0) return confidences def _median_kmeans(stylo_vectors, k): ''' Run kmeans. Find the median in the largest cluster. Calculate confidences of all data points as the (normalized) distance from the median. ''' if not (len(stylo_vectors) and len(stylo_vectors[0]) == 1): raise ValueError("Cluster method '_median_kmeans' can only handle 1-dimensional stylometric vectors.") return feature_mat = array(stylo_vectors) normalized_features = whiten(feature_mat) centroids, assigned_clusters = kmeans2(normalized_features, k, minit = 'points') # find largest cluster, and call it the "non-plagiarized" cluster non_plag_cluster = Counter(assigned_clusters).most_common()[0][0] # non-plag is largest cluster non_plag_vectors = [x for i, x in enumerate(stylo_vectors, 0) if assigned_clusters[i] == non_plag_cluster] # get median of non-plagiarized cluster non_plag_vectors_copy = non_plag_vectors[:] non_plag_vectors_copy.sort() median = _get_list_median(non_plag_vectors_copy) # find max dist from median and build confidences max_dist = float(max([abs(vec[0] - median) for vec in stylo_vectors])) if max_dist > 0: confidences = [abs(vec[0] - median) / max_dist for vec in stylo_vectors] else: confidences = [0 for vec in stylo_vectors] return confidences def _median_simple(stylo_vectors): ''' Given a list of 1-dimensional stylo_vectors, generated confidences in the following way: 1. Find median of stylo_vectors 2. Find max distance from median 3. Construct confidences for points by taking their percentage of the max distance from median ''' length = len(stylo_vectors) if length > 0 and len(stylo_vectors[0]) == 1: stylo_vectors_copy = stylo_vectors[:] stylo_vectors_copy.sort() median = _get_list_median(stylo_vectors_copy) max_dist = float(max(median - stylo_vectors_copy[0][0], stylo_vectors_copy[-1][0] - median)) if max_dist > 0: confidences = [abs(x[0] - median) / max_dist for x in stylo_vectors] else: confidences = [0 for x in stylo_vectors] return confidences else: raise ValueError("Cluster method 'median_simple' can only handle 1-dimensional stylometric vectors.") def _get_list_median(vectors): ''' Helper function that returns the median of the given SORTED vector list. ''' length = len(vectors) if length % 2 == 0: return (vectors[length / 2][0] + vectors[(length / 2) - 1][0]) / 2.0 else: return float(vectors[length / 2][0]) def _nn_confidences(items): from classify import NeuralNetworkConfidencesClassifier classifier = NeuralNetworkConfidencesClassifier() return classifier.nn_confidences(items) def _combine_confidences(feature_vectors, feature_confidence_weights=None): weights_sum = float(sum(feature_confidence_weights)) # "normalize" (I don't know if that's the right word) the weights, and make sure none are equal to 0 feature_confidence_weights = [max(0.00001, x/weights_sum) for x in feature_confidence_weights] confidence_vectors = [] for fi in xrange(len(feature_vectors[0])): single_feature_vecs = [[x[fi]] for x in feature_vectors] confs = _kmeans(single_feature_vecs, 2) for i, confidence in enumerate(confs, 0): if len(confidence_vectors) <= i: confidence_vectors.append([]) confidence_vectors[i].append(confidence * feature_confidence_weights[fi]) confidences = [] for vec in confidence_vectors: confidences.append(min(sum(vec), 1)) return confidences def _agglom(stylo_vectors, k): ''' Given a list of stylo_vectors, where each element is itself a list ('vector'), return our confidence that each vector is in the plagiarism cluster where the i_th element in the returned list represents the confidence assigned to the i_th input vector Performs agglomerative clustering on <stylo_vectors> and returns the level in the dendogram with at most <k> clusters TODO allow for more parameters to be passed to the <kmeans2> function ''' feature_mat = array(stylo_vectors) pairwise_dists = pdist(feature_mat) # Linkage matrix has somewhat complicated structure, but stores # all levels of the agglomerative clustering process, and can # be passed into other functions to extract info about the clusters. See: # http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html linkage_mat = linkage(pairwise_dists) assigned_clusters = fcluster(linkage_mat, k, criterion = 'maxclust') # Get confidences # TODO: Develop a real notion of confidence for agglom clustering plag_cluster = Counter(assigned_clusters).most_common()[-1][0] return [1 if x == plag_cluster else 0 for x in assigned_clusters] def _hmm(stylo_vectors, k): ''' Given a list of stylo_vectors, where each element of the list is a feature vector, use a hidden Markov model to assign one of k preposed state values to the vectors, Observed outputs assigned similar state values are of the same cluster. To Do: Return a list of confidence values for the vector assignments where the i_th element in the returned list represents the confidence assigned to the i_th input vector. ''' #get centroids and cluster assignments centroids, assigned_clusters = hmm.hmm_cluster(stylo_vectors, k) # Get confidences plag_cluster = Counter(assigned_clusters).most_common()[-1][0] #plag_cluster is smallest cluster #not_plag_cluster = Counter(assigned_clusters).most_common()[0][0] #not_plag_clust is largest cluster cluster_assign = [1 if x == plag_cluster else 0 for x in assigned_clusters] #confidences = hmm.get_confidences1(stylo_vectors, centroids, cluster_assign) confidences = hmm.get_confidences3(stylo_vectors, centroids, cluster_assign) #return cluster_assign , confidences return confidences def two_normal_test(n, spacing): first = [[random.normal()] for x in range(n)] second = [[random.normal(spacing)] for x in range(n)] for c in ["kmeans", "agglom", "hmm"]: print c, cluster(c, 2, first + second) def _test(): fs = [ [4.5, 5.2, 1.9], [1.1, 2.03, 2.45], [4.5, 5.2, 8.1] ] cluster_one = [ [1.0, 1.0], [1.25, 1.25], [1.5, 1.5], [1.75, 1.75], [2.0, 2.0] ] cluster_two = [ [10.0, 10.0], [10.25, 10.25], [10.5, 10.5], [10.75, 10.75], [11.0, 11.0] ] fs_obvious = cluster_one + cluster_two for method in ["kmeans", "agglom", "hmm", "kmedians"]: print method, cluster(method, 2, fs_obvious) # print cluster("kmeans", 2, fs_obvious) # print cluster("agglom", 2, fs_obvious) # print cluster("hmm", 2, fs_obvious) # print "hi", cluster("kmedians", 2, fs_obvious) print cluster("kmeans", 2, fs) print cluster("agglom", 2, fs) print cluster("hmm", 2, fs) print cluster("kmedians", 2, fs) def _all_clusters_all_features(): import plagcomps.evaluation.intrinsic as ev clusterings = [ (ev.cluster, "simple_median", ("median_simple", None)), (ev.cluster, "kmeans_median", ("median_kmeans", 2)), (ev.cluster, "kmedians", ("kmedians", 2)), (ev.cluster, "kmeans", ("kmeans", 2)), (ev.cluster, "agglom", ("agglom", 2)), (ev.cluster, "hmm", ("hmm", 2)), #(ev.cluster, "outlier", ("outlier", 2)) was crashing (ev.cluster, "kmeans", ("kmeans", 3)), (ev.cluster, "kmeans", ("kmeans", 4)), (ev.cluster, "kmeans", ("kmeans", 5)) ] unique_features = [] for char_feature in [ "punctuation_percentage", ]: for char_modifier in [ "", "avg(", "std(", "avg(avg(", "avg(std(", "avg(avg(avg(", "avg(avg(std(" ]: unique_features.append(char_modifier + char_feature + ")" * char_modifier.count("(")) for word_feature in [ "num_chars", "average_syllables_per_word", "stopword_percentage", "syntactic_complexity", "avg_external_word_freq_class", "avg_internal_word_freq_class", ]: for word_modifier in [ "", "avg(", "std(", "avg(avg(", "avg(std(" ]: unique_features.append(word_modifier + word_feature + ")" * word_modifier.count("(")) for sentence_feature in [ "flesch_reading_ease", "yule_k_characteristic", "honore_r_measure", "gunning_fog_index", ]: for sentence_modifier in [ "", "avg(", "std(" ]: unique_features.append(sentence_modifier + sentence_feature + ")" * sentence_modifier.count("(")) print "running on features:", unique_features for feature in unique_features: if feature != "yule_k_characteristic": print "running clusterings on", feature ev.compare_cluster_methods(feature, 200, clusterings) if __name__ == "__main__": #_test() _all_clusters_all_features()
39.045326
124
0.65189
1,759
13,783
4.910745
0.173394
0.050012
0.012966
0.01806
0.325654
0.245774
0.220769
0.160685
0.147025
0.122019
0
0.018105
0.246608
13,783
352
125
39.15625
0.813752
0.107741
0
0.185654
0
0
0.088701
0.014016
0
0
0
0.011364
0
0
null
null
0
0.046414
null
null
0.033755
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
1
0
0
0
0
0
0
0
0
2
c4a1211638c119d9ad0df222e32e9684356f5a4c
10,516
py
Python
pysnmp-with-texts/STACK-TOP.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/STACK-TOP.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/STACK-TOP.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module STACK-TOP (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STACK-TOP # Produced by pysmi-0.3.4 at Wed May 1 15:10:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") Counter64, ModuleIdentity, ObjectIdentity, Counter32, NotificationType, iso, Bits, IpAddress, enterprises, Gauge32, Unsigned32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "ModuleIdentity", "ObjectIdentity", "Counter32", "NotificationType", "iso", "Bits", "IpAddress", "enterprises", "Gauge32", "Unsigned32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "MibIdentifier") DisplayString, MacAddress, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "MacAddress", "TextualConvention") zte = MibIdentifier((1, 3, 6, 1, 4, 1, 3902)) zxr10 = MibIdentifier((1, 3, 6, 1, 4, 1, 3902, 3)) stacktop = ModuleIdentity((1, 3, 6, 1, 4, 1, 3902, 3, 301)) stacktop.setRevisions(('2004-05-14 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: stacktop.setRevisionsDescriptions(('',)) if mibBuilder.loadTexts: stacktop.setLastUpdated('200705280000Z') if mibBuilder.loadTexts: stacktop.setOrganization('ZTE Corp.') if mibBuilder.loadTexts: stacktop.setContactInfo('') if mibBuilder.loadTexts: stacktop.setDescription('') class VendorIdType(OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(3, 3) fixedLength = 3 sysMasterVoteTimes = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysMasterVoteTimes.setStatus('current') if mibBuilder.loadTexts: sysMasterVoteTimes.setDescription("How many times stack system's master device be voted.") sysMasterLastVoteTime = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 2), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysMasterLastVoteTime.setStatus('current') if mibBuilder.loadTexts: sysMasterLastVoteTime.setDescription("The ending time when stack system's master device be voted.") sysLastDetecTopEndTime = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 3), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysLastDetecTopEndTime.setStatus('current') if mibBuilder.loadTexts: sysLastDetecTopEndTime.setDescription('The ending time when the system detected top at the last time.') sysTopChagTimes = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysTopChagTimes.setStatus('current') if mibBuilder.loadTexts: sysTopChagTimes.setDescription('How many times the system top changed.') sysTopDetecMsgCount = MibScalar((1, 3, 6, 1, 4, 1, 3902, 3, 301, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysTopDetecMsgCount.setStatus('current') if mibBuilder.loadTexts: sysTopDetecMsgCount.setDescription('System topo detected topo protocol message count.') sysTopInfoTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6), ) if mibBuilder.loadTexts: sysTopInfoTable.setStatus('current') if mibBuilder.loadTexts: sysTopInfoTable.setDescription('A list of the topo information.') sysTopInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1), ).setIndexNames((0, "STACK-TOP", "sysDeviceMacAddr"), (0, "STACK-TOP", "sysDeviceStkPortIndex")) if mibBuilder.loadTexts: sysTopInfoEntry.setStatus('current') if mibBuilder.loadTexts: sysTopInfoEntry.setDescription('An entry to the topo info table.') sysDeviceMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 1), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceMacAddr.setStatus('current') if mibBuilder.loadTexts: sysDeviceMacAddr.setDescription('System Device mac address.') sysDeviceStkPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortIndex.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortIndex.setDescription('System device stack interface port index.') sysDeviceType = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceType.setStatus('current') if mibBuilder.loadTexts: sysDeviceType.setDescription('System device type.') sysDeviceStkPortNum = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortNum.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortNum.setDescription('System device stack interface port number.') sysDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceID.setStatus('current') if mibBuilder.loadTexts: sysDeviceID.setDescription('System device ID.') sysDeviceMasterPri = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceMasterPri.setStatus('current') if mibBuilder.loadTexts: sysDeviceMasterPri.setDescription("System device's priority in voting master device.") sysDeviceStkIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkIfStatus.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkIfStatus.setDescription('System device stack interface status 1: up 2: down.') sysDeviceStkIfPanel = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkIfPanel.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkIfPanel.setDescription('System device stack interface panel num.') sysDeviceStkIfPortID = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkIfPortID.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkIfPortID.setDescription('System device stack interface port num.') sysDeviceStkPortNeibMacAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 10), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortNeibMacAddr.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortNeibMacAddr.setDescription('System device stack interface neighbor device mac address.') sysDeviceStkPortNeibPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 6, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysDeviceStkPortNeibPortIndex.setStatus('current') if mibBuilder.loadTexts: sysDeviceStkPortNeibPortIndex.setDescription('System device stack interface neighbor device port index.') sysStkPortMsgStacTable = MibTable((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7), ) if mibBuilder.loadTexts: sysStkPortMsgStacTable.setStatus('current') if mibBuilder.loadTexts: sysStkPortMsgStacTable.setDescription('A list of the stack interface receive and send message statistic information.') sysStkPortMsgStacEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1), ).setIndexNames((0, "STACK-TOP", "sysStkDeviceID"), (0, "STACK-TOP", "sysStkDeviceStkIfIndex")) if mibBuilder.loadTexts: sysStkPortMsgStacEntry.setStatus('current') if mibBuilder.loadTexts: sysStkPortMsgStacEntry.setDescription('An entry to the stack interface receive and send message statistic information table.') sysStkDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkDeviceID.setStatus('current') if mibBuilder.loadTexts: sysStkDeviceID.setDescription('System device ID.') sysStkDeviceStkIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkDeviceStkIfIndex.setStatus('current') if mibBuilder.loadTexts: sysStkDeviceStkIfIndex.setDescription('System device stack interface index.') sysStkPortRecMsgCount = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkPortRecMsgCount.setStatus('current') if mibBuilder.loadTexts: sysStkPortRecMsgCount.setDescription('System stack interface received message count.') sysStkPortSendMsgCount = MibTableColumn((1, 3, 6, 1, 4, 1, 3902, 3, 301, 7, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sysStkPortSendMsgCount.setStatus('current') if mibBuilder.loadTexts: sysStkPortSendMsgCount.setDescription('System stack interface send message count.') mibBuilder.exportSymbols("STACK-TOP", sysTopChagTimes=sysTopChagTimes, zxr10=zxr10, PYSNMP_MODULE_ID=stacktop, stacktop=stacktop, VendorIdType=VendorIdType, sysLastDetecTopEndTime=sysLastDetecTopEndTime, sysStkPortMsgStacTable=sysStkPortMsgStacTable, sysStkPortSendMsgCount=sysStkPortSendMsgCount, sysTopDetecMsgCount=sysTopDetecMsgCount, sysDeviceMacAddr=sysDeviceMacAddr, sysDeviceType=sysDeviceType, sysDeviceID=sysDeviceID, sysMasterLastVoteTime=sysMasterLastVoteTime, zte=zte, sysDeviceStkIfStatus=sysDeviceStkIfStatus, sysTopInfoTable=sysTopInfoTable, sysStkPortRecMsgCount=sysStkPortRecMsgCount, sysStkPortMsgStacEntry=sysStkPortMsgStacEntry, sysStkDeviceStkIfIndex=sysStkDeviceStkIfIndex, sysDeviceMasterPri=sysDeviceMasterPri, sysMasterVoteTimes=sysMasterVoteTimes, sysDeviceStkIfPanel=sysDeviceStkIfPanel, sysTopInfoEntry=sysTopInfoEntry, sysDeviceStkPortNum=sysDeviceStkPortNum, sysDeviceStkPortNeibPortIndex=sysDeviceStkPortNeibPortIndex, sysDeviceStkIfPortID=sysDeviceStkIfPortID, sysDeviceStkPortNeibMacAddr=sysDeviceStkPortNeibMacAddr, sysStkDeviceID=sysStkDeviceID, sysDeviceStkPortIndex=sysDeviceStkPortIndex)
103.098039
1,126
0.787086
1,149
10,516
7.201915
0.174935
0.076858
0.134502
0.013051
0.472749
0.297885
0.233353
0.181994
0.139335
0.123625
0
0.060002
0.083967
10,516
101
1,127
104.118812
0.799024
0.029669
0
0
0
0
0.199608
0.008534
0
0
0
0
0
1
0
false
0
0.065217
0
0.097826
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
c4a653ab3da07850836f85b3f4fcdccb5d6ad103
723
py
Python
app/http/controllers/CountryHistoricController.py
Kolawole39/covid-africa-api
909fdc12392aea51f407c811a12310ea74decd6c
[ "MIT" ]
4
2020-04-09T18:27:31.000Z
2021-11-08T08:50:56.000Z
app/http/controllers/CountryHistoricController.py
Kolawole39/covid-africa-api
909fdc12392aea51f407c811a12310ea74decd6c
[ "MIT" ]
1
2020-05-10T16:30:53.000Z
2020-05-11T19:13:07.000Z
app/http/controllers/CountryHistoricController.py
Kolawole39/covid-africa-api
909fdc12392aea51f407c811a12310ea74decd6c
[ "MIT" ]
1
2021-04-03T10:37:36.000Z
2021-04-03T10:37:36.000Z
"""A CountryHistoricController Module.""" from masonite.request import Request from masonite.view import View from masonite.controllers import Controller from app.CountryHistoric import CountryHistoric class CountryHistoricController(Controller): """CountryHistoricController Controller Class.""" def __init__(self, request: Request): """CountryHistoricController Initializer Arguments: request {masonite.request.Request} -- The Masonite Request class. """ self.request = request def single(self, view: View, request: Request): country = CountryHistoric.where( 'name', request.param('country').capitalize()).all() return 'country'
27.807692
77
0.701245
66
723
7.621212
0.409091
0.111332
0.071571
0
0
0
0
0
0
0
0
0
0.20332
723
25
78
28.92
0.873264
0.275242
0
0
0
0
0.037267
0
0
0
0
0
0
1
0.181818
false
0
0.363636
0
0.727273
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
c4af79bff2d7f480f0bf14ce13d6610aa3fe0904
10,576
py
Python
2020/day05/boarding_passes.py
UpwardTrajectory/advent-of-code
8fc3ac3d6ef6a6b5d563af8eb2d91ec72c975f15
[ "MIT" ]
null
null
null
2020/day05/boarding_passes.py
UpwardTrajectory/advent-of-code
8fc3ac3d6ef6a6b5d563af8eb2d91ec72c975f15
[ "MIT" ]
null
null
null
2020/day05/boarding_passes.py
UpwardTrajectory/advent-of-code
8fc3ac3d6ef6a6b5d563af8eb2d91ec72c975f15
[ "MIT" ]
null
null
null
all_bps = """BFBBBBBLLR BBFFBBFRRL FBFBFFFRRL BBFFFBFRRL BFFBFBFRLL FFBBBFBLRL BFFFBFFLLR FBFFFFBLRR FBFFBBBRRR BFFBFFFLLR BFFFFFBLLL FFBBFFBLRR BFFFFFBRLR FBFBFBFLLL FFBFBFFLLL BBFFFFFLLL FFFBBBFLLL BBFFBFBLLR FFBFBFBRRR BFFBFFFRRR BBFFBFBRLR FFFBFBFLRL BBFFBBBLRR FBBFFFFLLR BBBFBBFLLL BFFFFBBRLL FBBFBFBRRL FFBBBFFRRR BBFFFFBRRR FBBBBFFLLR BFFFFFBLRR FFBBFBFLLR BFFBFBBLLL BBFBBBBLLL FBFBBBFRLL FFBFFFBLRL FFFFBBBLRL BBBBFBFRRR FFBBFBBRLL FFFBBBBRRL FFBFFFBRLR BFBFBFBLLL FFFBFFBLLL BBFBFBBLRL BBBBBFFLLL FBBBBFFRRR FBFFFFBLLL FFFFBBBRRL FBFBBBFRRR FBBFFBFLRL BFBFFBFLLR FFBBBFBLLL BFBFFFFLLL BBBFFFFLLL BFBBFBFRLR BFBBBBFLRL BBBFBFBLRL BFFFBFBLRL BFBBBBBRLL FBBBFFBRLL BFBFFBBRRL BFFBBBFLLR BFFBFFBRRR FBFBFBFRRL FBFBFBFLRL BBBFFFBRRR FBFFBBFRRR FFBBFFFRLL BFBFBBBLLR BFFFFBFLLR FFBBBBFRLR FFFBFFFRRR BFBBFFFRLL BBBFBFFLRL BFBBFBFLRR BBBBFBBLRL FBFBFBFLRR BBFBFBBLLL BFBBBFBLRL BFBBFBFLRL FFFBBFBLLL BBBFBFBLLR FBBBBBFLLR FFBBBFBRLL BBBBFBBRRL FBFFFBBRLL BBFBBFFRRL FBFFBFBLLL BFFBFBBRRL BFFFBFFRLR BBFBFBFRRR FBBFBFFRRR BBBFBFBLRR FFBFFBFRLR FFBFBBBLRL FFFFBBFRRL FFBBBFBRLR FBFBFBBLLL FBBBFBFRLL BBBBFBBLLR BFBFBBFRLR FBBFBBFLRR BBBBFBFLRL FBFBFBFRLL FFBFBFBLLR FBFFBBFRRL BFFFFFFRLR FFFFBFFRRL BBFFFBFLRR FBBFFBFRRL FFFFBFBLLL FFBBFFFRRL BBFBFFFRLL BFFFFBFRLR FBFBFBBRRL FBBFBBFRLR BFBFFFBRRL FFFBFFBRLR BFBFFBFLRL FBBFBFFRRL FFBFFFBLLL FBFFFBFRRR FBFFFBBRRL FBFFBFBRLL BFBFFFFRLL FFFBBBFLRR BBFFFFFLRR BFBBFBBLLR BFBFFBFLLL FBBBBFBLLR BFBBFFFLLR BFBBFFFRRL BFFBBFFLLR BBBFFFFRRL BBBFBBBLLR FFFBFBBRLL FFBFFBBLRR FFBFBBFLLL BBBFFBFRLL BBBFBFFLRR FBFBFFBRLR FBBFFBBLRL BBFBBFFLLR BBFBBFBRLR BFBFFBBRLR BBBBFFBRLL FFFBBBFRLL FBBFFFFRLR BFBBBBFRRR BBBBFFBLRR FBBBBBFLRR FBBBFFBLRL BFFBBBFRRR BBBBFBFRLL BFBBBFBLRR FFBFFFFLLL FBFFFFBRLL FFBFFBBRLR BFFBBFFLLL FFBFBFBLRL FFBFBFFRRR BBBFBBFLRR BBBFBBBLLL BFFFFFFLRL FBBBBBBRLR FFFBFBFLRR FFBBFFBRRL FBBFBBBRLR BBBFBBFLLR FFBFFBFLRR BFBBFBBRRL FBFFFBBLRL BFFBBFBLRL BBFFBFFLLL FBBBFBFRLR BBBBFFFRLL FFBFBFBLRR FBBFFFBRRL FFBBBFFLLL BBFFFBBLLR BFFFFBFRRL FBFFFFBRRL BFBBFFFRLR FFFBBBBLLL FBFBFBBRLR FFFBFBBRLR FBFBFFFLRR BFFFFFFRRR FFFFBBBRRR BBFBFFFRRL FFFBFBBLLL BFBBFBFLLR BBFBBBBRRL BBFFBBFRRR BBBFFBBLRL FBFBFFFLLR BFFFBBBRRR FFBFFFFLLR FBBBFBFLLL FBBBFBBLRR BBBFBFBRRR FBBBFBFRRL BBBBFFBRLR FBFBBBBLLR FFFFBBFRLR BBFBBBFLLL BBFBBBBLRR FFFFBFBRRR FBFFFBFLRR BFFFBBFLRR BBBFBFFLLR BFFBBBBRLR FBFBBFBLLR BFBBBFFLRR BFFBBFFRRR FFFBFFFRLL FFBFBBBRRR BBBFFFBLLR BBFFFFFLLR FBBBBFBLRR FBFBBFFRRL BFBFBFFRRL BFFFFBFRRR FFBFFBBLLL BFBFBFBRRR BFFFFFFLLR FFFBBFBRRL BFBBBFBRRL BBFFFBFRLL BFBBBBBLRL FBFBBFFLRR FFBBBFFRLR FBBBFBBRRR FFBBBFFRRL FFBBBBFLLR BBFBBFBRRL BBFBBBFRLL BBFFFFFLRL BBBFFFBLLL BBFFFFFRRR FFBFBBBLRR FFBBBFFLRR BFFBFBFRLR FFBBBFBRRR FBBBBFBLRL BBBFBBBRLL FBFBFFBRRL BFFFFBBRRL BBFFBBFRLR FFBFBFFRLR BFFFBFBRRR BBBFBBFRRL FFFBFFFLRL FBBFFBFRRR FFBBBBBLLL FFBFFBFLRL FBFBFBBLRR FFFBFFBRLL BBBFFFBRRL BFBFBBBRLL BBBFFFFLRR BBFFBFFLLR FBBFFBFLRR FBBBFFBLRR BFBFFBBLLL FBFFFBBRLR FBBFBBBLLR BFBBBBBRLR FBBBFFFLLL BFFFBBFLLL BFFFFBBRLR FBBFBFBRLL FBFFBFBLRL BBBFFFFRLL FBFFFFFRLL FBBBFBFLRL FBFBBFBRRL FFBFBFFLLR BBBFFBBLLL FFBFBBFLLR BBBFBBFRLL BFFBFBBLRR FBBFBBFRRL FBFFBFFLLL BFBBFBFLLL FFBBFFBRLL BFFFFFFLLL BFFFFFFRLL BFBFFFFLRR FFBBFFFLRR BBFFBBBRLR BFFFFBFLRR FFBFBFFLRR BBBBBFFLRL BBFBBBBRLR BFFBFFBRLL BFBFBBFLRL FBFBBFBLLL BFFBBFFRLR FFFFBFBRLR BFBFBFBRLL BFBBFFBLRR BBBBBFFRLL BBFFFBBRLL BFBFBBBLLL FBBBFFFLRR FBBBBBFRRL BFFBBFBRRL FFBBFFBLLL FBFFFBFRLL BBBFFFBRLL FFFBBFFLLL BBFBFBBLLR FFFBFFBLRL BFFBBBBLLL BBFFBFFLRR FFBBFBFLRR BBBBFBFRRL BBFBFBBRRR BBFFFFBLLR BBBBFFBLLR BBBFFBFLRR FFBFFBBLRL BBFBBBFRLR FBFFBFFLRL FFFFBFBLRL BFBFFFBLRL FBBBFBFLRR BFFFBBBLLL FBBBFFFRRR BFBFBFFLLR BFFBFBFLLR FFFBBBFRRL BBBFFBFLLR FFBFBFBLLL BFBBBFFRLR BBBFFBFRRL FBFBFFFRLR BFBFBBFRRL FBFFFFFLRR BFBFFBBLLR BBFBFBBRLR FBBBFFFLRL BBBBFBBRRR FFBBBBFLLL FBFFFBBLLR FFBBBBBRRR BFFFBBBLRR BBFBBBBRLL BBFBFBFLRR BFBBFFBLLR FBBFFBBRLL FBBBBFFRLL FBFBFFBLLR FFBFBBBRRL FFFBBFBRLL BFFBBFBLLR BBBBBFFRRL BFBBFFBRRL BFFBFFBRLR FFBFBBFRRL FFFFBBFLRL BBFFFFBLRL BFBFFFBRLL BFBFFFFRRR BBBFFBBRRL FFFFBBFLLL BBBFFFFLRL BBBFBFFLLL FBFBFFBRLL FBBFFFBLRL BFBFBFFLLL BBBFFFBLRR FBFBFBFRLR BFBFBFFLRL BFFFBBBRRL BFBFFBBRLL FFBFFFBRLL FFBFFBFLLR FFFBFFBRRL FFBBFFFLRL BFBFFFFRRL FBFFFFFRRR BBFBBFBLLR FFBFBFBRLR BFFFBFFRRR FBBBBFBLLL BBFFBBBRRR BBFBBBBRRR BBBFBBBLRR BBFBBFBRLL BFBFBFFLRR FBFFFBFLRL FFFFBFFRRR BFFBFFFLRR FBFFBBBRLL BFFFBFBLLL FBBFBFBLLR FFBFFBBRRR BFBFBBFLRR BBFFFFBLLL FBBFFFFRRR FBFBBBFRRL FBBFFFBLLR FBFBBFBRLR BBFFBBBLLR FFFBBFFLRL BBFFBFBRRR BFBFFFFLRL FFFFBFBRLL FBFFFBFRRL BBBFBBBLRL FFBBBFFRLL BBFBFFBRRL BFFBFFBLLL BBFBBFBRRR FBBFBBFLLR BFFFFFFLRR FBBBBBBRRR BBFBBBFRRL FFFBBBFLLR FBBBBFFLRL FBFFBFFRLL BFBFBFBRLR FBBBFFFRLL BBFFFBBRRR BBFBFBBLRR BFFFFFBRLL FBFBFFFLLL FBFFBFBLLR BFFBFFBRRL BFBBFFFLRR BFBBBFBLLR FFFBBBBRLR FFBFFBFRRL FFBBBFBLLR BBFBFFBRRR FFBBBBBRLR BBFFBBBLLL BFBBFFBLLL BFBFBBFRRR BBBBFFFLLL FBBFFBBRRL FFBBBFBRRL BFBFBBBRRR FBFBBFFLLL FFBBFFFLLR FBBBBBFLLL FFBFBFFLRL FFBFFBFRRR FBBBFBBRLR BFFFFBFLRL FFFBFFFLLR BBFBFFBLLR FFBBFFBLRL FFFBFBBLRL BFFFBBBRLR BBFFFFBRRL FBBFFBBLRR FBFFFFFLRL BBFFBFFRLR BBFBFFFRLR FFFBFBFRLR BFFFBBFRRL BBBFFBFLLL BBFBBBBLRL BFFFFFBLLR BFFFFBBLLR BBBFFBFRRR BBFFFFFRRL BBFFFFBRLR FFBBBFFLRL BFFFBBBRLL BFFFBBFRLL FBFBBBFRLR BBFBFBFRRL FBFFBFBRLR FBFFBFFRRR FBFFFBBLRR BFFFBBFLRL FBFBFFBLRL FBBBBBBRRL BFFFBFBRLR FBBBBFBRLL BBFFBBFLLR BBFBBFFLRR FBFFFBFLLR FBBBFBBLLL FFBFFFBLRR BBFBFFBLRR FFBFFBBRLL BFFBBFFRLL FBFFFFBRRR FFFBFBBRRL BBBBFBFLLR BBFBFFFLRL BFBFFFFRLR BBFBFFFRRR BBBFBBBRRL BFFBBBBLRR BFFFBBBLRL BBFFFBBRLR FBBBFFBRLR FBBBFFBLLL FBBBBBBLRL BBBFFFBLRL FBFBFFFLRL BFBFFBFRLL BBFFFFBRLL BBFFFFFRLL FFFBFFFRRL BBFFBBFLRR BBBBFFFRRL BFFBBBBLLR BBBBFFFRLR BBBFFFBRLR FBBFFBBRLR BFFBBFBLLL BBBFBBFLRL BFBFBBFLLR BBFBBFFLRL BFFBBBFRRL FFFFBBFLRR FBFFBBBLLR BFBFBFBLLR FBBBFFBRRR FBBBBBFRLR BBFBFFBRLR BBFFBFFRLL FFFBFFBLLR BBFFBFBLRR FBFFFBBRRR BFFBBBBRRR FBFFBBBRRL BBFBFBFLLR FBFBBFFLRL BBBBFFFRRR BBFBFFFLLL BFFFBFBLLR FBBBBFFLRR FBFFBBFLLL FFFFBFBRRL BBFBFBFLLL BFBBFFBLRL BFFFBFBLRR BBBBFFBRRR FBFBBFBRRR FBBFBFBRLR FBBFBFFLRR FBFBBBBLRR FBBFBFFRLR FBBBBBFLRL FBBFBFFRLL FFBBFFBRRR BFBFBFBLRR FBBFBBBLRL FBBBFBFRRR BFFBFBFRRL FBBFFFFLRL BFBBBBFRLR FFBFBBBRLL BFFBBBBRRL BFBBFBBLLL FBFBFFFRRR BFBFBFBLRL FBBFFBFLLR FFFBFBBRRR FBBBBFFLLL FBFBBBBLRL FBBFBFBLRL FFBBFBBRRR FBFBFFBLRR FBFBFBBLLR FFFBFBFRLL FFFFBBFRRR BFBBBBBLLL BBFBBBBLLR FBBFFFFRRL FBBFBFBLLL BFFFBBFLLR FBBBFFBLLR FFBFFBFLLL BBBFFBBLLR BFBFFFFLLR FBFBBBFLRR FFBBBBFRRL FFFFBBBLRR FFBFFFFRRL BFBBFFFLRL BBBFBFBLLL FBFBBFBLRR BBFBBFBLLL BFFBFBBRLR BFBBFBBRRR FFBBFBFRLL BFFBFBFLLL BFFBBFBLRR FBBBBFBRRL BFBFBBBLRR FBBBBBBLLL BFFFBBBLLR BBFBFFFLLR BBBFFBBRLL BFFBBBFLRR BFFBFBFRRR BBBBBFFRLR BFFBFFFRLR FBFFFFFLLL BFFFBFBRLL FBBFBBFLLL FBBFBFBRRR FBFFBBFLLR FBBBFBFLLR FFFBFFFLRR FFBBBBFRRR BBBBFBFLRR FBFBFFBRRR BFFBFFBLLR FFBBFBBRLR FBFBFBBRRR FFBBBBBLRL FBBBBBFRRR FFFBFBFRRL FFBFBFBRRL BFBBBFBRLR BBBFBFFRRR BFFBBFBRLR BFFBBBBRLL FBBBBFFRRL BBBFBBBRLR BFFFFFFRRL FFFBBFFLRR BBFBFFBLRL BFFBFBFLRR BBBFFBBLRR BFBFFBFRRR BBBBFFBLLL FBFFBBBLRR BBFFBBFLLL FBFBBBBRRR BBFFBFBLLL BBBBFFFLRR FBFFBBBRLR BFBFFFBLRR BBFBBFFLLL BFFBBFFRRL BFFFBFFRRL BBFFFBBLRR FFBFFFFLRL FFBFBBFRLL FBFBFFFRLL BBFFFBFRLR FFFBBFBLRR BFBBBFBLLL BBFBFBFRLL BFBFBBFRLL BFFFFFBRRL FFBFBBBRLR BFBBFFBRLR BFBFBFFRLR FBBBBBBLRR FFBBBBFLRL FFFFBFBLRR FFBFFFBRRR FFBFBBFRLR BBBFFBFLRL FBBBBFFRLR BFFBBFBRLL BFFBBBFRLR FFFBFFBRRR BBBFBBBRRR FBFFBFFRRL FBFFFBFLLL BFBBBFFRRL BBFBFBBRLL BBFBFBBRRL FFFBFBFRRR BFBBFBBLRR FFFBBBFRRR BFFBFBBLRL BFFBFFBLRR BFBBBFFRRR FFFBBBFLRL FFBBFBFRRR FFBFBFBRLL FFBFFFBLLR FBBBBBBRLL FFFFBFBLLR FFBBFFFRRR FFFBFFFLLL FFBBFBBLLR FFBBBBFLRR FBBFFBBLLL BFBBFBBRLR FFFBFBBLLR BBFFBFBLRL FFBFBBFRRR BBBBFBBRLR BBBFBBFRLR BBFFBFFRRR FFBBBBBLLR FBFFBFBLRR FBBBBFBRLR FFFFBBFLLR BFBFBBFLLL FBBFBFBLRR FBBFFBFRLL BBFFFFFRLR FFBBFBFLRL BFBFBBBRLR FBBFBBFRRR FBFBFBBLRL BBBFFBBRRR FBBFFBBRRR FBFFFFBRLR FBBFBBFLRL FFFBBFBRRR FBFBBBBRLR FBBFFBBLLR FFFBBBBRRR BBBBBFFLLR FFFFBBBLLL BFFBBBFRLL FBFBBFBLRL BBBBFBFRLR BBFBFFBLLL BFBFFBFLRR BFFFFFBLRL BBBFBBFRRR FFBBBBBLRR FBFFFFFLLR FBFBBFFRLL BFBBBBBRRL FBFBFBBRLL FBBFBBBRRL FBFFBBBLRL BFFFBFFLLL BFBBBBBRRR FFFBBFFRRR BBFBBBFLRL FFFFBBFRLL FBFFFFFRLR FFFFBBBRLR FBFFBBFRLR FFFFBBBRLL BBFFBBBLRL FFBFBBFLRR BFBBBBBLRR BFFFFBBLLL FBFBBBBRRL BBBFBFFRRL BFBBFBBLRL BFBBBBFRRL FBFFFBBLLL FFBBFBBLRL BBFBFFBRLL BBBFFFFRRR FFFBBBBLRR FFFBBFBLRL FFFBBBBLLR BFBFBBBRRL BBBBBFFLRR BBBBFBBLLL BBBBFBBLRR FFFBBBFRLR FBBBFFFLLR BFFFBFBRRL BBFFFBFLLR BFBBFBFRLL BFBBBFFLRL FFBFFBBRRL FBFBBFFRLR BFFFFFBRRR FBFFFFBLLR FBBFBFFLLR FBBBFFFRLR FBFBFBFLLR FFFBBFBLLR BFBFFBFRRL FFFBBFBRLR FFBBFBBLRR FBBBFBBLLR BBBFFFFLLR BBBBFBFLLL BBFFFBFLLL BFFFBFFLRL BBFBBFFRLR BBFFBBFLRL FBBBBFBRRR FBBFFBFLLL FFFBFFBLRR FFBBFFFRLR FBBFFFBRLR BBBFBFBRLL BFBBFFFLLL FFFBBFFRLL BBFFBFBRLL FFBBBBBRRL FBFFBBBLLL FBBFFFBRRR BFFFBFFRLL FFBBBFFLLR FBBFBBFRLL FBBFFFFLRR FBBBBBFRLL BBBFFBBRLR FBFFBBFLRL FBBFFFBLLL BFBBBFFRLL FFFBBFFRLR BFBFFFBLLL FFFFBBBLLR BFFBFFFLLL BFBBFFBRRR BFFBFBBLLR FFBFFBFRLL FFFBBFFLLR FBFFFFFRRL BFFBBFFLRR FFBBFFBLLR FBBBFFBRRL FBBBFBBLRL BBFFBFFLRL BBBBFFBRRL BFBFFBBLRL BFBBFBFRRR FFFBBBBRLL FBBFBBBRRR BBBBFFFLRL FBFFBFBRRR BBBBFFFLLR FBBFFBFRLR FFFBBBBLRL BBFBBFBLRL BFBBBBFLLR BBBFBFBRRL BFBBBBFLLL BFBFFFBRRR FFBBFFBRLR FBBBFFFRRL BFFFFBBRRR FBFBBFBRLL BFBBFFBRLL FBBFBFFLRL BFFBBBBLRL BFFBFBFLRL FBBBFBBRRL BFBBBBFLRR BFBFFBBRRR BFFFBBFRLR BFFBFFBLRL BFFBBFBRRR BBFFBBBRRL BBBBFBBRLL FBBFBBBLRR FFBFBFFRLL FFBFFFFRRR BFFBBFFLRL BFBBFBBRLL BFBFFBBLRR FBFBFBFRRR BBFFFBFRRR BBFBBFFRRR FFBFBBBLLR FFFBFBFLLL BBFFFBBLLL FFBBFBBLLL BFBBFFFRRR BFBFBBBLRL FBFBBBFLRL BFBFBFBRRL FFFBFBFLLR BBFFFFBLRR BBFBFBFRLR FFBBFBFLLL BFBBBFBRLL BBBFFBFRLR BFFFFBFLLL FFBBBBFRLL BBFBBFFRLL BFFFBFFLRR BBFBBBFLLR FFBFBBFLRL BBBBFFBLRL BFBBBFBRRR FBBFBFFLLL FBFFBFFRLR BFFBFFFLRL FBFFBFFLLR FBFBBBBRLL BBFFFBFLRL BBFBBFBLRR BFFFFBBLRL BBFBFBFLRL FBBFBBBRLL FBBFFFFRLL FFBFBBBLLL FFBFFBBLLR BFBBBFFLLR BBBFBFFRLR BFFBFFFRRL BBFFBBBRLL BBFFBBFRLL FBBBBBBLLR BFFBFBBRRR BBFFFBBRRL FFBFFFFRLL FFFBFBBLRR BBFFBFBRRL BBFFFBBLRL FBFFFFBLRL BFFFFBFRLL BFFBBBFLLL BFBBFBFRRL FBBFFFBLRR FFBFFFFRLR FBBFFFFLLL FBFBBFFRRR FBFBBFFLLR FFBFFFBRRL BFBBBBFRLL BFFBBBFLRL FBFFBFBRRL FFBFFFFLRR FBBBFBBRLL BBFBBBFRRR BFFBFFFRLL FFFBBFFRRL BFBFFFBLLR FBFFFBFRLR FBFBBBFLLL FFBBFBFRRL BBBFBFFRLL FBFFBFFLRR BBFBBBFLRR FFBBBFBLRR FFFBFFFRLR FBFBFFBLLL BFBBBFFLLL BFFFFBBLRR FBFBBBFLLR FBFFBBFLRR FFBBFBBRRL BBFBFFFLRR BBFFBFFRRL FFBBFFFLLL FFBFBFFRRL BBBFBFBRLR BFBFFFBRLR FBFBBBBLLL FFBBBBBRLL FBBFBBBLLL BFFFBBFRRR BFBFFBFRLR BBBFFFFRLR FBFFBBFRLL FFBBFBFRLR BFFBFBBRLL BFBFBFFRRR FBBFFFBRLL"""
11.005203
23
0.908377
962
10,576
9.985447
1
0
0
0
0
0
0
0
0
0
0
0
0.090961
10,576
960
24
11.016667
0.999168
0
0
0
0
0
0.998393
0
0
1
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
2
c4b96dbb8ead9259086dfdf973577eb4671ef709
316
py
Python
deploys/setup-infra/install_all.py
kimcu-on-thenet/coolstore-microservices
d2524bf56fc0219496fd1e499a663f3e63b42818
[ "MIT" ]
1
2019-08-03T17:42:39.000Z
2019-08-03T17:42:39.000Z
deploys/setup-infra/install_all.py
kimcu-on-thenet/coolstore-microservices
d2524bf56fc0219496fd1e499a663f3e63b42818
[ "MIT" ]
null
null
null
deploys/setup-infra/install_all.py
kimcu-on-thenet/coolstore-microservices
d2524bf56fc0219496fd1e499a663f3e63b42818
[ "MIT" ]
null
null
null
import get_aks_config import install_helm import install_istio import install_dashboard import create_aks import time def run(): create_aks.run() get_aks_config.run() install_helm.run() time.sleep(60) install_dashboard.run() install_istio.run() if __name__ == "__main__": run()
14.363636
27
0.712025
43
316
4.767442
0.395349
0.190244
0.117073
0
0
0
0
0
0
0
0
0.007905
0.199367
316
22
28
14.363636
0.802372
0
0
0
0
0
0.025237
0
0
0
0
0
0
1
0.066667
true
0
0.4
0
0.466667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
2
c4ba3f5b87fa0605de5974d25966d92384a0a499
612
py
Python
spanishdata/2007-2010/textRetrieve2007-2010.py
ab93/Text-Summarization
b99784cabe9cd6074cfe065542c2954077b17d60
[ "Apache-2.0" ]
4
2016-05-30T04:42:21.000Z
2021-04-26T16:32:12.000Z
spanishdata/2007-2010/textRetrieve2007-2010.py
ab93/Text-Summarization
b99784cabe9cd6074cfe065542c2954077b17d60
[ "Apache-2.0" ]
null
null
null
spanishdata/2007-2010/textRetrieve2007-2010.py
ab93/Text-Summarization
b99784cabe9cd6074cfe065542c2954077b17d60
[ "Apache-2.0" ]
3
2016-07-29T05:55:28.000Z
2018-05-13T15:25:42.000Z
import json count=0 countNoTitle=0 json_data=open('2007-10.json').read() jsoncontents = json.loads(json_data,strict=False) print len(jsoncontents['items']['item']) for i in range(0,len(jsoncontents['items']['item'])): content=jsoncontents['items']['item'][i]['discurso'] content=content.encode('utf-8') print "content ",content f = open('2007-10c'+str(count)+'.txt','wb') #content=content.encode('utf-8') try: title=jsoncontents['items']['item'][i]['titulo'] print count raw_input() except: #print count countNoTitle+=1 f.write(content) count+=1 f.close() print count print countNoTitle
21.103448
53
0.697712
88
612
4.818182
0.465909
0.160377
0.198113
0.113208
0.113208
0
0
0
0
0
0
0.034672
0.104575
612
28
54
21.857143
0.739051
0.068627
0
0.090909
0
0
0.156966
0
0
0
0
0
0
0
null
null
0
0.045455
null
null
0.227273
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
c4d10d3842362c8b5253681ecd28e26805a45699
271
py
Python
tests/locators/photo_gallery_locators.py
Alpaca00/alpaca_web
1db33978f774addbe456f750ffadf32d2f223610
[ "MIT" ]
4
2021-09-14T07:36:27.000Z
2021-09-18T15:10:24.000Z
tests/locators/photo_gallery_locators.py
Alpaca00/alpaca_web
1db33978f774addbe456f750ffadf32d2f223610
[ "MIT" ]
1
2021-12-14T20:32:29.000Z
2021-12-15T13:28:29.000Z
tests/locators/photo_gallery_locators.py
Alpaca00/squash-opponent
1db33978f774addbe456f750ffadf32d2f223610
[ "MIT" ]
null
null
null
from selenium.webdriver.common.by import By class PhotoGalleryLocators: lst_images = (By.XPATH, "//div[@class='container-lg']//img") modal_window = (By.XPATH, "//div[@class='modal-body']/img") modal_window_title = (By.XPATH, "//*[@id='exampleModalLabel']")
33.875
67
0.678967
34
271
5.294118
0.617647
0.116667
0.111111
0.166667
0
0
0
0
0
0
0
0
0.118081
271
7
68
38.714286
0.753138
0
0
0
0
0
0.335793
0.335793
0
0
0
0
0
1
0
false
0
0.2
0
1
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
c4e782a458b7b7f1a5cb3c67ea132b27dd6947ee
421
py
Python
arvestust/models/tests/save.py
lehvitus/arvestust
2d508317b744eaf12a643a398ff95723893a046a
[ "BSD-3-Clause" ]
1
2021-09-17T23:45:27.000Z
2021-09-17T23:45:27.000Z
arvestust/models/tests/save.py
lehvitus/arvestust
2d508317b744eaf12a643a398ff95723893a046a
[ "BSD-3-Clause" ]
3
2020-07-25T05:40:54.000Z
2020-08-11T04:01:19.000Z
arvestust/models/tests/save.py
lehvitus/arvestust
2d508317b744eaf12a643a398ff95723893a046a
[ "BSD-3-Clause" ]
null
null
null
from django.test import TestCase from ..save import Save class SaveTestCase(TestCase): def setUp(self): """ Create objects here... Example: Save.objects.create() """ pass def test_create_save(self): """ Run assertions here... Example: save = Save.objects.create() self.assertEqual(save.id, 1) """ pass
16.192308
36
0.527316
42
421
5.238095
0.5
0.1
0.136364
0
0
0
0
0
0
0
0
0.003731
0.36342
421
25
37
16.84
0.817164
0.344418
0
0.285714
0
0
0
0
0
0
0
0
0
1
0.285714
false
0.285714
0.285714
0
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
c4eb397f61695836b9f001f66e35f3d9b3a7e3af
639
py
Python
code/dqn/replay_memory.py
chickert/autonomous_vehicles
3061968524f1c507f409ee9aeaf8625d1c1f725c
[ "MIT" ]
null
null
null
code/dqn/replay_memory.py
chickert/autonomous_vehicles
3061968524f1c507f409ee9aeaf8625d1c1f725c
[ "MIT" ]
null
null
null
code/dqn/replay_memory.py
chickert/autonomous_vehicles
3061968524f1c507f409ee9aeaf8625d1c1f725c
[ "MIT" ]
null
null
null
from collections import namedtuple, deque import random import numpy as np # could also use randint + numpy to random sample (perhaps time is scaling linearly with rep_mem size) # Plot time to verify and check SARSD = namedtuple('SARSD', ('state', 'action', 'reward', 'next_state', 'done')) class ReplayMemory: def __init__(self, memory_size): self.memory = deque(maxlen=memory_size) def add(self, sarsd): self.memory.append(sarsd) def sample(self, batch_size): # assert len(self.memory) > batch_size, "Batch size is greater than memory size" return random.sample(self.memory, batch_size)
30.428571
102
0.707355
89
639
4.955056
0.550562
0.113379
0.068027
0.086168
0
0
0
0
0
0
0
0
0.194053
639
20
103
31.95
0.856311
0.327074
0
0
0
0
0.084507
0
0
0
0
0
0
1
0.272727
false
0
0.272727
0.090909
0.727273
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
c4f1a61885922def9578ed8c817e1b5c16bc23d7
645
py
Python
third_party/mordred/tests/Dummy.py
uta-smile/CD-MVGNN
b48f4cd14befed298980a83edb417ab6809f0af6
[ "MIT" ]
3
2022-02-06T09:13:51.000Z
2022-02-19T15:03:35.000Z
third_party/mordred/tests/Dummy.py
uta-smile/CD-MVGNN
b48f4cd14befed298980a83edb417ab6809f0af6
[ "MIT" ]
1
2022-02-14T23:16:27.000Z
2022-02-14T23:16:27.000Z
third_party/mordred/tests/Dummy.py
uta-smile/CD-MVGNN
b48f4cd14befed298980a83edb417ab6809f0af6
[ "MIT" ]
null
null
null
from third_party.mordred import Descriptor class Dummy1(Descriptor): pass class Dummy2(Dummy1): since = "1.0.0" def parameters(self): return () def calculate(self): return 0.0 rtype = float class Dummy3(Dummy2): @classmethod def preset(cls, version): yield cls() class Dummy4(Dummy3): def __init__(self, i=0): self.i = i def __eq__(self, other): return isinstance(other, Dummy4) and self.i == other.i def __str__(self): return "Dummy4_{}".format(self.i) @classmethod def preset(cls, version): yield cls(0) yield cls(1)
16.125
62
0.596899
82
645
4.52439
0.426829
0.053908
0.107817
0.123989
0.204852
0.204852
0.204852
0
0
0
0
0.037118
0.289922
645
39
63
16.538462
0.772926
0
0
0.16
0
0
0.021705
0
0
0
0
0
0
1
0.28
false
0.04
0.04
0.16
0.72
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
f20cb3cf9260038f3d81cef339e3f12b07855f55
192
py
Python
watchmen/common/utils/pickle_wrapper.py
Insurance-Metrics-Measure-Advisory/watchman-data-connector
8ecab0c5b28174f1611e51deba8d94a42f53d51d
[ "MIT" ]
125
2021-03-13T07:39:46.000Z
2022-02-28T03:14:17.000Z
watchmen/common/utils/pickle_wrapper.py
Insurance-Metrics-Measure-Advisory/watchman-data-connector
8ecab0c5b28174f1611e51deba8d94a42f53d51d
[ "MIT" ]
null
null
null
watchmen/common/utils/pickle_wrapper.py
Insurance-Metrics-Measure-Advisory/watchman-data-connector
8ecab0c5b28174f1611e51deba8d94a42f53d51d
[ "MIT" ]
17
2021-03-13T07:31:58.000Z
2021-05-20T09:38:02.000Z
import pickle def pickle_wrapper(data, type): pickle_data = pickle.dumps(data) return type.parse_raw( pickle_data, content_type='application/pickle', allow_pickle=True )
21.333333
73
0.71875
25
192
5.28
0.56
0.151515
0
0
0
0
0
0
0
0
0
0
0.1875
192
8
74
24
0.846154
0
0
0
0
0
0.09375
0
0
0
0
0
0
1
0.166667
false
0
0.166667
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
0
0
0
0
0
0
0
2
f21bad8ee7c45ebba08940d9ed43a6987d13630d
716
py
Python
examples/01 - Comprehensions/comprehensionsGoodBonus.py
ordasf/pythonperformance2
e9e0e763320af7e65330f8cd10a587f9ce253bda
[ "MIT" ]
null
null
null
examples/01 - Comprehensions/comprehensionsGoodBonus.py
ordasf/pythonperformance2
e9e0e763320af7e65330f8cd10a587f9ce253bda
[ "MIT" ]
null
null
null
examples/01 - Comprehensions/comprehensionsGoodBonus.py
ordasf/pythonperformance2
e9e0e763320af7e65330f8cd10a587f9ce253bda
[ "MIT" ]
null
null
null
import config import time my_config = config.get_config() number_of_loops = my_config.getint("Global", "number_of_loops") def good_list(): my_list = [value for value in range(number_of_loops)] def modulus_validation(value): return value % 2 == 0 def good_list_validation(): my_list = [value for value in range(number_of_loops) if modulus_validation(value)] def good_tuple(): my_tuple = tuple(value for value in range(number_of_loops)) def good_set(): my_set = {value for value in range(number_of_loops)} def good_dict(): my_dict = {value: value for value in range(number_of_loops)} start = time.time() good_list_validation() end = time.time() print(end - start)
19.351351
64
0.712291
111
716
4.306306
0.261261
0.117155
0.190377
0.156904
0.447699
0.405858
0.405858
0.405858
0.33682
0.330544
0
0.003419
0.182961
716
36
65
19.888889
0.813675
0
0
0
0
0
0.02933
0
0
0
0
0
0
1
0.285714
false
0
0.095238
0.047619
0.428571
0.047619
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
1ee8a645ad699ca333abb2752375901de230d93c
52,220
py
Python
Tests/test_function.py
elfscript/ironpython3
fde41d69ff178e60b33b68752e0ea8ba8f5e45e7
[ "Apache-2.0" ]
null
null
null
Tests/test_function.py
elfscript/ironpython3
fde41d69ff178e60b33b68752e0ea8ba8f5e45e7
[ "Apache-2.0" ]
null
null
null
Tests/test_function.py
elfscript/ironpython3
fde41d69ff178e60b33b68752e0ea8ba8f5e45e7
[ "Apache-2.0" ]
null
null
null
# Licensed to the .NET Foundation under one or more agreements. # The .NET Foundation licenses this file to you under the Apache 2.0 License. # See the LICENSE file in the project root for more information. import unittest from iptest import IronPythonTestCase, is_cli, is_mono, is_netcoreapp, is_posix, run_test, skipUnlessIronPython from types import FunctionType, MethodType global init def copyfunc(f, name): return FunctionType(f.__code__, f.__globals__, name, f.__defaults__, f.__closure__) def substitute_globals(f, name, globals): return FunctionType(f.__code__, globals, name, f.__defaults__, f.__closure__) global_variable = 13 def create_fn_with_closure(): x=13 def f(): return x return f def x(a,b,c): z = 8 if a < b: return c elif c < 5 : return a + b else: return z class C1: def f0(self): return 0 def f1(self, a): return 1 def f2(self, a, b): return 2 def f3(self, a, b, c): return 3 def f4(self, a, b, c, d): return 4 def f5(self, a, b, c, d, e): return 5 def f6(self, a, b, c, d, e, f): return 6 def f7(self, a, b, c, d, e, f, g): return 7 class FunctionTest(IronPythonTestCase): def test_basics(self): self.assertTrue(x(1,2,10) == 10) self.assertTrue(x(2,1,4) == 3) self.assertTrue(x(1,1,10) == 8) def f(): pass f.a = 10 self.assertTrue(f.a == 10) self.assertEqual(f.__module__, __name__) def g(): g.a = 20 g() self.assertTrue(g.a == 20) def foo(): pass self.assertEqual(foo.__code__.co_filename.lower().endswith('test_function.py'), True) self.assertEqual(foo.__code__.co_firstlineno, 66) # if you added lines to the top of this file you need to update this number. def test_inherit_function(self): def foo(): pass # Cannot inherit from a function def CreateSubType(t): class SubType(t): pass return SubType self.assertRaisesRegexp(TypeError, ".*\n?.* is not an acceptable base type", CreateSubType, type(foo)) def test_varargs(self): def a(*args): return args def b(*args): return a(*args) self.assertEqual(b(1,2,3), (1,2,3)) def test_default_values(self): def xwd(a=0,b=1,c=3): z = 8 if a < b: return c elif c < 5 : return a + b else: return z self.assertEqual(x,x) self.assertEqual(xwd(), 3) self.assertRaises(TypeError, (lambda:x())) self.assertEqual(xwd(2), 3) self.assertRaises(TypeError, (lambda:x(1))) self.assertEqual(xwd(0,5), 3) self.assertRaises(TypeError, (lambda:x(0,5))) self.assertEqual( (x == "not-a-Function3"), False) def test_missin_params(self): def y(a,b,c,d): return a+b+c+d def ywd(a=0, b=1, c=2, d=3): return a+b+c+d self.assertEqual(y, y) self.assertEqual(ywd(), 6) self.assertRaises(TypeError, y) self.assertEqual(ywd(4), 10) self.assertRaises(TypeError, y, 4) self.assertEqual(ywd(4,5), 14) self.assertRaises(TypeError, y, 4, 5) self.assertEqual(ywd(4,5,6), 18) self.assertRaises(TypeError, y, 4,5,6) self.assertEqual( (y == "not-a-Function4"), False) def test__doc__(self): def foo(): "hello world" self.assertEqual(foo.__doc__, 'hello world') def test_coverage(self): # function5 def f1(a=1, b=2, c=3, d=4, e=5): return a * b * c * d * e def f2(a, b=2, c=3, d=4, e=5): return a * b * c * d * e def f3(a, b, c=3, d=4, e=5): return a * b * c * d * e def f4(a, b, c, d=4, e=5): return a * b * c * d * e def f5(a, b, c, d, e=5): return a * b * c * d * e def f6(a, b, c, d, e): return a * b * c * d * e for f in (f1, f2, f3, f4, f5, f6): self.assertRaises(TypeError, f, 1, 1, 1, 1, 1, 1) # 6 args self.assertEqual(f(10,11,12,13,14), 10 * 11 * 12 * 13 * 14) # 5 args for f in (f1, f2, f3, f4, f5): self.assertEqual(f(10,11,12,13), 10 * 11 * 12 * 13 * 5) # 4 args for f in (f6,): self.assertRaises(TypeError, f, 1, 1, 1, 1) for f in (f1, f2, f3, f4): self.assertEqual(f(10,11,12), 10 * 11 * 12 * 4 * 5) # 3 args for f in (f5, f6): self.assertRaises(TypeError, f, 1, 1, 1) for f in (f1, f2, f3): self.assertEqual(f(10,11), 10 * 11 * 3 * 4 * 5) # 2 args for f in (f4, f5, f6): self.assertRaises(TypeError, f, 1, 1) for f in (f1, f2): self.assertEqual(f(10), 10 * 2 * 3 * 4 * 5) # 1 args for f in (f3, f4, f5, f6): self.assertRaises(TypeError, f, 1) for f in (f1,): self.assertEqual(f(), 1 * 2 * 3 * 4 * 5) # no args for f in (f2, f3, f4, f5, f6): self.assertRaises(TypeError, f) def test_class_method(self): # method class C2: pass c1, c2 = C1(), C2() line = "" for i in range(8): args = ",".join(['1'] * i) line += "self.assertEqual(c1.f%d(%s), %d)\n" % (i, args, i) line += "self.assertEqual(C1.f%d(c1,%s), %d)\n" % (i, args, i) #line += "try: C1.f%d(%s) \nexcept TypeError: pass \nelse: raise AssertionError\n" % (i, args) #line += "try: C1.f%d(c2, %s) \nexcept TypeError: pass \nelse: raise AssertionError\n" % (i, args) #print line exec(line) def test_set_attr_instance_method(self): C1.f0.attr = 1 self.assertEqual(C1.f0.attr, 1) self.assertEqual(dir(C1.f0).__contains__("attr"), True) self.assertEqual(C1.f0.__module__, __name__) def test_kwargs(self): def f(x=0, y=10, z=20, *args, **kws): return (x, y, z), args, kws self.assertTrue(f(10, l=20) == ((10, 10, 20), (), {'l': 20})) self.assertTrue(f(1, *(2,), **{'z':20}) == ((1, 2, 20), (), {})) self.assertTrue(f(*[1,2,3]) == ((1, 2, 3), (), {})) def a(*args, **kws): return args, kws def b(*args, **kws): return a(*args, **kws) self.assertTrue(b(1,2,3, x=10, y=20) == ((1, 2, 3), {'y': 20, 'x': 10})) def b(*args, **kws): return a(**kws) self.assertTrue(b(1,2,3, x=10, y=20) == ((), {'y': 20, 'x': 10})) try: b(**[]) self.assertTrue(False) except TypeError: pass def f(x, *args): return (x, args) self.assertEqual(f(1, *[2]), (1, (2,))) self.assertEqual(f(7, *(i for i in range(3))), (7, (0, 1, 2,))) self.assertEqual(f(9, *range(11, 13)), (9, (11, 12))) def test_sorted_kwargs(self): """verify we can call sorted w/ keyword args""" import operator inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)] getcount = operator.itemgetter(1) sorted_inventory = sorted(inventory, key=getcount) def test_kwargs2(self): """verify proper handling of keyword args for python functions""" def kwfunc(a,b,c): pass try: kwfunc(10, 20, b=30) self.assertTrue(False) except TypeError: pass try: kwfunc(10, None, b=30) self.assertTrue(False) except TypeError: pass try: kwfunc(10, None, 40, b=30) self.assertTrue(False) except TypeError: pass if is_cli: import System # Test Hashtable and Dictionary. htlist = [System.Collections.Generic.Dictionary[System.Object, System.Object]()] htlist += [System.Collections.Hashtable()] for ht in htlist: def foo(**kwargs): return kwargs['key'] ht['key'] = 'xyz' self.assertEqual(foo(**ht), 'xyz') def foo(a,b): return a-b self.assertEqual(foo(b=1, *(2,)), 1) # kw-args passed to init through method instance s = self class foo: def __init__(self, group=None, target=None): s.assertEqual(group, None) s.assertEqual(target,'baz') a = foo(target='baz') foo.__init__(a, target='baz') @skipUnlessIronPython() def test_params_method_no_params(self): """call a params method w/ no params""" import clr import System self.assertEqual('abc\ndef'.Split()[0], 'abc') self.assertEqual('abc\ndef'.Split()[1], 'def') x = 'a bc def'.Split() self.assertEqual(x[0], 'a') self.assertEqual(x[1], 'bc') self.assertEqual(x[2], '') self.assertEqual(x[3], '') self.assertEqual(x[4], 'def') # calling Double.ToString(...) should work - Double is # an OpsExtensibleType and doesn't define __str__ on this # overload self.assertEqual(System.Double.ToString(1.0, 'f', System.Globalization.CultureInfo.InvariantCulture), '1.00') def test_incorrect_number_of_args(self): """Incorrect number of arguments""" def f(a): pass if is_cli: self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (0 given)", f) self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (3 given)", f, 1, 2, 3) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", f) self.assertRaisesMessage(TypeError, "f() takes 1 positional argument but 3 were given", f, 1, 2, 3) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, dummy=2) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, dummy=2) #self.assertRaises calls f(*args), which generates a different AST than f(1,2,3) if is_cli: self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (0 given)", lambda:f()) self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (3 given)", lambda:f(1, 2, 3)) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", lambda:f()) self.assertRaisesMessage(TypeError, "f() takes 1 positional argument but 3 were given", lambda:f(1, 2, 3)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(dummy=2)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(1, dummy=2)) def f(a,b,c,d,e,f,g,h,i,j): pass if is_cli: self.assertRaisesMessage(TypeError, "f() takes exactly 10 arguments (0 given)", f) self.assertRaisesMessage(TypeError, "f() takes exactly 10 arguments (3 given)", f, 1, 2, 3) else: self.assertRaisesMessage(TypeError, "f() missing 10 required positional arguments: 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', and 'j'", f) self.assertRaisesMessage(TypeError, "f() missing 7 required positional arguments: 'd', 'e', 'f', 'g', 'h', 'i', and 'j'", f, 1, 2, 3) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, dummy=2) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, dummy=2) if is_cli: self.assertRaisesMessage(TypeError, "f() takes exactly 10 arguments (0 given)", lambda:f()) self.assertRaisesMessage(TypeError, "f() takes exactly 10 arguments (3 given)", lambda:f(1, 2, 3)) else: self.assertRaisesMessage(TypeError, "f() missing 10 required positional arguments: 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', and 'j'", lambda:f()) self.assertRaisesMessage(TypeError, "f() missing 7 required positional arguments: 'd', 'e', 'f', 'g', 'h', 'i', and 'j'", lambda:f(1, 2, 3)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(dummy=2)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(1, dummy=2)) def f(a, b=2): pass if is_cli: self.assertRaisesMessage(TypeError, "f() takes at least 1 argument (0 given)", f) self.assertRaisesMessage(TypeError, "f() takes at most 2 arguments (3 given)", f, 1, 2, 3) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", f) self.assertRaisesMessage(TypeError, "f() takes from 1 to 2 positional arguments but 3 were given", f, 1, 2, 3) if is_cli: #CPython bug 9326 self.assertRaisesMessage(TypeError, "f() takes at least 1 non-keyword argument (0 given)", f, b=2) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", f, b=2) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, dummy=3) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, b=2, dummy=3) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, 1, dummy=3) if is_cli: self.assertRaisesMessage(TypeError, "f() takes at least 1 argument (0 given)", lambda:f()) self.assertRaisesMessage(TypeError, "f() takes at most 2 arguments (3 given)", lambda:f(1, 2, 3)) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", lambda:f()) self.assertRaisesMessage(TypeError, "f() takes from 1 to 2 positional arguments but 3 were given", lambda:f(1, 2, 3)) if is_cli: #CPython bug 9326 self.assertRaisesMessage(TypeError, "f() takes at least 1 non-keyword argument (0 given)", lambda:f(b=2)) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", lambda:f(b=2)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(dummy=3)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(b=2, dummy=3)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(1, dummy=3)) def f(a, *argList): pass if is_cli: self.assertRaisesMessage(TypeError, "f() takes at least 1 argument (0 given)", f) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", f) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, dummy=2) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", f, 1, dummy=2) if is_cli: self.assertRaisesMessage(TypeError, "f() takes at least 1 argument (0 given)", lambda:f()) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", lambda:f()) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(dummy=2)) self.assertRaisesMessage(TypeError, "f() got an unexpected keyword argument 'dummy'", lambda:f(1, dummy=2)) def f(a, **keywordDict): pass if is_cli: self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (0 given)", f) self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (3 given)", f, 1, 2, 3) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", f) self.assertRaisesMessage(TypeError, "f() takes 1 positional argument but 3 were given", f, 1, 2, 3) if is_cli: #CPython bug 9326 self.assertRaisesMessage(TypeError, "f() takes exactly 1 non-keyword argument (0 given)", f, dummy=2) self.assertRaisesMessage(TypeError, "f() takes exactly 1 non-keyword argument (0 given)", f, dummy=2, dummy2=3) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", f, dummy=2) self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", f, dummy=2, dummy2=3) if is_cli: self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (0 given)", lambda:f()) self.assertRaisesMessage(TypeError, "f() takes exactly 1 argument (3 given)", lambda:f(1, 2, 3)) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", lambda:f()) self.assertRaisesMessage(TypeError, "f() takes 1 positional argument but 3 were given", lambda:f(1, 2, 3)) if is_cli: #CPython bug 9326 self.assertRaisesMessage(TypeError, "f() takes exactly 1 non-keyword argument (0 given)", lambda:f(dummy=2)) self.assertRaisesMessage(TypeError, "f() takes exactly 1 non-keyword argument (0 given)", lambda:f(dummy=2, dummy2=3)) else: self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", lambda:f(dummy=2)) self.assertRaisesMessage(TypeError, "f() missing 1 required positional argument: 'a'", lambda:f(dummy=2, dummy2=3)) if is_cli: self.assertRaisesMessage(TypeError, "abs() takes exactly 1 argument (0 given)", abs) self.assertRaisesMessage(TypeError, "abs() takes exactly 1 argument (3 given)", abs, 1, 2, 3) self.assertRaisesMessage(TypeError, "abs() got an unexpected keyword argument 'dummy'", abs, dummy=2) self.assertRaisesMessage(TypeError, "abs() takes exactly 1 argument (2 given)", abs, 1, dummy=2) self.assertRaisesMessage(TypeError, "abs() takes exactly 1 argument (0 given)", lambda:abs()) self.assertRaisesMessage(TypeError, "abs() takes exactly 1 argument (3 given)", lambda:abs(1, 2, 3)) self.assertRaisesMessage(TypeError, "abs() got an unexpected keyword argument 'dummy'", lambda:abs(dummy=2)) self.assertRaisesMessage(TypeError, "abs() takes exactly 1 argument (2 given)", lambda:abs(1, dummy=2)) else: self.assertRaisesMessage(TypeError, "abs() takes exactly one argument (0 given)", abs) self.assertRaisesMessage(TypeError, "abs() takes exactly one argument (3 given)", abs, 1, 2, 3) self.assertRaisesMessage(TypeError, "abs() takes no keyword arguments", abs, dummy=2) self.assertRaisesMessage(TypeError, "abs() takes no keyword arguments", abs, 1, dummy=2) self.assertRaisesMessage(TypeError, "abs() takes exactly one argument (0 given)", lambda:abs()) self.assertRaisesMessage(TypeError, "abs() takes exactly one argument (3 given)", lambda:abs(1, 2, 3)) self.assertRaisesMessage(TypeError, "abs() takes no keyword arguments", lambda:abs(dummy=2)) self.assertRaisesMessage(TypeError, "abs() takes no keyword arguments", lambda:abs(1, dummy=2)) # list([m]) has one default argument (built-in type) #self.assertRaisesMessage(TypeError, "list() takes at most 1 argument (2 given)", list, 1, 2) #self.assertRaisesMessage(TypeError, "'dummy' is an invalid keyword argument for this function", apply, list, [], dict({"dummy":2})) #======== BUG 697 =========== #self.assertRaisesMessage(TypeError, "'dummy' is an invalid keyword argument for this function", apply, list, [1], dict({"dummy":2})) # complex([x,y]) has two default argument (OpsReflectedType type) #self.assertRaisesMessage(TypeError, "complex() takes at most 2 arguments (3 given)", complex, 1, 2, 3) #self.assertRaisesMessage(TypeError, "'dummy' is an invalid keyword argument for this function", apply, complex, [], dict({"dummy":2})) #self.assertRaisesMessage(TypeError, "'dummy' is an invalid keyword argument for this function", apply, complex, [1], dict({"dummy":2})) # bool([x]) has one default argument (OpsReflectedType and valuetype type) #self.assertRaisesMessage(TypeError, "bool() takes at most 1 argument (2 given)", bool, 1, 2) #self.assertRaisesMessage(TypeError, "'dummy' is an invalid keyword argument for this function", apply, bool, [], dict({"dummy":2})) #self.assertRaisesMessage(TypeError, "'dummy' is an invalid keyword argument for this function", apply, bool, [1], dict({"dummy":2})) class UserClass(object): pass if is_cli: self.assertRaisesMessage(TypeError, "object.__new__() takes no parameters", UserClass, 1) with self.assertRaisesMessage(TypeError, "object.__new__() takes no parameters"): UserClass(*[], **dict({"dummy":2})) else: self.assertRaisesMessage(TypeError, "object() takes no parameters", UserClass, 1) with self.assertRaisesMessage(TypeError, "object() takes no parameters"): UserClass(*[], **dict({"dummy":2})) class OldStyleClass: pass if is_cli: self.assertRaisesMessage(TypeError, "object.__new__() takes no parameters", OldStyleClass, 1) with self.assertRaisesMessage(TypeError, "object.__new__() takes no parameters"): OldStyleClass(*[], **dict({"dummy":2})) else: self.assertRaisesMessage(TypeError, "object() takes no parameters", OldStyleClass, 1) with self.assertRaisesMessage(TypeError, "object() takes no parameters"): OldStyleClass(*[], **dict({"dummy":2})) @skipUnlessIronPython() def test_runtime_type_checking(self): """accepts / returns runtype type checking tests""" import clr @clr.accepts(object) def foo(x): return x self.assertEqual(foo('abc'), 'abc') self.assertEqual(foo(2), 2) self.assertEqual(foo(long(2)), long(2)) self.assertEqual(foo(2.0), 2.0) self.assertEqual(foo(True), True) @clr.accepts(str) def foo(x): return x self.assertEqual(foo('abc'), 'abc') self.assertRaises(AssertionError, foo, 2) self.assertRaises(AssertionError, foo, long(2)) self.assertRaises(AssertionError, foo, 2.0) self.assertRaises(AssertionError, foo, True) @clr.accepts(str, bool) def foo(x, y): return x, y self.assertEqual(foo('abc', True), ('abc', True)) self.assertRaises(AssertionError, foo, ('abc',2)) self.assertRaises(AssertionError, foo, ('abc',long(2))) self.assertRaises(AssertionError, foo, ('abc',2.0)) class bar: @clr.accepts(clr.Self(), str) def foo(self, x): return x a = bar() self.assertEqual(a.foo('xyz'), 'xyz') self.assertRaises(AssertionError, a.foo, 2) self.assertRaises(AssertionError, a.foo, long(2)) self.assertRaises(AssertionError, a.foo, 2.0) self.assertRaises(AssertionError, a.foo, True) @clr.returns(str) def foo(x): return x self.assertEqual(foo('abc'), 'abc') self.assertRaises(AssertionError, foo, 2) self.assertRaises(AssertionError, foo, long(2)) self.assertRaises(AssertionError, foo, 2.0) self.assertRaises(AssertionError, foo, True) @clr.accepts(bool) @clr.returns(str) def foo(x): if x: return str(x) else: return 0 self.assertEqual(foo(True), 'True') self.assertRaises(AssertionError, foo, 2) self.assertRaises(AssertionError, foo, long(2)) self.assertRaises(AssertionError, foo, False) @clr.returns(None) def foo(): pass self.assertEqual(foo(), None) def test_error_message(self): try: repr() except TypeError as e: # make sure we get the right type name when calling w/ wrong # of args self.assertTrue(str(e).startswith("repr()")) def test_caller_context(self): # access a method w/ caller context w/ an args parameter. def foo(*args): return hasattr(*args) self.assertEqual(foo('', 'index'), True) @skipUnlessIronPython() def test_dispatch_to_ReflectOptimized(self): """dispatch to a ReflectOptimized method""" from iptest.console_util import IronPythonInstance from System import Environment from sys import executable wkdir = self.test_dir if "-X:LightweightScopes" in Environment.GetCommandLineArgs(): ipi = IronPythonInstance(executable, wkdir, "-X:LightweightScopes", "-X:BasicConsole") else: ipi = IronPythonInstance(executable, wkdir, "-X:BasicConsole") if (ipi.Start()): try: result = ipi.ExecuteLine("from iptest.ipunittest import load_ironpython_test") result = ipi.ExecuteLine("load_ironpython_test()") result = ipi.ExecuteLine("from IronPythonTest import DefaultParams") response = ipi.ExecuteLine("DefaultParams.FuncWithDefaults(1100, z=82)") self.assertEqual(response, '1184') finally: ipi.End() def test_zip(self): p = ((1, 2),) self.assertEqual(list(zip(*(p * 10))), [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2, 2, 2, 2)]) self.assertEqual(list(zip(*(p * 10))), [(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2, 2, 2, 2)]) def test_super(self): class A(object): pass class B(A): pass #unbound super for x in [super(B), super(B,None)]: self.assertEqual(x.__thisclass__, B) self.assertEqual(x.__self__, None) self.assertEqual(x.__self_class__, None) # super w/ both types x = super(B,B) self.assertEqual(x.__thisclass__,B) self.assertEqual(x.__self_class__, B) self.assertEqual(x.__self__, B) # super w/ type and instance b = B() x = super(B, b) self.assertEqual(x.__thisclass__,B) self.assertEqual(x.__self_class__, B) self.assertEqual(x.__self__, b) # super w/ mixed types x = super(A,B) self.assertEqual(x.__thisclass__,A) self.assertEqual(x.__self_class__, B) self.assertEqual(x.__self__, B) # invalid super cases try: x = super(B, 'abc') self.assertUnreachable() except TypeError: pass try: super(B,A) self.assertUnreachable() except TypeError: pass class A(object): def __init__(self, name): self.__name__ = name def meth(self): return self.__name__ classmeth = classmethod(meth) class B(A): pass b = B('derived') self.assertEqual(super(B,b).__thisclass__.__name__, 'B') self.assertEqual(super(B,b).__self__.__name__, 'derived') self.assertEqual(super(B,b).__self_class__.__name__, 'B') self.assertEqual(super(B,b).classmeth(), 'B') # descriptor supper class A(object): def meth(self): return 'A' class B(A): def meth(self): return 'B' + self.__super.meth() B._B__super = super(B) b = B() self.assertEqual(b.meth(), 'BA') def test_class_method_calls(self): """class method should get correct meta class.""" class D(object): @classmethod def classmeth(cls): pass self.assertEqual(D.classmeth.__class__, MethodType) class MetaType(type): pass class D(object, metaclass = MetaType): @classmethod def classmeth(cls): pass self.assertEqual(D.classmeth.__class__, MethodType) def test_cases(self): def runTest(testCase): class foo(testCase.subtype): def __new__(cls, param): ret = testCase.subtype.__new__(cls, param) self.assertTrue(ret == testCase.newEq) self.assertTrue((ret != testCase.newEq) != True) return ret def __init__(self, param): testCase.subtype.__init__(self, param) self.assertTrue(self == testCase.initEq) self.assertTrue((self != testCase.initEq) != True) a = foo(testCase.param) self.assertTrue((type(a) == foo) == testCase.match) class TestCase(object): __slots__ = ['subtype', 'newEq', 'initEq', 'match', 'param'] def __init__(self, subtype, newEq, initEq, match, param): self.match = match self.subtype = subtype self.newEq = newEq self.initEq = initEq self.param = param cases = [TestCase(int, 2, 2, True, 2), TestCase(list, [], [2,3,4], True, (2,3,4)), TestCase(deque, deque(), deque((2,3,4)), True, (2,3,4)), TestCase(set, set(), set((2,3,4)), True, (2,3,4)), TestCase(frozenset, frozenset((2,3,4)), frozenset((2,3,4)), True, (2,3,4)), TestCase(tuple, (2,3,4), (2,3,4), True, (2,3,4)), TestCase(str, 'abc', 'abc', True, 'abc'), TestCase(float, 2.3, 2.3, True, 2.3), TestCase(type, type(object), type(object), False, object), TestCase(long, long(10000000000), long(10000000000), True, long(10000000000)), #TestCase(complex, complex(2.0, 0), complex(2.0, 0), True, 2.0), # complex is currently a struct w/ no extensibel, we fail here # TestCase(file, 'abc', True), # ??? ] for case in cases: runTest(case) @unittest.skipIf(is_posix or is_netcoreapp, 'missing System.Windows.Forms support') @skipUnlessIronPython() def test_call_base_init(self): """verify we can call the base init directly""" import clr clr.AddReferenceByPartialName('System.Windows.Forms') from System.Windows.Forms import Form class MyForm(Form): def __init__(self, title): Form.__init__(self) self.Text = title a = MyForm('abc') self.assertEqual(a.Text, 'abc') #TestCase(bool, True, True), # not an acceptable base type def test_func_flags(self): def foo0(): pass def foo1(*args): pass def foo2(**args): pass def foo3(*args, **kwargs): pass def foo4(a): pass def foo5(a, *args): pass def foo6(a, **args): pass def foo7(a, *args, **kwargs): pass def foo8(a,b,c,d,e,f): pass def foo9(a,b): pass self.assertEqual(foo0.__code__.co_flags & 12, 0) self.assertEqual(foo1.__code__.co_flags & 12, 4) self.assertEqual(foo2.__code__.co_flags & 12, 8) self.assertEqual(foo3.__code__.co_flags & 12, 12) self.assertEqual(foo4.__code__.co_flags & 12, 0) self.assertEqual(foo5.__code__.co_flags & 12, 4) self.assertEqual(foo6.__code__.co_flags & 12, 8) self.assertEqual(foo7.__code__.co_flags & 12, 12) self.assertEqual(foo8.__code__.co_flags & 12, 0) self.assertEqual(foo9.__code__.co_flags & 12, 0) self.assertEqual(foo0.__code__.co_argcount, 0) self.assertEqual(foo1.__code__.co_argcount, 0) self.assertEqual(foo2.__code__.co_argcount, 0) self.assertEqual(foo3.__code__.co_argcount, 0) self.assertEqual(foo4.__code__.co_argcount, 1) self.assertEqual(foo5.__code__.co_argcount, 1) self.assertEqual(foo6.__code__.co_argcount, 1) self.assertEqual(foo7.__code__.co_argcount, 1) self.assertEqual(foo8.__code__.co_argcount, 6) self.assertEqual(foo9.__code__.co_argcount, 2) def test_big_calls(self): # check various function call sizes and boundaries sizes = [3, 4, 5, 7, 8, 9, 13, 15, 16, 17, 23, 24, 25, 31, 32, 33, 47, 48, 49, 63, 64, 65, 127, 128, 129, 254, 255, 256, 257, 258, 511, 512, 513] # mono has a limitation of < 1023 if not is_mono: sizes.extend([1023, 1024, 1025, 2047, 2048, 2049]) for size in sizes: d = {} # w/o defaults if size <= 255 or is_cli: exec('def f(' + ','.join(['a' + str(i) for i in range(size)]) + '): return ' + ','.join(['a' + str(i) for i in range(size)]), d) else: with self.assertRaises(SyntaxError): exec('def f(' + ','.join(['a' + str(i) for i in range(size)]) + '): return ' + ','.join(['a' + str(i) for i in range(size)]), d) continue # w/ defaults exec('def g(' + ','.join(['a' + str(i) + '=' + str(i) for i in range(size)]) + '): return ' + ','.join(['a' + str(i) for i in range(size)]), d) if size <= 255 or is_cli: # CPython allows function definitions > 255, but not calls w/ > 255 params. exec('a = f(' + ', '.join([str(x) for x in range(size)]) + ')', d) self.assertEqual(d["a"], tuple(range(size))) exec('a = g()', d) self.assertEqual(d["a"], tuple(range(size))) exec('a = g(' + ', '.join([str(x) for x in range(size)]) + ')', d) self.assertEqual(d["a"], tuple(range(size))) exec('a = f(*(' + ', '.join([str(x) for x in range(size)]) + '))', d) self.assertEqual(d["a"], tuple(range(size))) def test_compile(self): x = compile("print(2/3)", "<string>", "exec", 8192) if is_cli: self.assertEqual(x.co_flags & 8192, 0) else: self.assertEqual(x.co_flags & 8192, 8192) x = compile("2/3", "<string>", "eval", 8192) self.assertEqual(eval(x), 2.0 / 3.0) names = [ "", ".", "1", "\n", " ", "@", "%^", "a", "A", "Abc", "aBC", "filename.py", "longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong", """ stuff more stuff last stuff """ ] for name in names: self.assertEqual(compile("print(2/3)", name, "exec", 8192).co_filename, name) def test_filename(self): c = compile("x = 2", "test", "exec") self.assertEqual(c.co_filename, 'test') def test_name(self): def f(): pass f.__name__ = 'g' self.assertEqual(f.__name__, 'g') if is_cli: self.assertTrue(repr(f).startswith('<function g')) else: self.assertTrue(repr(f).startswith('<function FunctionTest.test_name.<locals>.f')) f.__qualname__ = 'x' self.assertEqual(f.__qualname__, 'x') if is_cli: self.assertTrue(repr(f).startswith('<function g')) else: self.assertTrue(repr(f).startswith('<function x')) def test_argcount(self): def foo0(): pass def foo1(*args): pass def foo2(**args): pass def foo3(*args, **kwargs): pass def foo4(a): pass def foo5(a, *args): pass def foo6(a, **args): pass def foo7(a, *args, **kwargs): pass def foo8(a,b,c,d,e,f): pass def foo9(a,b): pass self.assertEqual(foo0.__code__.co_argcount, 0) self.assertEqual(foo1.__code__.co_argcount, 0) self.assertEqual(foo2.__code__.co_argcount, 0) self.assertEqual(foo3.__code__.co_argcount, 0) self.assertEqual(foo4.__code__.co_argcount, 1) self.assertEqual(foo5.__code__.co_argcount, 1) self.assertEqual(foo6.__code__.co_argcount, 1) self.assertEqual(foo7.__code__.co_argcount, 1) self.assertEqual(foo8.__code__.co_argcount, 6) self.assertEqual(foo9.__code__.co_argcount, 2) def test_defaults(self): defaults = [None, object, int, [], 3.14, [3.14], (None,), "a string"] for default in defaults: def helperFunc(): pass self.assertEqual(helperFunc.__defaults__, None) self.assertEqual(helperFunc.__defaults__, None) def helperFunc1(a): pass self.assertEqual(helperFunc1.__defaults__, None) self.assertEqual(helperFunc1.__defaults__, None) def helperFunc2(a=default): pass self.assertEqual(helperFunc2.__defaults__, (default,)) helperFunc2(a=7) self.assertEqual(helperFunc2.__defaults__, (default,)) def helperFunc3(a, b=default, c=[42]): c.append(b) self.assertEqual(helperFunc3.__defaults__, (default, [42])) helperFunc3("stuff") self.assertEqual(helperFunc3.__defaults__, (default, [42, default])) def test_splat_defaults(self): def g(a, b, x=None): return a, b, x def f(x, *args): return g(x, *args) self.assertEqual(f(1, *(2,)), (1,2,None)) def test_argument_eval_order(self): """Check order of evaluation of function arguments""" x = [1] def noop(a, b, c): pass noop(x.append(2), x.append(3), x.append(4)) self.assertEqual(x, [1,2,3,4]) def test_method_attr_access(self): class foo(object): def f(self): pass abc = 3 self.assertEqual(MethodType(foo, 'abc').abc, 3) #TODO: @skip("interpreted") # we don't have FuncEnv's in interpret modes so this always returns None def test_function_closure_negative(self): def f(): pass for assignment_val in [None, 1, "a string"]: with self.assertRaises(AttributeError): f.__closure__ = assignment_val def test_paramless_function_call_error(self): def f(): pass try: f(*(1, )) self.assertUnreachable() except TypeError: pass try: f(**{'abc':'def'}) self.assertUnreachable() except TypeError: pass def test_function_closure(self): def f(): pass self.assertEqual(f.__closure__, None) def f(): def g(): pass return g self.assertEqual(f().__closure__, None) def f(): x = 4 def g(): return x return g self.assertEqual(sorted([x.cell_contents for x in f().__closure__]), [4]) def f(): x = 4 def g(): y = 5 def h(): return x,y return h return g() self.assertEqual(sorted([x.cell_contents for x in f().__closure__]), [4, 5]) # don't use z def f(): x = 4 def g(): y = 5 z = 7 def h(): return x,y return h return g() self.assertEqual(sorted([x.cell_contents for x in f().__closure__]), [4, 5]) def f(): x = 4 def g(): y = 5 z = 7 def h(): return x,y,z return h return g() self.assertEqual(sorted([x.cell_contents for x in f().__closure__]), [4, 5, 7]) def f(): x = 4 a = 9 def g(): y = 5 z = 7 def h(): return x,y return h return g() self.assertEqual(sorted([x.cell_contents for x in f().__closure__]), [4, 5]) # closure cells are not recreated callRes = f() a = sorted([id(x) for x in callRes.__closure__]) b = sorted([id(x) for x in callRes.__closure__]) self.assertEqual(a, b) def f(): x = 4 a = 9 def g(): y = 5 z = 7 def h(): return x,y,a,z return h return g() self.assertEqual(sorted([x.cell_contents for x in f().__closure__]), [4, 5, 7, 9]) self.assertRaises(TypeError, hash, f().__closure__[0]) def f(): x = 5 def g(): return x return g def h(): x = 5 def g(): return x return g def j(): x = 6 def g(): return x return g self.assertEqual(f().__closure__[0], h().__closure__[0]) self.assertTrue(f().__closure__[0] != j().__closure__[0]) # <cell at 45: int object at 44> self.assertTrue(repr(f().__closure__[0]).startswith('<cell at ')) self.assertTrue(repr(f().__closure__[0]).find(': int object at ') != -1) def test_func_code(self): def foo(): pass def assign(): foo.__code__ = None self.assertRaises(TypeError, assign) def def_func_doc(self): foo.func_doc = 'abc' self.assertEqual(foo.__doc__, 'abc') foo.__doc__ = 'def' self.assertEqual(foo.func_doc, 'def') foo.func_doc = None self.assertEqual(foo.__doc__, None) self.assertEqual(foo.func_doc, None) def test_func_defaults(self): def f(a, b): return (a, b) f.__defaults__ = (1,2) self.assertEqual(f(), (1,2)) f.__defaults__ = (1,2,3,4) self.assertEqual(f(), (3,4)) f.__defaults__ = None self.assertRaises(TypeError, f) f.__defaults__ = (1,2) self.assertEqual(f.__defaults__, (1,2)) del f.__defaults__ self.assertEqual(f.__defaults__, None) del f.__defaults__ self.assertEqual(f.__defaults__, None) def func_with_many_args(one, two, three, four, five, six, seven, eight, nine, ten, eleven=None, twelve=None, thirteen=None, fourteen=None, fifteen=None, sixteen=None, seventeen=None, eighteen=None, nineteen=None): print('hello') func_with_many_args(None, None, None, None, None, None, None, None, None, None) def test_func_dict(self): def f(): pass f.abc = 123 self.assertEqual(f.__dict__, {'abc': 123}) f.__dict__ = {'def': 'def'} self.assertEqual(hasattr(f, 'def'), True) self.assertEqual(getattr(f, 'def'), 'def') f.__dict__ = {} self.assertEqual(hasattr(f, 'abc'), False) self.assertEqual(hasattr(f, 'def'), False) self.assertRaises(TypeError, lambda : delattr(f, '__dict__')) def test_method(self): method = MethodType(id, object()) self.assertEqual(method.__class__, MethodType) class myobj: def __init__(self, val): self.val = val self.called = [] def __hash__(self): self.called.append('hash') return hash(self.val) def __eq__(self, other): self.called.append('eq') return self.val == other.val def __call__(*args): pass func1, func2 = myobj(2), myobj(2) inst1, inst2 = myobj(3), myobj(3) m1 = MethodType(func1, inst1) m2 = MethodType(func2, inst2) self.assertEqual(m1, m2) self.assertTrue('eq' in func1.called) self.assertTrue('eq' in inst1.called) hash(m1) self.assertTrue('hash' in func1.called) self.assertTrue('hash' in inst1.called) def test_function_type(self): def f1(): pass def f2(a): pass def f3(a, b, c): pass def f4(*a, **b): pass def decorator(f): return f @decorator def f5(a): pass for x in [ f2, f3, f4, f5]: self.assertEqual(type(f1), type(x)) def test_name_mangled_params(self): def f1(__a): pass def f2(__a): return __a def f3(a, __a): return __a def f4(_a, __a): return _a + __a f1("12") self.assertEqual(f2("hello"), "hello") self.assertEqual(f3("a","b"), "b") self.assertEqual(f4("a","b"), "ab") def test_splat_none(self): def f(*args): pass def g(**kwargs): pass def h(*args, **kwargs): pass #CodePlex 20250 self.assertRaisesMessage(TypeError, "f() argument after * must be a sequence, not NoneType", lambda : f(*None)) self.assertRaisesMessage(TypeError, "g() argument after ** must be a mapping, not NoneType", lambda : g(**None)) self.assertRaisesMessage(TypeError, "h() argument after ** must be a mapping, not NoneType", lambda : h(*None, **None)) def test_exec_funccode(self): # can't exec a func code w/ parameters def f(a, b, c): print(a, b, c) self.assertRaises(TypeError, lambda : eval(f.__code__)) # can exec *args/**args def f(*args): pass exec(f.__code__, {}, {}) def f(*args, **kwargs): pass exec(f.__code__, {}, {}) # can't exec function which closes over vars def f(): x = 2 def g(): print(x) return g.__code__ self.assertRaises(TypeError, lambda : eval(f())) def test_exec_funccode_filename(self): import sys mod = type(sys)('fake_mod_name') mod.__file__ = 'some file' exec("def x(): pass", mod.__dict__) self.assertEqual(mod.x.__code__.co_filename, '<string>') def test_func_code_variables(self): def CompareCodeVars(code, varnames, names, freevars, cellvars): self.assertEqual(code.co_varnames, varnames) self.assertEqual(code.co_names, names) self.assertEqual(code.co_freevars, freevars) self.assertEqual(code.co_cellvars, cellvars) # simple local def f(): a = 2 CompareCodeVars(f.__code__, ('a', ), (), (), ()) # closed over var def f(): a = 2 def g(): a return g CompareCodeVars(f.__code__, ('g', ), (), (), ('a', )) CompareCodeVars(f().__code__, (), (), ('a', ), ()) # explicitly marked global def f(): global a a = 2 CompareCodeVars(f.__code__, (), ('a', ), (), ()) # implicit global def f(): some_global CompareCodeVars(f.__code__, (), ('some_global', ), (), ()) # global that's been "closed over" def f(): global a a = 2 def g(): a return g CompareCodeVars(f.__code__, ('g', ), ('a', ), (), ()) CompareCodeVars(f().__code__, (), ('a', ), (), ()) # multi-depth closure def f(): a = 2 def g(): x = a def h(): y = a return h return g CompareCodeVars(f.__code__, ('g', ), (), (), ('a', )) CompareCodeVars(f().__code__, ('x', 'h'), (), ('a', ), ()) CompareCodeVars(f()().__code__, ('y', ), (), ('a', ), ()) # multi-depth closure 2 def f(): a = 2 def g(): def h(): y = a return h return g CompareCodeVars(f.__code__, ('g', ), (), (), ('a', )) CompareCodeVars(f().__code__, ('h', ), (), ('a', ), ()) CompareCodeVars(f()().__code__, ('y', ), (), ('a', ), ()) # closed over parameter def f(a): def g(): return a return g CompareCodeVars(f.__code__, ('a', 'g'), (), (), ('a', )) CompareCodeVars(f(42).__code__, (), (), ('a', ), ()) def test_delattr(self): def f(): pass f.abc = 42 del f.abc def g(): f.abc self.assertRaises(AttributeError, g) def test_cp35180(self): def foo(): return 13 def bar(): return 42 dpf = copyfunc(foo, "dpf") self.assertEqual(dpf(), 13) foo.__code__ = bar.__code__ self.assertEqual(foo(), 42) self.assertEqual(dpf(), 13) self.assertEqual(foo.__module__, '__main__') self.assertEqual(dpf.__module__, '__main__') def test_cp34932(self): def get_global_variable(): return global_variable def set_global_variable(v): global global_variable global_variable = v alt_globals = {'global_variable' : 66 } get_global_variable_x = substitute_globals(get_global_variable, "get_global_variable_x", alt_globals) set_global_variable_x = substitute_globals(set_global_variable, "set_global_variable_x", alt_globals) self.assertEqual(get_global_variable(), 13) self.assertEqual(get_global_variable_x(), 66) self.assertEqual(get_global_variable(), 13) set_global_variable_x(7) self.assertEqual(get_global_variable_x(), 7) self.assertEqual(get_global_variable(), 13) self.assertEqual(get_global_variable_x.__module__, None) self.assertEqual(set_global_variable_x.__module__, None) get_global_variable_y = substitute_globals(get_global_variable, "get_global_variable_x", globals()) self.assertEqual(get_global_variable_y(), 13) self.assertEqual(get_global_variable_y.__module__, '__main__') def test_issue1351(self): class X(object): def __init__(self, res): self.called = [] self.res = res def __eq__(self, other): self.called.append('eq') return self.res def foo(self): pass a = X(True) b = X(False) self.assertEqual(a.foo, a.foo) self.assertNotIn('eq', a.called) self.assertEqual(a.foo, b.foo) self.assertIn('eq', a.called) self.assertEqual(b.foo, b.foo) self.assertNotIn('eq', b.called) self.assertNotEqual(b.foo, a.foo) self.assertIn('eq', b.called) @unittest.skipUnless(is_cli, "NotImplementedError only on IronPython") def test_function_type(self): fn_with_closure = create_fn_with_closure() def fn_no_closure(): pass self.assertRaises(NotImplementedError, copyfunc, fn_with_closure, "new_fn_name") self.assertRaises(NotImplementedError, FunctionType, fn_with_closure.__code__, fn_with_closure.__globals__, "name", fn_with_closure.__defaults__) self.assertRaises(NotImplementedError, FunctionType, fn_with_closure.__code__, fn_with_closure.__globals__, "name", fn_with_closure.__defaults__, fn_with_closure.__closure__) self.assertRaises(NotImplementedError, FunctionType, fn_no_closure.__code__, fn_no_closure.__globals__, "name", fn_no_closure.__defaults__, fn_with_closure.__closure__) run_test(__name__)
37.731214
347
0.562294
6,433
52,220
4.399036
0.089227
0.09488
0.11534
0.07813
0.59571
0.53804
0.477084
0.450263
0.436941
0.410651
0
0.035075
0.301168
52,220
1,383
348
37.758496
0.740389
0.071505
0
0.386497
0
0.003914
0.122231
0.011127
0.000978
0
0
0.000723
0.351272
1
0.220157
false
0.074364
0.015656
0.055773
0.319961
0.004892
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
1eee071e692e59954d230ecaeffaf649dc249395
240
py
Python
yambopy/bse/__init__.py
QU-XIAO/yambopy
ff65a4f90c1bfefe642ebc61e490efe781709ff9
[ "BSD-3-Clause" ]
21
2016-04-07T20:53:29.000Z
2021-05-14T08:06:02.000Z
yambopy/bse/__init__.py
alexmoratalla/yambopy
8ec0e1e18868ccaadb3eab36c55e6a47021e257d
[ "BSD-3-Clause" ]
22
2016-06-14T22:29:47.000Z
2021-09-16T15:36:26.000Z
yambopy/bse/__init__.py
alexmoratalla/yambopy
8ec0e1e18868ccaadb3eab36c55e6a47021e257d
[ "BSD-3-Clause" ]
15
2016-06-14T18:40:57.000Z
2021-08-07T13:17:43.000Z
# Copyright (C) 2018 Henrique Pereira Coutada Miranda # All rights reserved. # # This file is part of yambopy # # """ submodule with classes to read BSE optical absorption spectra claculations and information about the excitonic states """
21.818182
74
0.770833
32
240
5.78125
1
0
0
0
0
0
0
0
0
0
0
0.02
0.166667
240
10
75
24
0.905
0.916667
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
1ef17d4bf1909adc19f7d687d9500270c2c5a6a0
1,712
py
Python
janggoCompany/apply/models.py
jangheeseung/janggo_system
d251ad88483aa4a4ca43183cdb5d72ff98213540
[ "MIT" ]
null
null
null
janggoCompany/apply/models.py
jangheeseung/janggo_system
d251ad88483aa4a4ca43183cdb5d72ff98213540
[ "MIT" ]
null
null
null
janggoCompany/apply/models.py
jangheeseung/janggo_system
d251ad88483aa4a4ca43183cdb5d72ff98213540
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. TYPE_CHOICES = ( ('intern','intern'), ('employee','employee') ) class Hire(models.Model): kind = models.CharField(max_length=125) num = models.IntegerField() hire_type = models.CharField(max_length=125, choices=TYPE_CHOICES) created_at = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField() end_date = models.DateTimeField() content1 = models.TextField() content2 = models.TextField() def __str__(self): return self.kind def summary(self): return self.kind[:20] class Apply(models.Model): name = models.CharField(max_length=125, blank=True, null=True) age = models.IntegerField() phone = models.CharField(max_length=125, blank=True, null=True) e_mail = models.CharField(max_length=125, blank=True, null=True) address = models.CharField(max_length=125, blank=True, null=True) password = models.CharField(max_length=125, blank=True, null=True) college = models.CharField(max_length=125, blank=True, null=True) major = models.CharField(max_length=125, blank=True, null=True) graduate = models.BooleanField(default=False) document = models.FileField(upload_to='documents/', null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) hire = models.ForeignKey(Hire, on_delete = models.CASCADE) # 업로드된 파일과 객체를 삭제하는 메서드 def delete(self, *args, **kwargs): self.document.delete() self.filtered_document.delete() super(Apply, self).delete(*args, **kwargs) def __str__(self): return self.name
33.568627
70
0.688668
216
1,712
5.300926
0.351852
0.117904
0.141485
0.188646
0.448908
0.342358
0.342358
0.342358
0.268996
0
0
0.022367
0.190421
1,712
51
71
33.568627
0.803752
0.026869
0
0.105263
0
0
0.022837
0
0
0
0
0
0
1
0.105263
false
0.026316
0.026316
0.078947
0.815789
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
1ef1870cefc7f277338dbb93d9fc58436fe9fcf6
980
py
Python
bin/serve.py
pombredanne/charset_normalizer
4e1c47aaf13ea865024f9cbf434f5580939f5f35
[ "MIT" ]
null
null
null
bin/serve.py
pombredanne/charset_normalizer
4e1c47aaf13ea865024f9cbf434f5580939f5f35
[ "MIT" ]
7
2021-11-01T18:11:07.000Z
2022-03-28T18:11:20.000Z
bin/serve.py
pombredanne/charset_normalizer
4e1c47aaf13ea865024f9cbf434f5580939f5f35
[ "MIT" ]
null
null
null
from flask import Flask, jsonify, send_from_directory from glob import glob app = Flask(__name__) @app.route('/raw/<path:path>') def read_file(path): return send_from_directory('../char-dataset', path, as_attachment=True), 200, {"Content-Type": "text/plain"} @app.route("/") def read_targets(): return jsonify( [ el.replace("./char-dataset", "/raw").replace("\\", "/") for el in glob("./char-dataset/**/*") ] ) @app.route("/edge/empty/plain") def read_empty_response_plain(): return b"", 200, {"Content-Type": "text/plain"} @app.route("/edge/empty/json") def read_empty_response_json(): return b"{}", 200, {"Content-Type": "application/json"} @app.route("/edge/gb18030/json") def read_gb18030_response_json(): return '{"abc": "我没有埋怨,磋砣的只是一些时间。。今觀俗士之論也,以族舉德,以位命賢,茲可謂得論之一體矣,而未獲至論之淑真也。"}'.encode("gb18030"), 200, {"Content-Type": "application/json"} if __name__ == "__main__": app.run(host="127.0.0.1", port=8080)
25.789474
140
0.652041
130
980
4.7
0.430769
0.065466
0.091653
0.05892
0.219313
0.101473
0.101473
0
0
0
0
0.043943
0.140816
980
37
141
26.486486
0.68171
0
0
0
0
0
0.321429
0.059184
0
0
0
0
0
1
0.208333
false
0
0.083333
0.208333
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
480467f865fae8ba1e2bc45837c26434d52917dc
446
py
Python
src/tagger.py
bamdadsabbagh/tagger
c34eb031dd4fe4a0c5ecb228eb32ddfd73983214
[ "MIT" ]
1
2020-11-30T15:40:36.000Z
2020-11-30T15:40:36.000Z
src/tagger.py
bamdadsabbagh/tagger
c34eb031dd4fe4a0c5ecb228eb32ddfd73983214
[ "MIT" ]
30
2020-07-09T10:21:26.000Z
2022-02-04T16:12:24.000Z
src/tagger.py
bamdadsabbagh/tagger
c34eb031dd4fe4a0c5ecb228eb32ddfd73983214
[ "MIT" ]
null
null
null
# components from env import * from tagger_write_none import TaggerWriteNone from tagger_write_data import TaggerWriteData # packages import style def Tagger(files, discogs): if discogs is None: TaggerWriteNone(files) return print(style.blue(discogs['json'].get('artists_sort') + ' - ' + discogs['json'].get('title'))) print(style.blue(discogs['url'])) print() TaggerWriteData(files, discogs) return
20.272727
97
0.692825
52
446
5.846154
0.5
0.065789
0.098684
0.138158
0
0
0
0
0
0
0
0
0.190583
446
21
98
21.238095
0.842105
0.042601
0
0.153846
0
0
0.073113
0
0
0
0
0
0
1
0.076923
false
0
0.307692
0
0.538462
0.230769
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
4807f5a2dac238ed109d8d0b867dd586839c4db9
2,522
py
Python
vulnerabilities/tests/test_import_command.py
ziadhany/vulnerablecode
c94ed5701a70bc836a66484f6d54aacc81c4288f
[ "Apache-2.0" ]
null
null
null
vulnerabilities/tests/test_import_command.py
ziadhany/vulnerablecode
c94ed5701a70bc836a66484f6d54aacc81c4288f
[ "Apache-2.0" ]
null
null
null
vulnerabilities/tests/test_import_command.py
ziadhany/vulnerablecode
c94ed5701a70bc836a66484f6d54aacc81c4288f
[ "Apache-2.0" ]
null
null
null
# # Copyright (c) nexB Inc. and others. All rights reserved. # VulnerableCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/vulnerablecode for support or download. # See https://aboutcode.org for more information about nexB OSS projects. # from io import StringIO from unittest.mock import patch import pytest from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase from vulnerabilities.importer import AdvisoryData from vulnerabilities.importer import Importer class DummyImporter(Importer): spdx_license_expression = "dummy license" def advisory_data(self): return [] class UnLicensedImporter(Importer): def advisory_data(self): return [] MOCK_IMPORTERS_REGISTRY = [DummyImporter, UnLicensedImporter] MOCK_IMPORTERS_REGISTRY = { importer.qualified_name: importer for importer in MOCK_IMPORTERS_REGISTRY } @patch("vulnerabilities.importers.IMPORTERS_REGISTRY", MOCK_IMPORTERS_REGISTRY) class TestImportCommand(TestCase): def test_list_sources(self): buf = StringIO() call_command("import", "--list", stdout=buf) out = buf.getvalue() assert DummyImporter.qualified_name in out def test_missing_sources(self): with pytest.raises(CommandError) as cm: call_command("import", stdout=StringIO()) err = str(cm) assert 'Please provide at least one importer to run or use "--all"' in err def test_error_message_includes_unknown_sources(self): with pytest.raises(CommandError) as cm: call_command( "import", DummyImporter.qualified_name, "foo", "bar", stdout=StringIO(), ) err = str(cm) assert "bar" in err assert "foo" in err assert DummyImporter.qualified_name not in err def test_import_run(self): buf = StringIO() call_command("import", DummyImporter.qualified_name, stdout=buf) out = buf.getvalue() assert "Successfully imported data using" in out def test_bad_importer_fail_error(self): buf = StringIO() with pytest.raises(CommandError): call_command("import", UnLicensedImporter.qualified_name, stdout=buf) out = buf.getvalue() assert "Failed to run importer" in out
30.756098
82
0.687946
299
2,522
5.668896
0.371237
0.038938
0.050147
0.026549
0.260767
0.231268
0.120354
0.120354
0.070796
0.070796
0
0.002056
0.22839
2,522
81
83
31.135802
0.868962
0.1364
0
0.254545
0
0
0.100046
0.020286
0
0
0
0
0.127273
1
0.127273
false
0
0.509091
0.036364
0.745455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
480d2657a8bbaaff56ff6a7cc550eac181c4dba8
111
py
Python
04-control_structures/cycles_2.py
palmieric/Tecnologie_Web-Introduzione_a_Python
b10ce49a947b239ca2af1938248f7191937b2f89
[ "CC0-1.0" ]
3
2021-05-17T14:48:42.000Z
2021-05-24T10:12:06.000Z
04-control_structures/cycles_2.py
palmieric/Tecnologie_Web-Introduzione_a_Python
b10ce49a947b239ca2af1938248f7191937b2f89
[ "CC0-1.0" ]
null
null
null
04-control_structures/cycles_2.py
palmieric/Tecnologie_Web-Introduzione_a_Python
b10ce49a947b239ca2af1938248f7191937b2f89
[ "CC0-1.0" ]
2
2021-05-17T13:52:15.000Z
2021-05-24T10:44:54.000Z
# cycles 2 import random x = None while True: x = random.randint(1, 100) if x == 50: break print("x:", x)
11.1
27
0.612613
20
111
3.4
0.75
0
0
0
0
0
0
0
0
0
0
0.082353
0.234234
111
9
28
12.333333
0.717647
0.072072
0
0
0
0
0.019802
0
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0.142857
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
481b965bb62106b084dc7b9ac2639d6072035be9
260
py
Python
tests/selecting/test_retain_falsy.py
sixty-north/les_iterables
755cdde4dd9e3d56ce2f424ff0619bde7064e897
[ "MIT" ]
2
2020-07-04T22:21:10.000Z
2021-12-10T14:38:18.000Z
tests/selecting/test_retain_falsy.py
sixty-north/les_iterables
755cdde4dd9e3d56ce2f424ff0619bde7064e897
[ "MIT" ]
1
2020-05-26T12:01:50.000Z
2020-05-26T12:01:50.000Z
tests/selecting/test_retain_falsy.py
sixty-north/les_iterables
755cdde4dd9e3d56ce2f424ff0619bde7064e897
[ "MIT" ]
null
null
null
from hypothesis import given from hypothesis.strategies import integers, lists from les_iterables.selecting import retain_falsy @given(items=lists(integers())) def test_retain_falsy(items): result = list(retain_falsy(items)) assert not any(result)
21.666667
49
0.788462
35
260
5.714286
0.571429
0.165
0.16
0
0
0
0
0
0
0
0
0
0.130769
260
11
50
23.636364
0.884956
0
0
0
0
0
0
0
0
0
0
0
0.142857
1
0.142857
false
0
0.428571
0
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
482be7dd613a7b6adba2ff63e20a433e7aa4d956
1,714
py
Python
accounts/urls.py
devmahmud/Django-Board
89fe4694213678fd07ee035d57e642c415c8eb18
[ "MIT" ]
8
2019-10-12T18:28:20.000Z
2022-03-28T15:25:16.000Z
accounts/urls.py
devmahmud/Django-Board
89fe4694213678fd07ee035d57e642c415c8eb18
[ "MIT" ]
null
null
null
accounts/urls.py
devmahmud/Django-Board
89fe4694213678fd07ee035d57e642c415c8eb18
[ "MIT" ]
2
2021-08-01T17:23:48.000Z
2021-10-16T21:41:13.000Z
from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('login/', LoginView.as_view(template_name="registration/login.html"), name="login"), path('logout/', LogoutView.as_view(), name="logout"), path('register/', views.RegisterView.as_view(), name='register'), path('user/profile/', views.UserUpdateView.as_view(), name='profile'), path('password_change/', auth_views.PasswordChangeView.as_view( template_name='registration/password_change.html', ), name='password_change'), path('password_change_done/', auth_views.PasswordChangeDoneView.as_view( template_name='registration/password_change_done.html', ), name='password_change_done'), path('password_reset/', auth_views.PasswordResetView.as_view( template_name='registration/password_reset.html', email_template_name='registration/password_reset_email.html', subject_template_name='registration/password_reset_subject.txt'), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_done'), path('password_reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_confirm.html'), name='password_reset_confirm'), path('password_reset/complete/', auth_views.PasswordResetCompleteView.as_view( template_name='registration/password_reset_complete.html'), name='password_reset_complete'), ]
41.804878
93
0.735706
194
1,714
6.195876
0.21134
0.151414
0.179701
0.212978
0.302829
0.216306
0.216306
0
0
0
0
0.001352
0.137106
1,714
40
94
42.85
0.811359
0
0
0
0
0
0.368145
0.263127
0
0
0
0
0
1
0
false
0.677419
0.129032
0
0.129032
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
482eccd5c1bb9ab64e3b6f7fdbe62500c96011a6
2,475
py
Python
ooobuild/lo/form/component/html_form.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
ooobuild/lo/form/component/html_form.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
ooobuild/lo/form/component/html_form.py
Amourspirit/ooo_uno_tmpl
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Service Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.form.component import typing from abc import abstractproperty from ..x_reset import XReset as XReset_71670917 from ..x_submit import XSubmit as XSubmit_7b060988 from .form import Form as Form_ca1d0c51 if typing.TYPE_CHECKING: from ..form_submit_encoding import FormSubmitEncoding as FormSubmitEncoding_fdd50deb from ..form_submit_method import FormSubmitMethod as FormSubmitMethod_e2a90d25 class HTMLForm(Form_ca1d0c51, XReset_71670917, XSubmit_7b060988): """ Service Class This service specifies the special kind of Forms for HTML documents. An HTMLForm fulfills the specification of forms in HTML. It supplies the possibility of submitting or resetting the contents of a form. For more information on HTML forms, please see the documentation of HTML. See Also: `API HTMLForm <https://api.libreoffice.org/docs/idl/ref/servicecom_1_1sun_1_1star_1_1form_1_1component_1_1HTMLForm.html>`_ """ __ooo_ns__: str = 'com.sun.star.form.component' __ooo_full_ns__: str = 'com.sun.star.form.component.HTMLForm' __ooo_type_name__: str = 'service' @abstractproperty def SubmitEncoding(self) -> 'FormSubmitEncoding_fdd50deb': """ specifies the kind of encoding for submission. """ @abstractproperty def SubmitMethod(self) -> 'FormSubmitMethod_e2a90d25': """ specifies the kind of submission. """ @abstractproperty def TargetFrame(self) -> str: """ describes the frame, where to open the document specified by the TargetURL. """ @abstractproperty def TargetURL(self) -> str: """ specifies the URL, which should be used for submission. """ __all__ = ['HTMLForm']
33.90411
213
0.726465
326
2,475
5.365031
0.493865
0.034305
0.017153
0.024014
0.045169
0.032018
0.032018
0
0
0
0
0.036869
0.2
2,475
72
214
34.375
0.846465
0.546667
0
0.190476
0
0
0.13347
0.11807
0
0
0
0
0
1
0.190476
false
0
0.333333
0
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
483788050ba4dd86d94f6708a04072bf6132335a
771
py
Python
dataapp/migrations/0001_initial.py
prabhuroy/joker-bot
60ae8962e17f9263e249663d90906ae1a581d0f0
[ "MIT" ]
null
null
null
dataapp/migrations/0001_initial.py
prabhuroy/joker-bot
60ae8962e17f9263e249663d90906ae1a581d0f0
[ "MIT" ]
null
null
null
dataapp/migrations/0001_initial.py
prabhuroy/joker-bot
60ae8962e17f9263e249663d90906ae1a581d0f0
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2021-11-20 18:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UserData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('userid', models.CharField(blank=True, max_length=100, null=True)), ('stupid_count', models.IntegerField(default=0)), ('fat_count', models.IntegerField(default=0)), ('dumb_count', models.IntegerField(default=0)), ], ), ]
28.555556
114
0.59144
81
771
5.481481
0.691358
0.074324
0.155405
0.202703
0.209459
0
0
0
0
0
0
0.041219
0.276265
771
26
115
29.653846
0.75448
0.088197
0
0
1
0
0.07
0
0
0
0
0
0
1
0
false
0
0.111111
0
0.333333
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
4837a7c275dffbefa76ca52b460999c4413b3376
1,116
py
Python
tweetgo.py
ShreyasJothish/flask-graphene-neo4j
55e4828915a8a1788c869d103f6867066c00b58c
[ "MIT" ]
1
2019-06-01T15:22:32.000Z
2019-06-01T15:22:32.000Z
tweetgo.py
ShreyasJothish/flask-graphene-neo4j
55e4828915a8a1788c869d103f6867066c00b58c
[ "MIT" ]
null
null
null
tweetgo.py
ShreyasJothish/flask-graphene-neo4j
55e4828915a8a1788c869d103f6867066c00b58c
[ "MIT" ]
1
2021-09-28T01:19:08.000Z
2021-09-28T01:19:08.000Z
from py2neo.ogm import GraphObject, Property from py2neo.ogm import RelatedFrom class Tweet(GraphObject): text = Property() timestamp = Property() # Comment posted by a Person poster = RelatedFrom("Person", "COMMENT_POSTED") def add_or_update(self, **kwargs): for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) def __init__(self, **kwargs): self.add_or_update(**kwargs) def as_dict(self): return { 'key': self.__primaryvalue__, 'text': self.text, 'timestamp': self.timestamp } def update(self, **kwargs): self.add_or_update(**kwargs) # List interfaces def add_or_update_poster(self, poster): self.poster.update(poster) def remove_poster(self, poster): self.poster.remove(poster) # Object level interfaces def save(self, graph): graph.push(self) def delete(self, graph): graph.delete(self) # To avoid cyclic dependency import error from persongo import Person # noqa: E402 F401
23.25
52
0.62276
132
1,116
5.113636
0.409091
0.02963
0.065185
0.056296
0.168889
0.091852
0.091852
0
0
0
0
0.009864
0.273297
1,116
47
53
23.744681
0.822441
0.109319
0
0.068966
0
0
0.036437
0
0
0
0
0
0
1
0.275862
false
0
0.103448
0.034483
0.551724
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
4843f7c6d9e7d2caf7c51551131bab1185160cea
4,287
py
Python
cw_tiler/vector_utils.py
dlindenbaum/cw-tiler
2f306503d7399c365f76962afd526fae2fced843
[ "BSD-3-Clause" ]
1
2020-11-20T18:52:14.000Z
2020-11-20T18:52:14.000Z
cw_tiler/vector_utils.py
dlindenbaum/cw-tiler
2f306503d7399c365f76962afd526fae2fced843
[ "BSD-3-Clause" ]
1
2021-06-25T15:43:05.000Z
2021-06-25T15:43:05.000Z
cw_tiler/vector_utils.py
dlindenbaum/cw-tiler
2f306503d7399c365f76962afd526fae2fced843
[ "BSD-3-Clause" ]
null
null
null
## Note, for mac osx compatability import something from shapely.geometry before importing fiona or geopandas ## https://github.com/Toblerity/Shapely/issues/553 from shapely import geometry from shapely.geometry import box ### import geopandas as gpd from rasterio import features from rasterio import Affine import numpy as np def read_vector_file(geoFileName): """read in all Fiona Supported Files into geo DataFrame""" gdf = gpd.read_file(geoFileName) return gdf def transformToUTM(gdf, utm_crs, estimate=True, calculate_sindex=True): gdf = gdf.to_crs(utm_crs) if calculate_sindex: sindex = gdf.sindex return gdf def search_gdf_bounds(gdf, tile_bounds): tile_polygon = box(tile_bounds) smallGdf = search_gdf_polygon(gdf, tile_polygon) return smallGdf def search_gdf_polygon(gdf, tile_polygon): spatial_index = gdf.sindex possible_matches_index = list(spatial_index.intersection(tile_polygon.bounds)) possible_matches = gdf.iloc[possible_matches_index] precise_matches = possible_matches[possible_matches.intersects(tile_polygon)] if precise_matches.empty: precise_matches=gpd.GeoDataFrame(geometry=[]) return precise_matches def vector_tile_utm(gdf, tile_bounds, min_partial_perc=0.1, geom_type="Polygon", use_sindex=True): tile_polygon = box(*tile_bounds) small_gdf = clip_gdf(gdf, tile_polygon, min_partial_perc=min_partial_perc, geom_type=geom_type ) return small_gdf def getCenterOfGeoFile(gdf, estimate=True): #TODO implement calculate UTM from gdf see osmnx implementation pass def clip_gdf(geodf, poly_to_cut, min_partial_perc=0.0, geom_type="Polygon", use_sindex=True): """clip geoDDF to a provided polygon. Will add four (4) for additional columns origarea. If the geoDF is a set of Polygons, This is the original area of the polygons origlen. If the geoDF is a set of LineStrings, this is the original length of the polygons partialDec. This is the % of the polygon or line that was truncated. So NewArea/OrigArea. Can be used to filter out on very small slivers truncated. Binary Flag that specified if the polygon or line string has been modified 1=Truncated, 0=Not modified params: ______ geoDF, a geopandas Dataframe polyToCut: shapely polygon to cut geodataFrame By minpartialPerc: Defined as the minimum % of a polygon that should be included geom_type: is the geo Data Frame a polygon or LineString returns clippedGeoDF """ # check if geoDF has origAreaField if use_sindex: gdf = search_gdf_polygon(geodf, poly_to_cut) else: gdf = geodf.copy() if geom_type == "LineString": if 'origarea' in gdf.columns: pass else: gdf['origarea'] = 0 if 'origlen' in gdf.columns: pass else: gdf['origlen'] = gdf.length else: if 'origarea' in gdf.columns: pass else: gdf['origarea'] = gdf.area if 'origlen' in gdf.columns: pass else: gdf['origlen'] = 0 #TODO must implement different case for lines and for spatialIndex (Assume RTree is already performed) cutGeoDF = gdf.copy() cutGeoDF.geometry=gdf.intersection(poly_to_cut) if geom_type== 'Polygon': cutGeoDF['partialDec'] = cutGeoDF.area / cutGeoDF['origarea'] cutGeoDF = cutGeoDF.loc[cutGeoDF['partialDec'] > min_partial_perc].copy() cutGeoDF['truncated'] = (cutGeoDF['partialDec']!=1.0).astype(int) else: # cutGeoDF = cutGeoDF[cutGeoDF.geom_type != "GeometryCollection"] cutGeoDF['partialDec']=1 cutGeoDF['truncated']=0 return cutGeoDF def rasterize_gdf(gdf, burn_value=1, src_shape=None, src_transform=Affine(1.0, 0.0, 0.0, 0.0, 1.0, 0.0)): if not gdf.empty: img = features.rasterize( ((geom, burn_value) for geom in gdf.geometry), out_shape=src_shape, transform=src_transform, ) else: img = np.zeros(src_shape).astype(np.uint8) return img
26.462963
109
0.664801
558
4,287
4.949821
0.311828
0.006517
0.006517
0.023172
0.132875
0.115496
0.070963
0.057929
0.057929
0
0
0.00939
0.254724
4,287
161
110
26.627329
0.855086
0.278516
0
0.240506
0
0
0.058159
0
0
0
0
0.012422
0
1
0.101266
false
0.063291
0.075949
0
0.265823
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
484473ac19918a6fc7947f43e4269bf803260d0e
673
py
Python
tcrdist/tests/test_setup_tests.py
agartland/tcrdist3
34f8d50e7448b2bf7cf7cd9ab9a2d80759f47240
[ "MIT" ]
26
2020-12-28T17:37:01.000Z
2022-01-29T01:31:13.000Z
tcrdist/tests/test_setup_tests.py
agartland/tcrdist3
34f8d50e7448b2bf7cf7cd9ab9a2d80759f47240
[ "MIT" ]
31
2020-08-17T22:17:57.000Z
2022-03-18T23:47:34.000Z
tcrdist/tests/test_setup_tests.py
agartland/tcrdist3
34f8d50e7448b2bf7cf7cd9ab9a2d80759f47240
[ "MIT" ]
7
2020-08-18T23:55:40.000Z
2021-09-22T18:15:54.000Z
import pytest from tcrdist import setup_tests #get_url, download_and_extract_zip_file from tcrdist import paths import os def test_get_url(): url = setup_tests.get_url("bulk.csv.zip", source = 'dropbox') assert url == "https://www.dropbox.com/s/g6k2h1ed5d5sabz/bulk.csv.zip?dl=1" def test_download_and_extract_zip_file(): setup_tests.download_and_extract_zip_file(zipfile = "sant.csv.zip", source = 'dropbox', dest = paths.path_to_base) # assert download succeed assert os.path.isfile(os.path.join(paths.path_to_base, "sant.csv.zip")) # assert download + unzip succeed assert os.path.isfile(os.path.join(paths.path_to_base, "sant.csv"))
39.588235
118
0.7474
106
673
4.5
0.367925
0.050314
0.113208
0.132075
0.396226
0.238994
0.238994
0.238994
0.238994
0.238994
0
0.010274
0.132244
673
16
119
42.0625
0.806507
0.139673
0
0
0
0.090909
0.203125
0
0
0
0
0
0.272727
1
0.181818
false
0
0.363636
0
0.545455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
484967ac74f6d123dbdebf8bdbdd8cab5455056e
621
py
Python
smarty/tests/test_utils.py
openforcefield/smarty
882d54b6d6d0fada748c71789964b07be2210a6a
[ "MIT" ]
10
2018-03-29T15:31:50.000Z
2022-02-17T14:04:37.000Z
smarty/tests/test_utils.py
openforcefield/smarty
882d54b6d6d0fada748c71789964b07be2210a6a
[ "MIT" ]
14
2017-11-22T21:27:25.000Z
2019-01-24T04:50:42.000Z
smarty/tests/test_utils.py
openforcefield/smarty
882d54b6d6d0fada748c71789964b07be2210a6a
[ "MIT" ]
2
2019-03-05T22:52:26.000Z
2022-02-17T14:05:06.000Z
from functools import partial from smarty.utils import get_data_filename from unittest import TestCase import smarty class TestUtils(TestCase): def test_parse_odds_file(self): """ Testing parse_odds_file and get_data_filename """ # parse_odds_file uses get_data_filename so this run checks both odds = smarty.utils.parse_odds_file('odds_files/atom_index_odds.smarts', verbose = True) odds = smarty.utils.parse_odds_file('odds_files/bond_OR_bases.smarts') self.assertIsNone(odds[1], msg = "Parsing odds file with no odds should give None as the second entry")
38.8125
111
0.73752
90
621
4.833333
0.544444
0.110345
0.149425
0.091954
0.170115
0.170115
0.170115
0.170115
0
0
0
0.001996
0.193237
621
15
112
41.4
0.866267
0.175523
0
0
0
0
0.268443
0.131148
0
0
0
0
0.111111
1
0.111111
false
0
0.444444
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
484d8e9d7e1642b008767732581d28832ef16be5
429
py
Python
src/GPDS/social/models.py
vsantacoloma/usb-project-management-tool
8bd9fd08a6d1ba316a231cbb00252a115aed67f9
[ "MIT" ]
null
null
null
src/GPDS/social/models.py
vsantacoloma/usb-project-management-tool
8bd9fd08a6d1ba316a231cbb00252a115aed67f9
[ "MIT" ]
null
null
null
src/GPDS/social/models.py
vsantacoloma/usb-project-management-tool
8bd9fd08a6d1ba316a231cbb00252a115aed67f9
[ "MIT" ]
null
null
null
from django.contrib import admin from django.db import models from django.contrib.auth.models import User from project.models import Project from users.models import * # Create your models here. class Request(models.Model): to_user = models.ForeignKey(User, related_name='to_user') from_user = models.ForeignKey(User, related_name='from_user') project = models.ForeignKey(Project) admin.site.register(Request)
28.6
65
0.776224
60
429
5.45
0.383333
0.091743
0.103976
0.146789
0.214067
0.214067
0
0
0
0
0
0
0.135198
429
14
66
30.642857
0.881402
0.055944
0
0
0
0
0.039702
0
0
0
0
0
0
1
0
false
0
0.5
0
0.9
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
485a4ef6fd5ffefdea89f56ca06bb90b3bb0f3ed
225
py
Python
ObenedorDeEntrada.py
JEFMX/Codigo-Morse
a515d0c445eb296e3ef82cd7ccc6fc20f0501899
[ "CC0-1.0" ]
1
2021-03-18T18:15:20.000Z
2021-03-18T18:15:20.000Z
ObenedorDeEntrada.py
JEFMX/Codigo-Morse
a515d0c445eb296e3ef82cd7ccc6fc20f0501899
[ "CC0-1.0" ]
null
null
null
ObenedorDeEntrada.py
JEFMX/Codigo-Morse
a515d0c445eb296e3ef82cd7ccc6fc20f0501899
[ "CC0-1.0" ]
null
null
null
class ObtenedorDeEntrada: def getEntrada(self): f = open ('Entrada.txt','r') entrada = f.read() print(entrada) f.close() return entrada #input("Introduce el texto\n")
28.125
38
0.537778
24
225
5.041667
0.791667
0.132231
0
0
0
0
0
0
0
0
0
0
0.337778
225
8
38
28.125
0.812081
0.128889
0
0
0
0
0.063492
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.428571
0.142857
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
485b0affc26f41f7ac4a68970ecd1af7ac1b596e
9,931
py
Python
statsmodels/tsa/vector_ar/tests/test_coint.py
aliavni/statsmodels
ef5d57a8d45de76a895e9401705280d558d688ad
[ "BSD-3-Clause" ]
1
2022-01-24T15:17:37.000Z
2022-01-24T15:17:37.000Z
statsmodels/tsa/vector_ar/tests/test_coint.py
aliavni/statsmodels
ef5d57a8d45de76a895e9401705280d558d688ad
[ "BSD-3-Clause" ]
null
null
null
statsmodels/tsa/vector_ar/tests/test_coint.py
aliavni/statsmodels
ef5d57a8d45de76a895e9401705280d558d688ad
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """Test Johansen's Cointegration test against jplv, Spatial Econometrics Toolbox Created on Thu Aug 30 21:51:08 2012 Author: Josef Perktold """ import os import warnings import numpy as np from numpy.testing import assert_almost_equal, assert_equal import pandas as pd import pytest from statsmodels.tools.sm_exceptions import HypothesisTestWarning from statsmodels.tsa.vector_ar.vecm import coint_johansen current_path = os.path.dirname(os.path.abspath(__file__)) dta_path = os.path.join(current_path, "Matlab_results", "test_coint.csv") with open(dta_path, "rb") as fd: dta = np.genfromtxt(fd) class CheckCointJoh: def test_basic(self): assert_equal(self.res.ind, np.arange(len(self.res.ind), dtype=int)) assert_equal(self.res.r0t.shape, (self.nobs_r, 8)) def test_table_trace(self): table1 = np.column_stack((self.res.lr1, self.res.cvt)) assert_almost_equal(table1, self.res1_m.reshape(table1.shape, order='F')) def test_table_maxeval(self): table2 = np.column_stack((self.res.lr2, self.res.cvm)) assert_almost_equal(table2, self.res2_m.reshape(table2.shape, order='F')) def test_normalization(self): # GH 5517 evec = self.res.evec non_zero = evec.flat != 0 assert evec.flat[non_zero][0] > 0 class TestCointJoh12(CheckCointJoh): @classmethod def setup_class(cls): cls.res = coint_johansen(dta, 1, 2) cls.nobs_r = 173 - 1 - 2 cls.res1_m = np.array([241.985452556075, 166.4781461662553, 110.3298006342814, 70.79801574443575, 44.90887371527634, 27.22385073668511, 11.74205493173769, 3.295435325623445, 169.0618, 133.7852, 102.4674, 75.1027, 51.6492, 32.0645, 16.1619, 2.7055, 175.1584, 139.278, 107.3429, 79.34220000000001, 55.2459, 35.0116, 18.3985, 3.8415, 187.1891, 150.0778, 116.9829, 87.7748, 62.5202, 41.0815, 23.1485, 6.6349]) cls.res2_m = np.array([75.50730638981975, 56.14834553197396, 39.5317848898456, 25.8891420291594, 17.68502297859124, 15.48179580494741, 8.446619606114249, 3.295435325623445, 52.5858, 46.5583, 40.5244, 34.4202, 28.2398, 21.8731, 15.0006, 2.7055, 55.7302, 49.5875, 43.4183, 37.1646, 30.8151, 24.2522, 17.1481, 3.8415, 62.1741, 55.8171, 49.4095, 42.8612, 36.193, 29.2631, 21.7465, 6.6349,]) evec = np.array([ 0.01102517075074406, -0.2185481584930077, 0.04565819524210763, -0.06556394587400775, 0.04711496306104131, -0.1500111976629196, 0.03775327003706507, 0.03479475877437702, 0.007517888890275335, -0.2014629352546497, 0.01526001455616041, 0.0707900418057458, -0.002388919695513273, 0.04486516694838273, -0.02936314422571188, 0.009900554050392113, 0.02846074144367176, 0.02021385478834498, -0.04276914888645468, 0.1738024290422287, 0.07821155002012749, -0.1066523077111768, -0.3011042488399306, 0.04965189679477353, 0.07141291326159237, -0.01406702689857725, -0.07842109866080313, -0.04773566072362181, -0.04768640728128824, -0.04428737926285261, 0.4143225656833862, 0.04512787132114879, -0.06817130121837202, 0.2246249779872569, -0.009356548567565763, 0.006685350535849125, -0.02040894506833539, 0.008131690308487425, -0.2503209797396666, 0.01560186979508953, 0.03327070126502506, -0.263036624535624, -0.04669882107497259, 0.0146457545413255, 0.01408691619062709, 0.1004753600191269, -0.02239205763487946, -0.02169291468272568, 0.08782313160608619, -0.07696508791577318, 0.008925177304198475, -0.06230900392092828, -0.01548907461158638, 0.04574831652028973, -0.2972228156126774, 0.003469819004961912, -0.001868995544352928, 0.05993345996347871, 0.01213394328069316, 0.02096614212178651, -0.08624395993789938, 0.02108183181049973, -0.08470307289295617, -5.135072530480897e-005]) cls.evec_m = evec.reshape(cls.res.evec.shape, order='F') cls.eig_m = np.array([0.3586376068088151, 0.2812806889719111, 0.2074818815675726, 0.141259991767926, 0.09880133062878599, 0.08704563854307619, 0.048471840356709, 0.01919823444066367]) def test_evec(self): for col in range(self.evec_m.shape[1]): try: assert_almost_equal(self.res.evec[:, col], self.evec_m[:, col]) except AssertionError: assert_almost_equal(self.res.evec[:, col], -self.evec_m[:, col]) def test_evals(self): assert_almost_equal(self.res.eig, self.eig_m) class TestCointJoh09(CheckCointJoh): @classmethod def setup_class(cls): cls.res = coint_johansen(dta, 0, 9) cls.nobs_r = 173 - 1 - 9 #fprintf(1, '%18.16g, ', r1) cls.res1_m = np.array([307.6888935095814, 205.3839229398245, 129.1330243009336, 83.3101865760208, 52.51955460357912, 30.20027050520502, 13.84158157562689, 0.4117390188204866, 153.6341, 120.3673, 91.109, 65.8202, 44.4929, 27.0669, 13.4294, 2.7055, 159.529, 125.6185, 95.7542, 69.8189, 47.8545, 29.7961, 15.4943, 3.8415, 171.0905, 135.9825, 104.9637, 77.8202, 54.6815, 35.4628, 19.9349, 6.6349]) #r2 = [res.lr2 res.cvm] cls.res2_m = np.array([102.3049705697569, 76.25089863889085, 45.82283772491284, 30.7906319724417, 22.31928409837409, 16.35868892957814, 13.4298425568064, 0.4117390188204866, 49.2855, 43.2947, 37.2786, 31.2379, 25.1236, 18.8928, 12.2971, 2.7055, 52.3622, 46.2299, 40.0763, 33.8777, 27.5858, 21.1314, 14.2639, 3.8415, 58.6634, 52.3069, 45.8662, 39.3693, 32.7172, 25.865, 18.52, 6.6349]) class TestCointJohMin18(CheckCointJoh): @classmethod def setup_class(cls): cls.res = coint_johansen(dta, -1, 8) cls.nobs_r = 173 - 1 - 8 cls.res1_m = np.array([260.6786029744658, 162.7966072512681, 105.8253545950566, 71.16133060790817, 47.68490211260372, 28.11843682526138, 13.03968537077271, 2.25398078597622, 137.9954, 106.7351, 79.5329, 56.2839, 37.0339, 21.7781, 10.4741, 2.9762, 143.6691, 111.7797, 83.9383, 60.0627, 40.1749, 24.2761, 12.3212, 4.1296, 154.7977, 121.7375, 92.7136, 67.63670000000001, 46.5716, 29.5147, 16.364, 6.9406]) cls.res2_m = np.array([97.88199572319769, 56.97125265621156, 34.66402398714837, 23.47642849530445, 19.56646528734234, 15.07875145448866, 10.7857045847965, 2.25398078597622, 45.893, 39.9085, 33.9271, 27.916, 21.837, 15.7175, 9.4748, 2.9762, 48.8795, 42.7679, 36.6301, 30.4428, 24.1592, 17.7961, 11.2246, 4.1296, 55.0335, 48.6606, 42.2333, 35.7359, 29.0609, 22.2519, 15.0923, 6.9406]) class TestCointJoh25(CheckCointJoh): @classmethod def setup_class(cls): with warnings.catch_warnings(): warnings.simplefilter("ignore", category=HypothesisTestWarning) cls.res = coint_johansen(dta, 2, 5) cls.nobs_r = 173 - 1 - 5 # Note: critical values not available if trend>1 cls.res1_m = np.array([270.1887263915158, 171.6870096307863, 107.8613367358704, 70.82424032233558, 44.62551818267534, 25.74352073857572, 14.17882426926978, 4.288656185006764, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) cls.res1_m[cls.res1_m == 0] = np.nan cls.res2_m = np.array([98.50171676072955, 63.82567289491584, 37.03709641353485, 26.19872213966024, 18.88199744409963, 11.56469646930594, 9.890168084263012, 4.288656185006764, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) cls.res2_m[cls.res2_m == 0] = np.nan @pytest.mark.smoke def test_coint_johansen_0lag(reset_randomstate): # GH 5731 x_diff = np.random.normal(0, 1, 1000) x = pd.Series(np.cumsum(x_diff)) e1 = np.random.normal(0, 1, 1000) y = x + 5 + e1 data = pd.concat([x, y], axis=1) result = coint_johansen(data, det_order=-1, k_ar_diff=0) assert result.eig.shape == (2,)
62.06875
671
0.544457
1,110
9,931
4.795496
0.466667
0.017659
0.024798
0.031561
0.137141
0.08266
0.067631
0.067631
0.067631
0.067631
0
0.514554
0.346189
9,931
159
672
62.45912
0.305252
0.027389
0
0.127273
0
0
0.004043
0
0
0
0
0
0.1
1
0.1
false
0
0.072727
0
0.218182
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
48626a37e47d8fac074c567af61f259bd05f0255
1,020
py
Python
var/spack/repos/builtin/packages/py-pyparsing/package.py
HaochengLIU/spack
26e51ff1705a4d6234e2a0cf734f93f7f95df5cb
[ "ECL-2.0", "Apache-2.0", "MIT" ]
2
2018-11-27T03:39:44.000Z
2021-09-06T15:50:35.000Z
var/spack/repos/builtin/packages/py-pyparsing/package.py
HaochengLIU/spack
26e51ff1705a4d6234e2a0cf734f93f7f95df5cb
[ "ECL-2.0", "Apache-2.0", "MIT" ]
1
2019-01-11T20:11:52.000Z
2019-01-11T20:11:52.000Z
var/spack/repos/builtin/packages/py-pyparsing/package.py
HaochengLIU/spack
26e51ff1705a4d6234e2a0cf734f93f7f95df5cb
[ "ECL-2.0", "Apache-2.0", "MIT" ]
1
2020-10-14T14:20:17.000Z
2020-10-14T14:20:17.000Z
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPyparsing(PythonPackage): """A Python Parsing Module.""" homepage = "http://pyparsing.wikispaces.com/" url = "https://pypi.io/packages/source/p/pyparsing/pyparsing-2.2.0.tar.gz" import_modules = ['pyparsing'] version('2.2.0', '0214e42d63af850256962b6744c948d9') version('2.1.10', '065908b92904e0d3634eb156f44cc80e') version('2.0.3', '0fe479be09fc2cf005f753d3acc35939') patch('setuptools-import.patch', when='@:2.1.10') # Newer versions of setuptools require pyparsing. Although setuptools is an # optional dependency of pyparsing, if it is not found, setup.py will # fallback on distutils.core instead. Don't add a setuptools dependency # or we won't be able to bootstrap setuptools. # depends_on('py-setuptools', type='build')
36.428571
83
0.717647
132
1,020
5.530303
0.719697
0.010959
0.008219
0
0
0
0
0
0
0
0
0.11007
0.162745
1,020
27
84
37.777778
0.744731
0.502941
0
0
0
0.111111
0.507099
0.241379
0
0
0
0
0
1
0
false
0
0.333333
0
0.777778
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
4866230e43e001b0a70e2b191ecdc9e8e448fae5
480
py
Python
PA2/test/gennull.py
SebastianJay/LDI-Cool
85744fa493bd6a11463aababe7b484a57c6c47b7
[ "Apache-2.0" ]
null
null
null
PA2/test/gennull.py
SebastianJay/LDI-Cool
85744fa493bd6a11463aababe7b484a57c6c47b7
[ "Apache-2.0" ]
null
null
null
PA2/test/gennull.py
SebastianJay/LDI-Cool
85744fa493bd6a11463aababe7b484a57c6c47b7
[ "Apache-2.0" ]
null
null
null
#print 'hello \0' import sys # print out strings/comments/freestanding indentifers containing each element of ascii table # if guard prevents some chars from being printed sys.stdout.write('(*') for i in range(128): #if i == 0 or i == 10 or i == 13 or i == 26 or i == 34 or i == 92: # sys.stdout.write('\n') # continue #sys.stdout.write('"') sys.stdout.write(str(unichr(i))) #sys.stdout.write('"') sys.stdout.write('\n') sys.stdout.write('*)')
30
92
0.625
75
480
4
0.546667
0.21
0.326667
0.1
0.186667
0.186667
0
0
0
0
0
0.03937
0.20625
480
15
93
32
0.748032
0.627083
0
0
0
0
0.035088
0
0
0
0
0
0
1
0
false
0
0.166667
0
0.166667
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
48724ceb9e39205fcac9d531e2a397d59d32279e
1,588
py
Python
tests/mock_tieserver.py
hbazan/opendxl-tie-client-python
e874c268ea9d10307edd8f177fc39b2ac45a7d44
[ "Apache-2.0" ]
null
null
null
tests/mock_tieserver.py
hbazan/opendxl-tie-client-python
e874c268ea9d10307edd8f177fc39b2ac45a7d44
[ "Apache-2.0" ]
null
null
null
tests/mock_tieserver.py
hbazan/opendxl-tie-client-python
e874c268ea9d10307edd8f177fc39b2ac45a7d44
[ "Apache-2.0" ]
null
null
null
from dxlclient.service import ServiceRegistrationInfo from tests.mock_requesthandlers import * class MockTieServer(object): def __init__(self, client): self._client = client # Create DXL Service Registration object self._service_registration_info = ServiceRegistrationInfo( self._client, "/opendxl/mocktieserver" ) def __enter__(self): mock_callback = FakeTieServerCallback(self._client) self._service_registration_info.add_topic( dxltieclient.client.TIE_GET_FILE_REPUTATION_TOPIC, mock_callback ) self._service_registration_info.add_topic( dxltieclient.client.TIE_GET_CERT_REPUTATION_TOPIC, mock_callback ) self._service_registration_info.add_topic( dxltieclient.client.TIE_SET_FILE_REPUTATION_TOPIC, mock_callback ) self._service_registration_info.add_topic( dxltieclient.client.TIE_SET_CERT_REPUTATION_TOPIC, mock_callback ) self._service_registration_info.add_topic( dxltieclient.client.TIE_GET_FILE_FIRST_REFS, mock_callback ) self._service_registration_info.add_topic( dxltieclient.client.TIE_GET_CERT_FIRST_REFS, mock_callback ) self._client.register_service_sync(self._service_registration_info, 10) return self def __exit__(self, exc_type, exc_val, exc_tb): self._client.unregister_service_sync(self._service_registration_info, 10)
33.083333
81
0.68199
163
1,588
6.09816
0.269939
0.191147
0.20825
0.244467
0.615694
0.581489
0.581489
0.501006
0.501006
0.501006
0
0.00341
0.261335
1,588
47
82
33.787234
0.84399
0.023929
0
0.307692
0
0
0.014212
0.014212
0
0
0
0
0
1
0.076923
false
0
0.051282
0
0.179487
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
4875535ce479dc8b23521eed1398144d97add066
1,627
py
Python
testApi.py
1kko/mwsapi
fe0874f4be6013a39f0399677c6736a79ea7d602
[ "MIT" ]
null
null
null
testApi.py
1kko/mwsapi
fe0874f4be6013a39f0399677c6736a79ea7d602
[ "MIT" ]
null
null
null
testApi.py
1kko/mwsapi
fe0874f4be6013a39f0399677c6736a79ea7d602
[ "MIT" ]
1
2022-02-19T00:39:38.000Z
2022-02-19T00:39:38.000Z
#!/usr/bin/env python # -*- coding: UTF-8 -*- # coding=utf-8 from mwsapi import v3 key="YOUR API KEY" mws=v3(key, "public") print ("# StartTesting File API") print ("# Testing file.download") with open("4020ce0de0cc206f9bc241e5634a02da", "wb") as fd: fd.write(mws.file.download("4020ce0de0cc206f9bc241e5634a02da")) print ("Passed") print ("# Testing file.upload") assert mws.file.upload("4020ce0de0cc206f9bc241e5634a02da") print ("Passed") print ("# Testing file.mwsinfo") assert mws.file.mwsinfo("4020ce0de0cc206f9bc241e5634a02da") print ("Passed") print ("# Testing file.behaviorinfo") assert mws.file.behaviorinfo("4020ce0de0cc206f9bc241e5634a02da") print ("Passed") print ("# Testing file.staticinfo") assert mws.file.staticinfo("4020ce0de0cc206f9bc241e5634a02da") print ("Passed") print ("# Testing file.addinfo") assert mws.file.addinfo("4020ce0de0cc206f9bc241e5634a02da") print ("Passed") print ("# StartTesting URL API") print ("# Testing url.request") assert mws.url.request("https://www.malwares.com") print ("Passed") print ("# Testing url.info") assert mws.url.info("https://www.malwares.com") print ("Passed") print ("# StartTesting IP API") print ("# Testing ip.info") assert mws.ip.info("8.8.8.8") print ("Passed") print ("# StartTesting Hostname API") print ("# Testing hostname.info") assert mws.hostname.info("www.malwares.com") print ("Passed") print ("# StartTesting Tag API") print ("# Testing tag.search") assert mws.tag.search("ransomware") print ("Passed") print ("# Testing tag.search, with start time") assert mws.tag.search("ransomware", start="2018-06-05 00:00:00") print ("Passed")
25.421875
64
0.728334
202
1,627
5.866337
0.262376
0.121519
0.148523
0.135865
0.400844
0.353587
0.104641
0
0
0
0
0.105947
0.100799
1,627
63
65
25.825397
0.704033
0.033805
0
0.266667
0
0
0.521046
0.142857
0
0
0
0
0.244444
1
0
false
0.266667
0.022222
0
0.022222
0.644444
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
1
0
2
4884239e4ff5d2020e56a6e2c1dfd91c48f3c812
1,400
py
Python
src/openprocurement/tender/pricequotation/procedure/models/req_response.py
ProzorroUKR/openprocurement.api
2855a99aa8738fb832ee0dbad4e9590bd3643511
[ "Apache-2.0" ]
10
2020-02-18T01:56:21.000Z
2022-03-28T00:32:57.000Z
src/openprocurement/tender/pricequotation/procedure/models/req_response.py
quintagroup/openprocurement.api
2855a99aa8738fb832ee0dbad4e9590bd3643511
[ "Apache-2.0" ]
26
2018-07-16T09:30:44.000Z
2021-02-02T17:51:30.000Z
src/openprocurement/tender/pricequotation/procedure/models/req_response.py
ProzorroUKR/openprocurement.api
2855a99aa8738fb832ee0dbad4e9590bd3643511
[ "Apache-2.0" ]
15
2019-08-08T10:50:47.000Z
2022-02-05T14:13:36.000Z
# -*- coding: utf-8 -*- from uuid import uuid4 from schematics.exceptions import ValidationError from schematics.types.compound import ModelType from schematics.types.serializable import serializable from schematics.types import MD5Type, IntType from openprocurement.api.models import ( Model, Period, IsoDateTimeType, ListType, Reference, ) from schematics.types import StringType from openprocurement.api.constants import ( RELEASE_ECRITERIA_ARTICLE_17, CRITERION_REQUIREMENT_STATUSES_FROM, ) from openprocurement.tender.core.procedure.validation import ( validate_value_type, ) from openprocurement.tender.core.procedure.context import get_tender, get_bid, get_json_data, get_now from openprocurement.tender.core.procedure.utils import get_first_revision_date from openprocurement.tender.core.procedure.models.base import ( BaseBid, validate_object_id_uniq, ) from openprocurement.tender.core.models import ( BaseAward, QualificationMilestoneListMixin, validate_response_requirement_uniq, ) from logging import getLogger LOGGER = getLogger(__name__) class RequirementReference(Model): id = StringType(required=True) title = StringType() class RequirementResponse(Model): id = MD5Type(required=True, default=lambda: uuid4().hex) requirement = ModelType(RequirementReference, required=True) value = StringType(required=True)
29.787234
101
0.797143
156
1,400
6.987179
0.455128
0.122018
0.114679
0.133028
0.13945
0
0
0
0
0
0
0.005747
0.13
1,400
46
102
30.434783
0.889163
0.015
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.358974
0
0.538462
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
4887a70ba4b7a8e4dd2cd338266934a7aab95e7f
2,202
py
Python
Python/Utopia/gis_demo.py
Zentopia/Learning
7183b80357413f57953389cd41534bc341793c47
[ "MIT" ]
null
null
null
Python/Utopia/gis_demo.py
Zentopia/Learning
7183b80357413f57953389cd41534bc341793c47
[ "MIT" ]
null
null
null
Python/Utopia/gis_demo.py
Zentopia/Learning
7183b80357413f57953389cd41534bc341793c47
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib.ticker as tik import numpy as np import math EARTH_RADIUS = 6378137.0 def _get_pad(d): return d*math.pi/180.0 def _cal_to_coordinate(lat1,lng1,lat2,lng2): """ 北斗坐标计算距离 """ radLat1 = _get_pad(lat1) radLat2 = _get_pad(lat2) a = radLat1 - radLat2 b = _get_pad(lng1) - _get_pad(lng2) s = 2*math.asin(math.sqrt(math.pow(math.sin(a/2),2) + math.cos(radLat1)*math.cos(radLat2)*math.pow(math.sin(b/2),2))) s = s*EARTH_RADIUS s = round(s*10000)/10000.0 return s def _cal_to_coordinate_flat(lat1,lng1,lat2,lng2): """ 北斗坐标计算距离(椭圆) """ f = _get_pad((lat1 + lat2)/2) g = _get_pad((lat1 - lat2)/2) l = _get_pad((lng1 - lng2)/2) sg = math.sin(g) sl = math.sin(l) sf = math.sin(f) a = EARTH_RADIUS fl = 1/298.257; sg = sg*sg sl = sl*sl sf = sf*sf s = sg*(1-sl) + (1-sf)*sl c = (1-sg)*(1-sl) + sf*sl w = math.atan(math.sqrt(s/c)) r = math.sqrt(s*c)/w d = 2*w*a h1 = (3*r -1)/2/c h2 = (3*r +1)/2/s return round(d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg)), 5) if __name__ == '__main__': # lat1 = 40.07834518833333 #百度坐标:40.08551585036245 # lng1 = 116.35229350833333 #百度坐标:116.3650760781415 # lat2 = 40.078343548333336 #百度坐标:40.08551432847522 # lng2 = 116.35230061166666 #百度坐标:116.3650830928695 """ 采用百度接口进行测距:0.62253m """ #print(_cal_to_coordinate(lat1,lng1,lat2,lng2)) #print(_cal_to_coordinate_flat(lat1,lng1,lat2,lng2)) #0.63266 """ 采用百度接口进行测距:28.66m """ # lat3 = 40.06148084833333 #百度坐标:40.068496292867 # lng3 = 116.34078560166667 #百度坐标:116.35357120258114 # lat4 = 40.06173812833333 #百度坐标:40.06875366929153 # lng4 = 116.34076853166667 #百度坐标:116.35355431178137 #print(_cal_to_coordinate_flat(lat3,lng3,lat4,lng4)) #28.60446 lat3 = 40.049255738333336 lng3 = 116.34384970166667 lat4 = 40.049269198333334 lng4 = 116.343844065 print(_cal_to_coordinate_flat(lat3,lng3,lat4,lng4))
20.773585
121
0.594914
324
2,202
3.891975
0.32716
0.038065
0.071372
0.050753
0.208565
0.168121
0.168121
0.118953
0.063442
0
0
0.277981
0.253406
2,202
105
122
20.971429
0.489051
0.287012
0
0
0
0
0.005521
0
0
0
0
0
0
1
0.071429
false
0
0.095238
0.02381
0.238095
0.02381
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6f7fac46e38370ae59494133724300c42523f4ec
307
py
Python
py_tdlib/constructors/payment_receipt.py
Mr-TelegramBot/python-tdlib
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
[ "MIT" ]
24
2018-10-05T13:04:30.000Z
2020-05-12T08:45:34.000Z
py_tdlib/constructors/payment_receipt.py
MrMahdi313/python-tdlib
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
[ "MIT" ]
3
2019-06-26T07:20:20.000Z
2021-05-24T13:06:56.000Z
py_tdlib/constructors/payment_receipt.py
MrMahdi313/python-tdlib
2e2d21a742ebcd439971a32357f2d0abd0ce61eb
[ "MIT" ]
5
2018-10-05T14:29:28.000Z
2020-08-11T15:04:10.000Z
from ..factory import Type class paymentReceipt(Type): date = None # type: "int32" payments_provider_user_id = None # type: "int32" invoice = None # type: "invoice" order_info = None # type: "orderInfo" shipping_option = None # type: "shippingOption" credentials_title = None # type: "string"
27.909091
50
0.703583
37
307
5.675676
0.621622
0.228571
0.12381
0
0
0
0
0
0
0
0
0.015936
0.18241
307
10
51
30.7
0.820717
0.322476
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.125
0
1
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
6f8045298fd31f13280fdf8c59145acd3041d171
258
py
Python
preprocess/setting.py
sichun/lagou_personal_assistant
4a6c8971fe28cd06521675ae5bc84c3996cd03c5
[ "MIT" ]
null
null
null
preprocess/setting.py
sichun/lagou_personal_assistant
4a6c8971fe28cd06521675ae5bc84c3996cd03c5
[ "MIT" ]
null
null
null
preprocess/setting.py
sichun/lagou_personal_assistant
4a6c8971fe28cd06521675ae5bc84c3996cd03c5
[ "MIT" ]
null
null
null
types = {"workYear_types": ['应届毕业生', '1-3年', '3-5年', '5-10年', '10年以上', '不限'], "companySize_types": ['15-50人', '50-150人', '150-500人', '500-2000人', '2000人以上'], "financeStage_types": ['未融资', '天使轮', 'A轮', 'B轮', 'C轮', 'D轮及以上', '上市公司', '不需要融资']}
64.5
90
0.523256
33
258
4
0.909091
0
0
0
0
0
0
0
0
0
0
0.162037
0.162791
258
3
91
86
0.449074
0
0
0
0
0
0.531008
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6f80c5004b2404f61d68654350746ad0e56c52ec
661
py
Python
webvulnscan/attacks/cookiescan.py
hhucn/webvulnscan
efb812fd5483157528f37794acecafa35ed0d878
[ "MIT" ]
40
2015-01-15T14:52:51.000Z
2022-03-25T08:52:48.000Z
webvulnscan/attacks/cookiescan.py
RaviRaaja/webvulnscan
efb812fd5483157528f37794acecafa35ed0d878
[ "MIT" ]
1
2016-07-21T09:51:15.000Z
2016-10-02T17:45:37.000Z
webvulnscan/attacks/cookiescan.py
RaviRaaja/webvulnscan
efb812fd5483157528f37794acecafa35ed0d878
[ "MIT" ]
22
2015-01-23T04:21:21.000Z
2021-08-22T03:36:21.000Z
from ..utils import attack def check_for_cookies(headers): return "Set-Cookie" in headers or "Set-Cookies" in headers def secure_cache_control(page): if "Cache-Control" in page.headers: cache_control = page.headers["Cache-Control"] if cache_control in "no-cache" or cache_control in "private": return True if "max-age" in cache_control and "0" in cache_control: return True return False @attack() def cookiescan(client, log, page): if not check_for_cookies(page.headers): return if not secure_cache_control(page): log('vuln', page.url, u"Implicit Cacheable Cookies")
23.607143
69
0.670197
92
661
4.673913
0.391304
0.251163
0.111628
0.102326
0
0
0
0
0
0
0
0.00198
0.236006
661
27
70
24.481481
0.849505
0
0
0.117647
0
0
0.151286
0
0
0
0
0
0
1
0.176471
false
0
0.058824
0.058824
0.529412
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
6f82399f02a2f30a221f224f6c6d07b9582ef244
76
py
Python
modules/boost/simd/swar/py_data.py
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
2
2016-09-14T00:23:53.000Z
2018-01-14T12:51:18.000Z
modules/boost/simd/swar/py_data.py
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/swar/py_data.py
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
datas = { 'style' : 'sys', 'parent' :'boost', 'prefix' :['boost','simd'], }
12.666667
27
0.513158
8
76
4.875
0.875
0
0
0
0
0
0
0
0
0
0
0
0.144737
76
5
28
15.2
0.6
0
0
0
0
0
0.447368
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6f84e6a1558103129c95bc8840b93204231d8d98
481
py
Python
tests/extra/lookup_table_test.py
cornell-brg/lizard
7f9a78a913e64b5cfdee3a26223539ad225bd6da
[ "BSD-3-Clause" ]
50
2019-05-22T08:43:15.000Z
2022-03-21T23:58:50.000Z
tests/extra/lookup_table_test.py
cornell-brg/lizard
7f9a78a913e64b5cfdee3a26223539ad225bd6da
[ "BSD-3-Clause" ]
1
2019-07-27T18:51:52.000Z
2019-08-02T01:20:22.000Z
tests/extra/lookup_table_test.py
cornell-brg/lizard
7f9a78a913e64b5cfdee3a26223539ad225bd6da
[ "BSD-3-Clause" ]
11
2019-12-26T06:00:48.000Z
2022-03-27T02:29:35.000Z
import pytest from pymtl import * from tests.context import lizard from lizard.model.test_model import run_test_state_machine from lizard.util.rtl.lookup_table import LookupTable, LookupTableInterface from lizard.util.fl.lookup_table import LookupTableFL def test_state_machine(): run_test_state_machine( LookupTable, LookupTableFL, (LookupTableInterface(Bits(4), Bits(4)), { 0b1111: 0b1010, 0b0101: 0b0000 }), translate_model=True)
28.294118
74
0.75052
59
481
5.915254
0.491525
0.08596
0.137536
0.108883
0
0
0
0
0
0
0
0.055556
0.176715
481
16
75
30.0625
0.825758
0
0
0
0
0
0
0
0
0
0
0
0
1
0.071429
true
0
0.428571
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
2
6f926695a8c59fa6008062fd42dd8413a03ab12b
3,242
py
Python
utils/visualisation.py
hhj1897/fan_training
5882f9edf2f1a07c80a6d1f3341a7cf1d348e217
[ "MIT" ]
1
2021-12-11T21:31:57.000Z
2021-12-11T21:31:57.000Z
utils/visualisation.py
hhj1897/fan_training
5882f9edf2f1a07c80a6d1f3341a7cf1d348e217
[ "MIT" ]
null
null
null
utils/visualisation.py
hhj1897/fan_training
5882f9edf2f1a07c80a6d1f3341a7cf1d348e217
[ "MIT" ]
1
2021-12-11T21:31:49.000Z
2021-12-11T21:31:49.000Z
import cv2 import numpy as np __all__ = ['get_landmark_connectivity', 'plot_landmarks'] def get_landmark_connectivity(num_landmarks): if num_landmarks == 68: return ((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12), (12, 13), (13, 14), (14, 15), (15, 16), (17, 18), (18, 19), (19, 20), (20, 21), (22, 23), (23, 24), (24, 25), (25, 26), (27, 28), (28, 29), (29, 30), (30, 33), (31, 32), (32, 33), (33, 34), (34, 35), (36, 37), (37, 38), (38, 39), (40, 41), (41, 36), (42, 43), (43, 44), (44, 45), (45, 46), (46, 47), (47, 42), (48, 49), (49, 50), (50, 51), (51, 52), (52, 53), (53, 54), (54, 55), (55, 56), (56, 57), (57, 58), (58, 59), (59, 48), (60, 61), (61, 62), (62, 63), (63, 64), (64, 65), (65, 66), (66, 67), (67, 60), (39, 40)) elif num_landmarks == 100: return ((0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (10, 11), (11, 12), (12, 13), (13, 14), (14, 15), (15, 16), (17, 18), (18, 19), (19, 20), (20, 21), (22, 23), (23, 24), (24, 25), (25, 26), (68, 69), (69, 70), (70, 71), (72, 73), (73, 74), (74, 75), (36, 76), (76, 37), (37, 77), (77, 38), (38, 78), (78, 39), (39, 40), (40, 79), (79, 41), (41, 36), (42, 80), (80, 43), (43, 81), (81, 44), (44, 82), (82, 45), (45, 46), (46, 83), (83, 47), (47, 42), (27, 28), (28, 29), (29, 30), (30, 33), (31, 32), (32, 33), (33, 34), (34, 35), (84, 85), (86, 87), (48, 49), (49, 88), (88, 50), (50, 51), (51, 52), (52, 89), (89, 53), (53, 54), (54, 55), (55, 90), (90, 56), (56, 57), (57, 58), (58, 91), (91, 59), (59, 48), (60, 92), (92, 93), (93, 61), (61, 62), (62, 63), (63, 94), (94, 95), (95, 64), (64, 96), (96, 97), (97, 65), (65, 66), (66, 67), (67, 98), (98, 99), (99, 60), (17, 68), (21, 71), (22, 72), (26, 75)) else: return None def plot_landmarks(frame, landmarks, scores=None, threshold=0.2, connection_colour=(0, 255, 0), landmark_colour=(0, 0, 255), connection_thickness=1, landmark_radius=1, landmark_connectivity=None): num_landmarks = len(landmarks) if scores is None: scores = np.full((num_landmarks,), threshold + 1.0, dtype=float) if landmark_connectivity is None: landmark_connectivity = get_landmark_connectivity(len(landmarks)) if landmark_connectivity is not None: for (idx1, idx2) in landmark_connectivity: if (idx1 < num_landmarks and idx2 < num_landmarks and scores[idx1] >= threshold and scores[idx2] >= threshold): cv2.line(frame, tuple(landmarks[idx1].astype(int).tolist()), tuple(landmarks[idx2].astype(int).tolist()), color=connection_colour, thickness=connection_thickness, lineType=cv2.LINE_AA) for landmark, score in zip(landmarks, scores): if score >= threshold: cv2.circle(frame, tuple(landmark.astype(int).tolist()), landmark_radius, landmark_colour, -1)
63.568627
116
0.470389
486
3,242
3.069959
0.306584
0.107239
0.046247
0.012064
0.234584
0.234584
0.154156
0.154156
0.154156
0.154156
0
0.275563
0.288094
3,242
50
117
64.84
0.370884
0
0
0.090909
0
0
0.01203
0.007711
0
0
0
0
0
1
0.045455
false
0
0.045455
0
0.159091
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6f98393f43f8f340c4c76539b2caa7506ab7ccef
162
py
Python
daremightythings/__init__.py
drewmee/JPL-Interview
03d99b0eaace584a7b4f0465ab5f9819aefc3276
[ "MIT" ]
null
null
null
daremightythings/__init__.py
drewmee/JPL-Interview
03d99b0eaace584a7b4f0465ab5f9819aefc3276
[ "MIT" ]
null
null
null
daremightythings/__init__.py
drewmee/JPL-Interview
03d99b0eaace584a7b4f0465ab5f9819aefc3276
[ "MIT" ]
null
null
null
"""Top-level package for daremightythings.""" __author__ = """Drew Meyers""" __email__ = "drewm@mit.edu" __version__ = "0.1.0" from . import interviews, robots
20.25
45
0.703704
20
162
5.1
0.95
0
0
0
0
0
0
0
0
0
0
0.021277
0.12963
162
7
46
23.142857
0.702128
0.240741
0
0
0
0
0.247863
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6f9ffdbcb6ae125dbdb89be426e36522ef2ca3b7
137
py
Python
Ex10.py
ErickTeixeira777/Python-3
5bd886d13e8118bba556d499ecd6841e9cdb5e9f
[ "MIT" ]
null
null
null
Ex10.py
ErickTeixeira777/Python-3
5bd886d13e8118bba556d499ecd6841e9cdb5e9f
[ "MIT" ]
null
null
null
Ex10.py
ErickTeixeira777/Python-3
5bd886d13e8118bba556d499ecd6841e9cdb5e9f
[ "MIT" ]
null
null
null
real = float(input('Quanto vc tem de grana?')) usd = real / 5.63 print('Com R$: {:.2f} você pode comprar Usd: {:.2f}' .format(real, usd))
45.666667
72
0.627737
24
137
3.583333
0.791667
0
0
0
0
0
0
0
0
0
0
0.043103
0.153285
137
3
72
45.666667
0.698276
0
0
0
0
0
0.485507
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6fa6504bbca2ee95255161bdac322944f2055f21
801
py
Python
app/dao/Cardapio_dao.py
amandapersampa/FastFrango
23a69d80576f6cef754e9d3acacf9908a4da30cd
[ "MIT" ]
null
null
null
app/dao/Cardapio_dao.py
amandapersampa/FastFrango
23a69d80576f6cef754e9d3acacf9908a4da30cd
[ "MIT" ]
null
null
null
app/dao/Cardapio_dao.py
amandapersampa/FastFrango
23a69d80576f6cef754e9d3acacf9908a4da30cd
[ "MIT" ]
null
null
null
from app import db from app.models.Compra import Compra from sqlalchemy.orm import relationship class Cardapio_dao(db.Model): __tablename__ = "cardapio" id_cardapio = db.Column(db.Integer, primary_key=True) nome = db.Column(db.Integer) valor = db.Column(db.Float) def __init__(self, nome, valor): self.nome = nome self.valor = valor def to_JSON(self): p = Compra(self.id_compra, self.quantidade, self.valor, self.produto.nome) print(p.id_compra, self.produto.nome) return p.to_JSON() def salvar(self): db.session.add(self) db.session.commit() def listar(id): return Compra_dao.query.get(id) @staticmethod def findAll(): return Compra_dao.query.all()
25.03125
83
0.627965
106
801
4.584906
0.40566
0.049383
0.061728
0.069959
0
0
0
0
0
0
0
0
0.265918
801
32
84
25.03125
0.826531
0
0
0
0
0
0.010376
0
0
0
0
0
0
1
0.217391
false
0
0.130435
0.086957
0.695652
0.043478
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
6fa84fd1f51cc9ca4947bcf95acf2a5fe42effc8
939
py
Python
cgi-bin/writecsvtar.py
raspibo/ThermoRed
55f93e49e3fac6cc919c64d5246d6fdf77e641ee
[ "MIT" ]
null
null
null
cgi-bin/writecsvtar.py
raspibo/ThermoRed
55f93e49e3fac6cc919c64d5246d6fdf77e641ee
[ "MIT" ]
1
2015-02-03T18:30:29.000Z
2015-02-03T18:30:29.000Z
cgi-bin/writecsvtar.py
raspibo/ThermoRed
55f93e49e3fac6cc919c64d5246d6fdf77e641ee
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Archivia import shutil import time # Serve per la parte di gestione html in python import cgi import cgitb import time # Abilita gli errori al server web/http cgitb.enable() # Intestazione HTML print("<!DOCTYPE html>") print(""" <html> <head> <title>ThermoRed</title> <meta name="GENERATOR" content="Midnight Commander (mcedit)"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="Keywords" content="termoregolatore, thermo, temperatura, python"> <meta name="Author" content="Davide"> </head> <body> """) # End / Start body ## Inizio pagina web print("L'archivio avra` un nome simile a questo:", "temperature.csv."+time.strftime("%y%m%d%H%M"),"<br/>") print("Archiviazione ...<br/>") shutil.copyfile("temperature.csv","temperature.csv."+time.strftime("%y%m%d%H%M")) print("<br/>Archiviazione terminata<br/>") # End body/End html print(""" </body> </html> """)
19.163265
106
0.687966
130
939
4.969231
0.584615
0.041796
0.055728
0.080495
0.095975
0.095975
0.095975
0.095975
0.095975
0
0
0.002433
0.124601
939
48
107
19.5625
0.783455
0.197018
0
0.230769
0
0.038462
0.689933
0.099329
0
0
0
0
0
1
0
true
0
0.192308
0
0.192308
0.230769
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
6fbfe1918e6cf92f850a3d0ac9cdb3d1e5300988
3,995
py
Python
game-of-life.py
hkan/game-of-life
855fac7ea74637b1293f693b3169616da2739f6d
[ "Unlicense" ]
null
null
null
game-of-life.py
hkan/game-of-life
855fac7ea74637b1293f693b3169616da2739f6d
[ "Unlicense" ]
null
null
null
game-of-life.py
hkan/game-of-life
855fac7ea74637b1293f693b3169616da2739f6d
[ "Unlicense" ]
null
null
null
# -*- coding: utf-8 -*- import numpy as np grid_presets = { "3,1:2,1": np.array([ [0, 0, 0], [0, 1, 0], [0, 1, 0] ]), "9,3:7,3:5": np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], ]) } neighbor_coord_deltas = [ (-1, -1), # top left corner (-1, 0), # top (-1, +1), # top right corner ( 0, +1), # right (+1, +1), # bottom right corner (+1, 0), # bottom (+1, -1), # bottom left corner ( 0, -1), # left ] def paint_grid(grid): for row in grid: for col in row: if col == 0: print('-', end='') else: print('#', end='') print('') def debug_grid_data(data): for row in data: for col in row: print(' ' + str(int(col)) + ' ', end='') print('') def neighbor_coords(row_number, col_number, row_size, col_size): list_of_all_neighbor_coords = list((row_number + r, col_number + c) for (r, c) in neighbor_coord_deltas) # This filtering process eliminates coordinates that fall outside of the grid such as (-1, 0), (-1, -1) etc. list_of_coords_within_grid = filter( lambda coords: True if coords[0] >= 0 and coords[0] < row_size and coords[1] >= 0 and coords[1] < col_size else False, list_of_all_neighbor_coords ) # Running it through `list()` because the variable is actually a iterable, not list. return list(list_of_coords_within_grid) def get_neighbors_map(grid): (row_size, col_size) = grid.shape neighbors_map = np.ndarray(grid.shape) neighbors_map.fill(0) for row_number in range(row_size): for col_number in range(col_size): for (neighbor_row, neighbor_col) in neighbor_coords(row_number, col_number, row_size, col_size): if grid[neighbor_row, neighbor_col] == 1: neighbors_map[row_number][col_number] = neighbors_map[row_number][col_number] + 1 return neighbors_map def calculate_new_grid(neighbors_map: np.ndarray, grid: np.ndarray): (row_size, col_size) = neighbors_map.shape new_grid = np.ndarray(neighbors_map.shape) new_grid.fill(0) for row_number in range(row_size): for col_number in range(col_size): current_state = grid[row_number, col_number] # For only dead cells... if current_state == 0: # If it has exactly 3 neighbors... if neighbors_map[row_number, col_number] == 3: # It becomes populated. new_grid[row_number, col_number] = 1 continue # Rest of the checks are for alive cells... # If the cell has 2 or 3 neighbors, it lives for another day. if neighbors_map[row_number, col_number] == 2 or neighbors_map[row_number, col_number] == 3: new_grid[row_number, col_number] = 1 continue # If the cell has no neighbors, 1 neighbor, OR more than 3 neighbors, it dies. new_grid[row_number, col_number] = 0 return new_grid def loop(grid): paint_grid(grid) input('Press enter to calculate next iteration, or kntrl+C to exit.') neighbors_map = get_neighbors_map(grid) grid = calculate_new_grid(neighbors_map, grid) loop(grid) loop( np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], ]) )
31.706349
126
0.531414
633
3,995
3.192733
0.183254
0.139535
0.190005
0.231569
0.445324
0.319149
0.273627
0.222662
0.189015
0.189015
0
0.082994
0.324406
3,995
125
127
31.96
0.665802
0.14368
0
0.319149
0
0
0.023516
0
0
0
0
0
0
1
0.06383
false
0
0.010638
0
0.106383
0.053191
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6fc61a7fe44be372b912455c039482d40142d030
791
py
Python
froide/wsgi.py
manonthemat/froide
698c49935eaf2e922f3c9f6a46af0fd545ccbbbb
[ "MIT" ]
3
2015-03-22T16:08:01.000Z
2019-08-13T14:58:07.000Z
froide/wsgi.py
manonthemat/froide
698c49935eaf2e922f3c9f6a46af0fd545ccbbbb
[ "MIT" ]
95
2015-01-08T14:34:22.000Z
2020-12-11T05:30:06.000Z
froide/wsgi.py
ashmpace/question-mtl
5ce1289cd6db0e629aa138d2dee235d9a4c4546b
[ "MIT" ]
2
2017-02-27T21:34:26.000Z
2021-01-05T11:48:40.000Z
import os import sys # Calculate the path based on the location of the WSGI script. apache_configuration = os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.join(project, '..') sys.path.append(project) sys.path.append(workspace) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'froide.settings') os.environ.setdefault('DJANGO_CONFIGURATION', 'Production') from django.conf import settings from configurations.wsgi import get_wsgi_application application = get_wsgi_application() try: from whitenoise.django import DjangoWhiteNoise application = DjangoWhiteNoise(application) if settings.MEDIA_ROOT and settings.MEDIA_URL: application.add_files(settings.MEDIA_ROOT, prefix=settings.MEDIA_URL) except ImportError: pass
29.296296
77
0.797724
100
791
6.13
0.46
0.084829
0.042414
0.065253
0
0
0
0
0
0
0
0
0.11378
791
26
78
30.423077
0.874465
0.075853
0
0
0
0
0.09465
0.030178
0
0
0
0
0
1
0
false
0.052632
0.315789
0
0.315789
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
1
0
0
0
0
2
6fd3d57b6d1e6a827d099a613aecc89c5ae6f5b3
1,111
py
Python
src/server/errors.py
andreylipattsev/almanac.httparchive.org
a05ae166c09eecdcd34e0c1882d3003b5bfee6b6
[ "Apache-2.0" ]
1
2022-02-17T21:14:02.000Z
2022-02-17T21:14:02.000Z
src/server/errors.py
andreylipattsev/almanac.httparchive.org
a05ae166c09eecdcd34e0c1882d3003b5bfee6b6
[ "Apache-2.0" ]
107
2019-10-10T22:56:25.000Z
2021-06-03T05:28:54.000Z
src/server/errors.py
andreylipattsev/almanac.httparchive.org
a05ae166c09eecdcd34e0c1882d3003b5bfee6b6
[ "Apache-2.0" ]
2
2019-10-10T11:31:25.000Z
2020-07-19T04:20:42.000Z
from flask import abort, request from . import app from .helpers import render_error_template import logging # Catch all route for everything not matched elsewhere @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): # pragma: no cover abort(404, "Not Found") @app.errorhandler(400) def bad_request(e): # pragma: no cover logging.exception('An error occurred during a request due to bad request error: %s', request.path) return render_error_template(error=e, status_code=400) @app.errorhandler(404) def page_not_found(e): return render_error_template(error=e, status_code=404) @app.errorhandler(500) def handle_internal_server_error(e): # pragma: no cover logging.exception('An error occurred during a request due to internal server error: %s', request.path) return render_error_template(error=e, status_code=500) @app.errorhandler(502) def handle_bad_gateway(e): # pragma: no cover logging.exception('An error occurred during a request due to bad gateway: %s', request.path) return render_error_template(error=e, status_code=502)
31.742857
106
0.749775
167
1,111
4.850299
0.293413
0.067901
0.117284
0.123457
0.503704
0.503704
0.503704
0.503704
0.453086
0.453086
0
0.028302
0.141314
1,111
34
107
32.676471
0.820755
0.108011
0
0
0
0
0.216244
0
0
0
0
0
0
1
0.217391
false
0
0.173913
0.043478
0.565217
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
6fda28744b76bf7e5ba491755c2e892687a36044
3,644
py
Python
pydv/pdvnavbar.py
griffin28/PyDV
2ea2e904d95dd92722405ed7e19029a1f60fce12
[ "BSD-3-Clause" ]
2
2019-04-04T02:32:04.000Z
2019-04-06T16:43:26.000Z
pydv/pdvnavbar.py
griffin28/PyDV
2ea2e904d95dd92722405ed7e19029a1f60fce12
[ "BSD-3-Clause" ]
37
2019-04-03T23:25:09.000Z
2020-02-05T23:57:02.000Z
pydv/pdvnavbar.py
griffin28/PyDV
2ea2e904d95dd92722405ed7e19029a1f60fce12
[ "BSD-3-Clause" ]
2
2019-04-25T15:56:31.000Z
2019-09-04T20:16:50.000Z
# Copyright (c) 2011-2022, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # Written by Mason Kwiat, Douglas S. Miller, and Kevin Griffin, Edward Rusu # e-mail: rusu1@llnl.gov # LLNL-CODE-507071 # All rights reserved. # This file is part of PDV. For details, see <URL describing code and # how to download source>. Please also read "Additional BSD Notice". # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # Redistributions of source code must retain the above copyright # notice, this list of conditions and the disclaimer below. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the disclaimer (as noted below) # in the documentation and/or other materials provided with the # distribution. Neither the name of the LLNS/LLNL nor the names of # its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE # LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # Additional BSD Notice # 1. This notice is required to be provided under our contract with # the U.S. Department of Energy (DOE). This work was produced at # Lawrence Livermore National Laboratory under Contract # No. DE-AC52-07NA27344 with the DOE. # 2. Neither the United States Government nor Lawrence Livermore # National Security, LLC nor any of their employees, makes any # warranty, express or implied, or assumes any liability or # responsibility for the accuracy, completeness, or usefulness of any # information, apparatus, product, or process disclosed, or represents # that its use would not infringe privately-owned rights. # 3. Also, reference herein to any specific commercial products, # process, or services by trade name, trademark, manufacturer or # otherwise does not necessarily constitute or imply its endorsement, # recommendation, or favoring by the United States Government or # Lawrence Livermore National Security, LLC. The views and opinions # of authors expressed herein do not necessarily state or reflect # those of the United States Government or Lawrence Livermore National # Security, LLC, and shall not be used for advertising or product # endorsement purposes. from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT class PyDVToolbar(NavigationToolbar2QT): def __init__(self, canvas_, parent_, coordinates_): self.parent = parent_ NavigationToolbar2QT.__init__(self, canvas_, parent_, coordinates_) def edit_parameters(self): self.parent.plotChanged = True NavigationToolbar2QT.edit_parameters(self) def zoom(self, *args): self.parent.plotChanged = True NavigationToolbar2QT.zoom(self, *args)
46.717949
75
0.778814
507
3,644
5.56213
0.475345
0.042199
0.062057
0.058511
0.213121
0.116667
0.086525
0.086525
0.086525
0.086525
0
0.010877
0.167398
3,644
77
76
47.324675
0.918589
0.82876
0
0.181818
0
0
0
0
0
0
0
0
0
1
0.272727
false
0
0.090909
0
0.454545
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
6fdbb287295b2636d3544d02fffe1aff3fc6e597
2,675
py
Python
NikoLib/NKAppDataManager.py
nikoc2016/NikoKit
c78410c1d0897096c67b69ac3607b165372d09f0
[ "MIT" ]
null
null
null
NikoLib/NKAppDataManager.py
nikoc2016/NikoKit
c78410c1d0897096c67b69ac3607b165372d09f0
[ "MIT" ]
null
null
null
NikoLib/NKAppDataManager.py
nikoc2016/NikoKit
c78410c1d0897096c67b69ac3607b165372d09f0
[ "MIT" ]
null
null
null
import json import os import os.path as p from NikoKit.NikoStd.NKPrintableMixin import NKPrintableMixin from NikoKit.NikoLib.NKFileSystem import scout class NKAppDataMixin: @classmethod def new_appdata(cls): return {} def __init__(self, appdata_mgr, appdata_name, *args, **kwargs): self.appdata_mgr = appdata_mgr self.appdata_name = appdata_name super(NKAppDataMixin, self).__init__(*args, **kwargs) def load_appdata(self): local_appdata = self.appdata_mgr.get(self.appdata_name) appdata = self.new_appdata() if local_appdata: appdata.update(local_appdata) self.apply_appdata(appdata) def save_appdata(self): self.appdata_mgr.set(self.appdata_name, self.extract_appdata()) self.appdata_mgr.save(self.appdata_name) def extract_appdata(self): appdata = self.new_appdata() # Set appdata to this dict return appdata def apply_appdata(self, appdata): # You will have to set up appdata here pass class NKAppDataManager(NKPrintableMixin): def __init__(self, appdata_root): super(NKAppDataManager, self).__init__() self.appdata_root = appdata_root self.appdata_objects = {} self.appdata_ext = ".nkappdata" def get(self, appdata_name): if appdata_name in self.appdata_objects.keys(): return self.appdata_objects[appdata_name] else: return None def set(self, appdata_name, appdata_object): self.appdata_objects[appdata_name] = appdata_object def save(self, appdata_name): appdata_path = p.join(self.appdata_root, appdata_name + self.appdata_ext) scout(appdata_path) with open(appdata_path, "w", encoding="utf-8") as f: json.dump(self.appdata_objects[appdata_name], f, ensure_ascii=False) def load(self, appdata_name): appdata_path = p.join(self.appdata_root, appdata_name + self.appdata_ext) scout(appdata_path) with open(appdata_path, "r", encoding="utf-8") as f: self.appdata_objects[appdata_name] = json.load(f) def save_all(self): for appdata_name in self.appdata_objects.keys(): self.save(appdata_name) def load_all(self): scout(self.appdata_root) for appdata_filename in os.listdir(self.appdata_root): if p.splitext(appdata_filename)[1] == self.appdata_ext and p.isfile(p.join(self.appdata_root, appdata_filename)): self.load(appdata_name=p.splitext(appdata_filename)[0])
34.294872
106
0.65271
332
2,675
4.993976
0.23494
0.218938
0.072376
0.066345
0.274427
0.186369
0.170084
0.127865
0.127865
0.127865
0
0.002008
0.255327
2,675
77
107
34.74026
0.830321
0.022804
0
0.101695
0
0
0.008426
0
0
0
0
0
0
1
0.220339
false
0.016949
0.084746
0.016949
0.40678
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
6ff4b518fdd7b40fe5d2be802d2984c373273239
5,034
py
Python
backend/backend/settings.py
devillD/chat
61c3b92474463c16e73c7efbf68f626274103be4
[ "MIT" ]
68
2018-01-06T01:02:37.000Z
2022-03-25T17:01:29.000Z
backend/backend/settings.py
devillD/chat
61c3b92474463c16e73c7efbf68f626274103be4
[ "MIT" ]
12
2018-10-07T05:37:29.000Z
2022-03-02T03:59:17.000Z
backend/backend/settings.py
devillD/chat
61c3b92474463c16e73c7efbf68f626274103be4
[ "MIT" ]
32
2018-01-06T01:02:38.000Z
2022-03-04T16:13:13.000Z
""" Django settings for backend project. Generated by 'django-admin startproject' using Django 1.10.6. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ybm%7nr$nrqa7!x=$tb@+621y2am+*we^cl+v$&um()2km+i7-' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True APPEND_SLASH = False ALLOWED_HOSTS = ['*'] DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] CUSTOM_APPS = [ 'chat', 'profiles' ] THIRD_PARTY_APPS = [ 'corsheaders', 'rest_framework', 'channels' ] INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + CUSTOM_APPS MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' ASGI_APPLICATION = 'backend.routing.application' redis_host = os.environ.get('REDIS_HOST', 'localhost') # asgiredis CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", # "CONFIG": { # "hosts": [(redis_host, 6379)], # }, "ROUTING": "backend.routing.channel_routing", }, } # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases database_host = os.environ.get('DATABASE_HOST', '127.0.0.1') database_username = os.environ.get('DATABASE_USERNAME', 'chat') database_name = os.environ.get('DATABASE_NAME', 'chat') database_port = os.environ.get('DATABASE_PORT', '3340') database_password = os.environ.get('DATABASE_PASSWORD', '!23qweASD') database_engine = os.environ.get('DATABASE_ENGINE', 'django.db.backends.mysql') DATABASES = { 'default': { 'ENGINE': database_engine, 'NAME': database_name, 'USER': database_username, 'PASSWORD': database_password, 'HOST': database_host, 'PORT': database_port, } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # noqa }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # noqa }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',# noqa }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', # noqa }, ] # JWT Authentication REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } JWT_AUTH = { # @TODO add custom auth handler # 'JWT_RESPONSE_PAYLOAD_HANDLER': # 'profiles.views.jwt_response_payload_handler', 'JWT_VERIFY_EXPIRATION': False } # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
26.494737
98
0.690902
554
5,034
6.110108
0.368231
0.057607
0.045495
0.051699
0.162482
0.142984
0.119055
0.080945
0.036337
0
0
0.013215
0.173222
5,034
189
99
26.634921
0.800096
0.234406
0
0.034188
1
0.008547
0.477749
0.372775
0
0
0
0.005291
0
1
0
false
0.059829
0.008547
0
0.008547
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
b50e412c8337f3a1c10eebb300113e7d30d7c219
250
py
Python
setup.py
arteedecco/all-reviews-reports-merge
474868598d685997ac28577e9e5ffbaf90eb4e8f
[ "MIT" ]
null
null
null
setup.py
arteedecco/all-reviews-reports-merge
474868598d685997ac28577e9e5ffbaf90eb4e8f
[ "MIT" ]
null
null
null
setup.py
arteedecco/all-reviews-reports-merge
474868598d685997ac28577e9e5ffbaf90eb4e8f
[ "MIT" ]
null
null
null
from setuptools import setup setup( name='yourscript', version='0.1', py_modules=['yourscript'], install_requires=[ 'Click', 'openpyxl', ], entry_points=''' [console_scripts] merge=merge:cli ''', )
17.857143
30
0.568
24
250
5.75
0.875
0
0
0
0
0
0
0
0
0
0
0.01105
0.276
250
14
31
17.857143
0.751381
0
0
0
0
0
0.36255
0
0
0
0
0
0
1
0
true
0
0.076923
0
0.076923
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
b516cdf0eb3ef1e5a649492d9d3f9aefeb27ab25
262
py
Python
HR_IntroToConditionalStatements.py
bluewitch/Code-Blue-Python
07230fbc8e20d263950ad2476e79da12b64cff2d
[ "MIT" ]
null
null
null
HR_IntroToConditionalStatements.py
bluewitch/Code-Blue-Python
07230fbc8e20d263950ad2476e79da12b64cff2d
[ "MIT" ]
null
null
null
HR_IntroToConditionalStatements.py
bluewitch/Code-Blue-Python
07230fbc8e20d263950ad2476e79da12b64cff2d
[ "MIT" ]
1
2020-02-13T14:47:12.000Z
2020-02-13T14:47:12.000Z
#!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': #N = int(input()) N = int(input().strip()) # Done with Regular Expressions print("Not "*bool(re.match(r'^(..)(\1|\1{10,})?$','1'*N))+"Weird")
15.411765
70
0.591603
38
262
3.868421
0.710526
0.054422
0.122449
0
0
0
0
0
0
0
0
0.028169
0.187023
262
16
71
16.375
0.661972
0.225191
0
0
0
0
0.185
0
0
0
0
0
0
1
0
false
0
0.625
0
0.625
0.125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
82ef9bf8d3b8c396ce6cd81cd7b3c06fbdec3fe2
336
py
Python
blender/arm/logicnode/random/LN_random_color.py
niacdoial/armory
3f9b633fbf772017c576a3f77695a6c28d9956e1
[ "Zlib" ]
null
null
null
blender/arm/logicnode/random/LN_random_color.py
niacdoial/armory
3f9b633fbf772017c576a3f77695a6c28d9956e1
[ "Zlib" ]
null
null
null
blender/arm/logicnode/random/LN_random_color.py
niacdoial/armory
3f9b633fbf772017c576a3f77695a6c28d9956e1
[ "Zlib" ]
null
null
null
from arm.logicnode.arm_nodes import * class RandomColorNode(ArmLogicTreeNode): """Generates a random color.""" bl_idname = 'LNRandomColorNode' bl_label = 'Random Color' arm_version = 1 def init(self, context): super(RandomColorNode, self).init(context) self.add_output('NodeSocketColor', 'Color')
25.846154
51
0.690476
37
336
6.135135
0.702703
0.096916
0
0
0
0
0
0
0
0
0
0.003704
0.196429
336
12
52
28
0.837037
0.074405
0
0
1
0
0.160656
0
0
0
0
0
0
1
0.125
false
0
0.125
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
82f3baf0fddd8806dac41be7946a3057bc25e60f
591
py
Python
fwtorch/dataset/dali_base.py
Solacex/Flat-White
6d0f94180b6dfae45955595962f1965b26b2b6f5
[ "MIT" ]
2
2021-02-17T13:37:56.000Z
2021-02-17T13:40:45.000Z
fwtorch/dataset/dali_base.py
Solacex/Flat-White
6d0f94180b6dfae45955595962f1965b26b2b6f5
[ "MIT" ]
null
null
null
fwtorch/dataset/dali_base.py
Solacex/Flat-White
6d0f94180b6dfae45955595962f1965b26b2b6f5
[ "MIT" ]
null
null
null
import torch from nvidia.dali.pipeline import Pipeline import nvidia.dali.ops as ops from .Iterator import * import nvidia.dali.types as types class BasePipeline(Pipeline): def __init__(iterator, batch_size, num_threads, device_id): self.input = ops.ExternalSource()#ops.FileReader(iterator[0], share_id=device_id, num_shards=num_threads) self.label = ops.ExternalSource() self.decode = ops.ImageDecoder(device='mixed', output_type=types.RGB) self.label_decode = ops.ImageDecoder(device='mixed', output_type=types.msa) def define_graph(self):
36.9375
114
0.741117
80
591
5.2875
0.4625
0.070922
0.07565
0.12766
0.222222
0.222222
0.222222
0.222222
0
0
0
0.002
0.153976
591
15
115
39.4
0.844
0.120135
0
0
0
0
0.019342
0
0
0
0
0
0
0
null
null
0
0.416667
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
2
82f50340c6dfc530b155fcb07d8d75c874b1211e
3,304
py
Python
cfgrib/cfgrib_.py
shoyer/cfgrib
fe11a1b638b1779e51da87eaa30f1f12b2d0911c
[ "Apache-2.0" ]
null
null
null
cfgrib/cfgrib_.py
shoyer/cfgrib
fe11a1b638b1779e51da87eaa30f1f12b2d0911c
[ "Apache-2.0" ]
null
null
null
cfgrib/cfgrib_.py
shoyer/cfgrib
fe11a1b638b1779e51da87eaa30f1f12b2d0911c
[ "Apache-2.0" ]
null
null
null
# # Copyright 2017-2018 European Centre for Medium-Range Weather Forecasts (ECMWF). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: # Alessandro Amici - B-Open - https://bopen.eu # from __future__ import absolute_import, division, print_function import numpy as np from xarray import Variable from xarray.core import indexing from xarray.core.utils import Frozen, FrozenOrderedDict from xarray.backends.common import AbstractDataStore, BackendArray try: from xarray.backends.locks import ensure_lock, SerializableLock except ImportError: # no locking for xarray <= 0.11 def ensure_lock(lock): return lock class SerializableLock(object): def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass # FIXME: Add a dedicated lock, even if ecCodes is supposed to be thread-safe # in most circumstances. See: # https://confluence.ecmwf.int/display/ECC/Frequently+Asked+Questions ECCODES_LOCK = SerializableLock() class CfGribArrayWrapper(BackendArray): def __init__(self, datastore, array): self.datastore = datastore self.shape = array.shape self.dtype = array.dtype self.array = array def __getitem__(self, key): return indexing.explicit_indexing_adapter( key, self.shape, indexing.IndexingSupport.OUTER, self._getitem) def _getitem(self, key): with self.datastore.lock: return self.array[key] class CfGribDataStore(AbstractDataStore): """ Implements the ``xr.AbstractDataStore`` read-only API for a GRIB file. """ def __init__(self, filename, lock=None, **backend_kwargs): import cfgrib if lock is None: lock = ECCODES_LOCK self.lock = ensure_lock(lock) self.ds = cfgrib.open_file(filename, **backend_kwargs) def open_store_variable(self, name, var): if isinstance(var.data, np.ndarray): data = var.data else: wrapped_array = CfGribArrayWrapper(self, var.data) data = indexing.LazilyOuterIndexedArray(wrapped_array) encoding = self.ds.encoding.copy() encoding['original_shape'] = var.data.shape return Variable(var.dimensions, data, var.attributes, encoding) def get_variables(self): return FrozenOrderedDict((k, self.open_store_variable(k, v)) for k, v in self.ds.variables.items()) def get_attrs(self): return Frozen(self.ds.attributes) def get_dimensions(self): return Frozen(self.ds.dimensions) def get_encoding(self): dims = self.get_dimensions() encoding = { 'unlimited_dims': {k for k, v in dims.items() if v is None}, } return encoding
31.769231
81
0.680993
415
3,304
5.291566
0.440964
0.027322
0.01184
0.014572
0.020036
0
0
0
0
0
0
0.005917
0.232748
3,304
103
82
32.07767
0.860355
0.283293
0
0.034483
0
0
0.012012
0
0
0
0
0.009709
0
1
0.206897
false
0.034483
0.155172
0.086207
0.551724
0.017241
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
d2104987195e80827dbe101999b5e6c5a19d3497
660
py
Python
pirates/instance/DistributedTeleportZoneAI.py
Willy5s/Pirates-Online-Rewritten
7434cf98d9b7c837d57c181e5dabd02ddf98acb7
[ "BSD-3-Clause" ]
81
2018-04-08T18:14:24.000Z
2022-01-11T07:22:15.000Z
pirates/instance/DistributedTeleportZoneAI.py
Willy5s/Pirates-Online-Rewritten
7434cf98d9b7c837d57c181e5dabd02ddf98acb7
[ "BSD-3-Clause" ]
4
2018-09-13T20:41:22.000Z
2022-01-08T06:57:00.000Z
pirates/instance/DistributedTeleportZoneAI.py
Willy5s/Pirates-Online-Rewritten
7434cf98d9b7c837d57c181e5dabd02ddf98acb7
[ "BSD-3-Clause" ]
26
2018-05-26T12:49:27.000Z
2021-09-11T09:11:59.000Z
from pirates.instance.DistributedInstanceWorldAI import DistributedInstanceWorldAI from direct.directnotify import DirectNotifyGlobal from pirates.piratesbase import PiratesGlobals from pirates.pirate.DistributedPlayerPirateAI import DistributedPlayerPirateAI class DistributedTeleportZoneAI(DistributedInstanceWorldAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedTeleportZoneAI') def __init__(self, air): DistributedInstanceWorldAI.__init__(self, air) self.type = PiratesGlobals.INSTANCE_NONE def delete(self): self.air.deallocateZone(self.zoneId) DistributedInstanceWorldAI.delete(self)
36.666667
85
0.818182
54
660
9.833333
0.462963
0.062147
0.041431
0
0
0
0
0
0
0
0
0
0.124242
660
17
86
38.823529
0.918685
0
0
0
0
0
0.037879
0.037879
0
0
0
0
0
1
0.166667
false
0
0.333333
0
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
d211fa6e6146e61fe5e0e5468bdabfe011835d24
908
py
Python
core_utils/pdf_utils.py
veronicamanukyan/2021-2-level-ctlr
387c2fd3657544c439fff634e620790bf2529836
[ "MIT" ]
null
null
null
core_utils/pdf_utils.py
veronicamanukyan/2021-2-level-ctlr
387c2fd3657544c439fff634e620790bf2529836
[ "MIT" ]
19
2022-03-07T12:40:55.000Z
2022-03-30T15:51:37.000Z
core_utils/pdf_utils.py
veronicamanukyan/2021-2-level-ctlr
387c2fd3657544c439fff634e620790bf2529836
[ "MIT" ]
48
2022-01-17T10:10:26.000Z
2022-03-22T15:05:21.000Z
""" PDF files downloader implementation """ import wget import fitz from constants import ASSETS_PATH class PDFRawFile: """ PDF files downloader class implementation. Knows how to download PDF from a given URL. Manages PDF's text. """ def __init__(self, journal_url: str, journal_id: int): self._url = journal_url self._id = journal_id self.text = None def download(self): """ Downloads PDF file by the URL given. """ wget.download(self._url, str(ASSETS_PATH / f"{self._id}_raw.pdf")) def get_text(self): """ Gets text from the PDF file downloaded. """ text = "" with fitz.open(ASSETS_PATH / f"{self._id}_raw.pdf") as pdf: for page in pdf: text += page.get_text() return text @property def own_id(self): return self._id
21.619048
74
0.585903
117
908
4.358974
0.418803
0.047059
0.070588
0.058824
0.090196
0.090196
0.090196
0
0
0
0
0
0.316079
908
41
75
22.146341
0.821256
0.241189
0
0
0
0
0.058824
0
0
0
0
0
0
1
0.210526
false
0
0.157895
0.052632
0.526316
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
d212fedb060b369a9849a463c3bbdc3732186434
1,179
py
Python
keydb/client.py
userkimcs/keydb-python
589ad851292f1e4140dc238629ff2a56e089f402
[ "MIT" ]
7
2020-05-12T03:01:26.000Z
2021-09-29T13:29:48.000Z
keydb/client.py
userkimcs/keydb-python
589ad851292f1e4140dc238629ff2a56e089f402
[ "MIT" ]
null
null
null
keydb/client.py
userkimcs/keydb-python
589ad851292f1e4140dc238629ff2a56e089f402
[ "MIT" ]
4
2020-09-05T02:22:05.000Z
2021-04-30T00:51:34.000Z
from redis import * class KeyDB(StrictRedis): def __init__(self, **kwargs): super(KeyDB, self).__init__(**kwargs) def expiremember(self, key, subkey, delay, unit=None): """ Set timeout on a subkey. This feature only available on KeyDB https://docs.keydb.dev/docs/commands/#expiremember :param key: key added by `SADD key [subkeys]` :param subkey: subkey on the set :param delay: timeout :param unit: `s` or `ms` :return: 0 if the timeout was set, otherwise 0 """ args = [key, subkey, delay] if unit is not None and unit not in ['s', 'ms']: raise ValueError("`unit` must be s or ms") if unit: args.append(unit) return self.execute_command('EXPIREMEMBER', *args) def expirememberat(self, key, subkey, timestamp): """ Set timeout on a subkey by timestamp instead of seconds https://docs.keydb.dev/docs/commands/#expirememberat :param key: :param subkey: :param timestamp: :return: """ return self.execute_command('EXPIREMEMBERAT', key, subkey, timestamp)
31.026316
77
0.596268
144
1,179
4.8125
0.416667
0.051948
0.037518
0.037518
0.138528
0.083694
0
0
0
0
0
0.002407
0.295165
1,179
37
78
31.864865
0.831528
0.379983
0
0
0
0
0.08557
0
0
0
0
0
0
1
0.230769
false
0
0.076923
0
0.538462
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
d2156903e24e3b82bfc421ebb7ae383a58c4b646
114
py
Python
PythonBasics/ForLoops/Labs/even_powers.py
achoraev/SoftUni
0cc7db470a096cc33bbe0ca6bd90060b79120573
[ "Apache-2.0" ]
null
null
null
PythonBasics/ForLoops/Labs/even_powers.py
achoraev/SoftUni
0cc7db470a096cc33bbe0ca6bd90060b79120573
[ "Apache-2.0" ]
null
null
null
PythonBasics/ForLoops/Labs/even_powers.py
achoraev/SoftUni
0cc7db470a096cc33bbe0ca6bd90060b79120573
[ "Apache-2.0" ]
null
null
null
import math n = int(input()) for i in range(0, n + 1, 2): num = math.pow(2, i) print(f"{num:.0f}")
16.285714
29
0.5
22
114
2.590909
0.772727
0
0
0
0
0
0
0
0
0
0
0.061728
0.289474
114
7
30
16.285714
0.641975
0
0
0
0
0
0.082569
0
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0.2
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d219a4e4b8aa0d9ea29bcbf5451f0ff2c83e65ee
1,448
py
Python
samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py
JigarJoshi/openapi-generator
785535b8d6881b358463994823abbda2b26ff42e
[ "Apache-2.0" ]
11,868
2018-05-12T02:58:07.000Z
2022-03-31T21:19:39.000Z
samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py
JigarJoshi/openapi-generator
785535b8d6881b358463994823abbda2b26ff42e
[ "Apache-2.0" ]
9,672
2018-05-12T14:25:43.000Z
2022-03-31T23:59:30.000Z
samples/openapi3/client/petstore/python/tests_manual/test_composed_schema_with_props_and_no_add_props.py
JigarJoshi/openapi-generator
785535b8d6881b358463994823abbda2b26ff42e
[ "Apache-2.0" ]
4,776
2018-05-12T12:06:08.000Z
2022-03-31T19:52:51.000Z
""" OpenAPI Petstore This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import sys import unittest import petstore_api from petstore_api.model.tag import Tag globals()['Tag'] = Tag from petstore_api.model.composed_schema_with_props_and_no_add_props import ComposedSchemaWithPropsAndNoAddProps class TestComposedSchemaWithPropsAndNoAddProps(unittest.TestCase): """ComposedSchemaWithPropsAndNoAddProps unit test stubs""" def setUp(self): pass def tearDown(self): pass def testComposedSchemaWithPropsAndNoAddProps(self): """Test ComposedSchemaWithPropsAndNoAddProps""" inst = ComposedSchemaWithPropsAndNoAddProps(color='red') # ComposedSchemaWithPropsAndNoAddProps should only allow in the color property # once https://github.com/OpenAPITools/openapi-generator/pull/8816 lands # this will no longer work # TODO update the test then inst = ComposedSchemaWithPropsAndNoAddProps(color='red', id=1, name='foo') with self.assertRaises(petstore_api.ApiAttributeError): inst = ComposedSchemaWithPropsAndNoAddProps(color='red', id=1, name='foo', additional=5) if __name__ == '__main__': unittest.main()
31.478261
174
0.734116
156
1,448
6.692308
0.589744
0.042146
0.12931
0.137931
0.111111
0.111111
0.111111
0.111111
0
0
0
0.010998
0.183702
1,448
45
175
32.177778
0.87225
0.393646
0
0.111111
0
0
0.030989
0
0
0
0
0.022222
0.055556
1
0.166667
false
0.111111
0.277778
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
d223a1e2610370966021f952b3bfa6e8c54cc0cf
14,320
py
Python
core/doctype/profile/profile.py
hafeez3000/wnframework
1160c108fef8f4956f5e14a072ea43e75230b9eb
[ "MIT" ]
6
2015-08-24T23:10:57.000Z
2019-11-10T06:57:23.000Z
core/doctype/profile/profile.py
hafeez3000/wnframework
1160c108fef8f4956f5e14a072ea43e75230b9eb
[ "MIT" ]
null
null
null
core/doctype/profile/profile.py
hafeez3000/wnframework
1160c108fef8f4956f5e14a072ea43e75230b9eb
[ "MIT" ]
5
2015-01-05T06:59:45.000Z
2020-11-07T15:15:07.000Z
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import webnotes, json from webnotes.utils import cint, now, cstr from webnotes import _ class DocType: def __init__(self, doc, doclist): self.doc = doc self.doclist = doclist def autoname(self): """set name as email id""" if self.doc.name not in ('Guest','Administrator'): self.doc.email = self.doc.email.strip() self.doc.name = self.doc.email if webnotes.conn.exists("Profile", self.doc.name): webnotes.msgprint("Name Exists", raise_exception=True) def validate(self): self.in_insert = self.doc.fields.get("__islocal") if self.doc.name not in ('Guest','Administrator'): self.validate_email_type(self.doc.email) self.validate_max_users() self.add_system_manager_role() self.check_enable_disable() if self.in_insert: if self.doc.name not in ("Guest", "Administrator"): self.send_welcome_mail() webnotes.msgprint(_("Welcome Email Sent")) else: self.email_new_password() self.doc.new_password = "" def check_enable_disable(self): # do not allow disabling administrator/guest if not cint(self.doc.enabled) and self.doc.name in ["Administrator", "Guest"]: webnotes.msgprint("Hey! You cannot disable user: %s" % self.doc.name, raise_exception=1) if not cint(self.doc.enabled): self.a_system_manager_should_exist() # clear sessions if disabled if not cint(self.doc.enabled) and getattr(webnotes, "login_manager", None): webnotes.local.login_manager.logout(user=self.doc.name) def validate_max_users(self): """don't allow more than max users if set in conf""" from webnotes import conf # check only when enabling a user if 'max_users' in conf and self.doc.enabled and \ self.doc.name not in ["Administrator", "Guest"] and \ cstr(self.doc.user_type).strip() in ("", "System User"): active_users = webnotes.conn.sql("""select count(*) from tabProfile where ifnull(enabled, 0)=1 and docstatus<2 and ifnull(user_type, "System User") = "System User" and name not in ('Administrator', 'Guest', %s)""", (self.doc.name,))[0][0] if active_users >= conf.max_users and conf.max_users: webnotes.msgprint(""" You already have <b>%(active_users)s</b> active users, \ which is the maximum number that you are currently allowed to add. <br /><br /> \ So, to add more users, you can:<br /> \ 1. <b>Upgrade to the unlimited users plan</b>, or<br /> \ 2. <b>Disable one or more of your existing users and try again</b>""" \ % {'active_users': active_users}, raise_exception=1) def add_system_manager_role(self): # if adding system manager, do nothing if not cint(self.doc.enabled) or ("System Manager" in [user_role.role for user_role in self.doclist.get({"parentfield": "user_roles"})]): return if self.doc.user_type == "System User" and not self.get_other_system_managers(): webnotes.msgprint("""Adding System Manager Role as there must be atleast one 'System Manager'.""") self.doclist.append({ "doctype": "UserRole", "parentfield": "user_roles", "role": "System Manager" }) def email_new_password(self): if self.doc.new_password and not self.in_insert: from webnotes.auth import _update_password _update_password(self.doc.name, self.doc.new_password) self.password_update_mail(self.doc.new_password) webnotes.msgprint("New Password Emailed.") def on_update(self): # owner is always name webnotes.conn.set(self.doc, 'owner', self.doc.name) webnotes.clear_cache(user=self.doc.name) def reset_password(self): from webnotes.utils import random_string, get_url key = random_string(32) webnotes.conn.set_value("Profile", self.doc.name, "reset_password_key", key) self.password_reset_mail(get_url("/update-password?key=" + key)) def get_other_system_managers(self): return webnotes.conn.sql("""select distinct parent from tabUserRole user_role where role='System Manager' and docstatus<2 and parent not in ('Administrator', %s) and exists (select * from `tabProfile` profile where profile.name=user_role.parent and enabled=1)""", (self.doc.name,)) def get_fullname(self): """get first_name space last_name""" return (self.doc.first_name or '') + \ (self.doc.first_name and " " or '') + (self.doc.last_name or '') def password_reset_mail(self, link): """reset password""" txt = """ ## Password Reset Dear %(first_name)s, Please click on the following link to update your new password: <a href="%(link)s">%(link)s</a> Thank you,<br> %(user_fullname)s """ self.send_login_mail("Your " + webnotes.get_config().get("app_name") + " password has been reset", txt, {"link": link}) def password_update_mail(self, password): txt = """ ## Password Update Notification Dear %(first_name)s, Your password has been updated. Here is your new password: %(new_password)s Thank you,<br> %(user_fullname)s """ self.send_login_mail("Your " + webnotes.get_config().get("app_name") + " password has been reset", txt, {"new_password": password}) def send_welcome_mail(self): """send welcome mail to user with password and login url""" from webnotes.utils import random_string, get_url self.doc.reset_password_key = random_string(32) link = get_url("/update-password?key=" + self.doc.reset_password_key) txt = """ ## %(company)s Dear %(first_name)s, A new account has been created for you. Your login id is: %(user)s To complete your registration, please click on the link below: <a href="%(link)s">%(link)s</a> Thank you,<br> %(user_fullname)s """ self.send_login_mail("Welcome to " + webnotes.get_config().get("app_name"), txt, { "link": link }) def send_login_mail(self, subject, txt, add_args): """send mail with login details""" import os from webnotes.utils.email_lib import sendmail_md from webnotes.profile import get_user_fullname from webnotes.utils import get_url full_name = get_user_fullname(webnotes.session['user']) if full_name == "Guest": full_name = "Administrator" args = { 'first_name': self.doc.first_name or self.doc.last_name or "user", 'user': self.doc.name, 'company': webnotes.conn.get_default('company') or webnotes.get_config().get("app_name"), 'login_url': get_url(), 'product': webnotes.get_config().get("app_name"), 'user_fullname': full_name } args.update(add_args) sender = webnotes.session.user not in ("Administrator", "Guest") and webnotes.session.user or None sendmail_md(recipients=self.doc.email, sender=sender, subject=subject, msg=txt % args) def a_system_manager_should_exist(self): if not self.get_other_system_managers(): webnotes.msgprint(_("""Hey! There should remain at least one System Manager"""), raise_exception=True) def on_trash(self): webnotes.clear_cache(user=self.doc.name) if self.doc.name in ["Administrator", "Guest"]: webnotes.msgprint("""Hey! You cannot delete user: %s""" % (self.name, ), raise_exception=1) self.a_system_manager_should_exist() # disable the user and log him/her out self.doc.enabled = 0 if getattr(webnotes.local, "login_manager", None): webnotes.local.login_manager.logout(user=self.doc.name) # delete their password webnotes.conn.sql("""delete from __Auth where user=%s""", self.doc.name) # delete todos webnotes.conn.sql("""delete from `tabToDo` where owner=%s""", self.doc.name) webnotes.conn.sql("""update tabToDo set assigned_by=null where assigned_by=%s""", self.doc.name) # delete events webnotes.conn.sql("""delete from `tabEvent` where owner=%s and event_type='Private'""", self.doc.name) webnotes.conn.sql("""delete from `tabEvent User` where person=%s""", self.doc.name) # delete messages webnotes.conn.sql("""delete from `tabComment` where comment_doctype='Message' and (comment_docname=%s or owner=%s)""", (self.doc.name, self.doc.name)) def before_rename(self, olddn, newdn, merge=False): webnotes.clear_cache(user=olddn) self.validate_rename(olddn, newdn) def validate_rename(self, olddn, newdn): # do not allow renaming administrator and guest if olddn in ["Administrator", "Guest"]: webnotes.msgprint("""Hey! You are restricted from renaming the user: %s""" % \ (olddn, ), raise_exception=1) self.validate_email_type(newdn) def validate_email_type(self, email): from webnotes.utils import validate_email_add email = email.strip() if not validate_email_add(email): webnotes.msgprint("%s is not a valid email id" % email) raise Exception def after_rename(self, olddn, newdn, merge=False): tables = webnotes.conn.sql("show tables") for tab in tables: desc = webnotes.conn.sql("desc `%s`" % tab[0], as_dict=1) has_fields = [] for d in desc: if d.get('Field') in ['owner', 'modified_by']: has_fields.append(d.get('Field')) for field in has_fields: webnotes.conn.sql("""\ update `%s` set `%s`=%s where `%s`=%s""" % \ (tab[0], field, '%s', field, '%s'), (newdn, olddn)) # set email webnotes.conn.sql("""\ update `tabProfile` set email=%s where name=%s""", (newdn, newdn)) # update __Auth table if not merge: webnotes.conn.sql("""update __Auth set user=%s where user=%s""", (newdn, olddn)) def add_roles(self, *roles): for role in roles: if role in [d.role for d in self.doclist.get({"doctype":"UserRole"})]: continue self.bean.doclist.append({ "doctype": "UserRole", "parentfield": "user_roles", "role": role }) self.bean.save() @webnotes.whitelist() def get_languages(): from webnotes.translate import get_lang_dict languages = get_lang_dict().keys() languages.sort() return [""] + languages @webnotes.whitelist() def get_all_roles(arg=None): """return all roles""" return [r[0] for r in webnotes.conn.sql("""select name from tabRole where name not in ('Administrator', 'Guest', 'All') order by name""")] @webnotes.whitelist() def get_user_roles(arg=None): """get roles for a user""" return webnotes.get_roles(webnotes.form_dict['uid']) @webnotes.whitelist() def get_perm_info(arg=None): """get permission info""" return webnotes.conn.sql("""select parent, permlevel, `read`, `write`, submit, cancel, amend from tabDocPerm where role=%s and docstatus<2 order by parent, permlevel""", webnotes.form_dict['role'], as_dict=1) @webnotes.whitelist(allow_guest=True) def update_password(new_password, key=None, old_password=None): # verify old password if key: user = webnotes.conn.get_value("Profile", {"reset_password_key":key}) if not user: return _("Cannot Update: Incorrect / Expired Link.") elif old_password: user = webnotes.session.user if not webnotes.conn.sql("""select user from __Auth where password=password(%s) and user=%s""", (old_password, user)): return _("Cannot Update: Incorrect Password") from webnotes.auth import _update_password _update_password(user, new_password) webnotes.conn.set_value("Profile", user, "reset_password_key", "") return _("Password Updated") @webnotes.whitelist(allow_guest=True) def sign_up(email, full_name): profile = webnotes.conn.get("Profile", {"email": email}) if profile: if profile.disabled: return _("Registered but disabled.") else: return _("Already Registered") else: if webnotes.conn.sql("""select count(*) from tabProfile where TIMEDIFF(%s, modified) > '1:00:00' """, now())[0][0] > 200: raise Exception, "Too Many New Profiles" from webnotes.utils import random_string profile = webnotes.bean({ "doctype":"Profile", "email": email, "first_name": full_name, "enabled": 1, "new_password": random_string(10), "user_type": "Website User" }) profile.ignore_permissions = True profile.insert() return _("Registration Details Emailed.") @webnotes.whitelist(allow_guest=True) def reset_password(user): user = webnotes.form_dict.get('user', '') if user in ["demo@erpnext.com", "Administrator"]: return "Not allowed" if webnotes.conn.sql("""select name from tabProfile where name=%s""", user): # Hack! webnotes.session["user"] = "Administrator" profile = webnotes.bean("Profile", user) profile.get_controller().reset_password() return "Password reset details sent to your email." else: return "No such user (%s)" % user def profile_query(doctype, txt, searchfield, start, page_len, filters): from webnotes.widgets.reportview import get_match_cond return webnotes.conn.sql("""select name, concat_ws(' ', first_name, middle_name, last_name) from `tabProfile` where ifnull(enabled, 0)=1 and docstatus < 2 and name not in ('Administrator', 'Guest') and user_type != 'Website User' and (%(key)s like "%(txt)s" or concat_ws(' ', first_name, middle_name, last_name) like "%(txt)s") %(mcond)s order by case when name like "%(txt)s" then 0 else 1 end, case when concat_ws(' ', first_name, middle_name, last_name) like "%(txt)s" then 0 else 1 end, name asc limit %(start)s, %(page_len)s""" % {'key': searchfield, 'txt': "%%%s%%" % txt, 'mcond':get_match_cond(doctype, searchfield), 'start': start, 'page_len': page_len}) def get_total_users(): """Returns total no. of system users""" return webnotes.conn.sql("""select count(*) from `tabProfile` where enabled = 1 and user_type != 'Website User' and name not in ('Administrator', 'Guest')""")[0][0] def get_active_users(): """Returns No. of system users who logged in, in the last 3 days""" return webnotes.conn.sql("""select count(*) from `tabProfile` where enabled = 1 and user_type != 'Website User' and name not in ('Administrator', 'Guest') and hour(timediff(now(), last_login)) < 72""")[0][0] def get_website_users(): """Returns total no. of website users""" return webnotes.conn.sql("""select count(*) from `tabProfile` where enabled = 1 and user_type = 'Website User'""")[0][0] def get_active_website_users(): """Returns No. of website users who logged in, in the last 3 days""" return webnotes.conn.sql("""select count(*) from `tabProfile` where enabled = 1 and user_type = 'Website User' and hour(timediff(now(), last_login)) < 72""")[0][0]
33.773585
101
0.694204
2,077
14,320
4.64131
0.159846
0.039212
0.029668
0.026141
0.360996
0.286929
0.222614
0.191286
0.141286
0.118776
0
0.005497
0.161522
14,320
423
102
33.853428
0.797368
0.032332
0
0.201923
0
0
0.360928
0.01471
0
0
0
0.002364
0
0
null
null
0.115385
0.054487
null
null
0.032051
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
d227debd1174576671e25f5c6b7ffec5525a686d
30,607
py
Python
binancechain/transaction_pb2.py
lmacken/binance-chain-python
483e51394ebc9f9998f5248910ac7b7dff7198f9
[ "MIT" ]
22
2019-04-27T02:14:52.000Z
2021-01-04T00:37:41.000Z
binancechain/transaction_pb2.py
redquantum/binance-chain-python
483e51394ebc9f9998f5248910ac7b7dff7198f9
[ "MIT" ]
7
2019-04-28T20:57:49.000Z
2021-09-03T03:39:22.000Z
binancechain/transaction_pb2.py
redquantum/binance-chain-python
483e51394ebc9f9998f5248910ac7b7dff7198f9
[ "MIT" ]
9
2019-04-27T23:43:51.000Z
2021-04-15T18:09:51.000Z
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: transaction.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='transaction.proto', package='transaction', syntax='proto3', serialized_pb=_b('\n\x11transaction.proto\x12\x0btransaction\"U\n\x05StdTx\x12\x0c\n\x04msgs\x18\x01 \x03(\x0c\x12\x12\n\nsignatures\x18\x02 \x03(\x0c\x12\x0c\n\x04memo\x18\x03 \x01(\t\x12\x0e\n\x06source\x18\x04 \x01(\x03\x12\x0c\n\x04\x64\x61ta\x18\x05 \x01(\x0c\"\\\n\x0cStdSignature\x12\x0f\n\x07pub_key\x18\x01 \x01(\x0c\x12\x11\n\tsignature\x18\x02 \x01(\x0c\x12\x16\n\x0e\x61\x63\x63ount_number\x18\x03 \x01(\x03\x12\x10\n\x08sequence\x18\x04 \x01(\x03\"\x05\n\x03Msg\"\x8d\x01\n\x08NewOrder\x12\x0e\n\x06sender\x18\x01 \x01(\x0c\x12\n\n\x02id\x18\x02 \x01(\t\x12\x0e\n\x06symbol\x18\x03 \x01(\t\x12\x11\n\tordertype\x18\x04 \x01(\x03\x12\x0c\n\x04side\x18\x05 \x01(\x03\x12\r\n\x05price\x18\x06 \x01(\x03\x12\x10\n\x08quantity\x18\x07 \x01(\x03\x12\x13\n\x0btimeinforce\x18\x08 \x01(\x03\"<\n\x0b\x43\x61ncelOrder\x12\x0e\n\x06sender\x18\x01 \x01(\x0c\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\r\n\x05refid\x18\x03 \x01(\t\"P\n\x04Send\x12\"\n\x06inputs\x18\x01 \x03(\x0b\x32\x12.transaction.Input\x12$\n\x07outputs\x18\x02 \x03(\x0b\x32\x13.transaction.Output\"&\n\x05Token\x12\r\n\x05\x64\x65nom\x18\x01 \x01(\t\x12\x0e\n\x06\x61mount\x18\x02 \x01(\x03\";\n\x05Input\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x0c\x12!\n\x05\x63oins\x18\x02 \x03(\x0b\x32\x12.transaction.Token\"<\n\x06Output\x12\x0f\n\x07\x61\x64\x64ress\x18\x01 \x01(\x0c\x12!\n\x05\x63oins\x18\x02 \x03(\x0b\x32\x12.transaction.Token\"6\n\x06\x46reeze\x12\x0c\n\x04\x66rom\x18\x01 \x01(\x0c\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x0e\n\x06\x61mount\x18\x03 \x01(\x03\"8\n\x08Unfreeze\x12\x0c\n\x04\x66rom\x18\x01 \x01(\x0c\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x0e\n\x06\x61mount\x18\x03 \x01(\x03\"S\n\x04Vote\x12\x13\n\x0bproposal_id\x18\x01 \x01(\x03\x12\r\n\x05voter\x18\x02 \x01(\x0c\x12\'\n\x06option\x18\x03 \x01(\x0e\x32\x17.transaction.VoteOption\"[\n\x05Issue\x12\x0c\n\x04\x66rom\x18\x01 \x01(\x0c\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0e\n\x06symbol\x18\x03 \x01(\t\x12\x14\n\x0ctotal_supply\x18\x04 \x01(\x03\x12\x10\n\x08mintable\x18\x05 \x01(\x08\"4\n\x04Mint\x12\x0c\n\x04\x66rom\x18\x01 \x01(\x0c\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x0e\n\x06\x61mount\x18\x03 \x01(\x03\"4\n\x04\x42urn\x12\x0c\n\x04\x66rom\x18\x01 \x01(\x0c\x12\x0e\n\x06symbol\x18\x02 \x01(\t\x12\x0e\n\x06\x61mount\x18\x03 \x01(\x03*G\n\nVoteOption\x12\x0b\n\x07Unknown\x10\x00\x12\x07\n\x03Yes\x10\x01\x12\x0b\n\x07\x41\x62stain\x10\x02\x12\x06\n\x02No\x10\x03\x12\x0e\n\nNoWithVeto\x10\x04\x62\x06proto3') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _VOTEOPTION = _descriptor.EnumDescriptor( name='VoteOption', full_name='transaction.VoteOption', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='Unknown', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='Yes', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='Abstain', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='No', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='NoWithVeto', index=4, number=4, options=None, type=None), ], containing_type=None, options=None, serialized_start=1073, serialized_end=1144, ) _sym_db.RegisterEnumDescriptor(_VOTEOPTION) VoteOption = enum_type_wrapper.EnumTypeWrapper(_VOTEOPTION) Unknown = 0 Yes = 1 Abstain = 2 No = 3 NoWithVeto = 4 _STDTX = _descriptor.Descriptor( name='StdTx', full_name='transaction.StdTx', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='msgs', full_name='transaction.StdTx.msgs', index=0, number=1, type=12, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='signatures', full_name='transaction.StdTx.signatures', index=1, number=2, type=12, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='memo', full_name='transaction.StdTx.memo', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='source', full_name='transaction.StdTx.source', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='transaction.StdTx.data', index=4, number=5, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=34, serialized_end=119, ) _STDSIGNATURE = _descriptor.Descriptor( name='StdSignature', full_name='transaction.StdSignature', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='pub_key', full_name='transaction.StdSignature.pub_key', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='signature', full_name='transaction.StdSignature.signature', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='account_number', full_name='transaction.StdSignature.account_number', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='sequence', full_name='transaction.StdSignature.sequence', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=121, serialized_end=213, ) _MSG = _descriptor.Descriptor( name='Msg', full_name='transaction.Msg', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=215, serialized_end=220, ) _NEWORDER = _descriptor.Descriptor( name='NewOrder', full_name='transaction.NewOrder', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='sender', full_name='transaction.NewOrder.sender', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='id', full_name='transaction.NewOrder.id', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='symbol', full_name='transaction.NewOrder.symbol', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='ordertype', full_name='transaction.NewOrder.ordertype', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='side', full_name='transaction.NewOrder.side', index=4, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='price', full_name='transaction.NewOrder.price', index=5, number=6, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='quantity', full_name='transaction.NewOrder.quantity', index=6, number=7, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='timeinforce', full_name='transaction.NewOrder.timeinforce', index=7, number=8, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=223, serialized_end=364, ) _CANCELORDER = _descriptor.Descriptor( name='CancelOrder', full_name='transaction.CancelOrder', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='sender', full_name='transaction.CancelOrder.sender', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='symbol', full_name='transaction.CancelOrder.symbol', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='refid', full_name='transaction.CancelOrder.refid', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=366, serialized_end=426, ) _SEND = _descriptor.Descriptor( name='Send', full_name='transaction.Send', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='inputs', full_name='transaction.Send.inputs', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='outputs', full_name='transaction.Send.outputs', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=428, serialized_end=508, ) _TOKEN = _descriptor.Descriptor( name='Token', full_name='transaction.Token', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='denom', full_name='transaction.Token.denom', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='amount', full_name='transaction.Token.amount', index=1, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=510, serialized_end=548, ) _INPUT = _descriptor.Descriptor( name='Input', full_name='transaction.Input', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='address', full_name='transaction.Input.address', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='coins', full_name='transaction.Input.coins', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=550, serialized_end=609, ) _OUTPUT = _descriptor.Descriptor( name='Output', full_name='transaction.Output', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='address', full_name='transaction.Output.address', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='coins', full_name='transaction.Output.coins', index=1, number=2, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=611, serialized_end=671, ) _FREEZE = _descriptor.Descriptor( name='Freeze', full_name='transaction.Freeze', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='from', full_name='transaction.Freeze.from', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='symbol', full_name='transaction.Freeze.symbol', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='amount', full_name='transaction.Freeze.amount', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=673, serialized_end=727, ) _UNFREEZE = _descriptor.Descriptor( name='Unfreeze', full_name='transaction.Unfreeze', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='from', full_name='transaction.Unfreeze.from', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='symbol', full_name='transaction.Unfreeze.symbol', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='amount', full_name='transaction.Unfreeze.amount', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=729, serialized_end=785, ) _VOTE = _descriptor.Descriptor( name='Vote', full_name='transaction.Vote', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='proposal_id', full_name='transaction.Vote.proposal_id', index=0, number=1, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='voter', full_name='transaction.Vote.voter', index=1, number=2, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='option', full_name='transaction.Vote.option', index=2, number=3, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=787, serialized_end=870, ) _ISSUE = _descriptor.Descriptor( name='Issue', full_name='transaction.Issue', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='from', full_name='transaction.Issue.from', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='name', full_name='transaction.Issue.name', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='symbol', full_name='transaction.Issue.symbol', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='total_supply', full_name='transaction.Issue.total_supply', index=3, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='mintable', full_name='transaction.Issue.mintable', index=4, number=5, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=872, serialized_end=963, ) _MINT = _descriptor.Descriptor( name='Mint', full_name='transaction.Mint', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='from', full_name='transaction.Mint.from', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='symbol', full_name='transaction.Mint.symbol', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='amount', full_name='transaction.Mint.amount', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=965, serialized_end=1017, ) _BURN = _descriptor.Descriptor( name='Burn', full_name='transaction.Burn', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='from', full_name='transaction.Burn.from', index=0, number=1, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='symbol', full_name='transaction.Burn.symbol', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='amount', full_name='transaction.Burn.amount', index=2, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=1019, serialized_end=1071, ) _SEND.fields_by_name['inputs'].message_type = _INPUT _SEND.fields_by_name['outputs'].message_type = _OUTPUT _INPUT.fields_by_name['coins'].message_type = _TOKEN _OUTPUT.fields_by_name['coins'].message_type = _TOKEN _VOTE.fields_by_name['option'].enum_type = _VOTEOPTION DESCRIPTOR.message_types_by_name['StdTx'] = _STDTX DESCRIPTOR.message_types_by_name['StdSignature'] = _STDSIGNATURE DESCRIPTOR.message_types_by_name['Msg'] = _MSG DESCRIPTOR.message_types_by_name['NewOrder'] = _NEWORDER DESCRIPTOR.message_types_by_name['CancelOrder'] = _CANCELORDER DESCRIPTOR.message_types_by_name['Send'] = _SEND DESCRIPTOR.message_types_by_name['Token'] = _TOKEN DESCRIPTOR.message_types_by_name['Input'] = _INPUT DESCRIPTOR.message_types_by_name['Output'] = _OUTPUT DESCRIPTOR.message_types_by_name['Freeze'] = _FREEZE DESCRIPTOR.message_types_by_name['Unfreeze'] = _UNFREEZE DESCRIPTOR.message_types_by_name['Vote'] = _VOTE DESCRIPTOR.message_types_by_name['Issue'] = _ISSUE DESCRIPTOR.message_types_by_name['Mint'] = _MINT DESCRIPTOR.message_types_by_name['Burn'] = _BURN DESCRIPTOR.enum_types_by_name['VoteOption'] = _VOTEOPTION StdTx = _reflection.GeneratedProtocolMessageType('StdTx', (_message.Message,), dict( DESCRIPTOR = _STDTX, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.StdTx) )) _sym_db.RegisterMessage(StdTx) StdSignature = _reflection.GeneratedProtocolMessageType('StdSignature', (_message.Message,), dict( DESCRIPTOR = _STDSIGNATURE, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.StdSignature) )) _sym_db.RegisterMessage(StdSignature) Msg = _reflection.GeneratedProtocolMessageType('Msg', (_message.Message,), dict( DESCRIPTOR = _MSG, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Msg) )) _sym_db.RegisterMessage(Msg) NewOrder = _reflection.GeneratedProtocolMessageType('NewOrder', (_message.Message,), dict( DESCRIPTOR = _NEWORDER, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.NewOrder) )) _sym_db.RegisterMessage(NewOrder) CancelOrder = _reflection.GeneratedProtocolMessageType('CancelOrder', (_message.Message,), dict( DESCRIPTOR = _CANCELORDER, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.CancelOrder) )) _sym_db.RegisterMessage(CancelOrder) Send = _reflection.GeneratedProtocolMessageType('Send', (_message.Message,), dict( DESCRIPTOR = _SEND, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Send) )) _sym_db.RegisterMessage(Send) Token = _reflection.GeneratedProtocolMessageType('Token', (_message.Message,), dict( DESCRIPTOR = _TOKEN, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Token) )) _sym_db.RegisterMessage(Token) Input = _reflection.GeneratedProtocolMessageType('Input', (_message.Message,), dict( DESCRIPTOR = _INPUT, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Input) )) _sym_db.RegisterMessage(Input) Output = _reflection.GeneratedProtocolMessageType('Output', (_message.Message,), dict( DESCRIPTOR = _OUTPUT, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Output) )) _sym_db.RegisterMessage(Output) Freeze = _reflection.GeneratedProtocolMessageType('Freeze', (_message.Message,), dict( DESCRIPTOR = _FREEZE, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Freeze) )) _sym_db.RegisterMessage(Freeze) Unfreeze = _reflection.GeneratedProtocolMessageType('Unfreeze', (_message.Message,), dict( DESCRIPTOR = _UNFREEZE, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Unfreeze) )) _sym_db.RegisterMessage(Unfreeze) Vote = _reflection.GeneratedProtocolMessageType('Vote', (_message.Message,), dict( DESCRIPTOR = _VOTE, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Vote) )) _sym_db.RegisterMessage(Vote) Issue = _reflection.GeneratedProtocolMessageType('Issue', (_message.Message,), dict( DESCRIPTOR = _ISSUE, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Issue) )) _sym_db.RegisterMessage(Issue) Mint = _reflection.GeneratedProtocolMessageType('Mint', (_message.Message,), dict( DESCRIPTOR = _MINT, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Mint) )) _sym_db.RegisterMessage(Mint) Burn = _reflection.GeneratedProtocolMessageType('Burn', (_message.Message,), dict( DESCRIPTOR = _BURN, __module__ = 'transaction_pb2' # @@protoc_insertion_point(class_scope:transaction.Burn) )) _sym_db.RegisterMessage(Burn) # @@protoc_insertion_point(module_scope)
34.236018
2,481
0.717091
3,941
30,607
5.304999
0.070287
0.063137
0.058162
0.051562
0.696944
0.659014
0.658966
0.644043
0.638638
0.592624
0
0.045312
0.144836
30,607
893
2,482
34.274356
0.753458
0.032999
0
0.691554
1
0.003672
0.154106
0.108361
0
0
0
0
0
1
0
false
0
0.008568
0
0.008568
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d22a9c09fd82acef5ca72bbd2931ab6a01a4d35e
737
py
Python
src/backend/backend/profiles/models.py
jordimart/findmenu-ng-django
14606889f8b8a1aeb49c87128de6efe084377365
[ "MIT" ]
null
null
null
src/backend/backend/profiles/models.py
jordimart/findmenu-ng-django
14606889f8b8a1aeb49c87128de6efe084377365
[ "MIT" ]
null
null
null
src/backend/backend/profiles/models.py
jordimart/findmenu-ng-django
14606889f8b8a1aeb49c87128de6efe084377365
[ "MIT" ]
null
null
null
from django.db import models from ..core.models import TimestampedModel from ..authentication.models import User class Profile(TimestampedModel): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True,) image = models.URLField(blank=True) city = models.CharField(blank=True, max_length=40) name = models.CharField(blank=True, max_length=40) first_name = models.CharField(blank=True, max_length=40) last_name = models.CharField(blank=True, max_length=40) date_birth = models.CharField(blank=True, max_length=40) friends = models.IntegerField(default=0) restaurants = models.IntegerField(default=0) def __str__(self): return self.user.username
35.095238
63
0.744912
96
737
5.583333
0.427083
0.117537
0.186567
0.223881
0.348881
0.348881
0.348881
0.218284
0
0
0
0.019139
0.149254
737
20
64
36.85
0.835726
0
0
0
0
0
0
0
0
0
0
0
0
1
0.0625
false
0
0.1875
0.0625
1
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d23fc75c6f45d0e523326c4b77609e03009b7065
1,681
py
Python
vbclient/common/utils.py
huaweicloudsdk/osc_vbs
98834c9425af3e8bff6e2db4602c3f7bd72829bd
[ "Apache-2.0" ]
3
2017-01-23T03:36:00.000Z
2021-01-30T14:00:34.000Z
vbclient/common/utils.py
huaweicloudsdk/osc_vbs
98834c9425af3e8bff6e2db4602c3f7bd72829bd
[ "Apache-2.0" ]
3
2017-02-23T01:52:02.000Z
2017-02-25T07:55:27.000Z
vbclient/common/utils.py
huaweicloudsdk/osc_vbs
98834c9425af3e8bff6e2db4602c3f7bd72829bd
[ "Apache-2.0" ]
1
2017-09-18T22:04:54.000Z
2017-09-18T22:04:54.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from datetime import datetime def get_id(obj): """Get obj's uuid or object itself if no uuid Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ try: return obj.uuid or obj['uuid'] except AttributeError: return obj def remove_empty_from_dict(original): """get a new dict which removes keys with empty values :param dict original: original dict, should not be None :return: a new dict which removes keys with empty values """ return dict((k, v) for k, v in original.iteritems() if v) def str_range(start, end): """get range with string type""" return [str(i) for i in range(start, end)] def format_time(time_in_long, _format='%Y-%m-%d %H:%M:%S'): if time_in_long: # if time-long is with mill seconds if time_in_long > pow(10, 12): time_in_long /= 1000 timestamp = datetime.fromtimestamp(time_in_long) return timestamp.strftime(_format) else: return ''
31.716981
77
0.679952
257
1,681
4.377432
0.509728
0.053333
0.044444
0.028444
0.069333
0.069333
0.069333
0.069333
0.069333
0
0
0.01007
0.232005
1,681
52
78
32.326923
0.861348
0.584771
0
0
0
0
0.03271
0
0
0
0
0
0
1
0.222222
false
0
0.055556
0
0.611111
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
d24dbf01c99b22cb426f083f92b5419b9199266f
80
py
Python
study-notes/geekbang.org/视频课/零基础学Python/06 | 变量的定义和常用操作/network_bandwidth.py
coderZsq/coderZsq.practice.data
234cf757219b9e46082f883f9bd19088a65a771e
[ "MIT" ]
3
2019-08-02T03:53:03.000Z
2020-03-16T07:13:22.000Z
study-notes/geekbang.org/视频课/零基础学Python/06 | 变量的定义和常用操作/network_bandwidth.py
coderZsq/coderZsq.practice.data
234cf757219b9e46082f883f9bd19088a65a771e
[ "MIT" ]
2
2019-05-24T11:52:31.000Z
2019-07-29T02:39:22.000Z
study-notes/geekbang.org/视频课/零基础学Python/06 | 变量的定义和常用操作/network_bandwidth.py
coderZsq/coderZsq.practice.data
234cf757219b9e46082f883f9bd19088a65a771e
[ "MIT" ]
1
2019-08-06T07:51:20.000Z
2019-08-06T07:51:20.000Z
# 网络带宽计算 # print(100 / 8) bandwidth = 100 ratio = 8 print(bandwidth / ratio)
8.888889
24
0.65
11
80
4.727273
0.545455
0
0
0
0
0
0
0
0
0
0
0.129032
0.225
80
8
25
10
0.709677
0.2625
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d2597830301608743775c41c9c723258aa5697ab
577
py
Python
prac.py
mayanks888/QATM_pytorch_ros2
936ff265e4c0f0cbfa63855e07a95e15b2b0e336
[ "MIT" ]
null
null
null
prac.py
mayanks888/QATM_pytorch_ros2
936ff265e4c0f0cbfa63855e07a95e15b2b0e336
[ "MIT" ]
null
null
null
prac.py
mayanks888/QATM_pytorch_ros2
936ff265e4c0f0cbfa63855e07a95e15b2b0e336
[ "MIT" ]
null
null
null
import pandas as pd import cv2 bbox_info=[1449, 538, 1479 ,605] temp_path='/home/mayank_sati/Desktop/one_Shot_learning/image_xs/1566366024136726396_369144.535422_4321493.08002.jpg' img = cv2.imread(temp_path) frame = img[int(bbox_info[1]):int(bbox_info[3]), int(bbox_info[0]):int(bbox_info[3])] frame = img[(bbox_info[1]):(bbox_info[3]), (bbox_info[0]):(bbox_info[3])] xmin=int(bbox_info[0]) xmax=int(bbox_info[2]) ymin=int(bbox_info[1]) ymax=int(bbox_info[3]) # crop_img = img[y:y+h, x:x+w] crop_img = img[538:605, 1449:1479] crop_img1 = img[ymin:ymax, xmin:xmax] print(1)
30.368421
116
0.736568
111
577
3.612613
0.423423
0.259352
0.219451
0.089776
0
0
0
0
0
0
0
0.162921
0.074523
577
19
117
30.368421
0.588015
0.048527
0
0
0
0
0.189781
0.189781
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0.071429
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d2668ff2ee2f27255e785c33647e9bbd3ba562fb
1,923
py
Python
exam_settings.py
BjornFJohansson/molbio_test_generator
ee96873b2c4c4930834729a82d1d4097e2f54943
[ "BSD-2-Clause" ]
null
null
null
exam_settings.py
BjornFJohansson/molbio_test_generator
ee96873b2c4c4930834729a82d1d4097e2f54943
[ "BSD-2-Clause" ]
null
null
null
exam_settings.py
BjornFJohansson/molbio_test_generator
ee96873b2c4c4930834729a82d1d4097e2f54943
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- student_list_file = "alunos.txt" shelf_file = "shelf.shelf" included_files_location = u"/home/bjorn/Dropbox/python_packages/bio_info_questions/bio_info_questions/files_to_be_included" password_to_open_exam = u"zyxpep93" password_to_see_correct_exam = u"LWQsGHefywehfLSFKG6Q3W" exam_folder = "./empty_exams" start_separator = u"\n=========== start of exame =====================================================\n" question_separator = u"\n*********** Question {} ***********\n" endseparator = u"\n========== end of exame ========================================================" header = u'''================================================================================ Genética Molecular e Bioinformática 2704N9 | Licenciatura em Bioquímica Nome {name} Número mecanográfico (mec) {mec} Exam date 2014-06-25|Wednesday June 25|Week 25 Unix time stamp {timestamp} ================================================================================ Instruções para o exame: Este exame tem {number_of_questions} questões. Deve responder às questões dentro neste documento. Preencha a sua resposta, substituindo os simbolos "?". Por favor NÂO MODIFIQUE MAIS NADA no exame, será corrigido automaticamente. em particular, não modifique ou remova o QuestionID, que serve para identificar as respostas certas. Instructions for completing the exam: This exam has {number_of_questions} questions. You shuld respond to these questions within this document. Fill in your answers where you find the "?" symbol(s) in each question. Please do not edit anything else, as this exam will be automatically corrected. In particular, do NOT modify the QuestionID as this is used for identifying the correct answer. '''
46.902439
131
0.590224
216
1,923
5.125
0.671296
0.00542
0.028907
0
0
0
0
0
0
0
0
0.014139
0.190848
1,923
40
132
48.075
0.697301
0.021841
0
0
0
0
0.808409
0.228313
0
0
0
0
0
1
0
false
0.064516
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
d26ffb29c1b105e644396bb04783df94f4f8ada8
129
py
Python
venv/lib/python3.6/site-packages/pylint/test/extensions/data/bad_builtin.py
aitoehigie/britecore_flask
eef1873dbe6b2cc21f770bc6dec783007ae4493b
[ "MIT" ]
null
null
null
venv/lib/python3.6/site-packages/pylint/test/extensions/data/bad_builtin.py
aitoehigie/britecore_flask
eef1873dbe6b2cc21f770bc6dec783007ae4493b
[ "MIT" ]
1
2021-06-01T23:32:38.000Z
2021-06-01T23:32:38.000Z
venv/lib/python3.6/site-packages/pylint/test/extensions/data/bad_builtin.py
aitoehigie/britecore_flask
eef1873dbe6b2cc21f770bc6dec783007ae4493b
[ "MIT" ]
null
null
null
# pylint: disable=missing-docstring TEST = map(str, (1, 2, 3)) # [bad-builtin] TEST1 = filter(str, (1, 2, 3)) # [bad-builtin]
25.8
47
0.612403
20
129
3.95
0.7
0.101266
0.126582
0.151899
0.405063
0.405063
0
0
0
0
0
0.065421
0.170543
129
4
48
32.25
0.672897
0.472868
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d2714b490faee527bf61baefc249241f4ebbdaf5
148
py
Python
tests/fixtures/test_inline_graphics/content_01_expected.py
elifesciences/elife-tools
ee345bf0e6703ef0f7e718355e85730abbdfd117
[ "MIT" ]
9
2015-04-16T08:13:31.000Z
2020-05-18T14:03:06.000Z
tests/fixtures/test_inline_graphics/content_01_expected.py
elifesciences/elife-tools
ee345bf0e6703ef0f7e718355e85730abbdfd117
[ "MIT" ]
310
2015-02-11T00:30:09.000Z
2021-07-14T23:58:50.000Z
tests/fixtures/test_inline_graphics/content_01_expected.py
elifesciences/elife-tools
ee345bf0e6703ef0f7e718355e85730abbdfd117
[ "MIT" ]
9
2015-02-04T01:21:28.000Z
2021-06-15T12:50:47.000Z
expected = [ { "xlink_href": "elife00013inf001", "type": "inline-graphic", "position": 1, "ordinal": 1, } ]
16.444444
41
0.459459
11
148
6.090909
0.909091
0
0
0
0
0
0
0
0
0
0
0.106383
0.364865
148
8
42
18.5
0.606383
0
0
0
0
0
0.398649
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d27303be5165de1e6c544bf23f2ed85b45e0b9ab
1,017
py
Python
vnpy_esunny/api/generator/esunny_md_commen_constant.py
Edanflame/vnpy_esunny
71e4067911793533cd2947535163dbceb011b102
[ "MIT" ]
null
null
null
vnpy_esunny/api/generator/esunny_md_commen_constant.py
Edanflame/vnpy_esunny
71e4067911793533cd2947535163dbceb011b102
[ "MIT" ]
null
null
null
vnpy_esunny/api/generator/esunny_md_commen_constant.py
Edanflame/vnpy_esunny
71e4067911793533cd2947535163dbceb011b102
[ "MIT" ]
4
2021-07-28T06:52:13.000Z
2022-03-30T03:39:16.000Z
APIYNFLAG_YES = "Y" APIYNFLAG_NO = "N" APILOGLEVEL_NONE = "N" APILOGLEVEL_ERROR = "E" APILOGLEVEL_WARNING = "W" APILOGLEVEL_DEBUG = "D" TAPI_COMMODITY_TYPE_NONE = "N" TAPI_COMMODITY_TYPE_SPOT = "P" TAPI_COMMODITY_TYPE_FUTURES = "F" TAPI_COMMODITY_TYPE_OPTION = "O" TAPI_COMMODITY_TYPE_SPREAD_MONTH = "S" TAPI_COMMODITY_TYPE_SPREAD_COMMODITY = "M" TAPI_COMMODITY_TYPE_BUL = "U" TAPI_COMMODITY_TYPE_BER = "E" TAPI_COMMODITY_TYPE_STD = "D" TAPI_COMMODITY_TYPE_STG = "G" TAPI_COMMODITY_TYPE_PRT = "R" TAPI_COMMODITY_TYPE_BLT = "L" TAPI_COMMODITY_TYPE_BRT = "Q" TAPI_COMMODITY_TYPE_DIRECTFOREX = "X" TAPI_COMMODITY_TYPE_INDIRECTFOREX = "I" TAPI_COMMODITY_TYPE_CROSSFOREX = "C" TAPI_COMMODITY_TYPE_INDEX = "Z" TAPI_COMMODITY_TYPE_STOCK = "T" TAPI_COMMODITY_TYPE_SPOT_TRADINGDEFER = "Y" TAPI_COMMODITY_TYPE_FUTURE_LOCK = "J" TAPI_COMMODITY_TYPE_EFP = "A" TAPI_COMMODITY_TYPE_TAS = "B" TAPI_CALLPUT_FLAG_CALL = "C" TAPI_CALLPUT_FLAG_PUT = "P" TAPI_CALLPUT_FLAG_NONE = "N" TAPI_AUTHTYPE_DIRECT = "1" TAPI_AUTHTYPE_RELAY = "2"
29.911765
43
0.80531
155
1,017
4.709677
0.419355
0.391781
0.512329
0.049315
0
0
0
0
0
0
0
0.002179
0.097345
1,017
33
44
30.818182
0.793028
0
0
0
0
0
0.032448
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d2777a03ee938020381699cf3c583a8569fa44ce
638
py
Python
tests/test_admin.py
cperrin88/django-treenode
48a037d6eb87ea766e8812c9918ae74375b9e4ea
[ "MIT" ]
259
2018-05-03T08:30:56.000Z
2022-03-30T12:57:12.000Z
tests/test_admin.py
cperrin88/django-treenode
48a037d6eb87ea766e8812c9918ae74375b9e4ea
[ "MIT" ]
47
2018-05-09T07:50:56.000Z
2022-02-11T22:16:03.000Z
tests/test_admin.py
cperrin88/django-treenode
48a037d6eb87ea766e8812c9918ae74375b9e4ea
[ "MIT" ]
23
2018-05-18T07:14:11.000Z
2022-02-11T21:09:34.000Z
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.staticfiles import finders from django.test import TestCase # from treenode.admin import TreeNodeModelAdmin class TreeNodeAdminTestCase(TestCase): def setUp(self): pass def tearDown(self): pass def assertStaticFile(self, path): result = finders.find(path) self.assertTrue(result != None) def test_staticfiles(self): if 'treenode' not in settings.INSTALLED_APPS: return self.assertStaticFile('treenode/css/treenode.css') self.assertStaticFile('treenode/js/treenode.js')
23.62963
58
0.684953
71
638
6.126761
0.521127
0.068966
0.050575
0
0
0
0
0
0
0
0
0.002012
0.221003
638
26
59
24.538462
0.873239
0.105016
0
0.125
0
0
0.098592
0.084507
0
0
0
0
0.25
1
0.25
false
0.125
0.1875
0
0.5625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
d283b0f35605f21c6517e9dd272d8354544105aa
1,053
py
Python
biller/charges.py
trickeydan/biller
52c7c586ff76f7556a449ff7c0e1ec488fd47f78
[ "MIT" ]
null
null
null
biller/charges.py
trickeydan/biller
52c7c586ff76f7556a449ff7c0e1ec488fd47f78
[ "MIT" ]
null
null
null
biller/charges.py
trickeydan/biller
52c7c586ff76f7556a449ff7c0e1ec488fd47f78
[ "MIT" ]
null
null
null
import enum from .payment import PaymentAmount class ChargeType(enum.Enum): STATIC = 'static' VARIABLE = 'variable' class Charge: def __init__(self, data): self.data = data @property def description(self): return self.data['description'] @property def type(self): return ChargeType(self.data['type']) @property def amount(self): # The total amount if 'cost' in self.data: return PaymentAmount(self.data['cost']) if 'unit_cost' in self.data and 'unit_amount' in self.data: return PaymentAmount(self.data['unit_cost'] * self.data['unit_amount']) raise ValueError('Bad Cost info on Charge') class ChargeList: def __init__(self, data): self.data = data def __iter__(self): self.position = -1 # Nasty Hack ALERT! return self def __next__(self): self.position += 1 if self.position >= len(self.data): raise StopIteration return Charge(self.data[self.position])
21.489796
83
0.615385
126
1,053
4.984127
0.325397
0.178344
0.057325
0.047771
0.203822
0.203822
0.203822
0
0
0
0
0.002632
0.278253
1,053
49
84
21.489796
0.823684
0.032289
0
0.21875
0
0
0.098328
0
0
0
0
0
0
1
0.21875
false
0
0.0625
0.0625
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
962b61904ed722e7dc15d9be92448889fbeea748
985
py
Python
clist/migrations/0051_auto_20201008_2322.py
horacexd/clist
9759dfea97b86514bec9825d2430abc36decacf0
[ "Apache-2.0" ]
166
2019-05-16T23:46:08.000Z
2022-03-31T05:20:23.000Z
clist/migrations/0051_auto_20201008_2322.py
horacexd/clist
9759dfea97b86514bec9825d2430abc36decacf0
[ "Apache-2.0" ]
92
2020-01-18T22:51:53.000Z
2022-03-12T01:23:57.000Z
clist/migrations/0051_auto_20201008_2322.py
VadVergasov/clist
4afcdfe88250d224043b28efa511749347cec71c
[ "Apache-2.0" ]
23
2020-02-09T17:38:43.000Z
2021-12-09T14:39:07.000Z
# Generated by Django 2.2.13 on 2020-10-10 01:22 from django.db import migrations import pyclist.indexes class Migration(migrations.Migration): dependencies = [ ('clist', '0050_resource_short_host'), ] operations = [ migrations.AddIndex( model_name='contest', index=pyclist.indexes.GistIndexTrgrmOps(fields=['title'], name='clist_conte_title_a56b78_gist'), ), migrations.AddIndex( model_name='problem', index=pyclist.indexes.GistIndexTrgrmOps(fields=['name'], name='clist_probl_name_e9002d_gist'), ), migrations.AddIndex( model_name='resource', index=pyclist.indexes.GistIndexTrgrmOps(fields=['host'], name='clist_resou_host_7b7aef_gist'), ), migrations.AddIndex( model_name='resource', index=pyclist.indexes.GistIndexTrgrmOps(fields=['short_host'], name='clist_resou_short_h_a8f6a1_gist'), ), ]
31.774194
115
0.641624
101
985
6.009901
0.425743
0.115321
0.151565
0.177924
0.456343
0.266886
0.266886
0.266886
0.266886
0.266886
0
0.044
0.238579
985
30
116
32.833333
0.765333
0.046701
0
0.416667
1
0
0.211313
0.149413
0
0
0
0
0
1
0
false
0
0.083333
0
0.208333
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
962fcc56a35724a97f2a956de837486ab520c1d6
900
py
Python
tests/test_connection_handler.py
ajbeach2/drf-elasticsearch-dsl
2b55a295ece0438d6dd0ac92e291d0a69deb66ca
[ "MIT" ]
3
2017-12-27T01:10:53.000Z
2019-04-12T02:11:41.000Z
tests/test_connection_handler.py
ajbeach2/drf-elasticsearch-dsl
2b55a295ece0438d6dd0ac92e291d0a69deb66ca
[ "MIT" ]
5
2020-06-05T17:49:44.000Z
2021-06-10T20:35:59.000Z
tests/test_connection_handler.py
ajbeach2/drf-elasticsearch-dsl
2b55a295ece0438d6dd0ac92e291d0a69deb66ca
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_drf-elasticsearch-dsl ------------ Tests for `drf-elasticsearch-dsl` connection_handler module. """ from django.test import TestCase from drf_elasticsearch_dsl.connection_handler import connection_handler from .search_indexes import ContactSerializerDocument class TestConnectionHandler(TestCase): def setUp(self): self.documents = connection_handler.documents self.contact_index = ContactSerializerDocument._doc_type.index def test_documents(self): self.assertEqual(self.documents[ContactSerializerDocument.model_label], ContactSerializerDocument) def test_get_index(self): self.assertEqual( connection_handler.get_index( ContactSerializerDocument.model_label), ContactSerializerDocument) def tearDown(self): pass
26.470588
79
0.71
87
900
7.137931
0.448276
0.136876
0.091787
0.093398
0.318841
0
0
0
0
0
0
0.001391
0.201111
900
33
80
27.272727
0.862309
0.16
0
0.117647
0
0
0
0
0
0
0
0
0.117647
1
0.235294
false
0.058824
0.176471
0
0.470588
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
96340d5b89ef9e69c7332ec3a6e79a6d4717a5b9
463
py
Python
PythonBehave/flaskr/aynch_calculator.py
adamd1985/BDDArticle
be1f7fd67d8e195c31864622966ee88d3a2e257a
[ "Apache-2.0" ]
null
null
null
PythonBehave/flaskr/aynch_calculator.py
adamd1985/BDDArticle
be1f7fd67d8e195c31864622966ee88d3a2e257a
[ "Apache-2.0" ]
null
null
null
PythonBehave/flaskr/aynch_calculator.py
adamd1985/BDDArticle
be1f7fd67d8e195c31864622966ee88d3a2e257a
[ "Apache-2.0" ]
null
null
null
users_calculation = {} def request_addition(user, num1, num2): users_calcs = users_calculation.get(user) if (users_calcs is None): users_calcs = list() users_calcs.append(num1+num2) users_calculation[user] = users_calcs def get_last_calculation(user): users_calcs = users_calculation.get(user) results = None if (users_calcs is not None and len(users_calcs) > 0): results = users_calcs.pop() return results
21.045455
58
0.693305
62
463
4.919355
0.370968
0.295082
0.085246
0.170492
0.216393
0.216393
0
0
0
0
0
0.013736
0.213823
463
21
59
22.047619
0.824176
0
0
0.153846
0
0
0
0
0
0
0
0
0
1
0.153846
false
0
0
0
0.230769
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
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
963cc86eb5bed9a3d4b71531b99f7a465359bd63
219
py
Python
Curso Python/PythonExercicios/venv/ex014.py
marcos-saba/Cursos
1c063392867e9ed86d141dad8861a2a35488b1c6
[ "MIT" ]
null
null
null
Curso Python/PythonExercicios/venv/ex014.py
marcos-saba/Cursos
1c063392867e9ed86d141dad8861a2a35488b1c6
[ "MIT" ]
null
null
null
Curso Python/PythonExercicios/venv/ex014.py
marcos-saba/Cursos
1c063392867e9ed86d141dad8861a2a35488b1c6
[ "MIT" ]
null
null
null
print('*'*5, 'CONVERSOR DE TEMPERATURA', '*'*5) temp = float(input('Informe a temperatura em °C: ')) f = temp*1.800 + 32 print(f'A temperatura de {temp:.1f}°C é equivalente a {f:.1f}°F.') print('*'*10, '+++++', '*'*10)
36.5
66
0.589041
39
219
3.384615
0.538462
0.181818
0
0
0
0
0
0
0
0
0
0.073684
0.13242
219
5
67
43.8
0.605263
0
0
0
0
0
0.538813
0
0
0
0
0
0
1
0
false
0
0
0
0
0.6
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
963ce1e12af3b5f07cb91cc19d46b27cb1ede4c3
205
py
Python
src/main/resources/docs/tests/W0223_3.py
h314to/codacy-pylint
9d31567db6188e1b31ce0e1567998f64946502df
[ "Apache-2.0" ]
null
null
null
src/main/resources/docs/tests/W0223_3.py
h314to/codacy-pylint
9d31567db6188e1b31ce0e1567998f64946502df
[ "Apache-2.0" ]
null
null
null
src/main/resources/docs/tests/W0223_3.py
h314to/codacy-pylint
9d31567db6188e1b31ce0e1567998f64946502df
[ "Apache-2.0" ]
null
null
null
##Patterns: W0223 import abc class AbstractClass(metaclass=abc.ABCMeta): @abc.abstractmethod def abstract_method(self): pass ##Err: W0223 class ConcreteClass(AbstractClass): pass
12.8125
43
0.707317
22
205
6.545455
0.727273
0
0
0
0
0
0
0
0
0
0
0.04878
0.2
205
15
44
13.666667
0.829268
0.121951
0
0.285714
0
0
0
0
0
0
0
0
0
1
0.142857
false
0.285714
0.142857
0
0.571429
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
963cf0ed50373c2a8e619b72ac73e40dbedde2c3
564
py
Python
syspy/implementations/tests/test_source_executables.py
mrgarelli/PySys
f5e61b01ab43525b66f104ef3140b6d1c68e2ebc
[ "MIT" ]
1
2019-09-02T17:18:26.000Z
2019-09-02T17:18:26.000Z
syspy/implementations/tests/test_source_executables.py
mrgarelli/PySys
f5e61b01ab43525b66f104ef3140b6d1c68e2ebc
[ "MIT" ]
null
null
null
syspy/implementations/tests/test_source_executables.py
mrgarelli/PySys
f5e61b01ab43525b66f104ef3140b6d1c68e2ebc
[ "MIT" ]
null
null
null
import pytest from mock import patch from mock.mock import Mock call = Mock() from ..source_executables import remove_unwanted with_unwanted_file = ['file1', '__pycache__', '__init__.py', 'file2', '.pytest_cache'] sources_only = ['file1', 'file2'] ignore_sources = ['__init__.py', '__pycache__', '.pytest_cache'] class TestRemoveUnwantedFiles: def test_removes_init_py(self): assert sources_only == remove_unwanted(with_unwanted_file, ignore_sources) def test_removes_nothing(self): assert sources_only == remove_unwanted(sources_only, ignore_sources)
28.2
86
0.780142
72
564
5.583333
0.402778
0.109453
0.089552
0.129353
0.288557
0.174129
0
0
0
0
0
0.007952
0.108156
564
19
87
29.684211
0.791252
0
0
0
0
0
0.159574
0
0
0
0
0
0.153846
1
0.153846
false
0
0.307692
0
0.538462
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
963eeb39055a52996eef8e68d646294ea0983119
248
py
Python
api/config.py
juanhenaoparra/manage-my-agenda
894e1de122fc1c1b6469cdf0c6290510ef8fba75
[ "MIT" ]
null
null
null
api/config.py
juanhenaoparra/manage-my-agenda
894e1de122fc1c1b6469cdf0c6290510ef8fba75
[ "MIT" ]
null
null
null
api/config.py
juanhenaoparra/manage-my-agenda
894e1de122fc1c1b6469cdf0c6290510ef8fba75
[ "MIT" ]
null
null
null
from configparser import ConfigParser from util.singleton import Singleton class Config(metaclass=Singleton): def __init__(self, path:str='instance/config.ini'): self.path = path self.data = ConfigParser() self.data.read(self.path)
24.8
53
0.75
32
248
5.6875
0.53125
0.131868
0
0
0
0
0
0
0
0
0
0
0.145161
248
9
54
27.555556
0.858491
0
0
0
0
0
0.076613
0
0
0
0
0
0
1
0.142857
false
0
0.285714
0
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
96406ce744f78cbc06e19269aff121d6737167d8
1,292
py
Python
src/kusto/azext_kusto/generated/_client_factory.py
tilnl/azure-cli-extensions
ef9946bbcde34bb51343554a8f2a8dedd1f7d44a
[ "MIT" ]
1
2020-09-23T16:13:36.000Z
2020-09-23T16:13:36.000Z
src/kusto/azext_kusto/generated/_client_factory.py
tilnl/azure-cli-extensions
ef9946bbcde34bb51343554a8f2a8dedd1f7d44a
[ "MIT" ]
null
null
null
src/kusto/azext_kusto/generated/_client_factory.py
tilnl/azure-cli-extensions
ef9946bbcde34bb51343554a8f2a8dedd1f7d44a
[ "MIT" ]
1
2020-07-28T18:01:53.000Z
2020-07-28T18:01:53.000Z
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- def cf_kusto(cli_ctx, *_): from azure.cli.core.commands.client_factory import get_mgmt_service_client from ..vendored_sdks.kusto import KustoManagementClient return get_mgmt_service_client(cli_ctx, KustoManagementClient) def cf_cluster(cli_ctx, *_): return cf_kusto(cli_ctx).cluster def cf_cluster_principal_assignment(cli_ctx, *_): return cf_kusto(cli_ctx).cluster_principal_assignment def cf_database(cli_ctx, *_): return cf_kusto(cli_ctx).database def cf_database_principal_assignment(cli_ctx, *_): return cf_kusto(cli_ctx).database_principal_assignment def cf_attached_database_configuration(cli_ctx, *_): return cf_kusto(cli_ctx).attached_database_configuration def cf_data_connection(cli_ctx, *_): return cf_kusto(cli_ctx).data_connection
32.3
79
0.676471
155
1,292
5.277419
0.412903
0.102689
0.085575
0.111247
0.266504
0.266504
0.266504
0.205379
0.107579
0
0
0
0.144737
1,292
39
80
33.128205
0.740271
0.339783
0
0
0
0
0
0
0
0
0
0
0
1
0.4375
false
0
0.125
0.375
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
96408e0925342d0ec52d06db9b50cc177bd8326d
581
py
Python
tests/framework/Optimizers/BealeFailureRejection/bealeRejection.py
mattdon/raven
b5b4a9fc96cec37ca5fb3757c45653eec66522f1
[ "Apache-2.0" ]
null
null
null
tests/framework/Optimizers/BealeFailureRejection/bealeRejection.py
mattdon/raven
b5b4a9fc96cec37ca5fb3757c45653eec66522f1
[ "Apache-2.0" ]
null
null
null
tests/framework/Optimizers/BealeFailureRejection/bealeRejection.py
mattdon/raven
b5b4a9fc96cec37ca5fb3757c45653eec66522f1
[ "Apache-2.0" ]
null
null
null
# from https://en.wikipedia.org/wiki/Test_functions_for_optimization # # takes input parameters x,y # returns value in "ans" # optimal minimum at f(3,0.5) = 0 # parameter range is -4.5 <= x,y <= 4.5 def evaluate(x,y): return (1.5 - x + x*y)**2 + (2.25 - x + x*y*y)**2 + (2.625 - x + x*y*y*y)**2 def run(self,Inputs): if abs(self.y - 0.24392555296) <= 0.00001 and abs(self.x - 0.247797586626) <= 0.00001 : print("Expected failure for testing ... x:"+str(self.x)+" | y:"+str(self.y)) raise Exception("expected failure for testing") self.ans = evaluate(self.x,self.y)
36.3125
89
0.635112
108
581
3.388889
0.490741
0.038251
0.02459
0.021858
0
0
0
0
0
0
0
0.117769
0.166954
581
15
90
38.733333
0.63843
0.320138
0
0
0
0
0.175258
0
0
0
0
0
0
1
0.285714
false
0
0
0.142857
0.428571
0.142857
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
9642151d84b9bb0b36fcbd7232047ddd65fa63a0
318
py
Python
resource.py
bigbase-media/ivf_blueprint_leon
5521ffa380b9d4894dc85d43439542b5768ce14e
[ "MIT" ]
27
2019-07-03T08:04:31.000Z
2022-03-28T01:53:03.000Z
resource.py
bigbase-media/ivf-blueprint-leon
5521ffa380b9d4894dc85d43439542b5768ce14e
[ "MIT" ]
2
2019-08-20T11:47:02.000Z
2020-05-13T07:45:19.000Z
resource.py
bigbase-media/ivf_blueprint_leon
5521ffa380b9d4894dc85d43439542b5768ce14e
[ "MIT" ]
11
2019-10-09T07:55:16.000Z
2022-03-13T01:04:49.000Z
# -*- coding: utf-8 -*- def create(): resourceDict = dict() return resourceDict def addOne(resourceDict, key, value): if (len(key)<=2): return 'err' if (key[0:2]!="##"): print("key must be like '##xx' : %s " % key) return 'err' resourceDict[key] = value return 'ok'
18.705882
52
0.528302
39
318
4.307692
0.589744
0.178571
0.238095
0
0
0
0
0
0
0
0
0.017621
0.286164
318
16
53
19.875
0.722467
0.066038
0
0.181818
0
0
0.133106
0
0
0
0
0
0
1
0.181818
false
0
0
0
0.545455
0.090909
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
964782ea9dd672a7606d9dc430b201d9df1ebce1
19,196
py
Python
game_models/ddqn_game_model.py
xqlin98/atari
d74f0fe604c9bf165a7678384451d36953fe9a60
[ "MIT" ]
null
null
null
game_models/ddqn_game_model.py
xqlin98/atari
d74f0fe604c9bf165a7678384451d36953fe9a60
[ "MIT" ]
null
null
null
game_models/ddqn_game_model.py
xqlin98/atari
d74f0fe604c9bf165a7678384451d36953fe9a60
[ "MIT" ]
null
null
null
import numpy as np import os import random import shutil from statistics import mean from tensorflow.python.keras.backend import dtype from game_models.base_game_model import BaseGameModel from convolutional_neural_network import ConvolutionalNeuralNetwork import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as T from collections import namedtuple, deque GAMMA = 0.99 MEMORY_SIZE = 900000 # BATCH_SIZE = 128 BATCH_SIZE = 128 TRAINING_FREQUENCY = 4 TARGET_NETWORK_UPDATE_FREQUENCY = 40000 # MODEL_PERSISTENCE_UPDATE_FREQUENCY = 10000 MODEL_PERSISTENCE_UPDATE_FREQUENCY = 5000 # REPLAY_START_SIZE = 50000 REPLAY_START_SIZE = 5000 # EXPLORATION_MAX = 1.0 EXPLORATION_MAX = 0.95 EXPLORATION_MIN = 0.1 EXPLORATION_TEST = 0.02 # EXPLORATION_STEPS = 850000 EXPLORATION_STEPS = 850000 EXPLORATION_DECAY = (EXPLORATION_MAX-EXPLORATION_MIN)/EXPLORATION_STEPS device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(device) class DDQNGameModel(BaseGameModel): def __init__(self, game_name, mode_name, input_shape, action_space, logger_path, model_path): BaseGameModel.__init__(self, game_name, mode_name, logger_path, input_shape, action_space) self.model_path = model_path # self.ddqn = ConvolutionalNeuralNetwork(self.input_shape, action_space).model # if os.path.isfile(self.model_path): # self.ddqn.load_weights(self.model_path) def _save_model(self): self.ddqn.save_weights(self.model_path) class DDQNSolver(DDQNGameModel): def __init__(self, game_name, input_shape, action_space): testing_model_path = "./output/neural_nets/" + game_name + "/ddqn/testing/model.h5" assert os.path.exists(os.path.dirname(testing_model_path)), "No testing model in: " + str(testing_model_path) DDQNGameModel.__init__(self, game_name, "DDQN testing", input_shape, action_space, "./output/logs/" + game_name + "/ddqn/testing/" + self._get_date() + "/", testing_model_path) def move(self, state): if np.random.rand() < EXPLORATION_TEST: return random.randrange(self.action_space) q_values = self.ddqn.predict(np.expand_dims(np.asarray(state).astype(np.float64), axis=0), batch_size=1) return np.argmax(q_values[0]) # class DDQNTrainer(DDQNGameModel): # def __init__(self, game_name, input_shape, action_space): # DDQNGameModel.__init__(self, # game_name, # "DDQN training", # input_shape, # action_space, # "./output/logs/" + game_name + "/ddqn/training/" + self._get_date() + "/", # "./output/neural_nets/" + game_name + "/ddqn/" + self._get_date() + "/model.h5") # if os.path.exists(os.path.dirname(self.model_path)): # shutil.rmtree(os.path.dirname(self.model_path), ignore_errors=True) # os.makedirs(os.path.dirname(self.model_path)) # self.ddqn_target = ConvolutionalNeuralNetwork(self.input_shape, action_space).model # self._reset_target_network() # self.epsilon = EXPLORATION_MAX # self.memory = [] # def move(self, state): # if np.random.rand() < self.epsilon or len(self.memory) < REPLAY_START_SIZE: # return random.randrange(self.action_space) # q_values = self.ddqn.predict(np.expand_dims(np.asarray(state).astype(np.float64), axis=0), batch_size=1) # return np.argmax(q_values[0]) # def remember(self, current_state, action, reward, next_state, terminal): # self.memory.append({"current_state": current_state, # "action": action, # "reward": reward, # "next_state": next_state, # "terminal": terminal}) # if len(self.memory) > MEMORY_SIZE: # self.memory.pop(0) # def step_update(self, total_step): # if len(self.memory) < REPLAY_START_SIZE: # return # if total_step % TRAINING_FREQUENCY == 0: # loss, accuracy, average_max_q = self._train() # self.logger.add_loss(loss) # self.logger.add_accuracy(accuracy) # self.logger.add_q(average_max_q) # self._update_epsilon() # if total_step % MODEL_PERSISTENCE_UPDATE_FREQUENCY == 0: # self._save_model() # if total_step % TARGET_NETWORK_UPDATE_FREQUENCY == 0: # self._reset_target_network() # print('{{"metric": "epsilon", "value": {}}}'.format(self.epsilon)) # print('{{"metric": "total_step", "value": {}}}'.format(total_step)) # def _train(self): # batch = np.asarray(random.sample(self.memory, BATCH_SIZE)) # if len(batch) < BATCH_SIZE: # return # current_states = [] # q_values = [] # max_q_values = [] # current_states = np.asarray(tuple(map(lambda s: np.asarray(s['current_state']), # batch))).astype(np.float64) # next_states = np.asarray(tuple(map(lambda s: np.asarray(s['next_state']), # batch))).astype(np.float64) # next_states_prediction = self.ddqn_target.predict(next_states) # next_q_value = np.max(next_states_prediction, axis=1) # for entry in batch: # current_state = np.expand_dims(np.asarray(entry["current_state"]).astype(np.float64), axis=0) # current_states.append(current_state) # next_state = np.expand_dims(np.asarray(entry["next_state"]).astype(np.float64), axis=0) # next_state_prediction = self.ddqn_target.predict(next_state).ravel() # next_q_value = np.max(next_state_prediction) # q = list(self.ddqn.predict(current_state)[0]) # if entry["terminal"]: # q[entry["action"]] = entry["reward"] # else: # q[entry["action"]] = entry["reward"] + GAMMA * next_q_value # q_values.append(q) # max_q_values.append(np.max(q)) # fit = self.ddqn.fit(np.asarray(current_states).squeeze(), # np.asarray(q_values).squeeze(), # batch_size=BATCH_SIZE, # verbose=0) # loss = fit.history["loss"][0] # accuracy = fit.history["accuracy"][0] # return loss, accuracy, mean(max_q_values) # def _train(self): # # torch version of training # batch = np.asarray(random.sample(self.memory, BATCH_SIZE)) # if len(batch) < BATCH_SIZE: # return # current_states = [] # q_values = [] # max_q_values = [] # non_final_mask = torch.tensor(tuple(map(lambda s: s["terminal"] != True, # batch)), device=device, dtype=torch.bool) # non_final_next_states = torch.cat([s["next_state"] for s in batch # if s["terminal"] != True]) # state_batch = torch.tensor(list(map(lambda s: np.asarray(s['current_state']), # batch)), dtype=torch.float64) # action_batch = torch.tensor(list(map(lambda s: np.asarray(s['action']), # batch)), dtype=torch.Long) # reward_batch = torch.tensor(list(map(lambda s: np.asarray(s['reward']), # batch)), dtype=torch.float64) # state_action_values = self.ddqn(state_batch).gather(1, action_batch) # next_state_values = torch.zeros(BATCH_SIZE, device=device) # next_state_values[non_final_mask] = self.ddqn_target(non_final_next_states).max(1)[0].detach() # expected_state_action_values = (next_state_values * GAMMA) + reward_batch # # Compute Huber loss # criterion = nn.SmoothL1Loss() # loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1)) # # Optimize the model # optimizer = optim.RMSprop(self.ddqn.parameters()) # optimizer.zero_grad() # loss.backward() # for param in self.ddqn.parameters(): # param.grad.data.clamp_(-1, 1) # optimizer.step() # return 0, 0, 0 # def _update_epsilon(self): # self.epsilon -= EXPLORATION_DECAY # self.epsilon = max(EXPLORATION_MIN, self.epsilon) # def _reset_target_network(self): # self.ddqn_target.set_weights(self.ddqn.get_weights()) class DQNbn(nn.Module): def __init__(self, c, h, w, outputs): super(DQN, self).__init__() self.conv1 = nn.Conv2d(c, 16, kernel_size=5, stride=2) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) self.bn3 = nn.BatchNorm2d(32) # Number of Linear input connections depends on output of conv2d layers # and therefore the input image size, so compute it. def conv2d_size_out(size, kernel_size = 5, stride = 2): return (size - (kernel_size - 1) - 1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs) # Called with either one element to determine next action, or a batch # during optimization. Returns tensor([[left0exp,right0exp]...]). def forward(self, x): x = x.to(device) x = F.relu(self.bn1(self.conv1(x))) x = F.relu(self.bn2(self.conv2(x))) x = F.relu(self.bn3(self.conv3(x))) return self.head(x.view(x.size(0), -1)) class DQN(nn.Module): def __init__(self, c, h, w, outputs): super(DQN, self).__init__() self.conv1 = nn.Conv2d(c, 16, kernel_size=5, stride=2) # self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 32, kernel_size=5, stride=2) # self.bn2 = nn.BatchNorm2d(32) self.conv3 = nn.Conv2d(32, 32, kernel_size=5, stride=2) # self.bn3 = nn.BatchNorm2d(32) # Number of Linear input connections depends on output of conv2d layers # and therefore the input image size, so compute it. def conv2d_size_out(size, kernel_size = 5, stride = 2): return (size - (kernel_size - 1) - 1) // stride + 1 convw = conv2d_size_out(conv2d_size_out(conv2d_size_out(w))) convh = conv2d_size_out(conv2d_size_out(conv2d_size_out(h))) linear_input_size = convw * convh * 32 self.head = nn.Linear(linear_input_size, outputs) # Called with either one element to determine next action, or a batch # during optimization. Returns tensor([[left0exp,right0exp]...]). def forward(self, x): x = x.to(device) / 255 x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) return self.head(x.view(x.size(0), -1)) Transition = namedtuple('Transition', ('current_state', 'action' , 'reward', 'next_state', 'terminal')) class ReplayMemory(object): def __init__(self, capacity): self.memory = deque([],maxlen=capacity) def push(self, *args): """Save a transition""" self.memory.append(Transition(*args)) def sample(self, batch_size): return random.sample(self.memory, batch_size) def __len__(self): return len(self.memory) class DDQNTrainer_torch(DDQNGameModel): def __init__(self, game_name, input_shape, action_space): DDQNGameModel.__init__(self, game_name, "DDQN training", input_shape, action_space, "./output/logs/" + game_name + "/ddqn/training/" + self._get_date() + "/", "./output/neural_nets/" + game_name + "/ddqn/" + self._get_date() + "/model.pt") if os.path.exists(os.path.dirname(self.model_path)): shutil.rmtree(os.path.dirname(self.model_path), ignore_errors=True) os.makedirs(os.path.dirname(self.model_path)) self.ddqn = DQN(*input_shape, action_space).to(device) self.optimizer = optim.RMSprop(self.ddqn.parameters(),lr=0.00025, alpha=0.95, eps=0.01) # self.optimizer = optim.Adam(self.ddqn.parameters(), lr=0.00025) self.ddqn_target = DQN(*input_shape, action_space).to(device) self._reset_target_network() self.epsilon = EXPLORATION_MAX self.memory = ReplayMemory(MEMORY_SIZE) self.pre_run = 0 def move(self, state): if np.random.rand() < self.epsilon or len(self.memory) < REPLAY_START_SIZE: return random.randrange(self.action_space) q_values = self.ddqn(torch.tensor(np.expand_dims(np.asarray(state).astype(np.float64) , axis=0),device=device, dtype=torch.float32)) return np.argmax(q_values[0].detach().cpu().numpy()) def remember(self, current_state, action, reward, next_state, terminal): self.memory.push(torch.unsqueeze(torch.tensor(np.asarray(current_state), dtype=torch.float32),dim=0), torch.unsqueeze(torch.tensor(np.asarray(action), dtype=torch.int64),dim=0), torch.tensor(np.asarray(reward), dtype=torch.float32), torch.unsqueeze(torch.tensor(np.asarray(next_state), dtype=torch.float32),dim=0), torch.tensor(terminal != True, dtype=torch.bool)) if len(self.memory) > MEMORY_SIZE: self.memory.pop(0) def step_update(self, total_step, run): if len(self.memory) < REPLAY_START_SIZE: return if total_step % TRAINING_FREQUENCY == 0: loss, accuracy, average_max_q = self._train() self.logger.add_loss(loss) self.logger.add_accuracy(accuracy) self.logger.add_q(average_max_q) self._update_epsilon() if total_step % MODEL_PERSISTENCE_UPDATE_FREQUENCY == 0: self._save_model() if total_step % TARGET_NETWORK_UPDATE_FREQUENCY == 0: self._reset_target_network() print('{{"metric": "epsilon", "value": {}}}'.format(self.epsilon)) print('{{"metric": "total_step", "value": {}}}'.format(total_step)) def _train(self): # torch version of training batch = self.memory.sample(BATCH_SIZE) if len(batch) < BATCH_SIZE: return batch = Transition(*zip(*batch)) # non_final_mask = torch.tensor(tuple(map(lambda s: s["terminal"] != True, # batch)), device=device, dtype=torch.bool) # non_final_next_states = torch.tensor([np.asarray(s["next_state"]) for s in batch # if s["terminal"] != True], dtype=torch.float32, device=device) # state_batch = torch.tensor(list(map(lambda s: np.asarray(s['current_state']), # batch)), dtype=torch.float32, device=device) # action_batch = torch.unsqueeze(torch.tensor(list(map(lambda s: s['action'], # batch)), dtype=torch.int64, device=device),dim=1) # reward_batch = torch.tensor(list(map(lambda s: s['reward'], # batch)), dtype=torch.float32, device=device) non_final_mask = torch.tensor(batch.terminal, device=device) non_final_next_states = torch.cat([s for s,t in zip(batch.next_state,batch.terminal) if t]).to(device) state_batch = torch.cat(batch.current_state).to(device) action_batch = torch.unsqueeze(torch.cat(batch.action),dim=1).to(device) reward_batch = torch.tensor(batch.reward, device=device) state_action_values = self.ddqn(state_batch).gather(1, action_batch) next_state_values = torch.zeros(BATCH_SIZE, device=device) next_state_values[non_final_mask] = self.ddqn_target(non_final_next_states).max(1)[0].detach() expected_state_action_values = (next_state_values * GAMMA) + reward_batch # Compute Huber loss criterion = nn.SmoothL1Loss() loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1)) # Optimize the model self.optimizer.zero_grad() loss.backward() for param in self.ddqn.parameters(): param.grad.data.clamp_(-1, 1) self.optimizer.step() return float(loss.detach().cpu().numpy()), 0, float(torch.mean(next_state_values).detach().cpu().numpy()) def _update_epsilon(self): self.epsilon -= EXPLORATION_DECAY self.epsilon = max(EXPLORATION_MIN, self.epsilon) def _reset_target_network(self): self.ddqn_target.load_state_dict(self.ddqn.state_dict()) def _save_model(self): torch.save(self.ddqn.state_dict(), self.model_path) def _load_model(self): self.ddqn.load_state_dict(torch.load(self.model_path)) self.ddqn.eval() class DDQNSolver_torch(DDQNGameModel): def __init__(self, game_name, input_shape, action_space): testing_model_path = "./output/neural_nets/" + game_name + "/ddqn/testing/model.pt" assert os.path.exists(os.path.dirname(testing_model_path)), "No testing model in: " + str(testing_model_path) DDQNGameModel.__init__(self, game_name, "DDQN testing", input_shape, action_space, "./output/logs/" + game_name + "/ddqn/testing/" + self._get_date() + "/", testing_model_path) self.ddqn = DQN(*input_shape, action_space).to(device) self._load_model() def _load_model(self): self.ddqn.load_state_dict(torch.load(self.model_path)) self.ddqn.eval() def move(self, state): if np.random.rand() < EXPLORATION_TEST: return random.randrange(self.action_space) q_values = self.ddqn(torch.tensor(np.expand_dims(np.asarray(state).astype(np.float64) , axis=0),device=device, dtype=torch.float32)) return np.argmax(q_values[0].detach().cpu().numpy()) def step_update(self, total_step, run): pass
41.730435
117
0.595124
2,313
19,196
4.703415
0.117164
0.024267
0.022061
0.028955
0.764317
0.743635
0.692159
0.64721
0.631676
0.630113
0
0.02093
0.283184
19,196
460
118
41.730435
0.769695
0.415503
0
0.382775
0
0
0.038319
0.00967
0
0
0
0
0.009569
1
0.129187
false
0.004785
0.066986
0.019139
0.301435
0.014354
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
964be75e90e217e0bb48025e75b3b11baa5f166a
1,518
py
Python
code/pytorch/LAMPO/core/augmented_tasks/tasks.py
hzm2016/assistive-gym-robosuite
5c529f4444cc386383618bfa584341740a8468f9
[ "MIT" ]
1
2021-11-22T07:45:28.000Z
2021-11-22T07:45:28.000Z
code/pytorch/LAMPO/core/augmented_tasks/tasks.py
hzm2016/assistive-gym-robosuite
5c529f4444cc386383618bfa584341740a8468f9
[ "MIT" ]
null
null
null
code/pytorch/LAMPO/core/augmented_tasks/tasks.py
hzm2016/assistive-gym-robosuite
5c529f4444cc386383618bfa584341740a8468f9
[ "MIT" ]
null
null
null
from rlbench.tasks import ReachTarget as RT, WaterPlants as WP, CloseDrawer as CD from pyrep.backend import sim import numpy as np from rlbench.backend.task import Task import math class AugmentedTask(Task): def set_additional_info(self, *args, **kwargs): raise Exception("not implemented") def get_dense_reward(self) -> float: raise Exception("not implemented") class ReachTarget(RT): def set_additional_info(self, robot): self._robot = robot def get_dense_reward(self): state, points = sim.simCheckProximitySensor(self._initial_objs_in_scene[5][0]._handle, self.robot.arm.get_tip().get_handle()) points_1 = sim.simGetObjectPosition(self._initial_objs_in_scene[5][0]._handle, self.robot.arm.get_tip().get_handle()) reward = - np.sqrt(points_1[0] ** 2 + points_1[1] ** 2 + points_1[2] ** 2) if state == 1: reward = 1. return reward class CloseDrawer(CD): def set_additional_info(self, robot): self._robot = robot def get_dense_reward(self): rew = np.abs(self.joints[0].get_joint_position() - self._success_conditions[0]._original_pos) if rew >= 0.06: return 1. else: return rew/0.12 class WaterPlants(WP): def set_additional_info(self, robot): self._robot = robot def get_dense_reward(self): return 0.
27.107143
101
0.611989
193
1,518
4.590674
0.341969
0.081264
0.072235
0.090293
0.396163
0.345372
0.345372
0.345372
0.345372
0.345372
0
0.02403
0.28722
1,518
55
102
27.6
0.794824
0
0
0.361111
0
0
0.019763
0
0
0
0
0
0
1
0.222222
false
0
0.138889
0.027778
0.583333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
965240125b85de0c797ebd56d2cb28ca08c83ac3
888
py
Python
src/base/domain.py
antunesleo/manotes-api
ea954e3570a1a4c163328288a9a328859c421f29
[ "MIT" ]
13
2018-12-11T10:54:19.000Z
2020-08-07T01:23:43.000Z
src/base/domain.py
antunesleo/manotes-api
ea954e3570a1a4c163328288a9a328859c421f29
[ "MIT" ]
1
2020-01-12T04:03:08.000Z
2020-01-12T04:03:08.000Z
src/base/domain.py
antunesleo/manotes-api
ea954e3570a1a4c163328288a9a328859c421f29
[ "MIT" ]
3
2019-03-27T11:37:49.000Z
2019-05-31T02:05:00.000Z
from src import exceptions class Actor(object): pass class Entity(object): pass class Aggregate(object): active_repository = None def __init__(self, db_instance): self.db_instance = db_instance @classmethod def create_with_id(cls, id): db_instance = cls.active_repository.one_or_none(id=id) if db_instance is None: raise exceptions.NotFound('Could not find a entity with id {}'.format(id)) return cls(db_instance=db_instance) @classmethod def create_with_instance(cls, db_instance): return cls(db_instance) @classmethod def _create_with_keys(cls, **keys): db_instance = cls.active_repository.one_or_none(**keys) if db_instance is None: raise exceptions.NotFound('Could not find a user with keys: {}'.format(keys)) return cls(db_instance=db_instance)
25.371429
89
0.677928
119
888
4.798319
0.310924
0.227671
0.091068
0.105079
0.602452
0.602452
0.476357
0.476357
0.189142
0.189142
0
0
0.23536
888
34
90
26.117647
0.840943
0
0
0.375
0
0
0.077703
0
0
0
0
0
0
1
0.166667
false
0.083333
0.041667
0.041667
0.5
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
9659b9d0cb2cd5a16db35cc029407ba657e526f1
2,406
py
Python
client/python/kwkhtmltopdf_client.py
yvaucher/kwkhtmltopdf
d1e3a7d1f90968a17033454e3cbf1d73ffa86d70
[ "MIT" ]
4
2019-03-01T15:01:46.000Z
2021-03-26T10:17:58.000Z
client/python/kwkhtmltopdf_client.py
yvaucher/kwkhtmltopdf
d1e3a7d1f90968a17033454e3cbf1d73ffa86d70
[ "MIT" ]
9
2019-03-06T17:22:25.000Z
2022-02-22T17:35:02.000Z
client/python/kwkhtmltopdf_client.py
yvaucher/kwkhtmltopdf
d1e3a7d1f90968a17033454e3cbf1d73ffa86d70
[ "MIT" ]
6
2019-03-06T16:56:19.000Z
2022-01-11T07:23:13.000Z
#!/usr/bin/env python # Copyright (c) 2019 ACSONE SA/NV # Distributed under the MIT License (http://opensource.org/licenses/MIT) from __future__ import print_function import os import sys import requests CHUNK_SIZE = 2 ** 16 class Error(Exception): pass class UsageError(Error): pass class ServerError(Error): pass def wkhtmltopdf(args): url = os.getenv("KWKHTMLTOPDF_SERVER_URL") parts = [] def add_option(option): # TODO option encoding? parts.append(("option", (None, option))) def add_file(filename): with open(filename, "rb") as f: parts.append(("file", (filename, f.read()))) if "-" in args: raise UsageError("stdin/stdout input is not implemented") output = "-" if len(args) >= 2 and not args[-1].startswith("-") and not args[-2].startswith("-"): output = args[-1] args = args[:-1] for arg in args: if arg.startswith("-"): add_option(arg) elif arg.startswith("http://") or arg.startswith("https://"): add_option(arg) elif arg.startswith("file://"): add_file(arg[7:]) elif os.path.isfile(arg): # TODO better way to detect args that are actually options # TODO in case an option has the same name as an existing file # TODO only way I see so far is enumerating them in a static # TODO datastructure (that can be initialized with a quick parse # TODO of wkhtmltopdf --extended-help) add_file(arg) else: add_option(arg) if not parts: add_option("-h") try: r = requests.post(url, files=parts) r.raise_for_status() if output == "-": if sys.version_info[0] < 3: out = sys.stdout else: out = sys.stdout.buffer else: out = open(output, "wb") for chunk in r.iter_content(chunk_size=CHUNK_SIZE): out.write(chunk) except requests.exceptions.ChunkedEncodingError: # TODO look if client and server could use trailer headers # TODO to report errors raise ServerError("kwkhtmltopdf server error, consult server log") if __name__ == "__main__": try: wkhtmltopdf(sys.argv[1:]) except Error as e: print(e, file=sys.stderr) sys.exit(-1)
26.152174
88
0.586866
306
2,406
4.51634
0.48366
0.032562
0.026049
0.023155
0.041968
0.041968
0
0
0
0
0
0.010113
0.30133
2,406
91
89
26.43956
0.812017
0.208229
0
0.189655
0
0
0.082893
0.012144
0
0
0
0.010989
0
1
0.051724
false
0.051724
0.068966
0
0.172414
0.034483
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
965d06b2a49489ae1c3d1a03947debd66de98f11
1,829
py
Python
src/strips_hgn/features/global_features.py
matgreco/trainhgn
4da36033512b904e0547b31e5cb8ad9249e1d343
[ "MIT" ]
5
2020-11-29T05:22:24.000Z
2022-01-28T22:52:43.000Z
src/strips_hgn/features/global_features.py
matgreco/trainhgn
4da36033512b904e0547b31e5cb8ad9249e1d343
[ "MIT" ]
null
null
null
src/strips_hgn/features/global_features.py
matgreco/trainhgn
4da36033512b904e0547b31e5cb8ad9249e1d343
[ "MIT" ]
4
2020-08-14T01:26:52.000Z
2021-08-30T14:21:53.000Z
from typing import List, Type from strips_hgn.features import GlobalFeatureMapper from strips_hgn.hypergraph.hypergraph_view import HypergraphView from strips_hgn.utils import Number class EmptyGlobalFeatureMapper(GlobalFeatureMapper): """ Global Feature Mapper that does nothing """ def hypergraph_view_to_feature( self, hypergraph_view: HypergraphView ) -> List[Number]: return [] @classmethod def name(cls) -> str: return "none" @classmethod def input_size(cls) -> int: return 0 class NumberOfNodesAndEdgesGlobalFeatureMapper(GlobalFeatureMapper): """ Map a Hypergraph View to a feature vector containing the number of nodes and edges in the hypergraph. [number of nodes, number of hyperedges] For STRIPS problems, this corresponds to the number of propositions and grounded actions, respectively. """ def hypergraph_view_to_feature( self, hypergraph_view: HypergraphView ) -> List[Number]: return [len(hypergraph_view.nodes), len(hypergraph_view.hyperedges)] @classmethod def name(cls) -> str: return "num_nodes_and_edges" @classmethod def input_size(cls) -> int: return 2 # Used for command line args GLOBAL_FEATURE_MAPPERS = { feature_mapper_cls.name(): feature_mapper_cls for feature_mapper_cls in ( EmptyGlobalFeatureMapper, NumberOfNodesAndEdgesGlobalFeatureMapper, ) } DEFAULT_GLOBAL_FEATURE_MAPPER = EmptyGlobalFeatureMapper.name() assert DEFAULT_GLOBAL_FEATURE_MAPPER in GLOBAL_FEATURE_MAPPERS def get_global_feature_mapper(mapper: str) -> Type[GlobalFeatureMapper]: if mapper not in GLOBAL_FEATURE_MAPPERS: raise ValueError(f"Unsupported global feature mapper {mapper}") return GLOBAL_FEATURE_MAPPERS[mapper]
26.897059
76
0.732641
206
1,829
6.300971
0.349515
0.090139
0.07319
0.029276
0.214176
0.214176
0.167951
0.114022
0.114022
0.114022
0
0.00137
0.20175
1,829
67
77
27.298507
0.887671
0.172772
0
0.358974
0
0
0.044068
0
0
0
0
0
0.025641
1
0.179487
false
0
0.102564
0.153846
0.512821
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
9661caebebb52f426d4207d1d2177f1abe1f9bb0
2,655
py
Python
BizWxUtil.py
xeeboy/BizWxCryptor
10269ebc39f306c2977282dcba45d7ef3a88440c
[ "MIT" ]
29
2019-04-16T17:45:03.000Z
2022-01-26T11:54:00.000Z
BizWxUtil.py
xeeboy/BizWxCryptor
10269ebc39f306c2977282dcba45d7ef3a88440c
[ "MIT" ]
1
2019-04-10T06:01:39.000Z
2019-04-10T07:27:28.000Z
BizWxUtil.py
xeeboy/BizWxCryptor
10269ebc39f306c2977282dcba45d7ef3a88440c
[ "MIT" ]
12
2019-05-15T08:48:59.000Z
2022-01-26T11:54:01.000Z
from django.http import HttpResponse from .WXBizMsgCrypt import WXBizMsgCrypt,ResponseMessage,generateNonce import xml.etree.cElementTree as ET def getCryptor(): # TODO hard code configuration sToken = "edit_this" sEncodingAESKey = "edit_this" sCorpID = "edit_this" return WXBizMsgCrypt(sToken,sEncodingAESKey,sCorpID) def responseEcho(request): sVerifyMsgSig = request.GET.get('msg_signature') sVerifyNonce = request.GET.get('nonce') sVerifyTimeStamp = request.GET.get('timestamp') sVerifyEchoStr = request.GET.get('echostr') wxcpt = getCryptor() ret,sEchoStr=wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,sVerifyNonce,sVerifyEchoStr) if ret != 0 : print("ERR: VerifyURL ret: " + str(ret)) return HttpResponse("ERR: VerifyURL ret: " + str(ret)) return HttpResponse(sEchoStr) # decrypt message and ruturn as python dict def parseMessage(request): encrypted_xml = request.body.decode('utf-8') sVerifyMsgSig = request.GET.get('msg_signature') sVerifyNonce = request.GET.get('nonce') sVerifyTimeStamp = request.GET.get('timestamp') wxcpt = getCryptor() ret,xml_content = wxcpt.DecryptMsg(encrypted_xml,sVerifyMsgSig,sVerifyTimeStamp,sVerifyNonce) if ret != 0 : print("ERR: VerifyURL ret: " + str(ret)) return HttpResponse("ERR: VerifyURL ret: " + str(ret)) type_fields = { "text":["ToUserName","FromUserName","CreateTime","MsgType","Content","MsgId","AgentID"], "image":["ToUserName","FromUserName","CreateTime","MsgType","PicUrl","MediaId","MsgId","AgentID"], "voice":["ToUserName","FromUserName","CreateTime","MsgType","Format","MediaId","MsgId","AgentID"], "video":["ToUserName","FromUserName","CreateTime","MsgType","ThumbMediaId","MediaId","MsgId","AgentID"], "location":["ToUserName","FromUserName","CreateTime","MsgType","Location_X","Location_Y","Scale","Label","MsgId","AgentID"], "link":["ToUserName","FromUserName","CreateTime","MsgType","Title","Description","PicUrl","MsgId","AgentID"] } xml_tree = ET.fromstring(xml_content) type_name = xml_tree.find("MsgType").text msg = {} for nodename in type_fields[type_name]: msg[nodename] = xml_tree.find(nodename).text return msg def parseResponse(resp_dict): wxcpt = getCryptor() xml_message = ResponseMessage(resp_dict).xml nonce = generateNonce() ret,returnMsg = wxcpt.EncryptMsg(xml_message,nonce) if ret != 0 : print("ERR: VerifyURL ret: " + str(ret)) return HttpResponse("ERR: VerifyURL ret: " + str(ret)) return HttpResponse(returnMsg)
38.478261
132
0.685499
281
2,655
6.398577
0.338078
0.038932
0.050612
0.060067
0.256396
0.256396
0.256396
0.256396
0.256396
0.256396
0
0.001801
0.163465
2,655
68
133
39.044118
0.807744
0.026365
0
0.346154
1
0
0.256202
0
0
0
0
0.014706
0
1
0.076923
false
0
0.057692
0
0.269231
0.057692
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
2
9673d3b15c2ead4e093d455f9bd27e1c1e57d9a2
5,494
py
Python
src/textbook_src/ch07/positional_list.py
AlexMGitHub/DS-A_Python
a4770c95ef2f76917fb1d8bc8c11433828a735a3
[ "MIT" ]
null
null
null
src/textbook_src/ch07/positional_list.py
AlexMGitHub/DS-A_Python
a4770c95ef2f76917fb1d8bc8c11433828a735a3
[ "MIT" ]
null
null
null
src/textbook_src/ch07/positional_list.py
AlexMGitHub/DS-A_Python
a4770c95ef2f76917fb1d8bc8c11433828a735a3
[ "MIT" ]
null
null
null
# Copyright 2013, Michael H. Goldwasser # # Developed for use with the book: # # Data Structures and Algorithms in Python # Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser # John Wiley & Sons, 2013 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from .doubly_linked_base import _DoublyLinkedBase class PositionalList(_DoublyLinkedBase): """A sequential container of elements allowing positional access.""" #-------------------------- nested Position class -------------------------- class Position: """An abstraction representing the location of a single element. Note that two position instaces may represent the same inherent location in the list. Therefore, users should always rely on syntax 'p == q' rather than 'p is q' when testing equivalence of positions. """ def __init__(self, container, node): """Constructor should not be invoked by user.""" self._container = container self._node = node def element(self): """Return the element stored at this Position.""" return self._node._element def __eq__(self, other): """Return True if other is a Position representing the same location.""" return type(other) is type(self) and other._node is self._node def __ne__(self, other): """Return True if other does not represent the same location.""" return not (self == other) # opposite of __eq__ #------------------------------- utility methods ------------------------------- def _validate(self, p): """Return position's node, or raise appropriate error if invalid.""" if not isinstance(p, self.Position): raise TypeError('p must be proper Position type') if p._container is not self: raise ValueError('p does not belong to this container') if p._node._next is None: # convention for deprecated nodes raise ValueError('p is no longer valid') return p._node def _make_position(self, node): """Return Position instance for given node (or None if sentinel).""" if node is self._header or node is self._trailer: return None # boundary violation else: return self.Position(self, node) # legitimate position #------------------------------- accessors ------------------------------- def first(self): """Return the first Position in the list (or None if list is empty).""" return self._make_position(self._header._next) def last(self): """Return the last Position in the list (or None if list is empty).""" return self._make_position(self._trailer._prev) def before(self, p): """Return the Position just before Position p (or None if p is first).""" node = self._validate(p) return self._make_position(node._prev) def after(self, p): """Return the Position just after Position p (or None if p is last).""" node = self._validate(p) return self._make_position(node._next) def __iter__(self): """Generate a forward iteration of the elements of the list.""" cursor = self.first() while cursor is not None: yield cursor.element() cursor = self.after(cursor) #------------------------------- mutators ------------------------------- # override inherited version to return Position, rather than Node def _insert_between(self, e, predecessor, successor): """Add element between existing nodes and return new Position.""" node = super()._insert_between(e, predecessor, successor) return self._make_position(node) def add_first(self, e): """Insert element e at the front of the list and return new Position.""" return self._insert_between(e, self._header, self._header._next) def add_last(self, e): """Insert element e at the back of the list and return new Position.""" return self._insert_between(e, self._trailer._prev, self._trailer) def add_before(self, p, e): """Insert element e into list before Position p and return new Position.""" original = self._validate(p) return self._insert_between(e, original._prev, original) def add_after(self, p, e): """Insert element e into list after Position p and return new Position.""" original = self._validate(p) return self._insert_between(e, original, original._next) def delete(self, p): """Remove and return the element at Position p.""" original = self._validate(p) return self._delete_node(original) # inherited method returns element def replace(self, p, e): """Replace the element at Position p with e. Return the element formerly at Position p. """ original = self._validate(p) old_value = original._element # temporarily store old element original._element = e # replace with new element return old_value # return the old element value
40.10219
82
0.658537
735
5,494
4.798639
0.296599
0.034023
0.022115
0.031188
0.269067
0.245534
0.197335
0.154239
0.138361
0.113978
0
0.002088
0.215508
5,494
136
83
40.397059
0.816241
0.517474
0
0.098361
0
0
0.034164
0
0
0
0
0
0
1
0.295082
false
0
0.016393
0
0.622951
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
967603ce5a09279d1dc8ac35c7c4b32234726860
415
py
Python
security-key-spaces.py
shreyakupadhyay/Hacks-py
d779e6eeca0a42dab68e599c1e48143338662a28
[ "MIT" ]
11
2015-07-12T09:06:58.000Z
2020-09-16T06:35:39.000Z
security-key-spaces.py
shreyakupadhyay/Hacks-py
d779e6eeca0a42dab68e599c1e48143338662a28
[ "MIT" ]
null
null
null
security-key-spaces.py
shreyakupadhyay/Hacks-py
d779e6eeca0a42dab68e599c1e48143338662a28
[ "MIT" ]
6
2017-06-07T01:16:39.000Z
2020-04-30T21:42:21.000Z
# Enter your code here. Read input from STDIN. Print output to STDOUT import sys arr=raw_input() e=int(raw_input()) array=[] for i in range(0,len(arr)): if(chr(ord(arr[i])+e)>'9'): array.append(chr(ord(arr[i])+e-10)) elif(chr(ord(arr[i])+e)>'z'): array.append(chr(ord(arr[i])+e-26)) else: array.append(chr(ord(arr[i])+e)) for i in range(0,len(arr)): sys.stdout.write(array[i])
25.9375
69
0.609639
79
415
3.177215
0.455696
0.119522
0.179283
0.199203
0.494024
0.406375
0.406375
0
0
0
0
0.020349
0.171084
415
15
70
27.666667
0.709302
0.161446
0
0.153846
0
0
0.00578
0
0
0
0
0.066667
0
1
0
false
0
0.076923
0
0.076923
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
1
0
0
0
0
0
0
0
0
0
0
2
967d32715ca786a66ec1eca473890ea6ed191500
1,621
py
Python
dialga/datasetops.py
Gokkulnath/Dialga
bc906ce8fdcc010f266e15d40e0433d537943e8d
[ "Apache-2.0" ]
null
null
null
dialga/datasetops.py
Gokkulnath/Dialga
bc906ce8fdcc010f266e15d40e0433d537943e8d
[ "Apache-2.0" ]
3
2020-11-13T18:36:59.000Z
2022-02-10T01:19:57.000Z
dialga/datasetops.py
Gokkulnath/Dialga
bc906ce8fdcc010f266e15d40e0433d537943e8d
[ "Apache-2.0" ]
1
2021-07-01T08:01:08.000Z
2021-07-01T08:01:08.000Z
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_datasetops.ipynb (unless otherwise specified). __all__ = ['Resize_Image', 'Resize_Imgs_Directory', 'stratified_sample_df'] # Cell import os import sys import PIL from PIL import Image from glob import glob from multiprocessing import pool from multiprocessing.dummy import Pool as ThreadPool import pandas as pd # path=''.join(sys.argv[1:]) # TODO : Need to Write Better Logic for Folder Creation and CLI parsing to pass no of Threads # TODO : Suffix or Prefix Change ? def Resize_Image( filepath ): im = Image.open( filepath ) im = im.resize((256,256) ,PIL.Image.BILINEAR) im.save('Resized_'+filepath) def Resize_Imgs_Directory(path,ext=''): os.makedirs("Resized_"+path) files=glob(path+'/*'+ext) pool = ThreadPool(8) pool.map( Resize_Image, files) # Cell def stratified_sample_df(df, col, n_samples,mode='min'): ''' Add Verbose method to print out log ''' if mode=='min': n = min(n_samples, df[col].value_counts().min()) df_ = df.groupby(col).apply(lambda x: x.sample(n)) df_.index = df_.index.droplevel(0) return df_ elif mode=='max': max_size = max(n_samples,df[col].value_counts().max()) lst = [df] for class_index, group in df.groupby(col): lst.append(group.sample(max_size-len(group), replace=True)) return pd.concat(lst) else: max_size = n_samples lst = [df] for class_index, group in df.groupby(col): lst.append(group.sample(max_size-len(group), replace=True)) return pd.concat(lst)
28.946429
93
0.661937
235
1,621
4.421277
0.446809
0.030799
0.034649
0.025024
0.238691
0.238691
0.192493
0.192493
0.192493
0.192493
0
0.008627
0.213448
1,621
55
94
29.472727
0.806275
0.178902
0
0.222222
1
0
0.061115
0.016043
0
0
0
0.018182
0
1
0.083333
false
0
0.222222
0
0.388889
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
2