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
81f8d698a3ddfe36ef13f1113078ded3a3fb3cf5
865
py
Python
checkov/terraform/checks/resource/aws/EKSSecretsEncryption.py
cclauss/checkov
60a385fcaff1499cf00c2d0018575fe5ab71f556
[ "Apache-2.0" ]
1
2021-01-26T12:46:32.000Z
2021-01-26T12:46:32.000Z
checkov/terraform/checks/resource/aws/EKSSecretsEncryption.py
cclauss/checkov
60a385fcaff1499cf00c2d0018575fe5ab71f556
[ "Apache-2.0" ]
1
2021-06-02T02:53:31.000Z
2021-06-02T02:53:31.000Z
checkov/terraform/checks/resource/aws/EKSSecretsEncryption.py
cclauss/checkov
60a385fcaff1499cf00c2d0018575fe5ab71f556
[ "Apache-2.0" ]
null
null
null
from checkov.common.models.enums import CheckResult, CheckCategories from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck class EKSSecretsEncryption(BaseResourceCheck): def __init__(self): name = "Ensure EKS Cluster has Secrets Encryption Enabled" id = "CKV_AWS_58" supported_resources = ['aws_eks_cluster'] categories = [CheckCategories.KUBERNETES] super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) def scan_resource_conf(self, conf): if "encryption_config" in conf.keys() and "resources" in conf["encryption_config"][0] and \ "secrets" in conf["encryption_config"][0]["resources"][0]: return CheckResult.PASSED else: return CheckResult.FAILED check = EKSSecretsEncryption()
39.318182
106
0.713295
93
865
6.397849
0.516129
0.090756
0.053782
0.07395
0.077311
0
0
0
0
0
0
0.007174
0.19422
865
21
107
41.190476
0.846485
0
0
0
0
0
0.17341
0
0
0
0
0
0
1
0.125
false
0.0625
0.125
0
0.4375
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
81ffc4260214e21a8fbb8d247a68944ab547969b
643
py
Python
example/usage/example_kate.py
vodka2/vkaudiotoken-python
5720e4cf77f5e1b20c3bf57f3df0717638a539e0
[ "MIT" ]
32
2020-07-21T18:32:59.000Z
2022-03-20T21:16:11.000Z
example/usage/example_kate.py
vodka2/vkaudiotoken-python
5720e4cf77f5e1b20c3bf57f3df0717638a539e0
[ "MIT" ]
1
2020-10-04T04:41:06.000Z
2020-10-05T11:43:48.000Z
example/usage/example_kate.py
vodka2/vkaudiotoken-python
5720e4cf77f5e1b20c3bf57f3df0717638a539e0
[ "MIT" ]
2
2021-09-21T01:17:05.000Z
2022-03-17T10:17:22.000Z
from __future__ import print_function try: import vkaudiotoken except ImportError: import path_hack from vkaudiotoken import supported_clients import sys import requests import json token = sys.argv[1] user_agent = supported_clients.KATE.user_agent sess = requests.session() sess.headers.update({'User-Agent': user_agent}) def prettyprint(result): print(json.dumps(json.loads(result.content.decode('utf-8')), indent=2)) prettyprint(sess.get( "https://api.vk.com/method/audio.getById", params=[('access_token', token), ('audios', '371745461_456289486,-41489995_202246189'), ('v', '5.95')] ))
21.433333
75
0.715397
82
643
5.439024
0.670732
0.080717
0
0
0
0
0
0
0
0
0
0.075092
0.150855
643
29
76
22.172414
0.741758
0
0
0
0
0
0.180404
0.060653
0
0
0
0
0
1
0.047619
false
0
0.380952
0
0.428571
0.190476
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
0
0
0
1
c301529eb7d8f8a6047d8e286ff806d7da8427d3
2,235
py
Python
tools/testrunner/outproc/message.py
LancerWang001/v8
42ff4531f590b901ade0a18bfd03e56485fe2452
[ "BSD-3-Clause" ]
20,995
2015-01-01T05:12:40.000Z
2022-03-31T21:39:18.000Z
tools/testrunner/outproc/message.py
Andrea-MariaDB-2/v8
a0f0ebd7a876e8cb2210115adbfcffe900e99540
[ "BSD-3-Clause" ]
333
2020-07-15T17:06:05.000Z
2021-03-15T12:13:09.000Z
tools/testrunner/outproc/message.py
Andrea-MariaDB-2/v8
a0f0ebd7a876e8cb2210115adbfcffe900e99540
[ "BSD-3-Clause" ]
4,523
2015-01-01T15:12:34.000Z
2022-03-28T06:23:41.000Z
# Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import itertools import os import re from . import base class OutProc(base.ExpectedOutProc): def __init__(self, expected_outcomes, basepath, expected_fail, expected_filename, regenerate_expected_files): super(OutProc, self).__init__(expected_outcomes, expected_filename, regenerate_expected_files) self._basepath = basepath self._expected_fail = expected_fail def _is_failure_output(self, output): fail = output.exit_code != 0 if fail != self._expected_fail: return True expected_lines = [] # Can't use utils.ReadLinesFrom() here because it strips whitespace. with open(self._basepath + '.out') as f: for line in f: if line.startswith("#") or not line.strip(): continue expected_lines.append(line) raw_lines = output.stdout.splitlines() actual_lines = [ s for s in raw_lines if not self._ignore_line(s) ] if len(expected_lines) != len(actual_lines): return True # Try .js first, and fall back to .mjs. # TODO(v8:9406): clean this up by never separating the path from # the extension in the first place. base_path = self._basepath + '.js' if not os.path.exists(base_path): base_path = self._basepath + '.mjs' env = { 'basename': os.path.basename(base_path), } for (expected, actual) in itertools.izip_longest( expected_lines, actual_lines, fillvalue=''): pattern = re.escape(expected.rstrip() % env) pattern = pattern.replace('\\*', '.*') pattern = pattern.replace('\\{NUMBER\\}', '\d+(?:\.\d*)?') pattern = '^%s$' % pattern if not re.match(pattern, actual): return True return False def _ignore_line(self, string): """Ignore empty lines, valgrind output, Android output.""" return ( not string or not string.strip() or string.startswith("==") or string.startswith("**") or string.startswith("ANDROID") or # Android linker warning. string.startswith('WARNING: linker:') )
32.867647
72
0.648322
282
2,235
4.968085
0.425532
0.034261
0.038544
0.048537
0.094218
0.038544
0
0
0
0
0
0.006471
0.239374
2,235
67
73
33.358209
0.817647
0.195526
0
0.061224
0
0
0.045378
0
0
0
0
0.014925
0
1
0.061224
false
0
0.081633
0
0.265306
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
c3027f734157db362e121ea8ce2b5d36ad4e6075
604
py
Python
gemtown/users/urls.py
doramong0926/gemtown
2c39284e3c68f0cc11994bed0ee2abaad0ea06b6
[ "MIT" ]
null
null
null
gemtown/users/urls.py
doramong0926/gemtown
2c39284e3c68f0cc11994bed0ee2abaad0ea06b6
[ "MIT" ]
5
2020-09-04T20:13:39.000Z
2022-02-17T22:03:33.000Z
gemtown/users/urls.py
doramong0926/gemtown
2c39284e3c68f0cc11994bed0ee2abaad0ea06b6
[ "MIT" ]
null
null
null
from django.urls import path from . import views app_name = "users" urlpatterns = [ path("all/", view=views.UserList.as_view(), name="all_user"), path("<int:user_id>/password/", view=views.ChangePassword.as_view(), name="change password"), path("<int:user_id>/follow/", view=views.FollowUser.as_view(), name="follow user"), path("<int:user_id>/unfollow/", view=views.UnfollowUser.as_view(), name="unfollow user"), path("<int:user_id>/", view=views.UserFeed.as_view(), name="user_detail_infomation"), path("login/facebook/", view=views.FacebookLogin.as_view(), name="fb_login"), ]
50.333333
97
0.701987
85
604
4.811765
0.364706
0.132029
0.146699
0.127139
0.124694
0
0
0
0
0
0
0
0.099338
604
12
98
50.333333
0.751838
0
0
0
0
0
0.300826
0.147107
0
0
0
0
0
1
0
false
0.090909
0.181818
0
0.181818
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c302fe24cced11c5bc506098882205738bad2b79
3,132
py
Python
Packs/Thycotic/Integrations/Thycotic/Thycotic_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
799
2016-08-02T06:43:14.000Z
2022-03-31T11:10:11.000Z
Packs/Thycotic/Integrations/Thycotic/Thycotic_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
9,317
2016-08-07T19:00:51.000Z
2022-03-31T21:56:04.000Z
Packs/Thycotic/Integrations/Thycotic/Thycotic_test.py
diCagri/content
c532c50b213e6dddb8ae6a378d6d09198e08fc9f
[ "MIT" ]
1,297
2016-08-04T13:59:00.000Z
2022-03-31T23:43:06.000Z
import pytest from Thycotic import Client, \ secret_password_get_command, secret_username_get_command, \ secret_get_command, secret_password_update_command, secret_checkout_command, secret_checkin_command, \ secret_delete_command, folder_create_command, folder_delete_command, folder_update_command from test_data.context import GET_PASSWORD_BY_ID_CONTEXT, GET_USERNAME_BY_ID_CONTENT, \ SECRET_GET_CONTENT, SECRET_PASSWORD_UPDATE_CONTEXT, SECRET_CHECKOUT_CONTEXT, SECRET_CHECKIN_CONTEXT, \ SECRET_DELETE_CONTEXT, FOLDER_CREATE_CONTEXT, FOLDER_DELETE_CONTEXT, FOLDER_UPDATE_CONTEXT from test_data.http_responses import GET_PASSWORD_BY_ID_RAW_RESPONSE, GET_USERNAME_BY_ID_RAW_RESPONSE, \ SECRET_GET_RAW_RESPONSE, SECRET_PASSWORD_UPDATE_RAW_RESPONSE, SECRET_CHECKOUT_RAW_RESPONSE, \ SECRET_CHECKIN_RAW_RESPONSE, SECRET_DELETE_RAW_RESPONSE, FOLDER_CREATE_RAW_RESPONSE, FOLDER_DELETE_RAW_RESPONSE, \ FOLDER_UPDATE_RAW_RESPONSE GET_PASSWORD_BY_ID_ARGS = {"secret_id": "4"} GET_USERNAME_BY_ID_ARGS = {"secret_id": "4"} SECRET_GET_ARGS = {"secret_id": "4"} SECRET_PASSWORD_UPDATE_ARGS = {"secret_id": "4", "newpassword": "NEWPASSWORD1"} SECRET_CHECKOUT_ARGS = {"secret_id": "4"} SECRET_CHECKIN_ARGS = {"secret_id": "4"} SECRET_DELETE_ARGS = {"id": "9"} FOLDER_CREATE_ARGS = {"folderName": "xsoarFolderTest3", "folderTypeId": "1", "parentFolderId": "3"} FOLDER_DELETE_ARGS = {"folder_id": "9"} FOLDER_UPDATE_ARGS = {"id": "12", "folderName": "xsoarTF3New"} @pytest.mark.parametrize('command, args, http_response, context', [ (secret_password_get_command, GET_PASSWORD_BY_ID_ARGS, GET_PASSWORD_BY_ID_RAW_RESPONSE, GET_PASSWORD_BY_ID_CONTEXT), (secret_username_get_command, GET_USERNAME_BY_ID_ARGS, GET_USERNAME_BY_ID_RAW_RESPONSE, GET_USERNAME_BY_ID_CONTENT), (secret_get_command, SECRET_GET_ARGS, SECRET_GET_RAW_RESPONSE, SECRET_GET_CONTENT), (secret_password_update_command, SECRET_PASSWORD_UPDATE_ARGS, SECRET_PASSWORD_UPDATE_RAW_RESPONSE, SECRET_PASSWORD_UPDATE_CONTEXT), (secret_checkout_command, SECRET_CHECKOUT_ARGS, SECRET_CHECKOUT_RAW_RESPONSE, SECRET_CHECKOUT_CONTEXT), (secret_checkin_command, SECRET_CHECKIN_ARGS, SECRET_CHECKIN_RAW_RESPONSE, SECRET_CHECKIN_CONTEXT), (secret_delete_command, SECRET_DELETE_ARGS, SECRET_DELETE_RAW_RESPONSE, SECRET_DELETE_CONTEXT), (folder_create_command, FOLDER_CREATE_ARGS, FOLDER_CREATE_RAW_RESPONSE, FOLDER_CREATE_CONTEXT), (folder_delete_command, FOLDER_DELETE_ARGS, FOLDER_DELETE_RAW_RESPONSE, FOLDER_DELETE_CONTEXT), (folder_update_command, FOLDER_UPDATE_ARGS, FOLDER_UPDATE_RAW_RESPONSE, FOLDER_UPDATE_CONTEXT) ]) def test_thycotic_commands(command, args, http_response, context, mocker): mocker.patch.object(Client, '_generate_token') client = Client(server_url="https://thss.softwarium.net/SecretServer", username="xsoar1", password="HfpuhXjv123", proxy=False, verify=False) mocker.patch.object(Client, '_http_request', return_value=http_response) outputs = command(client, **args) results = outputs.to_context() assert results.get("EntryContext") == context
60.230769
120
0.814815
412
3,132
5.616505
0.165049
0.095073
0.073466
0.038894
0.52809
0.185825
0.063526
0.025929
0
0
0
0.006714
0.096424
3,132
51
121
61.411765
0.810954
0
0
0
0
0
0.098659
0
0
0
0
0
0.023256
1
0.023256
false
0.27907
0.093023
0
0.116279
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c307055a5d64c20c7212a67b032444ffbf9d764a
569
py
Python
Linear_Insertion_Sort.py
toppassion/python-master-app
21d854186664440f997bfe53010b242f62979e7f
[ "MIT" ]
null
null
null
Linear_Insertion_Sort.py
toppassion/python-master-app
21d854186664440f997bfe53010b242f62979e7f
[ "MIT" ]
null
null
null
Linear_Insertion_Sort.py
toppassion/python-master-app
21d854186664440f997bfe53010b242f62979e7f
[ "MIT" ]
1
2021-12-08T11:38:20.000Z
2021-12-08T11:38:20.000Z
def Linear_Search(Test_arr, val): index = 0 for i in range(len(Test_arr)): if val > Test_arr[i]: index = i+1 return index def Insertion_Sort(Test_arr): for i in range(1, len(Test_arr)): val = Test_arr[i] j = Linear_Search(Test_arr[:i], val) Test_arr.pop(i) Test_arr.insert(j, val) return Test_arr if __name__ == "__main__": Test_list = input("Enter the list of Numbers: ").split() Test_list = [int(i) for i in Test_list] print(f"Binary Insertion Sort: {Insertion_Sort(Test_list)}")
27.095238
64
0.616872
91
569
3.571429
0.373626
0.215385
0.055385
0.116923
0
0
0
0
0
0
0
0.007126
0.260105
569
21
64
27.095238
0.764846
0
0
0
0
0
0.149123
0.047368
0
0
0
0
0
1
0.117647
false
0
0
0
0.235294
0.058824
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
0
0
0
1
c308e55ef9a8f6ca2122399901177b70c65eef30
1,208
py
Python
test/test_everything.py
jameschapman19/Eigengame
165d1bf35076fbfc6e65a987cb2e09a174776927
[ "MIT" ]
null
null
null
test/test_everything.py
jameschapman19/Eigengame
165d1bf35076fbfc6e65a987cb2e09a174776927
[ "MIT" ]
null
null
null
test/test_everything.py
jameschapman19/Eigengame
165d1bf35076fbfc6e65a987cb2e09a174776927
[ "MIT" ]
null
null
null
import jax.numpy as jnp import numpy as np from jax import random from algorithms import Game, GHA, Oja, Krasulina, Numpy def test_pca(): """ At the moment just checks they all run. Returns ------- """ n = 10 p = 2 n_components = 2 batch_size = 2 epochs = 10 key = random.PRNGKey(0) X = random.normal(key, (n, p)) X = X / jnp.linalg.norm(X, axis=0) numpy = Numpy(n_components=n_components).fit(X) game = Game( n_components=n_components, batch_size=batch_size, epochs=epochs ).fit(X) gha = GHA(n_components=n_components, batch_size=batch_size, epochs=epochs).fit( X ) oja = Oja(n_components=n_components, batch_size=batch_size, epochs=epochs).fit( X ) krasulina = Krasulina( n_components=n_components, batch_size=batch_size, epochs=epochs ).fit(X) assert ( np.testing.assert_almost_equal( [ game.score(X), gha.score(X), oja.score(X), krasulina.score(X), ], numpy.score(X), decimal=0, ) is None )
24.16
83
0.543874
152
1,208
4.171053
0.328947
0.190852
0.094637
0.173502
0.353312
0.353312
0.353312
0.353312
0.353312
0.353312
0
0.012723
0.349338
1,208
49
84
24.653061
0.793893
0.046358
0
0.102564
0
0
0
0
0
0
0
0
0.051282
1
0.025641
false
0
0.102564
0
0.128205
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
0
0
0
1
c311dcd3f870bbdf6b67118d6ccc561653945f40
259
py
Python
show_model_info.py
panovr/Brain-Tumor-Segmentation
bf1ac2360af46a484d632474ce93de339ad2b496
[ "MIT" ]
null
null
null
show_model_info.py
panovr/Brain-Tumor-Segmentation
bf1ac2360af46a484d632474ce93de339ad2b496
[ "MIT" ]
null
null
null
show_model_info.py
panovr/Brain-Tumor-Segmentation
bf1ac2360af46a484d632474ce93de339ad2b496
[ "MIT" ]
null
null
null
import bts.model as model import torch device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') BATCH_SIZE = 6 FILTER_LIST = [16,32,64,128,256] unet_model = model.DynamicUNet(FILTER_LIST) unet_model.summary(batch_size=BATCH_SIZE, device=device)
28.777778
69
0.783784
43
259
4.534884
0.581395
0.138462
0
0
0
0
0
0
0
0
0
0.055556
0.096525
259
8
70
32.375
0.777778
0
0
0
0
0
0.027027
0
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c3159e702eacd0f494cdd9cb0e3428247b34b8ae
669
py
Python
tests/biology/test_join_fasta.py
shandou/pyjanitor
d7842613b4e4a7532a88f673fd54e94c3ba5a96b
[ "MIT" ]
1
2021-03-25T10:46:57.000Z
2021-03-25T10:46:57.000Z
tests/biology/test_join_fasta.py
shandou/pyjanitor
d7842613b4e4a7532a88f673fd54e94c3ba5a96b
[ "MIT" ]
null
null
null
tests/biology/test_join_fasta.py
shandou/pyjanitor
d7842613b4e4a7532a88f673fd54e94c3ba5a96b
[ "MIT" ]
null
null
null
import importlib import os import pytest from helpers import running_on_ci import janitor.biology # noqa: F403, F401 # Skip all tests if Biopython not installed pytestmark = pytest.mark.skipif( (importlib.util.find_spec("Bio") is None) & ~running_on_ci(), reason="Biology tests relying on Biopython only required for CI", ) @pytest.mark.biology def test_join_fasta(biodf): """Test adding sequence from FASTA file in ``sequence`` column.""" df = biodf.join_fasta( filename=os.path.join(pytest.TEST_DATA_DIR, "sequences.fasta"), id_col="sequence_accession", column_name="sequence", ) assert "sequence" in df.columns
25.730769
71
0.714499
92
669
5.054348
0.619565
0.03871
0.047312
0
0
0
0
0
0
0
0
0.010949
0.180867
669
25
72
26.76
0.837591
0.179372
0
0
0
0
0.197417
0
0
0
0
0
0.058824
1
0.058824
false
0
0.352941
0
0.411765
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
0
0
0
1
c31bd0f2505a1c4be1c52fbd6469723bb696bfa9
2,470
py
Python
account/models.py
Hasanozzaman-Khan/Django-User-Authentication
96482a51ed01bbdc7092d6ca34383054967a8aa0
[ "MIT" ]
null
null
null
account/models.py
Hasanozzaman-Khan/Django-User-Authentication
96482a51ed01bbdc7092d6ca34383054967a8aa0
[ "MIT" ]
null
null
null
account/models.py
Hasanozzaman-Khan/Django-User-Authentication
96482a51ed01bbdc7092d6ca34383054967a8aa0
[ "MIT" ]
null
null
null
from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from PIL import Image # Create your models here. class Home(models.Model): pass class CustomUserManager(BaseUserManager): """Manager for user profiles""" def create_user(self, email, first_name, last_name, password=None): """Create a new user profile""" if not email: raise ValueError("User must have an email address.") email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password): """Create and save a new superuser with given details""" user = self.create_user(email, first_name, last_name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class CustomRegisterModel(AbstractBaseUser, PermissionsMixin): """ Database model for users in the system """ email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_email_verified = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def get_full_name(self): """Retrieve full name of user""" return self.first_name + " " + self.last_name def get_short_name(self): """Retrieve short name of user""" return self.first_name def __str__(self): """Return string representation of our user""" return self.email class ProfileModel(models.Model): user = models.OneToOneField(CustomRegisterModel, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_picture') def __str__(self): return f"{self.user.first_name}'s profile" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path)
30.493827
90
0.676923
309
2,470
5.239482
0.36246
0.05559
0.044472
0.052502
0.170476
0.170476
0.11365
0
0
0
0
0.010898
0.219838
2,470
80
91
30.875
0.829268
0.106883
0
0.125
0
0
0.053044
0.01107
0
0
0
0
0
1
0.145833
false
0.104167
0.0625
0.020833
0.645833
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c32367d43e08138167f815beb65fbee346856f66
1,965
py
Python
old_test/test-large.py
briandobbins/pynio
1dd5fc0fc133f2b8d329ae68929bd3c6c1c5fa7c
[ "Apache-2.0" ]
null
null
null
old_test/test-large.py
briandobbins/pynio
1dd5fc0fc133f2b8d329ae68929bd3c6c1c5fa7c
[ "Apache-2.0" ]
null
null
null
old_test/test-large.py
briandobbins/pynio
1dd5fc0fc133f2b8d329ae68929bd3c6c1c5fa7c
[ "Apache-2.0" ]
null
null
null
from __future__ import print_function, division import numpy as np import Nio import time, os # # Creating a file # init_time = time.clock() ncfile = 'test-large.nc' if (os.path.exists(ncfile)): os.system("/bin/rm -f " + ncfile) opt = Nio.options() opt.Format = "LargeFile" opt.PreFill = False file = Nio.open_file(ncfile, 'w', options=opt) file.title = "Testing large files and dimensions" file.create_dimension('big', 2500000000) bigvar = file.create_variable('bigvar', "b", ('big',)) print("created bigvar") # note it is incredibly slow to write a scalar to a large file variable # so create an temporary variable x that will get assigned in steps x = np.empty(1000000,dtype = 'int8') #print x x[:] = 42 t = list(range(0,2500000000,1000000)) ii = 0 for i in t: if (i == 0): continue print(t[ii],i) bigvar[t[ii]:i] = x[:] ii += 1 x[:] = 84 bigvar[2499000000:2500000000] = x[:] bigvar[-1] = 84 bigvar.units = "big var units" #print bigvar[-1] print(bigvar.dimensions) # check unlimited status for dim in list(file.dimensions.keys()): print(dim, " unlimited: ",file.unlimited(dim)) print(file) print("closing file") print('elapsed time: ',time.clock() - init_time) file.close() #quit() # # Reading a file # print('opening file for read') print('elapsed time: ',time.clock() - init_time) file = Nio.open_file(ncfile, 'r') print('file is open') print('elapsed time: ',time.clock() - init_time) print(file.dimensions) print(list(file.variables.keys())) print(file) print("reading variable") print('elapsed time: ',time.clock() - init_time) x = file.variables['bigvar'] print(x[0],x[1000000],x[249000000],x[2499999999]) print("max and min") min = x[:].min() max = x[:].max() print(min, max) print('elapsed time: ',time.clock() - init_time) # check unlimited status for dim in list(file.dimensions.keys()): print(dim, " unlimited: ",file.unlimited(dim)) print("closing file") print('elapsed time: ',time.clock() - init_time) file.close()
23.674699
71
0.689567
303
1,965
4.419142
0.339934
0.041822
0.067961
0.089619
0.344287
0.315907
0.315907
0.241972
0.214339
0.214339
0
0.05549
0.137913
1,965
82
72
23.963415
0.734947
0.122646
0
0.271186
0
0
0.181871
0
0
0
0
0
0
1
0
false
0
0.067797
0
0.067797
0.40678
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
0
0
1
0
1
c327543b799027a0d190954bd8149ab8b7d7603f
809
py
Python
scrapets/extract.py
ownport/scrapets
e52609aae4d55fb9d4315f90d4e2fe3804ef8ff6
[ "MIT" ]
2
2017-06-22T15:45:52.000Z
2019-08-23T03:34:40.000Z
scrapets/extract.py
ownport/scrapets
e52609aae4d55fb9d4315f90d4e2fe3804ef8ff6
[ "MIT" ]
9
2016-10-23T17:56:34.000Z
2016-12-12T10:39:23.000Z
scrapets/extract.py
ownport/scrapets
e52609aae4d55fb9d4315f90d4e2fe3804ef8ff6
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from HTMLParser import HTMLParser # ------------------------------------------------------- # # LinkExtractor: extract links from html page # class BaseExtractor(HTMLParser): def __init__(self): HTMLParser.__init__(self) self._links = [] @property def links(self): return self._links class LinkExtractor(BaseExtractor): def handle_starttag(self, tag, attrs): if tag == 'a': links = [v for k,v in attrs if k == 'href' and v not in self._links] self._links.extend(links) class ImageLinkExtractor(BaseExtractor): def handle_starttag(self, tag, attrs): if tag == 'img': links = [v for k,v in attrs if k == 'src' and v not in self._links] self._links.extend(links)
20.74359
80
0.566131
95
809
4.652632
0.368421
0.122172
0.099548
0.135747
0.479638
0.479638
0.479638
0.479638
0.479638
0.171946
0
0.001675
0.262052
809
38
81
21.289474
0.738693
0.15204
0
0.222222
0
0
0.016176
0
0
0
0
0
0
1
0.222222
false
0
0.055556
0.055556
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
0
0
0
0
1
c3283cdb2fefed11f9dc322c324670fa2d4fbccd
1,069
py
Python
tests/unit/utils/filebuffer_test.py
gotcha/salt
7b84c704777d3d2062911895dc3fdf93d40e9848
[ "Apache-2.0" ]
2
2019-03-30T02:12:56.000Z
2021-03-08T18:59:46.000Z
tests/unit/utils/filebuffer_test.py
gotcha/salt
7b84c704777d3d2062911895dc3fdf93d40e9848
[ "Apache-2.0" ]
null
null
null
tests/unit/utils/filebuffer_test.py
gotcha/salt
7b84c704777d3d2062911895dc3fdf93d40e9848
[ "Apache-2.0" ]
1
2020-12-04T11:28:06.000Z
2020-12-04T11:28:06.000Z
# -*- coding: utf-8 -*- ''' tests.unit.utils.filebuffer_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)` :copyright: © 2012 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. ''' # Import salt libs from saltunittest import TestCase, TestLoader, TextTestRunner from salt.utils.filebuffer import BufferedReader, InvalidFileMode class TestFileBuffer(TestCase): def test_read_only_mode(self): with self.assertRaises(InvalidFileMode): BufferedReader('/tmp/foo', mode='a') with self.assertRaises(InvalidFileMode): BufferedReader('/tmp/foo', mode='ab') with self.assertRaises(InvalidFileMode): BufferedReader('/tmp/foo', mode='w') with self.assertRaises(InvalidFileMode): BufferedReader('/tmp/foo', mode='wb') if __name__ == "__main__": loader = TestLoader() tests = loader.loadTestsFromTestCase(TestFileBuffer) TextTestRunner(verbosity=1).run(tests)
30.542857
75
0.663237
111
1,069
6.288288
0.558559
0.045845
0.114613
0.200573
0.338109
0.338109
0.338109
0.338109
0
0
0
0.009249
0.190833
1,069
34
76
31.441176
0.796532
0.268475
0
0.25
0
0
0.061089
0
0
0
0
0
0.25
1
0.0625
false
0
0.125
0
0.25
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
0
0
0
1
c3292201406d3697087e8916c4dd2621e50dc55a
192
py
Python
src/wwucs/bot/__init__.py
reillysiemens/wwucs-bot
9e48ba5dc981e36cd8b18345bcbd3768c3deeeb8
[ "0BSD" ]
null
null
null
src/wwucs/bot/__init__.py
reillysiemens/wwucs-bot
9e48ba5dc981e36cd8b18345bcbd3768c3deeeb8
[ "0BSD" ]
null
null
null
src/wwucs/bot/__init__.py
reillysiemens/wwucs-bot
9e48ba5dc981e36cd8b18345bcbd3768c3deeeb8
[ "0BSD" ]
null
null
null
"""WWUCS Bot module.""" __all__ = [ "__author__", "__email__", "__version__", ] __author__ = "Reilly Tucker Siemens" __email__ = "reilly@tuckersiemens.com" __version__ = "0.1.0"
16
38
0.651042
19
192
5.105263
0.736842
0
0
0
0
0
0
0
0
0
0
0.019108
0.182292
192
11
39
17.454545
0.598726
0.088542
0
0
0
0
0.473373
0.142012
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
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
1
c332e2fe6b727044df2454bc3e05a8e3dca73a1d
4,773
py
Python
examples/authentication/demo_auth.py
jordiyeh/safrs
eecfaf6d63ed44b9dc44b7b86c600db02989b512
[ "MIT" ]
null
null
null
examples/authentication/demo_auth.py
jordiyeh/safrs
eecfaf6d63ed44b9dc44b7b86c600db02989b512
[ "MIT" ]
null
null
null
examples/authentication/demo_auth.py
jordiyeh/safrs
eecfaf6d63ed44b9dc44b7b86c600db02989b512
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # This is a demo application to demonstrate the functionality of the safrs_rest REST API with authentication # # you will have to install the requirements: # pip3 install passlib flask_httpauth flask_login # # This script can be ran standalone like this: # python3 demo_auth.py [Listener-IP] # This will run the example on http://Listener-Ip:5000 # # - A database is created and a item is added # - User is created and the User endpoint is protected by user:admin & pass: adminPASS # - swagger2 documentation is generated # import sys import os import logging import builtins from functools import wraps from flask import Flask, redirect, jsonify, make_response from flask import abort, request, g, url_for from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, String from safrs import SAFRSBase, SAFRSJSONEncoder, Api, jsonapi_rpc from flask_swagger_ui import get_swaggerui_blueprint from flask_sqlalchemy import SQLAlchemy from flask_httpauth import HTTPBasicAuth from passlib.apps import custom_app_context as pwd_context from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) from flask.ext.login import LoginManager, UserMixin, \ login_required, login_user, logout_user db = SQLAlchemy() auth = HTTPBasicAuth() # Example sqla database object class Item(SAFRSBase, db.Model): ''' description: Item description ''' __tablename__ = 'items' id = Column(String, primary_key=True) name = Column(String, default = '') class User(SAFRSBase, db.Model): ''' description: User description ''' __tablename__ = 'users' id = db.Column(String, primary_key=True) username = db.Column(db.String(32), index=True) password_hash = db.Column(db.String(64)) custom_decorators = [auth.login_required] @jsonapi_rpc(http_methods = ['POST']) def hash_password(self, password): self.password_hash = pwd_context.encrypt(password) @jsonapi_rpc(http_methods = ['POST']) def verify_password(self, password): return pwd_context.verify(password, self.password_hash) @jsonapi_rpc(http_methods = ['POST']) def generate_auth_token(self, expiration=600): s = Serializer(app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}) @staticmethod @jsonapi_rpc(http_methods = ['POST']) def verify_auth_token(token): s = Serializer(app.config['SECRET_KEY']) try: data = s.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token user = User.query.get(data['id']) return user def start_app(app): api = Api(app, api_spec_url = '/api/swagger', host = '{}:{}'.format(HOST,PORT), schemes = [ "http" ] ) item = Item(name='test',email='em@il') user = User(username='admin') user.hash_password('adminPASS') api.expose_object(Item) api.expose_object(User) # Set the JSON encoder used for object to json marshalling app.json_encoder = SAFRSJSONEncoder # Register the API at /api/docs swaggerui_blueprint = get_swaggerui_blueprint('/api', '/api/swagger.json') app.register_blueprint(swaggerui_blueprint, url_prefix='/api') print('Starting API: http://{}:{}/api'.format(HOST,PORT)) app.run(host=HOST, port = PORT) # # APP Initialization # app = Flask('demo_app') app.config.update( SQLALCHEMY_DATABASE_URI = 'sqlite://', SQLALCHEMY_TRACK_MODIFICATIONS = False, SECRET_KEY = b'sdqfjqsdfqizroqnxwc', DEBUG = True) HOST = sys.argv[1] if len(sys.argv) > 1 else '0.0.0.0' PORT = 5000 db.init_app(app) # # Authentication and custom routes # @auth.verify_password def verify_password(username_or_token, password): user = User.verify_auth_token(username_or_token) if not user: # try to authenticate with username/password user = User.query.filter_by(username=username_or_token).first() if not user or not user.verify_password(password): return False print('Authentication Successful for "{}"'.format(user.username)) return True @app.route('/') def goto_api(): return redirect('/api') @app.teardown_appcontext def shutdown_session(exception=None): '''cfr. http://flask.pocoo.org/docs/0.12/patterns/sqlalchemy/''' db.session.remove() # Start the application with app.app_context(): db.create_all() start_app(app)
31.82
109
0.673581
591
4,773
5.284264
0.368866
0.020173
0.017931
0.026897
0.099904
0.083253
0.021774
0
0
0
0
0.007297
0.224806
4,773
149
110
32.033557
0.836757
0.191284
0
0.089888
0
0
0.063479
0
0
0
0
0
0
1
0.089888
false
0.11236
0.179775
0.022472
0.47191
0.05618
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
0
0
1
c333f525069086ebb8689eece355d91dd6b64f69
8,757
py
Python
model/BPE.py
djmhunt/TTpy
0f0997314bf0f54831494b2ef1a64f1bff95c097
[ "MIT" ]
null
null
null
model/BPE.py
djmhunt/TTpy
0f0997314bf0f54831494b2ef1a64f1bff95c097
[ "MIT" ]
4
2020-04-19T11:43:41.000Z
2020-07-21T09:57:51.000Z
model/BPE.py
djmhunt/TTpy
0f0997314bf0f54831494b2ef1a64f1bff95c097
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ :Author: Dominic Hunt """ import logging import numpy as np import scipy as sp import collections import itertools from model.modelTemplate import Model class BPE(Model): """The Bayesian predictor model Attributes ---------- Name : string The name of the class used when recording what has been used. Parameters ---------- alpha : float, optional Learning rate parameter epsilon : float, optional Noise parameter. The larger it is the less likely the model is to choose the highest expected reward number_actions : integer, optional The maximum number of valid actions the model can expect to receive. Default 2. number_cues : integer, optional The initial maximum number of stimuli the model can expect to receive. Default 1. number_critics : integer, optional The number of different reaction learning sets. Default number_actions*number_cues validRewards : list,np.ndarray, optional The different reward values that can occur in the task. Default ``array([0, 1])`` action_codes : dict with string or int as keys and int values, optional A dictionary used to convert between the action references used by the task or dataset and references used in the models to describe the order in which the action information is stored. dirichletInit : float, optional The initial values for values of the dirichlet distribution. Normally 0, 1/2 or 1. Default 1 prior : array of floats in ``[0, 1]``, optional Ignored in this case stimFunc : function, optional The function that transforms the stimulus into a form the model can understand and a string to identify it later. Default is blankStim rewFunc : function, optional The function that transforms the reward into a form the model can understand. Default is blankRew decFunc : function, optional The function that takes the internal values of the model and turns them in to a decision. Default is model.decision.discrete.weightProb See Also -------- model.BP : This model is heavily based on that one """ def __init__(self, alpha=0.3, epsilon=0.1, dirichletInit=1, validRewards=np.array([0, 1]), **kwargs): super(BPE, self).__init__(**kwargs) self.alpha = alpha self.epsilon = epsilon self.validRew = validRewards self.rewLoc = collections.OrderedDict(((k, v) for k, v in itertools.izip(self.validRew, range(len(self.validRew))))) self.dirichletVals = np.ones((self.number_actions, self.number_cues, len(self.validRew))) * dirichletInit self.expectations = self.updateExpectations(self.dirichletVals) self.parameters["epsilon"] = self.epsilon self.parameters["alpha"] = self.alpha self.parameters["dirichletInit"] = dirichletInit # Recorded information self.recDirichletVals = [] def returnTaskState(self): """ Returns all the relevant data for this model Returns ------- results : dict The dictionary contains a series of keys including Name, Probabilities, Actions and Events. """ results = self.standardResultOutput() results["dirichletVals"] = np.array(self.recDirichletVals) return results def storeState(self): """ Stores the state of all the important variables so that they can be accessed later """ self.storeStandardResults() self.recDirichletVals.append(self.dirichletVals.copy()) def rewardExpectation(self, observation): """Calculate the estimated reward based on the action and stimuli This contains parts that are task dependent Parameters ---------- observation : {int | float | tuple} The set of stimuli Returns ------- actionExpectations : array of floats The expected rewards for each action stimuli : list of floats The processed observations activeStimuli : list of [0, 1] mapping to [False, True] A list of the stimuli that were or were not present """ activeStimuli, stimuli = self.stimulus_shaper.processStimulus(observation) actionExpectations = self._actExpectations(self.dirichletVals, stimuli) return actionExpectations, stimuli, activeStimuli def delta(self, reward, expectation, action, stimuli): """ Calculates the comparison between the reward and the expectation Parameters ---------- reward : float The reward value expectation : float The expected reward value action : int The chosen action stimuli : {int | float | tuple | None} The stimuli received Returns ------- delta """ modReward = self.reward_shaper.processFeedback(reward, action, stimuli) return modReward def updateModel(self, delta, action, stimuli, stimuliFilter): """ Parameters ---------- delta : float The difference between the reward and the expected reward action : int The action chosen by the model in this trialstep stimuli : list of float The weights of the different stimuli in this trialstep stimuliFilter : list of bool A list describing if a stimulus cue is present in this trialstep """ # Find the new activities self._newExpect(action, delta, stimuli) # Calculate the new probabilities # We need to combine the expectations before calculating the probabilities actionExpectations = self._actExpectations(self.dirichletVals, stimuli) self.probabilities = self.calcProbabilities(actionExpectations) def _newExpect(self, action, delta, stimuli): self.dirichletVals[action, :, self.rewLoc[delta]] += self.alpha * stimuli/np.sum(stimuli) self.expectations = self.updateExpectations(self.dirichletVals) def _actExpectations(self, dirichletVals, stimuli): # If there are multiple possible stimuli, filter by active stimuli and calculate # calculate the expectations associated with each action. if self.number_cues > 1: actionExpectations = self.calcActExpectations(self.actStimMerge(dirichletVals, stimuli)) else: actionExpectations = self.calcActExpectations(dirichletVals[:, 0, :]) return actionExpectations def calcProbabilities(self, actionValues): # type: (np.ndarray) -> np.ndarray """ Calculate the probabilities associated with the actions Parameters ---------- actionValues : 1D ndArray of floats Returns ------- probArray : 1D ndArray of floats The probabilities associated with the actionValues """ cbest = actionValues == max(actionValues) deltaEpsilon = self.epsilon * (1 / self.number_actions) bestEpsilon = (1 - self.epsilon) / np.sum(cbest) + deltaEpsilon probArray = bestEpsilon * cbest + deltaEpsilon * (1 - cbest) return probArray def actorStimulusProbs(self): """ Calculates in the model-appropriate way the probability of each action. Returns ------- probabilities : 1D ndArray of floats The probabilities associated with the action choices """ probabilities = self.calcProbabilities(self.expectedRewards) return probabilities def actStimMerge(self, dirichletVals, stimuli): dirVals = dirichletVals * np.expand_dims(np.repeat([stimuli], self.number_actions, axis=0), 2) actDirVals = np.sum(dirVals, 1) return actDirVals def calcActExpectations(self, dirichletVals): actExpect = np.fromiter((np.sum(sp.stats.dirichlet(d).mean() * self.validRew) for d in dirichletVals), float, count=self.number_actions) return actExpect def updateExpectations(self, dirichletVals): def meanFunc(p, r=[]): return np.sum(sp.stats.dirichlet(p).mean() * r) expectations = np.apply_along_axis(meanFunc, 2, dirichletVals, r=self.validRew) return expectations
33.680769
145
0.628183
934
8,757
5.857602
0.296574
0.03418
0.008042
0.014805
0.127216
0.099799
0.057394
0.018278
0.018278
0
0
0.005361
0.29702
8,757
259
146
33.810811
0.883366
0.454836
0
0.059701
0
0
0.010109
0
0
0
0
0
0
1
0.208955
false
0
0.089552
0.014925
0.462687
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
0
0
0
1
c34648b7e6fe0e43164dec6e0c0022e1e1efabdd
1,485
py
Python
fb/forms.py
pure-python/brainmate
79c83e707a4811dd881832d22f17c29f33c4d7f2
[ "Apache-2.0" ]
null
null
null
fb/forms.py
pure-python/brainmate
79c83e707a4811dd881832d22f17c29f33c4d7f2
[ "Apache-2.0" ]
1
2016-04-14T14:42:52.000Z
2016-04-14T14:42:52.000Z
fb/forms.py
pure-python/brainmate
79c83e707a4811dd881832d22f17c29f33c4d7f2
[ "Apache-2.0" ]
null
null
null
from django.forms import ( Form, CharField, Textarea, PasswordInput, ChoiceField, DateField, ImageField, BooleanField, IntegerField, MultipleChoiceField ) from django import forms from fb.models import UserProfile class UserPostForm(Form): text = CharField(widget=Textarea( attrs={'rows': 1, 'cols': 40, 'class': 'form-control','placeholder': "What's on your mind?"})) class UserPostCommentForm(Form): text = CharField(widget=Textarea( attrs={'rows': 1, 'cols': 50, 'class': 'form-control','placeholder': "Write a comment..."})) class UserLogin(Form): username = CharField(max_length=30) password = CharField(widget=PasswordInput) class UserProfileForm(Form): first_name = CharField(max_length=100, required=False) last_name = CharField(max_length=100, required=False) gender = ChoiceField(choices=UserProfile.GENDERS, required=False) date_of_birth = DateField(required=False) avatar = ImageField(required=False) OPTIONS = ( ("Cars", "Cars"), ("Dogs", "Dogs"), ("Sports", "Sports"), ) interests = MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS, required=False) class QuestionFrom(Form): question_description = CharField(max_length=300) points = IntegerField() class AddAnswerForm(Form): answer_description = CharField(max_length=30) correct_answer = BooleanField(required=False)
31.595745
102
0.682828
152
1,485
6.592105
0.473684
0.090818
0.08982
0.045908
0.165669
0.165669
0.165669
0.08982
0.08982
0
0
0.015913
0.19596
1,485
46
103
32.282609
0.823283
0
0
0.058824
0
0
0.092929
0
0
0
0
0
0
1
0
false
0.058824
0.088235
0
0.705882
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c35493185a871b0c5b3f41a18ba8dd0865c75b5e
1,521
py
Python
var/spack/repos/builtin/packages/bcache/package.py
milljm/spack
b476f8aa63d48f4b959522ece0406caa32992d4a
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
var/spack/repos/builtin/packages/bcache/package.py
milljm/spack
b476f8aa63d48f4b959522ece0406caa32992d4a
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
var/spack/repos/builtin/packages/bcache/package.py
milljm/spack
b476f8aa63d48f4b959522ece0406caa32992d4a
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
# Copyright 2013-2020 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 Bcache(MakefilePackage): """Bcache is a patch for the Linux kernel to use SSDs to cache other block devices.""" homepage = "http://bcache.evilpiepirate.org" url = "https://github.com/g2p/bcache-tools/archive/v1.0.8.tar.gz" version('1.0.8', sha256='d56923936f37287efc57a46315679102ef2c86cd0be5874590320acd48c1201c') version('1.0.7', sha256='64d76d1085afba8c3d5037beb67bf9d69ee163f357016e267bf328c0b1807abd') version('1.0.6', sha256='9677c6da3ceac4e1799d560617c4d00ea7e9d26031928f8f94b8ab327496d4e0') version('1.0.5', sha256='1449294ef545b3dc6f715f7b063bc2c8656984ad73bcd81a0dc048cbba416ea9') version('1.0.4', sha256='102ffc3a8389180f4b491188c3520f8a4b1a84e5a7ca26d2bd6de1821f4d913d') depends_on('libuuid') depends_on('util-linux') depends_on('gettext') depends_on('pkgconfig', type='build') def setup_build_environment(self, env): env.append_flags('LDFLAGS', '-lintl') patch('func_crc64.patch', sha256='558b35cadab4f410ce8f87f0766424a429ca0611aa2fd247326ad10da115737d') def install(self, spec, prefix): mkdirp(prefix.bin) install('bcache-register', prefix.bin) install('bcache-super-show', prefix.bin) install('make-bcache', prefix.bin) install('probe-bcache', prefix.bin)
40.026316
104
0.738988
160
1,521
6.975
0.63125
0.035842
0.040323
0.039427
0
0
0
0
0
0
0
0.227586
0.142012
1,521
37
105
41.108108
0.627586
0.177515
0
0
0
0.045455
0.5
0.310178
0
0
0
0
0
1
0.090909
false
0
0.045455
0
0.272727
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c35a9f8a6f746b1900b91c33a9b1be7d36fdde7f
4,086
py
Python
data_collection/json2mongodb.py
kwond2/hedgehogs
58dbed549a1e78e401fc90c7a7041d9979cfc2e4
[ "MIT" ]
9
2018-02-06T19:08:16.000Z
2022-03-15T13:31:57.000Z
data_collection/json2mongodb.py
kwond2/hedgehogs
58dbed549a1e78e401fc90c7a7041d9979cfc2e4
[ "MIT" ]
37
2018-02-09T21:22:58.000Z
2021-12-13T19:51:24.000Z
data_collection/json2mongodb.py
kwond2/hedgehogs
58dbed549a1e78e401fc90c7a7041d9979cfc2e4
[ "MIT" ]
10
2018-02-27T20:26:55.000Z
2021-02-06T02:26:30.000Z
#-*- coding: utf-8 -*- # import os # from optparse import OptionParser # from pymongo import MongoClient, bulk # import json # import collections # import sys from import_hedgehogs import * HOST = '45.55.48.43' PORT = 27017 DB = 'SEC_EDGAR' class OrderedDictWithKeyEscaping(collections.OrderedDict): def __setitem__(self, key, value, dict_setitem=dict.__setitem__): # MongoDB complains when keys contain dots, so we call json.load with # a modified OrderedDict class which escapes dots in keys on the fly key = key.replace('.', '<DOT>') super(OrderedDictWithKeyEscaping, self).__setitem__(key, value)#, dict_setitem=dict.__setitem__) #super(OrderedDictWithKeyEscaping, self).__setitem__ #super() def save_to_mongodb(input_file_name, collectionID, usernameID, passwordID): with open(input_file_name) as fp: data = fp.read() json_ = json.loads(data, encoding='utf-8', object_pairs_hook=OrderedDictWithKeyEscaping) client = MongoClient(HOST, PORT, username=usernameID, password=passwordID, authMechanism ='SCRAM-SHA-1') # client.admin.authenticate('jgeorge','123',source= 'SEC_EDGAR') # print("arguments to function:", input_file_name, usernameID, collectionID) db = client[DB] collection = db[collectionID] # print(type(input_file_name)) # file = open(input_file_name, "r") # data = json.load(file) # print(type(data)) # print(type(file)) # data = json_util.loads(file.read()) # print(json_) for item in json_: collection.insert_one(item) # file.close() def get_collection_name(input_file_name): data_list = json.load(open(input_file_name)) data = dict(data_list[0]) ticker = "TICKER" quarter = "QUARTER" try: # year = data.get("Document And Entity Information [Abstract]") # print(year) year = data.get("Document And Entity Information [Abstract]").get("Document Fiscal Year Focus").get("value") quarter = data.get("Document And Entity Information [Abstract]").get("Document Fiscal Period Focus").get("value") ticker = data.get("Document And Entity Information [Abstract]").get("Entity Trading Symbol").get("value") except AttributeError: print("[EXCEPT] Issues with ", input_file_namex) # except AttributeError: # year = data.get("Document And Entity Information").get("Document Fiscal Year Focus").get("value") # quarter = data.get("Document And Entity Information").get("Document Fiscal Period Focus").get("value") # try: # ticker = data.get("Document And Entity Information [Abstract]").get("Entity Trading Symbol").get("value") # except: # ticker = data.get("Document And Entity Information [Abstract]").get("Trading Symbol").get("value") # try: # ticker = data.get("Document And Entity Information [Abstract]").get("Entity Trading Symbol").get("value") # except: # ticker = data.get("Document And Entity Information [Abstract]").get("Trading Symbol").get("value") # quarter = data.get("Document And Entity Information [Abstract]").get("Document Fiscal Period Focus").get("value") return str(ticker) + "_" + str(year) + "_" + str(quarter) def main(): cli_parser = OptionParser( usage='usage: %prog <input.json> <username> <password>' ) (options, args) = cli_parser.parse_args() # Input file checks if len(args) < 2: cli_parser.error("You have to supply 2 arguments, USAGE: .json username") input_file_name = args[0] if not os.path.exists(input_file_name): cli_parser.error("The input file %s you supplied does not exist" % input_file_name) # JAROD's FUNCTION collection = get_collection_name(input_file_name) #collection = (sys.argv[1]).strip('.') username = sys.argv[2] password = sys.argv[3] print("Adding to MongoDB...") #save_to_mongodb(input_file_name, collection, username) if __name__ == "__main__": print("[WARNING] STILL UNDER DEVELOPMENT") main()
41.272727
121
0.670338
502
4,086
5.290837
0.304781
0.066265
0.058735
0.074548
0.387801
0.387801
0.323042
0.317395
0.298193
0.278614
0
0.007929
0.197504
4,086
98
122
41.693878
0.802074
0.417523
0
0
0
0
0.213675
0
0
0
0
0
0
1
0.086957
false
0.086957
0.021739
0
0.152174
0.065217
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
0
0
1
c35c97b552a6619198e65898ccb72250776063d5
1,867
py
Python
molecule/default/tests/test_default.py
escalate/ansible-influxdb-docker
bbb2c259bd1de3c4c40322103a05894494af7104
[ "MIT" ]
null
null
null
molecule/default/tests/test_default.py
escalate/ansible-influxdb-docker
bbb2c259bd1de3c4c40322103a05894494af7104
[ "MIT" ]
null
null
null
molecule/default/tests/test_default.py
escalate/ansible-influxdb-docker
bbb2c259bd1de3c4c40322103a05894494af7104
[ "MIT" ]
null
null
null
"""Role testing files using testinfra""" def test_config_directory(host): """Check config directory""" f = host.file("/etc/influxdb") assert f.is_directory assert f.user == "influxdb" assert f.group == "root" assert f.mode == 0o775 def test_data_directory(host): """Check data directory""" d = host.file("/var/lib/influxdb") assert d.is_directory assert d.user == "influxdb" assert d.group == "root" assert d.mode == 0o700 def test_backup_directory(host): """Check backup directory""" b = host.file("/var/backups/influxdb") assert b.is_directory assert b.user == "influxdb" assert b.group == "root" assert b.mode == 0o775 def test_influxdb_service(host): """Check InfluxDB service""" s = host.service("influxdb") assert s.is_running assert s.is_enabled def test_influxdb_docker_container(host): """Check InfluxDB docker container""" d = host.docker("influxdb.service").inspect() assert d["HostConfig"]["Memory"] == 1073741824 assert d["Config"]["Image"] == "influxdb:latest" assert d["Config"]["Labels"]["maintainer"] == "me@example.com" assert "INFLUXD_REPORTING_DISABLED=true" in d["Config"]["Env"] assert "internal" in d["NetworkSettings"]["Networks"] assert \ "influxdb" in d["NetworkSettings"]["Networks"]["internal"]["Aliases"] def test_backup(host): """Check if the backup runs successfully""" cmd = host.run("/usr/local/bin/backup-influxdb.sh") assert cmd.succeeded def test_backup_cron_job(host): """Check backup cron job""" f = host.file("/var/spool/cron/crontabs/root") assert "/usr/local/bin/backup-influxdb.sh" in f.content_string def test_restore(host): """Check if the restore runs successfully""" cmd = host.run("/usr/local/bin/restore-influxdb.sh") assert cmd.succeeded
28.287879
77
0.664167
245
1,867
4.963265
0.306122
0.046053
0.044408
0.026316
0.134046
0.096217
0.060855
0.060855
0
0
0
0.01437
0.179968
1,867
65
78
28.723077
0.779882
0.136583
0
0.05
0
0
0.277778
0.115581
0
0
0
0
0.575
1
0.2
false
0
0
0
0.2
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
1
0
0
0
0
0
0
0
0
0
1
c368cab3b6e074a25c4387726e3ddcf458b2da2f
384
py
Python
sapextractor/utils/fields_corresp/extract_dd03t.py
aarkue/sap-meta-explorer
613bf657bbaa72a3781a84664e5de7626516532f
[ "Apache-2.0" ]
2
2021-02-10T08:09:35.000Z
2021-05-21T06:25:34.000Z
sapextractor/utils/fields_corresp/extract_dd03t.py
aarkue/sap-meta-explorer
613bf657bbaa72a3781a84664e5de7626516532f
[ "Apache-2.0" ]
null
null
null
sapextractor/utils/fields_corresp/extract_dd03t.py
aarkue/sap-meta-explorer
613bf657bbaa72a3781a84664e5de7626516532f
[ "Apache-2.0" ]
3
2021-11-22T13:27:00.000Z
2022-03-16T22:08:51.000Z
def apply(con, target_language="E"): dict_field_desc = {} try: df = con.prepare_and_execute_query("DD03T", ["DDLANGUAGE", "FIELDNAME", "DDTEXT"], " WHERE DDLANGUAGE = '"+target_language+"'") stream = df.to_dict("records") for el in stream: dict_field_desc[el["FIELDNAME"]] = el["DDTEXT"] except: pass return dict_field_desc
34.909091
135
0.611979
46
384
4.847826
0.630435
0.121076
0.174888
0
0
0
0
0
0
0
0
0.006849
0.239583
384
10
136
38.4
0.756849
0
0
0
0
0
0.195313
0
0
0
0
0
0
1
0.1
false
0.1
0
0
0.2
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c37f533b46624d83873bcd5b9e4314c8ccb4405c
11,734
py
Python
myo/device_listener.py
ehliang/myo-unlock
059e130a90e44df3869dd892e216c020d6d97a7e
[ "MIT" ]
1
2021-06-25T02:27:31.000Z
2021-06-25T02:27:31.000Z
myo/device_listener.py
ehliang/myo-unlock
059e130a90e44df3869dd892e216c020d6d97a7e
[ "MIT" ]
null
null
null
myo/device_listener.py
ehliang/myo-unlock
059e130a90e44df3869dd892e216c020d6d97a7e
[ "MIT" ]
null
null
null
# Copyright (c) 2015 Niklas Rosenstein # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import abc import six import time import threading import warnings from .lowlevel.enums import EventType, Pose, Arm, XDirection from .utils.threading import TimeoutClock from .vector import Vector from .quaternion import Quaternion class DeviceListener(six.with_metaclass(abc.ABCMeta)): """ Interface for listening to data sent from a Myo device. Return False from one of its callback methods to instruct the Hub to stop processing. The *DeviceListener* operates between the high and low level of the myo Python bindings. The ``myo`` object that is passed to callback methods is a :class:`myo.lowlevel.ctyping.Myo` object. """ def on_event(self, kind, event): """ Called before any of the event callbacks. """ def on_event_finished(self, kind, event): """ Called after the respective event callbacks have been invoked. This method is *always* triggered, even if one of the callbacks requested the stop of the Hub. """ def on_pair(self, myo, timestamp): pass def on_unpair(self, myo, timestamp): pass def on_connect(self, myo, timestamp): pass def on_disconnect(self, myo, timestamp): pass def on_pose(self, myo, timestamp, pose): pass def on_orientation_data(self, myo, timestamp, orientation): pass def on_accelerometor_data(self, myo, timestamp, acceleration): pass def on_gyroscope_data(self, myo, timestamp, gyroscope): pass def on_rssi(self, myo, timestamp, rssi): pass def on_emg(self, myo, timestamp, emg): pass def on_unsync(self, myo, timestamp): pass def on_sync(self, myo, timestamp, arm, x_direction): pass def on_unlock(self, myo, timestamp): pass def on_lock(self, myo, timestamp): pass class Feed(DeviceListener): """ This class implements the :class:`DeviceListener` interface to collect all data and make it available to another thread on-demand. .. code-block:: python import myo as libmyo feed = libmyo.device_listener.Feed() hub = libmyo.Hub() hub.run(1000, feed) try: while True: myos = feed.get_connected_devices() if myos: print myos[0], myos[0].orientation time.sleep(0.5) finally: hub.stop(True) hub.shutdown() """ class MyoProxy(object): __slots__ = ('synchronized,_pair_time,_unpair_time,_connect_time,' '_disconnect_time,_myo,_emg,_orientation,_acceleration,' '_gyroscope,_pose,_arm,_xdir,_rssi,_firmware_version').split(',') def __init__(self, low_myo, timestamp, firmware_version): super(Feed.MyoProxy, self).__init__() self.synchronized = threading.Condition() self._pair_time = timestamp self._unpair_time = None self._connect_time = None self._disconnect_time = None self._myo = low_myo self._emg = None self._orientation = Quaternion.identity() self._acceleration = Vector(0, 0, 0) self._gyroscope = Vector(0, 0, 0) self._pose = Pose.rest self._arm = None self._xdir = None self._rssi = None self._firmware_version = firmware_version def __repr__(self): result = '<MyoProxy (' with self.synchronized: if self.connected: result += 'connected) at 0x{0:x}>'.format(self._myo.value) else: result += 'disconnected)>' return result def __assert_connected(self): if not self.connected: raise RuntimeError('Myo was disconnected') @property def connected(self): with self.synchronized: return (self._connect_time is not None and self._disconnect_time is None) @property def paired(self): with self.synchronized: return (self.myo_ is None or self._unpair_time is not None) @property def pair_time(self): return self._pair_time @property def unpair_time(self): with self.synchronized: return self._unpair_time @property def connect_time(self): return self._connect_time @property def disconnect_time(self): with self.synchronized: return self._disconnect_time @property def firmware_version(self): return self._firmware_version @property def orientation(self): with self.synchronized: return self._orientation.copy() @property def acceleration(self): with self.synchronized: return self._acceleration.copy() @property def gyroscope(self): with self.synchronized: return self._gyroscope.copy() @property def pose(self): with self.synchronized: return self._pose @property def arm(self): with self.synchronized: return self._arm @property def x_direction(self): with self.synchronized: return self._xdir @property def rssi(self): with self.synchronized: return self._rssi def set_locking_policy(self, locking_policy): with self.synchronized: self.__assert_connected() self._myo.set_locking_policy(locking_policy) def set_stream_emg(self, emg): with self.synchronized: self.__assert_connected() self._myo.set_stream_emg(emg) def vibrate(self, vibration_type): with self.synchronized: self.__assert_connected() self._myo.vibrate(vibration_type) def request_rssi(self): """ Requests the RSSI of the Myo armband. Until the RSSI is retrieved, :attr:`rssi` returns None. """ with self.synchronized: self.__assert_connected() self._rssi = None self._myo.request_rssi() def __init__(self): super(Feed, self).__init__() self.synchronized = threading.Condition() self._myos = {} def get_devices(self): """ get_devices() -> list of Feed.MyoProxy Returns a list of paired and connected Myo's. """ with self.synchronized: return list(self._myos.values()) def get_connected_devices(self): """ get_connected_devices(self) -> list of Feed.MyoProxy Returns a list of connected Myo's. """ with self.synchronized: return [myo for myo in self._myos.values() if myo.connected] def wait_for_single_device(self, timeout=None, interval=0.5): """ wait_for_single_device(timeout) -> Feed.MyoProxy or None Waits until a Myo is was paired **and** connected with the Hub and returns it. If the *timeout* is exceeded, returns None. This function will not return a Myo that is only paired but not connected. :param timeout: The maximum time to wait for a device. :param interval: The interval at which the function should exit sleeping. We can not sleep endlessly, otherwise the main thread can not be exit, eg. through a KeyboardInterrupt. """ timer = TimeoutClock(timeout) start = time.time() with self.synchronized: # As long as there are no Myo's connected, wait until we # get notified about a change. while not timer.exceeded: # Check if we found a Myo that is connected. for myo in six.itervalues(self._myos): if myo.connected: return myo remaining = timer.remaining if interval is not None and remaining > interval: remaining = interval self.synchronized.wait(remaining) return None # DeviceListener def on_event(self, kind, event): myo = event.myo timestamp = event.timestamp with self.synchronized: if kind == EventType.paired: fmw_version = event.firmware_version self._myos[myo.value] = self.MyoProxy(myo, timestamp, fmw_version) self.synchronized.notify_all() return True elif kind == EventType.unpaired: try: proxy = self._myos.pop(myo.value) except KeyError: message = "Myo 0x{0:x} was not in the known Myo's list" warnings.warn(message.format(myo.value), RuntimeWarning) else: # Remove the reference handle from the Myo proxy. with proxy.synchronized: proxy._unpair_time = timestamp proxy._myo = None finally: self.synchronized.notify_all() return True else: try: proxy = self._myos[myo.value] except KeyError: message = "Myo 0x{0:x} was not in the known Myo's list" warnings.warn(message.format(myo.value), RuntimeWarning) return True with proxy.synchronized: if kind == EventType.connected: proxy._connect_time = timestamp elif kind == EventType.disconnected: proxy._disconnect_time = timestamp elif kind == EventType.emg: proxy._emg = event.emg elif kind == EventType.arm_synced: proxy._arm = event.arm proxy._xdir = event.x_direction elif kind == EventType.rssi: proxy._rssi = event.rssi elif kind == EventType.pose: proxy._pose = event.pose elif kind == EventType.orientation: proxy._orientation = event.orientation proxy._gyroscope = event.gyroscope proxy._acceleration = event.acceleration
32.325069
82
0.587183
1,317
11,734
5.081245
0.22779
0.059773
0.059773
0.050508
0.204573
0.191721
0.106246
0.06306
0.046623
0.031978
0
0.003357
0.339952
11,734
362
83
32.414365
0.860684
0.260695
0
0.349057
0
0
0.03748
0.018861
0
0
0
0
0.023585
1
0.198113
false
0.066038
0.042453
0.014151
0.358491
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c3806b9e128d8474be2a0c8c16ed645a6cd61414
333
py
Python
utilities/poisson.py
lukepinkel/pylmm
b9e896222f077b000f9a752be77cfc9e60b49f19
[ "MIT" ]
null
null
null
utilities/poisson.py
lukepinkel/pylmm
b9e896222f077b000f9a752be77cfc9e60b49f19
[ "MIT" ]
null
null
null
utilities/poisson.py
lukepinkel/pylmm
b9e896222f077b000f9a752be77cfc9e60b49f19
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Aug 12 13:34:49 2020 @author: lukepinkel """ import numpy as np import scipy as sp import scipy.special def poisson_logp(x, mu, logp=True): p = sp.special.xlogy(x, mu) - sp.special.gammaln(x + 1) - mu if logp==False: p = np.exp(p) return p
19.588235
65
0.618619
57
333
3.596491
0.684211
0.107317
0
0
0
0
0
0
0
0
0
0.058366
0.228228
333
17
66
19.588235
0.7393
0.3003
0
0
0
0
0
0
0
0
0
0
0
1
0.125
false
0
0.375
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
5edd1d618589e67fdc13ac60dffe9edc5736896c
2,980
py
Python
scripts/core/soldier.py
whackashoe/entwinement
4acff2147b86e08e267fc50c327917a338c7bf36
[ "Unlicense" ]
1
2020-03-10T10:52:13.000Z
2020-03-10T10:52:13.000Z
scripts/core/soldier.py
whackashoe/entwinement
4acff2147b86e08e267fc50c327917a338c7bf36
[ "Unlicense" ]
null
null
null
scripts/core/soldier.py
whackashoe/entwinement
4acff2147b86e08e267fc50c327917a338c7bf36
[ "Unlicense" ]
null
null
null
d_soldiers = [] class Soldier: def __init__(self, id, name, team): self.id = id self.name = name self.team = team self.x = 0 self.y = 0 self.xVelo = 0 self.yVelo = 0 self.kills = 0 self.deaths = 0 self.alive = 'true' self.driving = 'false' self.gun = 0 self.ammo = 0 self.reloading = 'false' def setPosition(self, x, y, xv, yv): self.x = x self.y = y self.xVelo = xv self.yVelo = yv def setName(self, name): self.name = name def setTeam(self, team): self.team = team def setGun(self, gun): self.gun = gun def setGunInfo(self, gun, ammo, reloading): self.gun = gun self.ammo = ammo self.reloading = reloading def die(self): self.alive = 'false' self.driving = 'false' self.deaths += 1 def respawn(self): self.alive = 'true' def teleport(self, x, y): global com self.x = x self.y = y com += 'f_t s '+str(self.id)+' '+str(self.x)+' '+str(self.y)+';' def applyForce(self, xf, yf): global com com += 'f_af s '+str(self.id)+' '+str(xf)+' '+str(yf)+';' def setVelocity(self, xf, yf): global com self.xVelo = xf self.yVelo = yf com += 'f_v s '+str(self.id)+' '+str(self.xVelo)+' '+str(self.yVelo)+';' def changeTeam(self, team): global com self.team = team com += 's_ct '+str(self.id)+' '+str(self.team)+';' def changeGun(self, gun): global com self.gun = gun com += 's_cg '+str(self.id)+' '+str(self.gun)+';' def changeAttachment(self, type, amount): global com com += 's_ca '+str(self.id)+' '+str(type)+' '+str(amount)+';' def killSoldier(self): global com self.alive = false com += 's_ks '+str(id)+';' def respawnSoldier(self, spawn): global com com += 's_rs '+str(self.id)+' '+str(spawn)+';' def enterVehicle(self, vehicleId): global com com += 's_en '+str(self.id)+' '+str(vehicleId)+';' def exitVehicle(self): global com com += 's_ex '+str(self.id)+';' def addKill(self): global com self.kills += 1 com += 's_ak '+str(self.id)+';' def addDeath(self): global com self.deaths += 1 com += 's_ad '+str(self.id)+';' def dropGun(self): global com com += 's_dg '+str(self.id)+';' def addSoldier(team): global com com += 'a s '+str(team)+';' def getSoldier(n): global d_soldiers return d_soldiers[n] def getSoldierById(id): global d_soldiers for n in xrange(len(d_soldiers)): s = d_soldiers[n] if s.id == id: return s def getSoldiers(): global d_soldiers return d_soldiers def getSoldierCount(): global d_soldiers return len(d_soldiers) def getTeamKills(team): amount = 0 for n in xrange(len(d_soldiers)): s = d_soldiers[n] if s.team == team: amount += s.kills return amount def getTeamDeaths(team): amount = 0 for n in xrange(len(d_soldiers)): s = d_soldiers[n] if s.team == team: amount += s.deaths return amount def getTeamSize(team): amount = 0 for n in xrange(len(d_soldiers)): s = d_soldiers[n] if s.team == team: amount += 1 return amount
18.742138
74
0.617785
473
2,980
3.82241
0.183932
0.06969
0.059735
0.053097
0.254425
0.191925
0.126659
0.126659
0.126659
0.126659
0
0.006375
0.210403
2,980
158
75
18.860759
0.762006
0
0
0.424
0
0
0.042617
0
0
0
0
0
0
1
0.232
false
0
0
0
0.296
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
0
0
0
1
5edf63e904c948abd2995cb1fd09ff2f09a7f87a
572
py
Python
CursoEmVideo/Aula22/ex109/ex109.py
lucashsouza/Desafios-Python
abb5b11ebdfd4c232b4f0427ef41fd96013f2802
[ "MIT" ]
null
null
null
CursoEmVideo/Aula22/ex109/ex109.py
lucashsouza/Desafios-Python
abb5b11ebdfd4c232b4f0427ef41fd96013f2802
[ "MIT" ]
null
null
null
CursoEmVideo/Aula22/ex109/ex109.py
lucashsouza/Desafios-Python
abb5b11ebdfd4c232b4f0427ef41fd96013f2802
[ "MIT" ]
null
null
null
""" Modifique as funções que foram criadas no desafio 107 para que elas aceitem um parametro a mais, informando se o valor retornado por elas vai ser ou não formatado pela função moeda(), desenvolvida no desafio 108. """ from Aula22.ex109 import moeda from Aula22.ex109.titulo import titulo preco = float(input("Preço: R$")) titulo('Informações Calculadas: ') print(f"Metade: {moeda.metade(preco, True)}") print(f"Dobro: {moeda.dobro(preco, True)}") print(f"10% Acréscimo: {moeda.aumentar(preco, 10, True)}") print(f"10% Desconto: {moeda.diminuir(preco, 10, True)}")
28.6
59
0.737762
87
572
4.850575
0.62069
0.056872
0.07109
0.07109
0
0
0
0
0
0
0
0.048193
0.129371
572
19
60
30.105263
0.799197
0.370629
0
0
0
0
0.558405
0.125356
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.5
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
0
0
1
0
1
5eeebe655d0529cd4e57b3684dd0b12853503ba1
442
py
Python
greedy_algorithms/6_maximum_salary/largest_number.py
Desaiakshata/Algorithms-problems
90f4e40ba05e4bdfc783614bb70b9156b05eec0b
[ "MIT" ]
null
null
null
greedy_algorithms/6_maximum_salary/largest_number.py
Desaiakshata/Algorithms-problems
90f4e40ba05e4bdfc783614bb70b9156b05eec0b
[ "MIT" ]
null
null
null
greedy_algorithms/6_maximum_salary/largest_number.py
Desaiakshata/Algorithms-problems
90f4e40ba05e4bdfc783614bb70b9156b05eec0b
[ "MIT" ]
null
null
null
#Uses python3 import sys def largest_number(a): #write your code here res = "" while len(a)!=0: maxa = a[0] for x in a: if int(str(x)+str(maxa))>int(str(maxa)+str(x)): maxa = x res += str(maxa) a.remove(str(maxa)) return res if __name__ == '__main__': #input = sys.stdin.read() data = input().split(' ') a = data[1:] print(largest_number(a))
19.217391
59
0.506787
63
442
3.396825
0.539683
0.130841
0.130841
0
0
0
0
0
0
0
0
0.013605
0.334842
442
22
60
20.090909
0.714286
0.126697
0
0
0
0
0.023499
0
0
0
0
0.045455
0
1
0.066667
false
0
0.066667
0
0.2
0.066667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
5ef260b5bf84eb695b2bd8138b23ebab7ec1405b
4,779
py
Python
cno/chrutils.py
CherokeeLanguage/cherokee-audio-data
a10b7b38c0c1b56338561c917cef18a078ca573c
[ "CC0-1.0", "MIT" ]
2
2021-09-15T19:41:01.000Z
2022-01-12T17:57:08.000Z
cno/chrutils.py
CherokeeLanguage/cherokee-audio-data
a10b7b38c0c1b56338561c917cef18a078ca573c
[ "CC0-1.0", "MIT" ]
1
2021-10-08T18:06:29.000Z
2021-10-08T18:48:44.000Z
cno/chrutils.py
CherokeeLanguage/cherokee-audio-data
a10b7b38c0c1b56338561c917cef18a078ca573c
[ "CC0-1.0", "MIT" ]
null
null
null
#!/usr/bin/env python3 def test(): cedTest = ["U²sgal²sdi ạ²dv¹ne²³li⁴sgi.", "Ụ²wo²³dị³ge⁴ɂi gi²hli a¹ke²³he³²ga na ạ²chu⁴ja.", "Ạ²ni²³tạɂ³li ạ²ni²sgạ²ya a¹ni²no²hạ²li²³do³²he, ạ²hwi du¹ni²hyọ²he.", "Sa¹gwu⁴hno ạ²sgạ²ya gạ²lo¹gwe³ ga²ne²he sọ³ɂị³hnv³ hla².", "Na³hnv³ gạ²lo¹gwe³ ga²ne⁴hi u²dlv²³kwsạ²ti ge¹se³, ạ²le go²hu⁴sdi yu²³dv³²ne⁴la a¹dlv²³kwsge³.", "A¹na³ɂi²sv⁴hnv go²hu⁴sdi wu²³ni³go²he do²jụ²wạ³ɂị²hlv,", "na³hnv³ gạ²lo¹gwe³ ga²ne⁴hi kị²lạ²gwu ị²yv⁴da wị²du²³sdạ³yo²hle³ o²³sdạ²gwu nu²³ksẹ²stạ²nv⁴na ị²yu³sdi da¹sdạ²yo²hị²hv⁴.", "U²do²hị²yu⁴hnv³ wu²³yo³hle³ ạ²le u¹ni²go²he³ gạ²nv³gv⁴.", "Na³hnv³ gạ²lo¹gwe³ nị²ga²³ne³hv⁴na \"ạ²hwi e¹ni²yo³ɂa!\" u¹dv²hne.", "\"Ji²yo³ɂe³²ga\" u¹dv²hne na³ gạ²lo¹gwe³ ga²ne⁴hi, a¹dlv²³kwsgv³.", "U¹na³ne²lu²³gi³²se do²jụ²wạ³ɂị²hlv³ di³dla, nạ²ɂv²³hnị³ge⁴hnv wu²³ni³luh²ja u¹ni²go²he³ so²³gwị³li gạɂ³nv⁴.", "\"So²³gwị³lị³le³² i¹nạ²da²hị³si\" u¹dv²hne³ na³ u²yo²hlv⁴.", "\"Hạ²da²hị³se³²ga³\" a¹go¹se²³le³."] for a in cedTest: print("_______________"); print(); print(a); print(ced2mco(a)); asciiCedText = ["ga.2da.2de3ga", "ha.2da.2du1ga", "u2da.2di23nv32di", "u1da.2di23nv32sv23?i", "a1da.2de3go3?i"] for a in asciiCedText: print("_______________"); print(); print(a); print(ascii_ced2mco(a)); return # Converts MCO annotation into pseudo English phonetics for use by the aeneas alignment package # lines prefixed with '#' are returned with the '#' removed, but otherwise unchanged. def mco2espeak(text: str): import unicodedata as ud import re if (len(text.strip()) == 0): return "" # Handle specially flagged text if (text[0].strip() == "#"): if text[1] != "!": return text.strip()[1:] else: text = text[2:] newText = ud.normalize('NFD', text.strip()).lower() if (newText[0] == ""): newText = newText[1:] # remove all tone indicators newText = re.sub("[\u030C\u0302\u0300\u0301\u030b]", "", newText) newText = "[[" + newText.strip() + "]]" newText = newText.replace(" ", "]] [[") newText = newText.replace("'", "]]'[[") newText = newText.replace(".]]", "]].") newText = newText.replace(",]]", "]],") newText = newText.replace("!]]", "]]!") newText = newText.replace("?]]", "]]?") newText = newText.replace(":]]", "]]:") newText = newText.replace(";]]", "]];") newText = newText.replace("\"]]", "]]\"") newText = newText.replace("']]", "]]'") newText = newText.replace(" ]]", "]] ") newText = newText.replace("[[ ", " [[") newText = re.sub("(?i)([aeiouv]):", "\\1", newText) # convert all vowels into approximate espeak x-sampa escaped forms newText = newText.replace("A", "0") newText = newText.replace("a", "0") newText = newText.replace("v", "V") newText = newText.replace("tl", "tl#") newText = newText.replace("hl", "l#") newText = newText.replace("J", "dZ") newText = newText.replace("j", "dZ") newText = newText.replace("Y", "j") newText = newText.replace("y", "j") newText = newText.replace("Ch", "tS") newText = newText.replace("ch", "tS") newText = newText.replace("ɂ", "?") return newText def ced2mco(text: str): import unicodedata as ud import re tones2mco = [("²³", "\u030C"), ("³²", "\u0302"), ("¹", "\u0300"), ("²", ""), ("³", "\u0301"), ("⁴", "\u030b")] text = ud.normalize('NFD', text) text = re.sub("(?i)([aeiouv])([^¹²³⁴\u0323]+)", "\\1\u0323\\2", text) text = re.sub("(?i)([aeiouv])([¹²³⁴]+)$", "\\1\u0323\\2", text) text = re.sub("(?i)([aeiouv])([¹²³⁴]+)([^¹²³⁴a-zɂ])", "\\1\u0323\\2\\3", text) text = re.sub("(?i)([^aeiouv\u0323¹²³⁴]+)([¹²³⁴]+)", "\\2\\1", text) text = re.sub("(?i)([aeiouv])([¹²³⁴]+)", "\\1\\2:", text) text = text.replace("\u0323", "") text = re.sub("(?i)([aeiouv])²$", "\\1\u0304", text) text = re.sub("(?i)([aeiouv])²([^a-zɂ¹²³⁴:])", "\\1\u0304\\2", text) for ced2mcotone in tones2mco: text = text.replace(ced2mcotone[0], ced2mcotone[1]) # return ud.normalize('NFC', text) def ascii_ced2mco(text: str): import unicodedata as ud text = ud.normalize('NFD', text) return ced2mco(ascii_ced2ced(text)) def ascii_ced2ced(text: str): import unicodedata as ud text = ud.normalize('NFD', text) text = text.replace(".", "\u0323") text = text.replace("1", "¹") text = text.replace("2", "²") text = text.replace("3", "³") text = text.replace("4", "⁴") text = text.replace("?", "ɂ") return text if __name__ == "__main__": test()
38.232
138
0.586943
510
4,779
5.417647
0.347059
0.136808
0.18241
0.121607
0.345277
0.330076
0.285197
0.271444
0.152371
0.152371
0
0.111052
0.214271
4,779
124
139
38.540323
0.624767
0.06675
0
0.154639
0
0
0.310043
0.051898
0
0
0
0
0
1
0.051546
false
0
0.061856
0
0.185567
0.082474
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
0
0
0
1
5ef2f309d751c48873dcfc34c92ab93f2ef03256
1,793
py
Python
app/db_con.py
bmugenya/Zup
1677c1e4e263409f9f5fcaac7411dd403e32650e
[ "MIT" ]
null
null
null
app/db_con.py
bmugenya/Zup
1677c1e4e263409f9f5fcaac7411dd403e32650e
[ "MIT" ]
1
2020-03-06T17:32:15.000Z
2020-03-06T17:32:15.000Z
app/db_con.py
bmugenya/Zup
1677c1e4e263409f9f5fcaac7411dd403e32650e
[ "MIT" ]
null
null
null
import psycopg2 url = "dbname='da43n1slakcjkc' user='msqgxzgmcskvst' host='ec2-54-80-184-43.compute-1.amazonaws.com' port=5432 password='9281f925b1e2298e8d62812d9d4e430c1054db62e918c282d7039fa85b1759fa'" class database_setup(object): def __init__(self): self.conn = psycopg2.connect(url) self.cursor = self.conn.cursor() def destroy_tables(self): self.cursor.execute("""DROP TABLE IF EXISTS user CASCADE;""") self.conn.commit() def create_tables(self): self.cursor.execute("""CREATE TABLE IF NOT EXISTS Users ( user_id SERIAL NOT NULL, fname VARCHAR(25) NOT NULL, lname VARCHAR(25) NOT NULL, post_date DATE NOT NULL DEFAULT CURRENT_DATE, email VARCHAR(50) UNIQUE NOT NULL, password VARCHAR(256) NOT NULL, photo VARCHAR(255) NOT NULL, PRIMARY KEY (email) );""") self.cursor.execute("""CREATE TABLE IF NOT EXISTS Report ( report_id SERIAL NOT NULL, num_tweet INT NOT NULL, tweet VARCHAR(255) NOT NULL, plot_bar VARCHAR(255) NOT NULL, plot_pie VARCHAR(255) NOT NULL, post_date DATE NOT NULL DEFAULT CURRENT_DATE, email VARCHAR(50) REFERENCES Users(email) NOT NULL, PRIMARY KEY (report_id) );""") self.cursor.execute("""CREATE TABLE IF NOT EXISTS Config ( config_id SERIAL NOT NULL, consumerKey TEXT NOT NULL, consumerSecret TEXT NOT NULL, accessToken TEXT NOT NULL, accessSecret TEXT NOT NULL, email VARCHAR(50) REFERENCES Users(email) NOT NULL, PRIMARY KEY (config_id) );""") self.conn.commit()
34.480769
187
0.605131
210
1,793
5.07619
0.361905
0.131332
0.06379
0.06379
0.375235
0.301126
0.301126
0.301126
0.19137
0.19137
0
0.072581
0.308422
1,793
51
188
35.156863
0.787097
0
0
0.225
0
0.025
0.760178
0.092582
0
0
0
0
0
1
0.075
false
0.05
0.025
0
0.125
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
0
0
0
0
0
0
1
6f011e9d1e6d5fe45f9c159871d9be7ae9ea35b9
1,111
py
Python
snakes/help_info.py
japinol7/snakes
bb501736027897bacab498ad7bbbe622cf4b9755
[ "MIT" ]
12
2019-04-15T07:20:31.000Z
2019-05-18T22:03:35.000Z
snakes/help_info.py
japinol7/snakes
bb501736027897bacab498ad7bbbe622cf4b9755
[ "MIT" ]
null
null
null
snakes/help_info.py
japinol7/snakes
bb501736027897bacab498ad7bbbe622cf4b9755
[ "MIT" ]
null
null
null
"""Module help_info.""" __author__ = 'Joan A. Pinol (japinol)' class HelpInfo: """Manages information used for help purposes.""" def print_help_keys(self): print(' F1: \t show a help screen while playing the game' ' t: \t stats on/off\n' ' L_Ctrl + R_Alt + g: grid\n' ' p: \t pause\n' ' ESC: exit game\n' ' ^m: \t pause/resume music\n' ' ^s: \t sound effects on/off\n' ' Alt + Enter: change full screen / normal screen mode\n' ' ^h: \t shows this help\n' ' \t left, a: move snake to the left\n' ' \t right, d: move snake to the right\n' ' \t up, w: move snake up\n' ' \t down, s: move snake down\n' ' \t u 4: fire a light shot\n' ' \t i 5: fire a medium shot\n' ' \t j 1: fire a strong shot\n' ' \t k 2: fire a heavy shot\n' )
41.148148
73
0.417642
145
1,111
3.137931
0.537931
0.035165
0.03956
0.061538
0
0
0
0
0
0
0
0.008547
0.473447
1,111
26
74
42.730769
0.769231
0.054905
0
0
0
0
0.627838
0
0
0
0
0
0
1
0.047619
false
0
0
0
0.095238
0.095238
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
6f03742065f7d2c3fc2369fb406d4426cdddbeab
459
py
Python
Exercicios em Python/ex080.py
Raphael-Azevedo/Exercicios_Python
dece138f38edd02b0731aed78e44acccb021b3cb
[ "MIT" ]
null
null
null
Exercicios em Python/ex080.py
Raphael-Azevedo/Exercicios_Python
dece138f38edd02b0731aed78e44acccb021b3cb
[ "MIT" ]
null
null
null
Exercicios em Python/ex080.py
Raphael-Azevedo/Exercicios_Python
dece138f38edd02b0731aed78e44acccb021b3cb
[ "MIT" ]
null
null
null
n = [] i = 0 for c in range(0, 5): n1 = int(input('Digite um valor: ')) if c == 0 or n1 > n[-1]: n.append(n1) print(f'Adicionado na posição {c} da lista...') else: pos = 0 while pos < len(n): if n1 <= n[pos]: n.insert(pos, n1) print(f'Adicionado na posição {pos} da lista...') break pos += 1 print(f'Os valores digitados em ordem foram {n}')
25.5
65
0.461874
68
459
3.117647
0.544118
0.084906
0.075472
0.169811
0.254717
0.254717
0
0
0
0
0
0.043011
0.392157
459
17
66
27
0.716846
0
0
0
0
0
0.287582
0
0
0
0
0
0
1
0
false
0
0
0
0
0.1875
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
0
0
0
1
6f073d830bc26d55a9b16a99438ab898d40254be
3,418
py
Python
mcpyrate/markers.py
Technologicat/mcpyrate
8182a8d246554b152e281d0f6c912e35ea58c316
[ "MIT" ]
34
2020-10-13T19:22:36.000Z
2022-01-28T00:53:55.000Z
mcpyrate/markers.py
Technologicat/mcpyrate
8182a8d246554b152e281d0f6c912e35ea58c316
[ "MIT" ]
32
2020-10-16T16:29:54.000Z
2022-01-27T15:45:51.000Z
mcpyrate/markers.py
Technologicat/mcpyrate
8182a8d246554b152e281d0f6c912e35ea58c316
[ "MIT" ]
2
2020-10-17T19:07:26.000Z
2021-02-20T01:43:50.000Z
# -*- coding: utf-8; -*- """AST markers for internal communication. *Internal* here means they are to be never passed to Python's `compile`; macros may use them to work together. """ __all__ = ["ASTMarker", "get_markers", "delete_markers", "check_no_markers_remaining"] import ast from . import core, utils, walkers class ASTMarker(ast.AST): """Base class for AST markers. Markers are AST-node-like objects meant for communication between co-operating, related macros. They are also used by the macro expander to talk with itself during expansion. We inherit from `ast.AST`, so that during macro expansion, a marker behaves like a single AST node. It is a postcondition of a completed macro expansion that no markers remain in the AST. To help fail-fast, if you define your own marker types, use `get_markers` to check (at an appropriate point) that the expanded AST has no instances of your own markers remaining. (You'll want a base class for your own markers.) A typical usage example is in the quasiquote system, where the unquote operators (some of which expand to markers) may only appear inside a quoted section. So just before the quote operator exits, it checks that all quasiquote markers within that section have been compiled away. """ # TODO: Silly default `None`, because `copy` and `deepcopy` call `__init__` without arguments, # TODO: though the docs say they behave like `pickle` (and wouldn't thus need to call __init__ at all!). def __init__(self, body=None): """body: the actual AST that is annotated by this marker""" self.body = body self._fields = ["body"] # support ast.iter_fields def get_markers(tree, cls=ASTMarker): """Return a `list` of any `cls` instances found in `tree`. For output validation.""" class ASTMarkerCollector(walkers.ASTVisitor): def examine(self, tree): if isinstance(tree, cls): self.collect(tree) self.generic_visit(tree) w = ASTMarkerCollector() w.visit(tree) return w.collected def delete_markers(tree, cls=ASTMarker): """Delete any `cls` ASTMarker instances found in `tree`. The deletion takes place by replacing each marker node with the actual AST node stored in its `body` attribute. """ class ASTMarkerDeleter(walkers.ASTTransformer): def transform(self, tree): if isinstance(tree, cls): return self.visit(tree.body) return self.generic_visit(tree) return ASTMarkerDeleter().visit(tree) def check_no_markers_remaining(tree, *, filename, cls=None): """Check that `tree` has no AST markers remaining. If a class `cls` is provided, only check for markers that `isinstance(cls)`. If there are any, raise `MacroExpansionError`. No return value. `filename` is the full path to the `.py` file, for error reporting. Convenience function. """ cls = cls or ASTMarker remaining_markers = get_markers(tree, cls) if remaining_markers: codes = [utils.format_context(node, n=5) for node in remaining_markers] locations = [utils.format_location(filename, node, code) for node, code in zip(remaining_markers, codes)] report = "\n\n".join(locations) raise core.MacroExpansionError(f"{filename}: AST markers remaining after expansion:\n{report}")
37.977778
113
0.693681
475
3,418
4.911579
0.429474
0.034291
0.018003
0.019717
0.023146
0.023146
0
0
0
0
0
0.00075
0.219427
3,418
89
114
38.404494
0.873688
0.550614
0
0.064516
0
0
0.091298
0.018545
0
0
0
0.011236
0
1
0.193548
false
0
0.064516
0
0.483871
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
6f0bb8acf71ebb128d83c12c5909aa37ad5afe8a
940
py
Python
sizer.py
riffcc/librarian
f3cf8f4cc9f9a717e5f807a1d8558eb8c4e4d528
[ "MIT" ]
null
null
null
sizer.py
riffcc/librarian
f3cf8f4cc9f9a717e5f807a1d8558eb8c4e4d528
[ "MIT" ]
null
null
null
sizer.py
riffcc/librarian
f3cf8f4cc9f9a717e5f807a1d8558eb8c4e4d528
[ "MIT" ]
null
null
null
#!/usr/bin/python3 # Fetch torrent sizes # TODO: Report number of files before we go etc import os from torrentool.api import Torrent from fnmatch import fnmatch root = '/opt/radio/collections' pattern = "*.torrent" alltorrentsize = 0 print("Thanks for using The Librarian.") for path, subdirs, files in os.walk(root): for name in files: if fnmatch(name, pattern): torrentstats = Torrent.from_file(os.path.join(path, name)) alltorrentsize += torrentstats.total_size print('Torrent size ' + str(torrentstats.total_size) + ' for a total so far of ' + str(alltorrentsize)) print('DEBUG' + os.path.join(path, name)) # Reading filesize my_torrent = Torrent.from_file('/opt/radio/collections/arienscompanymanuals/archive.org/download/collection_01_ariens_manuals/collection_01_ariens_manuals_archive.torrent') size = my_torrent.total_size # Total files size in bytes. print(size)
34.814815
172
0.726596
127
940
5.267717
0.488189
0.049327
0.056801
0.041854
0.053812
0
0
0
0
0
0
0.007702
0.171277
940
27
173
34.814815
0.851091
0.135106
0
0
0
0
0.297899
0.197775
0
0
0
0.037037
0
1
0
false
0
0.176471
0
0.176471
0.235294
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
6f1051aadde1f5582ce2b30a763b8cd2ec505a2e
1,373
py
Python
tests/test_renderer.py
0xflotus/maildown
fa17ce6a29458da549a145741db8e5092def2176
[ "MIT" ]
626
2019-05-08T22:34:45.000Z
2022-03-31T07:29:35.000Z
tests/test_renderer.py
pythonthings/maildown
4e0caf297bdf264ab5ead537eb45d20f187971a1
[ "MIT" ]
12
2019-04-30T20:47:17.000Z
2019-06-27T11:19:46.000Z
tests/test_renderer.py
pythonthings/maildown
4e0caf297bdf264ab5ead537eb45d20f187971a1
[ "MIT" ]
36
2019-05-08T23:50:41.000Z
2021-07-30T17:46:24.000Z
import mock from maildown import renderer import mistune import pygments from pygments import lexers from pygments.formatters import html import premailer import jinja2 def test_highlight_renderer(monkeypatch): monkeypatch.setattr(mistune, "escape", mock.MagicMock()) monkeypatch.setattr(lexers, "get_lexer_by_name", mock.MagicMock()) monkeypatch.setattr(html, "HtmlFormatter", mock.MagicMock()) monkeypatch.setattr(pygments, "highlight", mock.MagicMock()) lexers.get_lexer_by_name.return_value = True html.HtmlFormatter.return_value = {} r = renderer.HighlightRenderer() r.block_code("code") mistune.escape.assert_called_with("code") r.block_code("code", "python") lexers.get_lexer_by_name.assert_called_with("python", stripall=True) pygments.highlight.assert_called_with("code", True, {}) def test_generate_content(monkeypatch): monkeypatch.setattr(mistune, "Markdown", mock.MagicMock()) monkeypatch.setattr(premailer, "transform", mock.MagicMock()) monkeypatch.setattr(renderer, "HighlightRenderer", mock.MagicMock()) monkeypatch.setattr(jinja2, "Template", mock.MagicMock()) renderer.HighlightRenderer.return_value = 1 premailer.transform.return_value = "" jinja2.Template.render.return_value = "" renderer.generate_content("") mistune.Markdown.assert_called_with(renderer=1)
33.487805
72
0.758194
156
1,373
6.487179
0.275641
0.142292
0.142292
0.183794
0.059289
0
0
0
0
0
0
0.004163
0.125273
1,373
40
73
34.325
0.838468
0
0
0
0
0
0.083758
0
0
0
0
0
0.129032
1
0.064516
false
0
0.258065
0
0.322581
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
0
0
0
1
6f1b8a527ec012630d1bead41b940dac1320a132
4,617
py
Python
source1/bsp/entities/portal2_entity_handlers.py
tltneon/SourceIO
418224918c2b062a4c78a41d4d65329ba2decb22
[ "MIT" ]
199
2019-04-02T02:30:58.000Z
2022-03-30T21:29:49.000Z
source1/bsp/entities/portal2_entity_handlers.py
syborg64/SourceIO
e4ba86d801f518e192260af08ef533759c2e1cc3
[ "MIT" ]
113
2019-03-03T19:36:25.000Z
2022-03-31T19:44:05.000Z
source1/bsp/entities/portal2_entity_handlers.py
syborg64/SourceIO
e4ba86d801f518e192260af08ef533759c2e1cc3
[ "MIT" ]
38
2019-05-15T16:49:30.000Z
2022-03-22T03:40:43.000Z
import math from mathutils import Euler import bpy from .portal2_entity_classes import * from .portal_entity_handlers import PortalEntityHandler local_entity_lookup_table = PortalEntityHandler.entity_lookup_table.copy() local_entity_lookup_table.update(entity_class_handle) class Portal2EntityHandler(PortalEntityHandler): entity_lookup_table = local_entity_lookup_table pointlight_power_multiplier = 1000 def handle_prop_weighted_cube(self, entity: prop_weighted_cube, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_weighted_cube', obj, 'props') def handle_prop_testchamber_door(self, entity: prop_testchamber_door, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_testchamber_door', obj, 'props') def handle_prop_floor_button(self, entity: prop_floor_button, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_floor_button', obj, 'props') def handle_prop_floor_ball_button(self, entity: prop_floor_ball_button, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_floor_ball_button', obj, 'props') def handle_prop_floor_cube_button(self, entity: prop_floor_cube_button, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_floor_cube_button', obj, 'props') def handle_prop_under_floor_button(self, entity: prop_under_floor_button, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_under_floor_button', obj, 'props') def handle_prop_tractor_beam(self, entity: prop_tractor_beam, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_tractor_beam', obj, 'props') def handle_logic_playmovie(self, entity: logic_playmovie, entity_raw: dict): obj = bpy.data.objects.new(self._get_entity_name(entity), None) self._set_location(obj, entity.origin) self._set_icon_if_present(obj, entity) self._set_entity_data(obj, {'entity': entity_raw}) self._put_into_collection('logic_playmovie', obj, 'logic') def handle_trigger_paint_cleanser(self, entity: trigger_paint_cleanser, entity_raw: dict): if 'model' not in entity_raw: return model_id = int(entity_raw.get('model')[1:]) mesh_object = self._load_brush_model(model_id, self._get_entity_name(entity)) self._set_location_and_scale(mesh_object, parse_float_vector(entity_raw.get('origin', '0 0 0'))) self._set_rotation(mesh_object, parse_float_vector(entity_raw.get('angles', '0 0 0'))) self._set_entity_data(mesh_object, {'entity': entity_raw}) self._put_into_collection('trigger_paint_cleanser', mesh_object, 'triggers') def handle_trigger_catapult(self, entity: trigger_catapult, entity_raw: dict): if 'model' not in entity_raw: return model_id = int(entity_raw.get('model')[1:]) mesh_object = self._load_brush_model(model_id, self._get_entity_name(entity)) self._set_location_and_scale(mesh_object, parse_float_vector(entity_raw.get('origin', '0 0 0'))) self._set_rotation(mesh_object, parse_float_vector(entity_raw.get('angles', '0 0 0'))) self._set_entity_data(mesh_object, {'entity': entity_raw}) self._put_into_collection('trigger_catapult', mesh_object, 'triggers') def handle_npc_wheatley_boss(self, entity: npc_wheatley_boss, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('npc_wheatley_boss', obj, 'npc') def handle_prop_exploding_futbol(self, entity: prop_exploding_futbol, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_exploding_futbol', obj, 'props') def handle_prop_exploding_futbol_socket(self, entity: prop_exploding_futbol_socket, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_exploding_futbol', obj, 'props') def handle_prop_exploding_futbol_spawnert(self, entity: prop_exploding_futbol_spawner, entity_raw: dict): obj = self._handle_entity_with_model(entity, entity_raw) self._put_into_collection('prop_exploding_futbol_spawner', obj, 'props')
53.068966
109
0.753736
637
4,617
4.971743
0.142857
0.102305
0.057468
0.083991
0.695295
0.598042
0.581307
0.539627
0.539627
0.539627
0
0.005101
0.150747
4,617
86
110
53.686047
0.802601
0
0
0.402985
0
0
0.09465
0.039203
0
0
0
0
0
1
0.208955
false
0
0.074627
0
0.358209
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
0
0
0
1
6f24c0d9627e8e593e0f3f03a5c6df58f6f65c2e
2,922
py
Python
lib/vapi_cli/users.py
nogayama/vision-tools
f3041b519f30037d5b6390bce36a7f5efd3ed6ae
[ "Apache-2.0" ]
15
2020-03-22T18:25:27.000Z
2021-12-03T05:49:32.000Z
lib/vapi_cli/users.py
nogayama/vision-tools
f3041b519f30037d5b6390bce36a7f5efd3ed6ae
[ "Apache-2.0" ]
8
2020-04-04T18:11:56.000Z
2021-07-27T18:06:47.000Z
lib/vapi_cli/users.py
nogayama/vision-tools
f3041b519f30037d5b6390bce36a7f5efd3ed6ae
[ "Apache-2.0" ]
19
2020-03-20T23:36:32.000Z
2022-01-10T20:38:48.000Z
#!/usr/bin/env python3 # IBM_PROLOG_BEGIN_TAG # # Copyright 2019,2020 IBM International Business Machines Corp. # # 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. # # IBM_PROLOG_END_TAG import logging as logger import sys import vapi import vapi_cli.cli_utils as cli_utils from vapi_cli.cli_utils import reportSuccess, reportApiError, translate_flags # All of Vision Tools requires python 3.6 due to format string # Make the check in a common location if sys.hexversion < 0x03060000: sys.exit("Python 3.6 or newer is required to run this program.") token_usage = """ Usage: users token --user=<user-name> --password=<password> Where: --user Required parameter containing the user login name --password Required parameter containing the user's password Gets an authentication token for the given user""" server = None # --- Token Operation ---------------------------------------------- def token(params): """ Handles getting an authentication token for a specific user""" user = params.get("--user", None) pw = params.get("--password", None) rsp = server.users.get_token(user, pw) if rsp is None or rsp.get("result", "fail") == "fail": reportApiError(server, f"Failed to get token for user '{user}'") else: reportSuccess(server, rsp["token"]) cmd_usage = f""" Usage: users {cli_utils.common_cmd_flags} <operation> [<args>...] Where: {cli_utils.common_cmd_flag_descriptions} <operation> is required and must be one of: token -- gets an authentication token for the given user Use 'users <operation> --help' for more information on a specific command.""" usage_stmt = { "usage": cmd_usage, "token": token_usage } operation_map = { "token": token } def main(params, cmd_flags=None): global server args = cli_utils.get_valid_input(usage_stmt, operation_map, argv=params, cmd_flags=cmd_flags) if args is not None: # When requesting a token, we need to ignore any existing token info if args.cmd_params["<operation>"] == "token": cli_utils.token = "" try: server = vapi.connect_to_server(cli_utils.host_name, cli_utils.token) except Exception as e: print("Error: Failed to setup server.", file=sys.stderr) logger.debug(e) return 1 args.operation(args.op_params) if __name__ == "__main__": main(None)
29.816327
97
0.687543
411
2,922
4.766423
0.425791
0.036753
0.032159
0.036753
0.075549
0.040837
0.040837
0.040837
0
0
0
0.011583
0.202259
2,922
97
98
30.123711
0.828829
0.326489
0
0.038462
0
0
0.382156
0.0459
0
0
0.005157
0
0
1
0.038462
false
0.057692
0.096154
0
0.153846
0.019231
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
0
0
1
6f2fda5d1a7f7912eef13fc0ff8b8f413ac5c9a7
1,373
py
Python
corehq/form_processor/migrations/0049_case_attachment_props.py
kkrampa/commcare-hq
d64d7cad98b240325ad669ccc7effb07721b4d44
[ "BSD-3-Clause" ]
1
2020-05-05T13:10:01.000Z
2020-05-05T13:10:01.000Z
corehq/form_processor/migrations/0049_case_attachment_props.py
kkrampa/commcare-hq
d64d7cad98b240325ad669ccc7effb07721b4d44
[ "BSD-3-Clause" ]
1
2019-12-09T14:00:14.000Z
2019-12-09T14:00:14.000Z
corehq/form_processor/migrations/0049_case_attachment_props.py
MaciejChoromanski/commcare-hq
fd7f65362d56d73b75a2c20d2afeabbc70876867
[ "BSD-3-Clause" ]
5
2015-11-30T13:12:45.000Z
2019-07-01T19:27:07.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django.db import models, migrations import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ('form_processor', '0048_attachment_content_length_blob_id'), ] operations = [ migrations.AddField( model_name='xformattachmentsql', name='properties', field=jsonfield.fields.JSONField(default=dict), preserve_default=True, ), migrations.AddField( model_name='caseattachmentsql', name='attachment_from', field=models.TextField(null=True), preserve_default=True, ), migrations.AddField( model_name='caseattachmentsql', name='properties', field=jsonfield.fields.JSONField(default=dict), preserve_default=True, ), migrations.AddField( model_name='caseattachmentsql', name='attachment_src', field=models.TextField(null=True), preserve_default=True, ), migrations.AddField( model_name='caseattachmentsql', name='identifier', field=models.CharField(default='', max_length=255), preserve_default=False, ), ]
29.212766
69
0.600874
117
1,373
6.803419
0.393162
0.113065
0.144472
0.169598
0.562814
0.562814
0.562814
0.562814
0.562814
0.562814
0
0.008325
0.300073
1,373
46
70
29.847826
0.819979
0.015295
0
0.6
0
0
0.145926
0.028148
0
0
0
0
0
1
0
false
0
0.1
0
0.175
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
0
0
0
1
6f459b6385eeaec430778e2b8c2a198dc774b06f
1,280
py
Python
tests/ws/TestWebsocketRegisterAgent.py
sinri/nehushtan
6fda496e16a8d443a86c617173d35f31c392beb6
[ "MIT" ]
null
null
null
tests/ws/TestWebsocketRegisterAgent.py
sinri/nehushtan
6fda496e16a8d443a86c617173d35f31c392beb6
[ "MIT" ]
1
2020-11-20T03:10:23.000Z
2020-11-20T09:30:34.000Z
tests/ws/TestWebsocketRegisterAgent.py
sinri/nehushtan
6fda496e16a8d443a86c617173d35f31c392beb6
[ "MIT" ]
1
2021-10-13T10:16:58.000Z
2021-10-13T10:16:58.000Z
import uuid from typing import Dict, List from nehushtan.ws.NehushtanWebsocketConnectionEntity import NehushtanWebsocketConnectionEntity class TestWebsocketRegisterAgent: def __init__(self): self.__map: Dict[str, NehushtanWebsocketConnectionEntity] = {} self.agent_identity = str(uuid.uuid4()) def register(self, websocket): entity = NehushtanWebsocketConnectionEntity(websocket) self.__map[entity.get_key()] = entity print(f"TestWebsocketRegisterAgent[{self.agent_identity}] registered [{entity.get_key()}]") return entity def unregister(self, key: str): if self.__map.get(key): del self.__map[key] print(f"TestWebsocketRegisterAgent[{self.agent_identity}] unregistered [{key}]") def read(self, key: str): print(f"TestWebsocketRegisterAgent[{self.agent_identity}] reading [{key}]") return self.__map.get(key) def list_for_server(self, local_key: str) -> List[NehushtanWebsocketConnectionEntity]: print(f"TestWebsocketRegisterAgent[{self.agent_identity}] listing for [{local_key}]") enities = [] for k, v in self.__map.items(): if v.get_local_key() == local_key: enities.append(v) return enities
36.571429
99
0.682813
134
1,280
6.298507
0.328358
0.049763
0.100711
0.170616
0.232227
0.232227
0
0
0
0
0
0.000986
0.207813
1,280
34
100
37.647059
0.831361
0
0
0
0
0
0.227344
0.153125
0
0
0
0
0
1
0.192308
false
0
0.115385
0
0.461538
0.153846
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
0
0
0
1
6f54793f102a2f9346990845e8357d9f1db537d3
4,330
py
Python
ck_airport.py
58565856/checkinpanel
58f2292d9c4d65f15ffd6bc4fa4b9f23214d3d72
[ "MIT" ]
3
2022-02-08T16:11:43.000Z
2022-03-23T16:18:59.000Z
ck_airport.py
58565856/checkinpanel
58f2292d9c4d65f15ffd6bc4fa4b9f23214d3d72
[ "MIT" ]
null
null
null
ck_airport.py
58565856/checkinpanel
58f2292d9c4d65f15ffd6bc4fa4b9f23214d3d72
[ "MIT" ]
2
2022-02-01T05:35:56.000Z
2022-02-10T01:37:38.000Z
# -*- coding: utf-8 -*- """ :author @Icrons cron: 20 10 * * * new Env('机场签到'); """ import json import re import traceback import requests import urllib3 from notify_mtr import send from utils import get_data urllib3.disable_warnings() class SspanelQd(object): def __init__(self, check_items): self.check_items = check_items @staticmethod def checkin(url, email, password): url = url.rstrip("/") email = email.split("@") if len(email) > 1: email = email[0] + "%40" + email[1] else: email = email[0] session = requests.session() """ 以下 except 都是用来捕获当 requests 请求出现异常时, 通过捕获然后等待网络情况的变化,以此来保护程序的不间断运行 """ try: session.get(url, verify=False) except requests.exceptions.ConnectionError: msg = url + "\n" + "网络不通" return msg except requests.exceptions.ChunkedEncodingError: msg = url + "\n" + "分块编码错误" return msg except Exception: msg = url + "\n" + "未知错误,请查看日志" print(f"未知错误,错误信息:\n{traceback.format_exc()}") return msg login_url = url + "/auth/login" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", } post_data = "email=" + email + "&passwd=" + password + "&code=" post_data = post_data.encode() try: res = session.post(login_url, post_data, headers=headers, verify=False) res_str = res.text.encode("utf-8").decode("unicode_escape") print(f"{url} 接口登录返回信息:{res_str}") res_dict = json.loads(res_str) if res_dict.get("ret") == 0: msg = url + "\n" + str(res_dict.get("msg")) return msg except Exception: msg = url + "\n" + "登录失败,请查看日志" print(f"登录失败,错误信息:\n{traceback.format_exc()}") return msg headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", "Referer": url + "/user", } try: response = session.post( url + "/user/checkin", headers=headers, verify=False ) res_str = response.text.encode("utf-8").decode("unicode_escape") print(f"{url} 接口签到返回信息:{res_str}") res_dict = json.loads(res_str) check_msg = res_dict.get("msg") if check_msg: msg = url + "\n" + str(check_msg) else: msg = url + "\n" + str(res_dict) except Exception: msg = url + "\n" + "签到失败,请查看日志" print(f"签到失败,错误信息:\n{traceback.format_exc()}") info_url = url + "/user" response = session.get(info_url, verify=False) """ 以下只适配了editXY主题 """ try: level = re.findall(r'\["Class", "(.*?)"],', response.text)[0] day = re.findall(r'\["Class_Expire", "(.*)"],', response.text)[0] rest = re.findall(r'\["Unused_Traffic", "(.*?)"]', response.text)[0] msg = ( url + "\n- 今日签到信息:" + str(msg) + "\n- 用户等级:" + str(level) + "\n- 到期时间:" + str(day) + "\n- 剩余流量:" + str(rest) ) except Exception: pass return msg def main(self): msg_all = "" for check_item in self.check_items: # 机场地址 url = str(check_item.get("url")) # 登录信息 email = str(check_item.get("email")) password = str(check_item.get("password")) if url and email and password: msg = self.checkin(url=url, email=email, password=password) else: msg = "配置错误" msg_all += msg + "\n\n" return msg_all if __name__ == "__main__": data = get_data() _check_items = data.get("AIRPORT", []) res = SspanelQd(check_items=_check_items).main() send("机场签到", res)
31.151079
138
0.505081
484
4,330
4.390496
0.303719
0.025412
0.029647
0.029647
0.283765
0.262588
0.217412
0.158118
0.131765
0.131765
0
0.025678
0.352425
4,330
138
139
31.376812
0.732168
0.019169
0
0.214953
0
0.018692
0.189664
0.034617
0
0
0
0
0
1
0.028037
false
0.056075
0.065421
0
0.168224
0.046729
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
0
0
1
6f5c96a2170db005f0df74623642b0c6df9f9c2a
433
py
Python
setup.py
astrodeepnet/sbi_experiments
70af041da08565ba15e0c011145b11ab3fd973d7
[ "MIT" ]
3
2021-12-11T20:57:07.000Z
2021-12-14T22:20:42.000Z
setup.py
astrodeepnet/sbi_experiments
70af041da08565ba15e0c011145b11ab3fd973d7
[ "MIT" ]
20
2021-11-15T17:08:54.000Z
2022-03-25T10:32:52.000Z
setup.py
astrodeepnet/sbi_experiments
70af041da08565ba15e0c011145b11ab3fd973d7
[ "MIT" ]
3
2021-11-22T21:44:04.000Z
2021-12-14T10:31:46.000Z
from setuptools import setup, find_packages setup( name='SBIExperiments', version='0.0.1', url='https://github.com/astrodeepnet/sbi_experiments', author='Justine Zeghal and friends', description='Package for numerical experiments of SBI tools', packages=find_packages(), install_requires=[ 'numpy>=1.19.2', 'jax>=0.2.0', 'tensorflow_probability>=0.14.1', 'scikit-learn>=0.21', 'jaxopt>=0.2' ], )
24.055556
63
0.681293
58
433
5
0.724138
0.082759
0
0
0
0
0
0
0
0
0
0.051771
0.152425
433
17
64
25.470588
0.73842
0
0
0
0
0
0.508083
0.069284
0
0
0
0
0
1
0
true
0
0.0625
0
0.0625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
1
6f6c63911e71ae7c84e18bedf35df7f0d63d41aa
437
py
Python
serialTest.py
fmuno003/SeniorDesign
113bdcf4cc906042f44736a1ffddb6ffff3a217e
[ "BSD-3-Clause" ]
1
2019-04-29T16:07:51.000Z
2019-04-29T16:07:51.000Z
serialTest.py
fmuno003/SeniorDesign
113bdcf4cc906042f44736a1ffddb6ffff3a217e
[ "BSD-3-Clause" ]
null
null
null
serialTest.py
fmuno003/SeniorDesign
113bdcf4cc906042f44736a1ffddb6ffff3a217e
[ "BSD-3-Clause" ]
null
null
null
import serial import RPi.GPIO as GPIO import time ser=serial.Serial("/dev/ttyACM0",9600) start_time = time.time() imu = open("IMU.txt","w") while time.time() - start_time <= 1: ser.readline() while time.time() - start_time <= 8: read_ser=ser.readline() if float(read_ser) == 0.00: pass else: read = read_ser.strip('\n') imu.write(read) imu.write('\n') imu.close()
19.863636
39
0.578947
63
437
3.920635
0.47619
0.129555
0.105263
0.145749
0.178138
0
0
0
0
0
0
0.03096
0.26087
437
21
40
20.809524
0.733746
0
0
0
0
0
0.057692
0
0
0
0
0
0
1
0
false
0.058824
0.176471
0
0.176471
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
6f70b2504b0ddf0927280e069e308de02195aea2
447
py
Python
linkit/models.py
what-digital/linkit
58fb7dc966e7b76b654c9bc5e52253eb81731e98
[ "MIT" ]
8
2019-06-11T14:09:12.000Z
2021-09-09T09:37:47.000Z
linkit/models.py
what-digital/linkit
58fb7dc966e7b76b654c9bc5e52253eb81731e98
[ "MIT" ]
7
2020-02-12T02:55:11.000Z
2020-08-27T09:54:54.000Z
linkit/models.py
what-digital/linkit
58fb7dc966e7b76b654c9bc5e52253eb81731e98
[ "MIT" ]
2
2020-06-18T09:54:20.000Z
2022-02-17T08:33:13.000Z
from django.db import models from filer.fields.file import FilerFileField class FakeLink(models.Model): """ In our widget we need to manually render a AdminFileFormField. Basically for every other Field type this is not a problem at all, but Failer needs a rel attribute which consists of a reverse relationship. We fake it with this model. """ fake_file = FilerFileField(blank=True, null=True, on_delete=models.CASCADE)
37.25
115
0.753915
67
447
5
0.791045
0
0
0
0
0
0
0
0
0
0
0
0.187919
447
11
116
40.636364
0.922865
0.519016
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.5
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
6f73d54d3a1a664d942bd0ee6d760eedb4233760
1,054
py
Python
ecommerce/User/admin.py
AwaleRohin/commerce-fm
cb5b43c999ae5be37957b29de9c07d5affc66fb0
[ "MIT" ]
18
2020-12-05T14:12:32.000Z
2022-03-11T20:15:22.000Z
ecommerce/User/admin.py
AwaleRohin/commerce-fm
cb5b43c999ae5be37957b29de9c07d5affc66fb0
[ "MIT" ]
1
2021-07-22T09:23:13.000Z
2021-07-22T09:23:13.000Z
ecommerce/User/admin.py
shakyasaijal/commerce-fm
358b6925f4b569dc374010d7cc7d4d560ede2b48
[ "MIT" ]
13
2020-10-15T10:17:35.000Z
2022-01-29T06:56:24.000Z
from django.contrib import admin from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import models if settings.HAS_ADDITIONAL_USER_DATA: try: class UserProfileInline(admin.TabularInline): model = models.UserProfile extra = 0 except (Exception, KeyError) as e: raise ImproperlyConfigured("User/admin.py:: Multi Vendor is turned on.") class UserAdmin(admin.ModelAdmin): list_display = ['get_full_name', 'email', 'is_verified'] search_fields = ['get_full_name', 'email', 'date_joined', 'username'] list_filter = ('groups',) if settings.HAS_ADDITIONAL_USER_DATA: inlines = [ UserProfileInline, ] def save_model(self, request, obj, form, change): if 'password' in form.changed_data: obj.set_password(request.POST['password']) obj.save() admin.site.register(models.User, UserAdmin) admin.site.register(models.IpAddress) admin.site.register(models.CityFromIpAddress) admin.site.register(models.Marketing)
31
80
0.712524
125
1,054
5.864
0.56
0.049113
0.092769
0.125512
0.084584
0.084584
0
0
0
0
0
0.001159
0.181214
1,054
34
81
31
0.848204
0
0
0.08
0
0
0.123223
0
0
0
0
0
0
1
0.04
false
0.08
0.16
0
0.48
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
4893210d0b7c805a88b25dd46688e23dd6ed78a0
6,517
py
Python
safe_control_gym/math_and_models/normalization.py
catgloss/safe-control-gym
b3f69bbed8577f64fc36d23677bf50027e991b2d
[ "MIT" ]
120
2021-08-16T13:55:47.000Z
2022-03-31T10:31:42.000Z
safe_control_gym/math_and_models/normalization.py
catgloss/safe-control-gym
b3f69bbed8577f64fc36d23677bf50027e991b2d
[ "MIT" ]
10
2021-10-19T07:19:23.000Z
2022-03-24T18:43:02.000Z
safe_control_gym/math_and_models/normalization.py
catgloss/safe-control-gym
b3f69bbed8577f64fc36d23677bf50027e991b2d
[ "MIT" ]
24
2021-08-28T17:21:09.000Z
2022-03-31T10:31:44.000Z
"""Perform normalization on inputs or rewards. """ import numpy as np import torch from gym.spaces import Box def normalize_angle(x): """Wraps input angle to [-pi, pi]. """ return ((x + np.pi) % (2 * np.pi)) - np.pi class RunningMeanStd(): """Calulates the running mean and std of a data stream. Attributes: mean (np.array): mean of data stream. var (np.array): variance of data stream. count (float): total count of data steam. """ def __init__(self, epsilon=1e-4, shape=()): """Initializes containers for data mean and variance. Args: epsilon (float): helps with arithmetic issues. shape (tuple): the shape of the data stream's output. """ self.mean = np.zeros(shape, np.float64) self.var = np.ones(shape, np.float64) self.count = epsilon def update(self, arr): """Update current stats with a new stream of data. Args: arr (np.array): 1D array of data, (batch_size, *shape). """ batch_mean = np.mean(arr, axis=0) batch_var = np.var(arr, axis=0) batch_count = arr.shape[0] self.update_from_moments(batch_mean, batch_var, batch_count) def update_from_moments(self, batch_mean, batch_var, batch_count): """Util function for `update` method. """ delta = batch_mean - self.mean tot_count = self.count + batch_count new_mean = self.mean + delta * batch_count / tot_count m_a = self.var * self.count m_b = batch_var * batch_count m_2 = m_a + m_b + np.square(delta) * self.count * batch_count / (self.count + batch_count) new_var = m_2 / (self.count + batch_count) new_count = batch_count + self.count self.mean = new_mean self.var = new_var self.count = new_count class BaseNormalizer(object): """Template/default normalizer. Attributes: read_only (bool): if to freeze the current stats being tracked. """ def __init__(self, read_only=False): self.read_only = read_only def set_read_only(self): self.read_only = True def unset_read_only(self): self.read_only = False def __call__(self, x, *args, **kwargs): """Invokes normalization on the given input. """ return x def state_dict(self): """Returns snapshot of current stats. """ return {} def load_state_dict(self, _): """Restores the stats from a snapshot. """ pass class MeanStdNormalizer(BaseNormalizer): """Normalize by the running average. """ def __init__(self, shape=(), read_only=False, clip=10.0, epsilon=1e-8): """Initializes the data stream tracker. Args: shape (tuple): shape of data being tracked. read_only (bool): if to freeze the tracker. clip (float): bounds on the data. epsilon (float): offset to provide divide-by-zero. """ super().__init__(read_only) self.read_only = read_only self.rms = RunningMeanStd(shape=shape) self.clip = clip self.epsilon = epsilon def __call__(self, x): """Update tracker given data, optionally normalize the data. """ x = np.asarray(x) if not self.read_only: self.rms.update(x) return np.clip( (x - self.rms.mean) / np.sqrt(self.rms.var + self.epsilon), -self.clip, self.clip) def state_dict(self): return {'mean': self.rms.mean, 'var': self.rms.var} def load_state_dict(self, saved): self.rms.mean = saved['mean'] self.rms.var = saved['var'] class RewardStdNormalizer(MeanStdNormalizer): """Reward normalization by running average of returns. Papers: * arxiv.org/pdf/1808.04355.pdf * arxiv.org/pdf/1810.12894.pdf Also see: * github.com/openai/baselines/issues/538 """ def __init__(self, gamma=0.99, read_only=False, clip=10.0, epsilon=1e-8): """Initializes the data stream tracker. Args: gamma (float): discount factor for rewards. read_only (bool): if to freeze the tracker. clip (float): bounds on the data. epsilon (float): offset to provide divide-by-zero. """ # Reward has default shape (1,) or just (). super().__init__((), read_only, clip, epsilon) self.gamma = gamma self.ret = None def __call__(self, x, dones): """Update tracker given reward, optionally normalize the reward (only scaling). """ x = np.asarray(x) if not self.read_only: # Track running average of forward discounted returns. if self.ret is None: self.ret = np.zeros(x.shape[0]) self.ret = self.ret * self.gamma + x self.rms.update(self.ret) # Prevent information leak from previous episodes. self.ret[dones.astype(np.long)] = 0 return np.clip(x / np.sqrt(self.rms.var + self.epsilon), -self.clip, self.clip) class RescaleNormalizer(BaseNormalizer): """Apply constant scaling. """ def __init__(self, coef=1.0): """Initializes with fixed scaling constant. Args: coef (float): scaling coefficient. """ super().__init__(self) self.coef = coef def __call__(self, x): """Scale the input. """ if not isinstance(x, torch.Tensor): x = np.asarray(x) return self.coef * x class ImageNormalizer(RescaleNormalizer): """Scale image pixles from [0,255] to [0,1]. """ def __init__(self): super().__init__(self, 1.0 / 255) class ActionUnnormalizer(BaseNormalizer): """Assumes policy output action is in [-1,1], unnormalize it for gym env. """ def __init__(self, action_space): """Defines the mean and std for the bounded action space. """ super().__init__() assert isinstance(action_space, Box), "action space must be gym.spaces.Box" low, high = action_space.low, action_space.high self.mean = (low + high) / 2.0 self.std = (high - low) / 2.0 def __call__(self, action): """Unnormalizes given input action. """ x = np.asarray(action) return self.mean + x * self.std
27.041494
98
0.584778
828
6,517
4.437198
0.240338
0.039194
0.020958
0.020686
0.21203
0.175014
0.132553
0.125749
0.125749
0.110506
0
0.015145
0.300905
6,517
240
99
27.154167
0.791264
0.343563
0
0.117021
0
0
0.012609
0
0
0
0
0
0.010638
1
0.223404
false
0.010638
0.031915
0.010638
0.414894
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
0
0
0
1
48976b6d6b5db52348271fa437cb2c3858865703
1,723
py
Python
proof_of_work/multiagent/turn_based/v6/environmentv6.py
michaelneuder/parkes_lab_fa19
18d9f564e0df9c17ac5d54619ed869d778d4f6a4
[ "MIT" ]
null
null
null
proof_of_work/multiagent/turn_based/v6/environmentv6.py
michaelneuder/parkes_lab_fa19
18d9f564e0df9c17ac5d54619ed869d778d4f6a4
[ "MIT" ]
null
null
null
proof_of_work/multiagent/turn_based/v6/environmentv6.py
michaelneuder/parkes_lab_fa19
18d9f564e0df9c17ac5d54619ed869d778d4f6a4
[ "MIT" ]
null
null
null
import numpy as np np.random.seed(0) class Environment(object): def __init__(self, alpha, T, mining_cost=0.5): self.alpha = alpha self.T = T self.current_state = None self.mining_cost = mining_cost def reset(self): self.current_state = (0, 0) return self.current_state def getNextStateAdopt(self, rand_val): self.current_state = (0, 0) return np.asarray(self.current_state), 0 def getNextStateOverride(self, rand_val): a, h = self.current_state if a <= h: self.current_state = (0, 0) return np.asarray(self.current_state), -100 self.current_state = (a - h - 1, 0) return np.asarray(self.current_state), h + 1 def getNextStateMine(self, rand_val): a, h = self.current_state if (a == self.T) or (h == self.T): return self.getNextStateAdopt(rand_val) if rand_val < self.alpha: self.current_state = (a + 1, h) else: self.current_state = (a, h + 1) return np.asarray(self.current_state), -1*self.alpha*self.mining_cost def takeAction(self, action, rand_val=None): assert(action in [0, 1, 2]) if not rand_val: rand_val = np.random.uniform() if action == 0: return self.getNextStateAdopt(rand_val) elif action == 1: return self.getNextStateOverride(rand_val) else: return self.getNextStateMine(rand_val) def main(): env = Environment(alpha=0.35, T=9) print(env.reset(0.01)) print(env.takeAction(2, 0.01)) print(env.takeAction(1, 0.01)) if __name__ == "__main__": main()
31.327273
77
0.585607
231
1,723
4.190476
0.220779
0.159091
0.231405
0.070248
0.411157
0.296488
0.200413
0.167355
0.167355
0.167355
0
0.032312
0.299478
1,723
55
78
31.327273
0.769677
0
0
0.191489
0
0
0.00464
0
0
0
0
0
0.021277
1
0.148936
false
0
0.021277
0
0.382979
0.06383
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
0
0
0
1
48a84cb7d32acc3cbc3af963ca0e81cc7ff163d9
424
py
Python
poem/Poem/urls_public.py
kzailac/poem
9f898e3cc3378ef1c49517b4cf6335a93a3f49b0
[ "Apache-2.0" ]
null
null
null
poem/Poem/urls_public.py
kzailac/poem
9f898e3cc3378ef1c49517b4cf6335a93a3f49b0
[ "Apache-2.0" ]
null
null
null
poem/Poem/urls_public.py
kzailac/poem
9f898e3cc3378ef1c49517b4cf6335a93a3f49b0
[ "Apache-2.0" ]
null
null
null
from django.conf.urls import include from django.http import HttpResponseRedirect from django.urls import re_path from Poem.poem_super_admin.admin import mysuperadmin urlpatterns = [ re_path(r'^$', lambda x: HttpResponseRedirect('/poem/superadmin/')), re_path(r'^superadmin/', mysuperadmin.urls), re_path(r'^saml2/', include(('djangosaml2.urls', 'poem'), namespace='saml2')), ]
32.615385
72
0.688679
50
424
5.72
0.44
0.083916
0.073427
0
0
0
0
0
0
0
0
0.008621
0.179245
424
12
73
35.333333
0.813218
0
0
0
0
0
0.148585
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
48ae6c1d7db7737a61286051c58656fa1c61b3ae
387
py
Python
osu/osu_overlay.py
HQupgradeHQ/Daylight
a110a0f618877f5cccd66c4d75115c765d8f62a0
[ "MIT" ]
2
2020-07-30T14:07:19.000Z
2020-08-01T05:28:29.000Z
osu/osu_overlay.py
HQupgradeHQ/Daylight
a110a0f618877f5cccd66c4d75115c765d8f62a0
[ "MIT" ]
null
null
null
osu/osu_overlay.py
HQupgradeHQ/Daylight
a110a0f618877f5cccd66c4d75115c765d8f62a0
[ "MIT" ]
null
null
null
import mpv import keyboard import time p = mpv.MPV() p.play("song_name.mp4") def play_pause(): p.pause = not p.pause keyboard.add_hotkey("e", play_pause) def full(): p.fullscreen = not p.fullscreen keyboard.add_hotkey("2", full) def go_to_start(): p.time_pos = 2 keyboard.add_hotkey("1", go_to_start) while 1: time.sleep(40)
12.09375
38
0.620155
60
387
3.816667
0.433333
0.144105
0.222707
0
0
0
0
0
0
0
0
0.024221
0.25323
387
31
39
12.483871
0.768166
0
0
0
0
0
0.044944
0
0
0
0
0
0
1
0.1875
false
0
0.1875
0
0.375
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
48bc4c72c304a6d7aeeb0dab781f82a2616fe4d3
4,766
py
Python
test/test_memory_leaks.py
elventear/psutil
c159f3352dc5f699143960840e4f6535174690ed
[ "BSD-3-Clause" ]
4
2015-01-06T01:39:12.000Z
2019-12-09T10:27:44.000Z
test/test_memory_leaks.py
elventear/psutil
c159f3352dc5f699143960840e4f6535174690ed
[ "BSD-3-Clause" ]
null
null
null
test/test_memory_leaks.py
elventear/psutil
c159f3352dc5f699143960840e4f6535174690ed
[ "BSD-3-Clause" ]
2
2016-10-21T03:15:34.000Z
2018-12-10T03:40:50.000Z
#!/usr/bin/env python # # $Id$ # """ Note: this is targeted for python 2.x. To run it under python 3.x you need to use 2to3 tool first: $ 2to3 -w test/test_memory_leaks.py """ import os import gc import sys import unittest import psutil from test_psutil import reap_children, skipUnless, skipIf, \ POSIX, LINUX, WINDOWS, OSX, BSD LOOPS = 1000 TOLERANCE = 4096 class TestProcessObjectLeaks(unittest.TestCase): """Test leaks of Process class methods and properties""" def setUp(self): gc.collect() def tearDown(self): reap_children() def execute(self, method, *args, **kwarks): # step 1 p = psutil.Process(os.getpid()) for x in xrange(LOOPS): obj = getattr(p, method) if callable(obj): retvalue = obj(*args, **kwarks) else: retvalue = obj # property del x, p, obj, retvalue gc.collect() rss1 = psutil.Process(os.getpid()).get_memory_info()[0] # step 2 p = psutil.Process(os.getpid()) for x in xrange(LOOPS): obj = getattr(p, method) if callable(obj): retvalue = obj(*args, **kwarks) else: retvalue = obj # property del x, p, obj, retvalue gc.collect() rss2 = psutil.Process(os.getpid()).get_memory_info()[0] # comparison difference = rss2 - rss1 if difference > TOLERANCE: self.fail("rss1=%s, rss2=%s, difference=%s" %(rss1, rss2, difference)) def test_name(self): self.execute('name') def test_cmdline(self): self.execute('cmdline') def test_ppid(self): self.execute('ppid') def test_uid(self): self.execute('uid') def test_uid(self): self.execute('gid') @skipIf(POSIX) def test_username(self): self.execute('username') def test_create_time(self): self.execute('create_time') def test_get_num_threads(self): self.execute('get_num_threads') def test_get_threads(self): self.execute('get_num_threads') def test_get_cpu_times(self): self.execute('get_cpu_times') def test_get_memory_info(self): self.execute('get_memory_info') def test_is_running(self): self.execute('is_running') @skipUnless(WINDOWS) def test_resume(self): self.execute('resume') @skipUnless(WINDOWS) def test_getcwd(self): self.execute('getcwd') @skipUnless(WINDOWS) def test_get_open_files(self): self.execute('get_open_files') @skipUnless(WINDOWS) def test_get_connections(self): self.execute('get_connections') class TestModuleFunctionsLeaks(unittest.TestCase): """Test leaks of psutil module functions.""" def setUp(self): gc.collect() def execute(self, function, *args, **kwarks): # step 1 for x in xrange(LOOPS): obj = getattr(psutil, function) if callable(obj): retvalue = obj(*args, **kwarks) else: retvalue = obj # property del x, obj, retvalue gc.collect() rss1 = psutil.Process(os.getpid()).get_memory_info()[0] # step 2 for x in xrange(LOOPS): obj = getattr(psutil, function) if callable(obj): retvalue = obj(*args, **kwarks) else: retvalue = obj # property del x, obj, retvalue gc.collect() rss2 = psutil.Process(os.getpid()).get_memory_info()[0] # comparison difference = rss2 - rss1 if difference > TOLERANCE: self.fail("rss1=%s, rss2=%s, difference=%s" %(rss1, rss2, difference)) def test_get_pid_list(self): self.execute('get_pid_list') @skipIf(POSIX) def test_pid_exists(self): self.execute('pid_exists', os.getpid()) def test_process_iter(self): self.execute('process_iter') def test_used_phymem(self): self.execute('used_phymem') def test_avail_phymem(self): self.execute('avail_phymem') def test_total_virtmem(self): self.execute('total_virtmem') def test_used_virtmem(self): self.execute('used_virtmem') def test_avail_virtmem(self): self.execute('avail_virtmem') def test_cpu_times(self): self.execute('cpu_times') def test_main(): test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(TestProcessObjectLeaks)) test_suite.addTest(unittest.makeSuite(TestModuleFunctionsLeaks)) unittest.TextTestRunner(verbosity=2).run(test_suite) if __name__ == '__main__': test_main()
24.822917
82
0.599245
571
4,766
4.831874
0.220666
0.065966
0.135919
0.045669
0.471185
0.391446
0.355926
0.355926
0.355926
0.355926
0
0.011417
0.283256
4,766
191
83
24.95288
0.796253
0.070709
0
0.460317
0
0
0.073459
0
0
0
0
0
0
1
0.246032
false
0
0.047619
0
0.309524
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
0
0
0
1
48bfa6a9870aa2f95044df7a3145739de4a0dc15
1,681
py
Python
tests/molecular/molecules/building_block/test_with_functional_groups.py
andrewtarzia/stk
1ac2ecbb5c9940fe49ce04cbf5603fd7538c475a
[ "MIT" ]
21
2018-04-12T16:25:24.000Z
2022-02-14T23:05:43.000Z
tests/molecular/molecules/building_block/test_with_functional_groups.py
JelfsMaterialsGroup/stk
0d3e1b0207aa6fa4d4d5ee8dfe3a29561abb08a2
[ "MIT" ]
8
2019-03-19T12:36:36.000Z
2020-11-11T12:46:00.000Z
tests/molecular/molecules/building_block/test_with_functional_groups.py
supramolecular-toolkit/stk
0d3e1b0207aa6fa4d4d5ee8dfe3a29561abb08a2
[ "MIT" ]
5
2018-08-07T13:00:16.000Z
2021-11-01T00:55:10.000Z
from ..utilities import ( has_same_structure, is_equivalent_molecule, is_equivalent_building_block, are_equivalent_functional_groups, ) def test_with_functional_groups(building_block, get_functional_groups): """ Test :meth:`.BuildingBlock.with_functional_groups`. Parameters ---------- building_block : :class:`.BuildingBlock` The building block to test. get_functional_groups : :class:`callable` Takes a single parameter, `building_block` and returns the `functional_groups` parameter to use for this test. Returns ------- None : :class:`NoneType` """ # Save clone to check immutability. clone = building_block.clone() _test_with_functional_groups( building_block=building_block, functional_groups=tuple(get_functional_groups(building_block)), ) is_equivalent_building_block(building_block, clone) has_same_structure(building_block, clone) def _test_with_functional_groups(building_block, functional_groups): """ Test :meth:`.BuildingBlock.with_functional_groups`. Parameters ---------- building_block : :class:`.BuildingBlock` The building block to test. functional_groups : :class:`tuple` of :class:`.FunctionalGroup` The functional groups the new building block should hold. Returns ------- None : :class:`NoneType` """ new = building_block.with_functional_groups(functional_groups) are_equivalent_functional_groups( new.get_functional_groups(), functional_groups, ) is_equivalent_molecule(building_block, new) has_same_structure(building_block, new)
26.68254
71
0.702558
182
1,681
6.120879
0.252747
0.221724
0.10772
0.104129
0.372531
0.320467
0.287253
0.21544
0.21544
0.21544
0
0
0.201666
1,681
62
72
27.112903
0.830104
0.418203
0
0
0
0
0
0
0
0
0
0
0
1
0.090909
false
0
0.045455
0
0.136364
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
0
0
0
1
48cd84239fff9070a94f62f2913b39c9eded80ea
204
py
Python
shiva/constants.py
tooxie/shiva-server
4d169aae8d4cb01133f62701b14610695e48c297
[ "MIT" ]
70
2015-01-09T15:15:15.000Z
2022-01-14T09:51:55.000Z
shiva/constants.py
tooxie/shiva-server
4d169aae8d4cb01133f62701b14610695e48c297
[ "MIT" ]
14
2015-01-04T10:08:26.000Z
2021-12-13T19:35:07.000Z
shiva/constants.py
tooxie/shiva-server
4d169aae8d4cb01133f62701b14610695e48c297
[ "MIT" ]
19
2015-01-02T22:42:01.000Z
2022-01-14T09:51:59.000Z
# -*- coding: utf-8 -*- class HTTP: BAD_REQUEST = 400 UNAUTHORIZED = 401 FORBIDDEN = 403 NOT_FOUND = 404 METHOD_NOT_ALLOWED = 405 CONFLICT = 409 UNSUPPORTED_MEDIA_TYPE = 415
17
32
0.632353
25
204
4.92
0.96
0
0
0
0
0
0
0
0
0
0
0.150685
0.284314
204
11
33
18.545455
0.691781
0.102941
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
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
1
48d0551fc7668ef91b0cbb625288bc4330046f92
642
py
Python
day8/test_day8.py
bwbeach/advent-of-code-2020
572810c3adae5815543efde17a4bca9596d05a5b
[ "CC0-1.0" ]
null
null
null
day8/test_day8.py
bwbeach/advent-of-code-2020
572810c3adae5815543efde17a4bca9596d05a5b
[ "CC0-1.0" ]
null
null
null
day8/test_day8.py
bwbeach/advent-of-code-2020
572810c3adae5815543efde17a4bca9596d05a5b
[ "CC0-1.0" ]
null
null
null
from day8.day8 import fix_code, parse_code, run SAMPLE_CODE_LOOP = """nop +0 acc +1 jmp +4 acc +3 jmp -3 acc -99 acc +1 jmp -4 acc +6 """ SAMPLE_CODE_HALT = """nop +0 acc +1 jmp +4 acc +3 jmp -3 acc -99 acc +1 nop -4 acc +6 """ def test_parse(): assert parse_code("nop +0\nacc +1\nacc -6") == [("nop", 0), ("acc", 1), ("acc", -6)] def test_run_loop(): code = parse_code(SAMPLE_CODE_LOOP) assert run(code) == ("loop", 5) def test_run_halt(): code = parse_code(SAMPLE_CODE_HALT) assert run(code) == ("halt", 8) def test_fix_code(): assert fix_code(parse_code(SAMPLE_CODE_LOOP)) == parse_code(SAMPLE_CODE_HALT)
15.285714
88
0.638629
116
642
3.301724
0.215517
0.140992
0.13577
0.198433
0.441253
0.292428
0.151436
0.151436
0.151436
0.151436
0
0.057692
0.190031
642
41
89
15.658537
0.678846
0
0
0.516129
0
0
0.260125
0
0
0
0
0
0.129032
1
0.129032
false
0
0.032258
0
0.16129
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
0
0
0
1
48d23528c08e020ee5f13c45ec80e61813e3bd41
6,128
py
Python
biosys/apps/main/tests/api/test_misc.py
florianm/biosys
934d06ed805b0734f3cb9a00feec6cd81a94e512
[ "Apache-2.0" ]
2
2018-04-09T04:02:30.000Z
2019-08-20T03:12:55.000Z
biosys/apps/main/tests/api/test_misc.py
florianm/biosys
934d06ed805b0734f3cb9a00feec6cd81a94e512
[ "Apache-2.0" ]
29
2016-01-20T08:14:15.000Z
2017-07-13T07:17:32.000Z
biosys/apps/main/tests/api/test_misc.py
florianm/biosys
934d06ed805b0734f3cb9a00feec6cd81a94e512
[ "Apache-2.0" ]
5
2016-01-14T23:02:36.000Z
2016-09-21T05:35:03.000Z
from django.shortcuts import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from main.models import Project from main.tests import factories from main.tests.api import helpers class TestWhoAmI(helpers.BaseUserTestCase): def setUp(self): super(TestWhoAmI, self).setUp() self.url = reverse('api:whoami') def test_get(self): client = self.anonymous_client self.assertEqual( client.get(self.url).status_code, status.HTTP_200_OK ) user = factories.UserFactory() user.set_password('password') user.save() client = APIClient() self.assertTrue(client.login(username=user.username, password='password')) resp = client.get(self.url) self.assertEqual( resp.status_code, status.HTTP_200_OK ) # test that the response contains username, first and last name and email at least and the id data = resp.json() self.assertEqual(user.username, data['username']) self.assertEqual(user.first_name, data['first_name']) self.assertEqual(user.last_name, data['last_name']) self.assertEqual(user.email, data['email']) self.assertEqual(user.id, data['id']) # test that the password is not in the returned fields self.assertFalse('password' in data) def test_not_allowed_methods(self): client = self.readonly_client self.assertEqual( client.post(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) self.assertEqual( client.put(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) self.assertEqual( client.patch(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) class TestStatistics(TestCase): def setUp(self): self.url = reverse('api:statistics') def test_get(self): anonymous = APIClient() client = anonymous self.assertIn( client.get(self.url).status_code, [status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN] ) user = factories.UserFactory.create() user.set_password('password') user.save() client = APIClient() self.assertTrue(client.login(username=user.username, password='password')) resp = client.get(self.url) self.assertEqual( resp.status_code, status.HTTP_200_OK ) # expected response with no data expected = { 'projects': {'total': 0}, 'datasets': { 'total': 0, 'generic': {'total': 0}, 'observation': {'total': 0}, 'speciesObservation': {'total': 0}, }, 'records': { 'total': 0, 'generic': {'total': 0}, 'observation': {'total': 0}, 'speciesObservation': {'total': 0}, }, 'sites': {'total': 0}, } self.assertEqual(expected, resp.json()) # create one project program = factories.ProgramFactory.create() project = factories.ProjectFactory.create(program=program) expected['projects']['total'] = 1 resp = client.get(self.url) self.assertEqual( resp.status_code, status.HTTP_200_OK ) self.assertEqual(expected, resp.json()) # create some sites count = 3 factories.SiteFactory.create_batch( count, project=project ) expected['sites']['total'] = count resp = client.get(self.url) self.assertEqual( resp.status_code, status.HTTP_200_OK ) self.assertEqual(expected, resp.json()) def test_not_allowed_methods(self): user = factories.UserFactory.create() user.set_password('password') user.save() client = APIClient() self.assertTrue(client.login(username=user.username, password='password')) self.assertEqual( client.post(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) self.assertEqual( client.put(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) self.assertEqual( client.patch(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) class TestSpecies(TestCase): # set the species list to be the testing one species_facade_class = helpers.LightSpeciesFacade def setUp(self): from main.api.views import SpeciesMixin SpeciesMixin.species_facade_class = self.species_facade_class self.url = reverse('api:species') def test_get(self): anonymous = APIClient() client = anonymous self.assertEqual( client.get(self.url).status_code, status.HTTP_200_OK ) user = factories.UserFactory.create() user.set_password('password') user.save() client = APIClient() self.assertTrue(client.login(username=user.username, password='password')) resp = client.get(self.url) self.assertEqual( resp.status_code, status.HTTP_200_OK ) def test_not_allowed_methods(self): user = factories.UserFactory.create() user.set_password('password') user.save() client = APIClient() self.assertTrue(client.login(username=user.username, password='password')) self.assertEqual( client.post(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) self.assertEqual( client.put(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED ) self.assertEqual( client.patch(self.url, {}).status_code, status.HTTP_405_METHOD_NOT_ALLOWED )
31.587629
101
0.590078
642
6,128
5.471963
0.174455
0.102477
0.077427
0.096783
0.627099
0.627099
0.606889
0.606889
0.596641
0.568745
0
0.015478
0.304178
6,128
193
102
31.751295
0.808396
0.041612
0
0.618182
0
0
0.056256
0
0
0
0
0
0.187879
1
0.054545
false
0.066667
0.048485
0
0.127273
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
48d29ebbfa1dba9c5ef7d472e7d45e6999e1c63b
531
py
Python
src/netwrok/analytics.py
simonwittber/netwrok-server
d4767faa766e7ecb0de0c912f0c0a26b45b84189
[ "MIT" ]
16
2015-12-01T14:42:30.000Z
2021-04-26T21:16:45.000Z
src/netwrok/analytics.py
DifferentMethods/netwrok-server
d4767faa766e7ecb0de0c912f0c0a26b45b84189
[ "MIT" ]
null
null
null
src/netwrok/analytics.py
DifferentMethods/netwrok-server
d4767faa766e7ecb0de0c912f0c0a26b45b84189
[ "MIT" ]
4
2015-03-02T07:19:15.000Z
2015-10-14T07:38:02.000Z
import asyncio import aiopg from . import nwdb from . import core @core.handler def register(client, path, event): """ Register an event occuring at path. Created time is automatically added. Useful for generic analytics type stuff. """ with (yield from nwdb.connection()) as conn: cursor = yield from conn.cursor() yield from cursor.execute(""" insert into analytics(member_id, path, event) select %s, %s, %s """, [client.session.get("member_id", None), path, event])
27.947368
76
0.653484
69
531
5
0.608696
0.078261
0.086957
0.110145
0
0
0
0
0
0
0
0
0.237288
531
18
77
29.5
0.851852
0.212806
0
0
0
0
0.246231
0
0
0
0
0
0
1
0.083333
false
0
0.333333
0
0.416667
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
0
0
0
1
48d3e34f960926be47270d979dba99f1e974b2b3
476
py
Python
main/test_data.py
anna01111/demo_web_ui_test_suite
69bedc25126b874774e2f51a83356dc9ee1b7e74
[ "CC0-1.0" ]
null
null
null
main/test_data.py
anna01111/demo_web_ui_test_suite
69bedc25126b874774e2f51a83356dc9ee1b7e74
[ "CC0-1.0" ]
null
null
null
main/test_data.py
anna01111/demo_web_ui_test_suite
69bedc25126b874774e2f51a83356dc9ee1b7e74
[ "CC0-1.0" ]
null
null
null
from faker import Faker """ More info: https://microservices-demo.github.io/docs/user-accounts.html """ # The demo app is shipped with the following account: username = 'user' password = 'password' # Fake data that is used for new registrations: faker = Faker() autogenerated_username = faker.user_name() autogenerated_first_name = faker.first_name() autogenerated_last_name = faker.last_name() autogenerated_email = faker.email() autogenerated_password = faker.password()
26.444444
71
0.779412
63
476
5.730159
0.555556
0.141274
0
0
0
0
0
0
0
0
0
0
0.115546
476
17
72
28
0.857482
0.203782
0
0
0
0
0.040404
0
0
0
0
0
0
1
0
false
0.222222
0.111111
0
0.111111
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
48d3f8d217b00f2ba74165ed887ea259202fee75
1,115
py
Python
pfr/run.py
AnnaMag/pdf-flask-react
de89eb13b2e2e0d4418c28041fe294205f528b96
[ "BSD-2-Clause" ]
2
2019-01-04T16:55:05.000Z
2019-08-28T20:16:47.000Z
pfr/run.py
AnnaMag/pdf-flask-react
de89eb13b2e2e0d4418c28041fe294205f528b96
[ "BSD-2-Clause" ]
2
2021-06-01T21:52:21.000Z
2021-12-13T19:43:43.000Z
pfr/run.py
AnnaMag/pdf-flask-react
de89eb13b2e2e0d4418c28041fe294205f528b96
[ "BSD-2-Clause" ]
null
null
null
from io import StringIO from io import BytesIO import urllib from urllib import request import utils from pdf_processing import scrape_gazette_names, get_info_outline from data_parsing import save_to_dict if __name__ == '__main__': # not saving anything locally, just the names listed on the webpage to access the files later url = 'http://www.gpwonline.co.za/Gazettes/Pages/Published-National-Regulation-Gazettes.aspx' doc_names = scrape_gazette_names(url) db_name = 'gov_docs' db_collection = 'nat_reg' collection = utils.set_collection(db_name, db_collection) for url in doc_names[0][3:5]: print(url) fp = BytesIO(urllib.request.urlopen(url).read()) info, device, pages_skipped = get_info_outline(fp) print(info) #pages_skipped should be pages for extraction- for now is to montitore problems gaz_dict = save_to_dict(device.interesting_text, device.aux_text, \ pages_skipped, info, device.page_number, url) print(gaz_dict) utils.write_db(collection, gaz_dict)
33.787879
97
0.699552
154
1,115
4.798701
0.525974
0.048714
0.032476
0
0
0
0
0
0
0
0
0.003476
0.226009
1,115
32
98
34.84375
0.852839
0.15157
0
0
0
0.045455
0.114528
0
0
0
0
0
0
1
0
false
0
0.318182
0
0.318182
0.136364
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
0
0
0
1
48d4f15c7fa28d9ec9d8b63f2ea935ca7b5152ba
1,246
py
Python
day9/day9.py
jaredledvina/adventofcode2020
2a31fd88c0b6bddd2c06327d04e6630b8fb29909
[ "MIT" ]
1
2020-12-09T14:50:49.000Z
2020-12-09T14:50:49.000Z
day9/day9.py
jaredledvina/adventofcode2020
2a31fd88c0b6bddd2c06327d04e6630b8fb29909
[ "MIT" ]
null
null
null
day9/day9.py
jaredledvina/adventofcode2020
2a31fd88c0b6bddd2c06327d04e6630b8fb29909
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import itertools def read_input(): with open('input.txt') as f: puzzle_input = f.read().splitlines() puzzle_input = [int(num) for num in puzzle_input] return puzzle_input def part1(puzzle_input): preamble = puzzle_input[:25] remaining = puzzle_input[25:] for item in remaining: found_match = False for product in itertools.product(preamble, preamble): if product[0] + product[1] == item: found_match = True preamble.append(item) preamble.pop(0) break if not found_match: return item def part2(puzzle_input): invalid = part1(puzzle_input) for position in range(len(puzzle_input)): combination_position = 0 for combination in itertools.accumulate(puzzle_input[position:]): if combination == invalid: return min(puzzle_input[position:combination_position+position]) + max(puzzle_input[position:combination_position+position]) combination_position += 1 def main(): puzzle_input = read_input() print(part1(puzzle_input)) print(part2(puzzle_input)) if __name__ == '__main__': main()
29.666667
140
0.629213
145
1,246
5.17931
0.344828
0.234354
0.063915
0.079893
0.122503
0.122503
0
0
0
0
0
0.01663
0.276083
1,246
42
141
29.666667
0.815965
0.016854
0
0
0
0
0.013878
0
0
0
0
0
0
1
0.121212
false
0
0.030303
0
0.242424
0.060606
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
0
0
0
1
48d79b6a3679e4354a437a7315a9dd9bd23f2c50
3,971
py
Python
scraper/edx.py
thanasis457/Mooc-platform
5ff3b7b43fadc86ec5d4d54db6963449a6610bb5
[ "MIT" ]
4
2020-08-30T12:18:27.000Z
2021-05-19T06:42:13.000Z
scraper/edx.py
thanasis457/Mooc-platform
5ff3b7b43fadc86ec5d4d54db6963449a6610bb5
[ "MIT" ]
1
2021-01-28T20:21:48.000Z
2021-01-28T20:21:48.000Z
scraper/edx.py
thanasis457/Mooc-platform
5ff3b7b43fadc86ec5d4d54db6963449a6610bb5
[ "MIT" ]
1
2020-09-14T13:20:05.000Z
2020-09-14T13:20:05.000Z
import requests, json, bs4, urllib.parse, math from . import Course, Platform class Edx(Platform): name = 'edX' def _urls(self): res = requests.get(make_url()) count = json.loads(res.text)['objects']['count'] num_pages = math.ceil(count / 20) urls = [make_url(page=page) for page in range(1, num_pages + 1)] return urls def _parse(self, url): res = requests.get(url) courses = [] results = res.json()['objects']['results'] for result in results: title = result['title'] if result['full_description']: description = html_to_text(result['full_description']) else: description = result['short_description'] snippet = '' if result['short_description'] and result['short_description'] != '.': snippet = result['short_description'] url = result['marketing_url'] tags = [subject_uuids.get(uuid) for uuid in result['subject_uuids']] partners = [result.get('org')] course = Course(title, partners, self.name, description, tags, url, snippet=snippet) courses.append(course) return courses subject_uuids = {'d8244ef2-45fb-4be3-a9d7-a6749cee3b19': 'Architecture', '2cc66121-0c07-407b-96c4-99305359a36f': 'Art & Culture', '9d5b5edb-254a-4d54-b430-776f1f00eaf0': 'Biology & Life Sciences', '409d43f7-ff36-4834-9c28-252132347d87': 'Business & Management', 'c5ec1f86-4e59-4273-8e22-ceec2b8d10a2': 'Chemistry', '605bb663-a342-4cf3-b5a5-fee2f33f1642': 'Communication', 'e52e2134-a4e4-4fcb-805f-cbef40812580': 'Computer Science', 'a168a80a-4b6c-4d92-9f1d-4c235206feaf': 'Data Analysis & Statistics', '34173fb0-fe3d-4715-b4e0-02a9426a873c': 'Design', 'bab458d9-19b3-476e-864f-8abd1d1aab44': 'Economics & Finance', '8ac7a3da-a60b-4565-b361-384baaa49279': 'Education & Teacher Training', '337dfb23-571e-49d7-9c8e-385120dea6f3': 'Electronics', '07406bfc-76c4-46cc-a5bf-2deace7995a6': 'Energy & Earth Sciences', '0d7bb9ed-4492-419a-bb44-415adafd9406': 'Engineering', '8aaac548-1930-4614-aeb4-a089dae7ae26': 'Environmental Studies', '8a552a20-963e-475c-9b0d-4c5efe22d015': 'Ethics', 'caa4db79-f325-41ca-8e09-d5bb6e148240': 'Food & Nutrition', '51a13a1c-7fc8-42a6-9e96-6636d10056e2': 'Health & Safety', 'c8579e1c-99f2-4a95-988c-3542909f055e': 'Histroy', '00e5d5e0-ce45-4114-84a1-50a5be706da5': 'Humanities', '32768203-e738-4627-8b04-78b0ed2b44cb': 'Language', '4925b67d-01c4-4287-a8d1-a3e0066113b8': 'Law', '74b6ed2a-3ba0-49be-adc9-53f7256a12e1': 'Literature', 'a669e004-cbc0-4b68-8882-234c12e1cce4': 'Math', 'a5db73b2-05b4-4284-beef-c7876ec1499b': 'Medicine', 'f520dcc1-f5b7-42fe-a757-8acfb1e9e79d': 'Music', '830f46dc-624e-46f4-9df0-e2bc6b346956': 'Philosophy & Ethics', '88eb7ca7-2296-457d-8aac-e5f7503a9333': 'Physics', 'f830cfeb-bb7e-46ed-859d-e2a9f136499f': 'Science', 'eefb009b-0a02-49e9-b1b1-249982b6ce86': 'Social Sciences'} def make_url(page=1): params = {'selected_facets[]': 'transcript_languages_exact:English', 'partner': 'edx', 'content_type[]': 'courserun', 'page': page, 'page_size': 20} return 'https://www.edx.org/api/v1/catalog/search?' + urllib.parse.urlencode(params) def html_to_text(html): soup = bs4.BeautifulSoup(html, 'lxml') return soup.text
44.617978
88
0.576681
384
3,971
5.895833
0.700521
0.019435
0.038869
0.025618
0
0
0
0
0
0
0
0.219979
0.289096
3,971
88
89
45.125
0.582005
0
0
0
0
0
0.447998
0.280534
0
0
0
0
0
1
0.057143
false
0
0.028571
0
0.171429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
48de82f88d77ad42fe5f179efaac8655f74f00d7
5,682
py
Python
tests/db/test_connector.py
DaWeSearch/backend
809e575ed730fce55d0e89a2fbc2031ba116f5e0
[ "MIT" ]
1
2021-02-15T01:05:22.000Z
2021-02-15T01:05:22.000Z
tests/db/test_connector.py
DaWeSearch/backend
809e575ed730fce55d0e89a2fbc2031ba116f5e0
[ "MIT" ]
null
null
null
tests/db/test_connector.py
DaWeSearch/backend
809e575ed730fce55d0e89a2fbc2031ba116f5e0
[ "MIT" ]
null
null
null
import unittest import os import json from functions.db.connector import * from functions.db.models import * from functions.authentication import * sample_search = { "search_groups": [ { "search_terms": ["blockchain", "distributed ledger"], "match": "OR" }, { "search_terms": ["energy", "infrastructure", "smart meter"], "match": "OR" } ], "match": "AND" } db_dict = {"db_name": "hallo", "api_key": "test"} class TestConnector(unittest.TestCase): def setUp(self): name = "test_review" self.review = add_review(name) self.sample_query = new_query(self.review, sample_search) with open('test_results.json', 'r') as file: self.results = json.load(file) save_results(self.results['records'], self.review, self.sample_query) def test_add_review(self): name = "test_review" new_review = add_review(name) review = get_review_by_id(new_review._id) review.delete() self.assertEqual(review._id, new_review._id) def test_save_results(self): query = new_query(self.review, sample_search) jsonpath = os.path.abspath(os.path.join( os.path.dirname(__file__), "..", "..", "test_results.json")) with open(jsonpath, 'r') as file: results = json.load(file) save_results(results['records'], self.review, query) results_from_db = get_persisted_results(query).get('results') self.assertEqual(len(results_from_db), len(results['records'])) def test_pagination(self): page1 = get_persisted_results(self.sample_query, 1, 10).get('results') self.assertTrue(len(page1) == 10) page2 = get_persisted_results(self.sample_query, 2, 10).get('results') self.assertTrue(len(page2) == 10) self.assertNotEqual(page1, page2) def test_get_list_of_dois_for_review(self): dois = get_dois_for_review(self.review) for record in self.results.get('records'): self.assertTrue(record.get('doi') in dois) def test_update_score(self): user = User(name="test user") doi = self.results.get('records')[0].get('doi') result = get_result_by_doi(self.review, doi) self.assertEqual(len(result.scores), 0) evaluation = { "user": "testmann", "score": 2, "comment": "test_comment" } update_score(self.review, result, evaluation) self.assertEqual(result.scores[0].score, 2) evaluation = { "user": "testmann", "score": 5, "comment": "joiefjlke" } update_score(self.review, result, evaluation) self.assertEqual(result.scores[0].score, 5) self.assertEqual(len(result.scores), 1) user.delete() def test_delete_results_for_review(self): num_results = len(get_dois_for_review(self.review)) self.assertGreater(num_results, 0) delete_results_for_review(self.review) num_results = len(get_dois_for_review(self.review)) self.assertEquals(num_results, 0) def tearDown(self): delete_results_for_review(self.review) self.review.delete() class TestUserDB(unittest.TestCase): # TODO rewrite test cases def setUp(self): username = "philosapiens" name = "Philippe" surname = "Kalinowski" email = "test@slr.com" password = "ABC123" # databases = DatabaseInfo() # databases.name = "SPRINGER_API" # databases.api_key = "5150230aac7a227ve33693f99b5697aa" # self.user = add_user(username, name, surname, email, password) def test_add_user(self): username = "philosapfiens" name = "Philippe" surname = "Kalinowski" email = "test@slr.com" password = "ABC123222" db_name = "SPRINGER_API" api_key = "5150230aac7a227ve33693f99b5697aa" # databases312 = DatabaseInfo.from_document(sample_databases) # print(databases312) new_user = add_user(username, name, surname, email, password) # update_databases(new_user, db_dict) # user = get_user_by_id(new_user.name) def test_get_user_by_username(self): user = get_user_by_username("philosapiens") print(user.email) def test_update_user(self): user = get_user_by_username("philosapiens") print(user.email) update_user(user, user.name, "btesfd", "changed@slr.com", user.password) user = get_user_by_username("philosapiens") print(user.email) def test_get_all_users(self): print(str(get_users())) def test_delete_users(self): user = get_user_by_username("philosapiens") delete_user(user) class TestAuth(unittest.TestCase): def setUp(self): username = "philosapiens" name = "Philippe" surname = "Kalinowski" email = "test@slr.com" password = "ABC123" def test_login(self): username = "philosapiens" password = "ABC123222" user = get_user_by_username(username) password_correct = check_if_password_is_correct(user, password) print(password_correct) token = get_jwt_for_user(user) print(type(token)) add_jwt_to_session(user, token) is_token_valid = check_for_token(token) print(is_token_valid) is_token_in_session = check_if_jwt_is_in_session(token) print(is_token_in_session) # remove_jwt_from_session(user) if __name__ == '__main__': unittest.main()
29.28866
80
0.62566
659
5,682
5.125948
0.201821
0.041445
0.033156
0.023091
0.368561
0.322676
0.240971
0.209295
0.183837
0.168443
0
0.022544
0.25836
5,682
193
81
29.440415
0.77907
0.067406
0
0.296296
0
0
0.119705
0.006051
0
0
0
0.005181
0.088889
1
0.118519
false
0.059259
0.044444
0
0.185185
0.059259
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
0
0
1
48e612645ef11a151beea876541ffc2a70be93e5
5,123
py
Python
src/cnc-app-name/views.py
scotchoaf/cnc-skeleton
2116bf3d61fc1ed834daeaa146f5730713300010
[ "MIT" ]
null
null
null
src/cnc-app-name/views.py
scotchoaf/cnc-skeleton
2116bf3d61fc1ed834daeaa146f5730713300010
[ "MIT" ]
null
null
null
src/cnc-app-name/views.py
scotchoaf/cnc-skeleton
2116bf3d61fc1ed834daeaa146f5730713300010
[ "MIT" ]
1
2019-04-08T14:54:12.000Z
2019-04-08T14:54:12.000Z
# Copyright (c) 2018, Palo Alto Networks # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Author: $YOURNAME and $EMAIL """ Palo Alto Networks cnc-skeleton This software is provided without support, warranty, or guarantee. Use at your own risk. """ from django import forms from django.contrib import messages from django.shortcuts import HttpResponseRedirect # Every app will need to import at least the CNCBaseFormView from pan_cnc.views import CNCBaseFormView, ProvisionSnippetView # All class attributes can be defined here or in the .pan-cnc.yaml # In this case, we have defined class level attributes there. This makes it possible to # create apps while writing no code at all. Just create a view in the .pan-cnc.yaml based on a # CNCBaseFormView and configure the attributes as needed. # If you want additional logic, then you subclass the CNCBaseFormView and add your logic there. # The two main methods to override are 'generate_dynamic_form' and 'form_valid'. # # generate_dynamic_form gets called before the web form is created and displayed to the user # # form_valid is called after they submit the form # class ExampleAppView(CNCBaseFormView): def form_valid(self, form): # we now have the form from the user, let's get some values to perform some logic # every variable entered by the user is saved in the user session. We can access it using this # convenience method: var_name = self.get_value_from_workflow('var_name', 'DEFAULT_IF_NOT_FOUND') var_name_again = self.get_value_from_workflow('var_name_again', 'DEFAULT_IF_NOT_FOUND') # silly exercise to just upper case the value entered by the user var_name_upper = str(var_name).upper() var_name_again_reverse = str(var_name_again)[::-1] # now, save the values back to the workflow self.save_value_to_workflow('var_name', var_name_upper) self.save_value_to_workflow('var_name_again', var_name_again_reverse) # and call our super to continue processing return super().form_valid(form) # Again override the ProvisionSnippetView as we are only building a workflow here. # CNCBaseFormView will only display the form and perform a redirect after 'form_valid' # however, ProvisionSnippetView will actually redirect to another CNC class based in the skillet type # I.e. this is where the logic of how to interact with APIs, PAN-OS devies, render templates, etc is all done # You usually want a child of this class to the 'last' in a chain if you need extended logic class ExampleAppPasswordView(ProvisionSnippetView): def get_snippet(self): return self.snippet # this method allows us to customize what is shown to the user beyond what is present in the loaded skillet # 'variables' section def generate_dynamic_form(self): # let's first get the generated from from our base class dynamic_form = super().generate_dynamic_form() dynamic_form.fields['password_2'] = forms.CharField(widget=forms.PasswordInput(render_value=True), initial='') return dynamic_form # the user has now completed the form and we have the results def form_valid(self, form): # Everything the user has entered will be available here in the 'workflow' # Note that any 'variable' entries defined in the .meta-cnc snippet will # be automatically added to the session workflow workflow = self.get_workflow() # get the values from the user submitted here var_name = workflow.get('var_name') var_name_again = workflow.get('var_name_again') example_password = workflow.get('example_password') # to access variables that were not defined in the snippet # you can grab them directly from the POST on the request object password_2 = self.request.POST['password_2'] print(f'checking if {example_password} matches {password_2}') if example_password != password_2: # Send an error message back to the user messages.add_message(self.request, messages.ERROR, 'Passwords do not match!') return HttpResponseRedirect('workflow00') print('Got some vars here!') print(f'Found value for var_name: {var_name}') print(f'Found another value for var_name_again {var_name_again}') return super().form_valid(form)
44.163793
111
0.728479
750
5,123
4.864
0.364
0.038377
0.032895
0.011513
0.077029
0.044682
0.033443
0
0
0
0
0.002976
0.212961
5,123
115
112
44.547826
0.901786
0.585204
0
0.114286
0
0
0.162397
0
0
0
0
0
0
1
0.114286
false
0.2
0.114286
0.028571
0.428571
0.114286
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
0
0
1
48e84fceaf520fea1c5ef759977376465d7f8dcf
1,514
py
Python
tests/test_docs.py
gitter-badger/pygsuite
536766c36f653edbc7585141f1c3327f508e19da
[ "MIT" ]
null
null
null
tests/test_docs.py
gitter-badger/pygsuite
536766c36f653edbc7585141f1c3327f508e19da
[ "MIT" ]
null
null
null
tests/test_docs.py
gitter-badger/pygsuite
536766c36f653edbc7585141f1c3327f508e19da
[ "MIT" ]
null
null
null
from pygsuite import DefaultFonts, TextStyle, Color from pygsuite.docs.doc_elements.paragraph import Paragraph BRIGHT_GREEN_HEX = "#72FF33" def test_text(test_document): document = test_document docbody = document.body docbody.delete() docbody.add_text( "TEST_CUSTOM\n", style=TextStyle(font_size=18, font_weight=200, color=Color(hex=BRIGHT_GREEN_HEX)), ) docbody.add_text("TEST_DEFAULT\n", style=DefaultFonts.NORMAL_TEXT) docbody.add_text("TEST_INDEX\n", style=DefaultFonts.NORMAL_TEXT, position=1) document.flush() text = [item for item in document.body if isinstance(item, Paragraph)] assert text[0].text.strip() == "TEST_INDEX" assert text[2].text.strip() == "TEST_DEFAULT" # TODO: return style objects assert text[1].elements[0].style.font_size == 18 def test_paragraph(test_document): document = test_document docbody = document.body docbody.delete() docbody.add_text( "TEST_CUSTOM\n", style=TextStyle(font_size=18, font_weight=200, color=Color(hex=BRIGHT_GREEN_HEX)), ) docbody.flush() docbody.content[1].text = "TEST_CUSTOM_SETTER" docbody.add_text("INSERT\n", position=0) docbody.flush() docbody.paragraphs[1].elements[0].style = TextStyle( font_size=24, font_weight=500, color=Color(hex=BRIGHT_GREEN_HEX) ) docbody.flush() assert docbody.content[2].text.strip() == "TEST_CUSTOM_SETTER" assert docbody.paragraphs[1].elements[0].style.font_size == 24
33.644444
90
0.707398
204
1,514
5.053922
0.264706
0.046557
0.067895
0.069835
0.499515
0.445199
0.353055
0.353055
0.310378
0.310378
0
0.027778
0.167768
1,514
44
91
34.409091
0.790476
0.017173
0
0.416667
0
0
0.084118
0
0
0
0
0.022727
0.138889
1
0.055556
false
0
0.055556
0
0.111111
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
48e948236c66512a216844a7ad0e87904606f55a
2,034
py
Python
flask_oauth2_login/base.py
BasicBeluga/flask-oauth2-login
5a12ec70bcea72b2de079c072213be54f29b70b7
[ "MIT" ]
42
2015-01-13T08:51:04.000Z
2022-01-14T04:15:31.000Z
flask_oauth2_login/base.py
BasicBeluga/flask-oauth2-login
5a12ec70bcea72b2de079c072213be54f29b70b7
[ "MIT" ]
5
2015-04-29T19:31:11.000Z
2020-03-28T19:37:43.000Z
flask_oauth2_login/base.py
BasicBeluga/flask-oauth2-login
5a12ec70bcea72b2de079c072213be54f29b70b7
[ "MIT" ]
28
2015-06-16T20:30:40.000Z
2021-04-08T15:33:10.000Z
from flask import request, session, url_for from requests_oauthlib import OAuth2Session class OAuth2Login(object): def __init__(self, app=None): if app: self.init_app(app) self.app = app def get_config(self, app, name, default_value=None): return app.config.get(self.config_prefix + name, default_value) def init_app(self, app): self.client_id = self.get_config(app, "CLIENT_ID") self.client_secret = self.get_config(app, "CLIENT_SECRET") self.scope = self.get_config(app, "SCOPE", self.default_scope).split(",") self.redirect_scheme = self.get_config(app, "REDIRECT_SCHEME", "https") app.add_url_rule( self.get_config(app, "REDIRECT_PATH", self.default_redirect_path), self.redirect_endpoint, self.login, ) @property def redirect_uri(self): return url_for( self.redirect_endpoint, _external=True, _scheme=self.redirect_scheme, ) def session(self): return OAuth2Session( self.client_id, redirect_uri=self.redirect_uri, scope=self.scope, ) def authorization_url(self, **kwargs): sess = self.session() auth_url, state = sess.authorization_url(self.auth_url, **kwargs) session[self.state_session_key] = state return auth_url def login(self): sess = self.session() # Get token try: sess.fetch_token( self.token_url, code=request.args["code"], client_secret=self.client_secret, ) # TODO: Check state except Warning: # Ignore warnings pass except Exception as e: return self.login_failure_func(e) # Get profile try: profile = self.get_profile(sess) except Exception as e: return self.login_failure_func(e) return self.login_success_func(sess.token, profile) def login_success(self, f): self.login_success_func = f return f def login_failure(self, f): self.login_failure_func = f return f def get_profile(self, sess): raise NotImplementedError
24.214286
77
0.675025
270
2,034
4.848148
0.262963
0.041253
0.049656
0.061115
0.161956
0.068755
0.068755
0.068755
0.068755
0.068755
0
0.001901
0.224189
2,034
83
78
24.506024
0.82763
0.02704
0
0.193548
0
0
0.032945
0
0
0
0
0.012048
0
1
0.16129
false
0.016129
0.032258
0.048387
0.354839
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
48f141e3c4e406a1ed8e50060eb75658e2cb4aab
202
py
Python
apps/summary/urls.py
sotkonstantinidis/testcircle
448aa2148fbc2c969e60f0b33ce112d4740a8861
[ "Apache-2.0" ]
3
2019-02-24T14:24:43.000Z
2019-10-24T18:51:32.000Z
apps/summary/urls.py
sotkonstantinidis/testcircle
448aa2148fbc2c969e60f0b33ce112d4740a8861
[ "Apache-2.0" ]
17
2017-03-14T10:55:56.000Z
2022-03-11T23:20:19.000Z
apps/summary/urls.py
sotkonstantinidis/testcircle
448aa2148fbc2c969e60f0b33ce112d4740a8861
[ "Apache-2.0" ]
2
2016-02-01T06:32:40.000Z
2019-09-06T04:33:50.000Z
from django.conf.urls import url from .views import SummaryPDFCreateView urlpatterns = [ url(r'^(?P<id>[\d]+)/$', SummaryPDFCreateView.as_view(), name='questionnaire_summary'), ]
18.363636
39
0.658416
22
202
5.954545
0.818182
0
0
0
0
0
0
0
0
0
0
0
0.188119
202
10
40
20.2
0.79878
0
0
0
0
0
0.183168
0.10396
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
48f9edbd6a5a7ba5a520ddc41c7a0b91f9666bf5
1,382
py
Python
cosmic_ray/operators/unary_operator_replacement.py
rob-smallshire/cosmic-ray
4fd751b38eee30568f8366e09452d7aa60be4e26
[ "MIT" ]
null
null
null
cosmic_ray/operators/unary_operator_replacement.py
rob-smallshire/cosmic-ray
4fd751b38eee30568f8366e09452d7aa60be4e26
[ "MIT" ]
null
null
null
cosmic_ray/operators/unary_operator_replacement.py
rob-smallshire/cosmic-ray
4fd751b38eee30568f8366e09452d7aa60be4e26
[ "MIT" ]
null
null
null
"""Implementation of the unary-operator-replacement operator. """ import ast from .operator import Operator from ..util import build_mutations # None indicates we want to delete the operator OPERATORS = (ast.UAdd, ast.USub, ast.Invert, ast.Not, None) def _to_ops(from_op): """ The sequence of operators which `from_op` could be mutated to. """ for to_op in OPERATORS: if to_op and isinstance(from_op, ast.Not): # 'not' can only be removed but not replaced with # '+', '-' or '~' b/c that may lead to strange results pass elif isinstance(from_op, ast.UAdd) and (to_op is None): # '+1' => '1' yields equivalent mutations pass else: yield to_op class MutateUnaryOperator(Operator): """An operator that modifies unary operators.""" def visit_UnaryOp(self, node): # pylint: disable=invalid-name """ http://greentreesnakes.readthedocs.io/en/latest/nodes.html#UnaryOp """ return self.visit_mutation_site( node, len(build_mutations([node.op], _to_ops))) def mutate(self, node, idx): "Perform the `idx`th mutation on node." _, to_op = build_mutations([node.op], _to_ops)[idx] if to_op: node.op = to_op() return node return node.operand
28.791667
78
0.607815
179
1,382
4.558659
0.49162
0.034314
0.029412
0.046569
0.061275
0.061275
0
0
0
0
0
0.00203
0.287265
1,382
47
79
29.404255
0.826396
0.351664
0
0.083333
0
0
0.042431
0
0
0
0
0
0
1
0.125
false
0.083333
0.125
0
0.416667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
48fa5657a82772ca80f844d0c1f8bca709ceaf35
2,069
py
Python
src/icolos/core/workflow_steps/calculation/rmsd.py
jharrymoore/Icolos
c60cc00c34208ab7011d41d52a74651763673e7a
[ "Apache-2.0" ]
11
2022-01-30T14:36:13.000Z
2022-03-22T09:40:57.000Z
src/icolos/core/workflow_steps/calculation/rmsd.py
jharrymoore/Icolos
c60cc00c34208ab7011d41d52a74651763673e7a
[ "Apache-2.0" ]
2
2022-03-23T07:56:49.000Z
2022-03-24T12:01:42.000Z
src/icolos/core/workflow_steps/calculation/rmsd.py
jharrymoore/Icolos
c60cc00c34208ab7011d41d52a74651763673e7a
[ "Apache-2.0" ]
8
2022-01-28T10:32:31.000Z
2022-03-22T09:40:59.000Z
from typing import List from pydantic import BaseModel from icolos.core.containers.compound import Conformer, unroll_conformers from icolos.utils.enums.step_enums import StepRMSDEnum, StepDataManipulationEnum from icolos.core.workflow_steps.step import _LE from icolos.core.workflow_steps.calculation.base import StepCalculationBase _SR = StepRMSDEnum() _SDM = StepDataManipulationEnum() class StepRMSD(StepCalculationBase, BaseModel): def __init__(self, **data): super().__init__(**data) # extend parameters if _SR.METHOD not in self.settings.additional.keys(): self.settings.additional[_SR.METHOD] = _SR.METHOD_ALIGNMOL def _calculate_RMSD(self, conformers: List[Conformer]): for conf in conformers: rmsd_matrix = self._calculate_rms_matrix( conformers=[conf] + conf.get_extra_data()[_SDM.KEY_MATCHED], rms_method=self._get_rms_method(), ) # use the specified tag name if it is the first value and append an index in case there are more for idx, col in enumerate(rmsd_matrix.columns[1:]): combined_tag = "".join([_SR.RMSD_TAG, "" if idx == 0 else str(idx)]) rmsd_value = rmsd_matrix.iloc[[0]][col][0] conf.get_molecule().SetProp(combined_tag, str(rmsd_value)) conf.get_extra_data()[_SDM.KEY_MATCHED][idx].get_molecule().SetProp( combined_tag, str(rmsd_value) ) def execute(self): # this assumes that the conformers that are to be matched for the calculation of the RMSD matrix, are attached # as a list in a generic data field with a specified key conformers = unroll_conformers(compounds=self.get_compounds()) self._calculate_RMSD(conformers=conformers) self._logger.log( f"Annotated {len(conformers)} conformers with RMSD values (tag: {_SR.RMSD_TAG}).", _LE.INFO, ) # TODO: add a nice pandas DF with the RMSD values to a generic data field
43.104167
118
0.669889
261
2,069
5.091954
0.417625
0.030098
0.031603
0.033108
0.145974
0.105342
0.105342
0.061701
0
0
0
0.002553
0.242629
2,069
47
119
44.021277
0.845565
0.168197
0
0
0
0
0.045481
0
0
0
0
0.021277
0
1
0.090909
false
0
0.181818
0
0.30303
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
5b011773dfebfb2a161d58f218cd80c611a2ea9c
578
py
Python
app_metrics.py
GSH-LAN/byceps
ab8918634e90aaa8574bd1bb85627759cef122fe
[ "BSD-3-Clause" ]
33
2018-01-16T02:04:51.000Z
2022-03-22T22:57:29.000Z
app_metrics.py
GSH-LAN/byceps
ab8918634e90aaa8574bd1bb85627759cef122fe
[ "BSD-3-Clause" ]
7
2019-06-16T22:02:03.000Z
2021-10-02T13:45:31.000Z
app_metrics.py
GSH-LAN/byceps
ab8918634e90aaa8574bd1bb85627759cef122fe
[ "BSD-3-Clause" ]
14
2019-06-01T21:39:24.000Z
2022-03-14T17:56:43.000Z
""" metrics application instance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ import os from byceps.config import ConfigurationError from byceps.metrics.application import create_app ENV_VAR_NAME_DATABASE_URI = 'DATABASE_URI' database_uri = os.environ.get(ENV_VAR_NAME_DATABASE_URI) if not database_uri: raise ConfigurationError( f"No database URI was specified via the '{ENV_VAR_NAME_DATABASE_URI}' " "environment variable.", ) app = create_app(database_uri)
22.230769
79
0.730104
73
578
5.534247
0.561644
0.217822
0.074257
0.133663
0.155941
0
0
0
0
0
0
0.01626
0.148789
578
25
80
23.12
0.804878
0.269896
0
0
0
0
0.243961
0.070048
0
0
0
0
0
1
0
false
0
0.272727
0
0.272727
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
0
0
0
1
5b084682efe35e9ca46aead0d385f2c28ccda23b
5,630
py
Python
apps/user/views.py
awsbreathpanda/dailyfresh
c218cdc3ea261b695ff00b6781ba3040f5d06eff
[ "MIT" ]
null
null
null
apps/user/views.py
awsbreathpanda/dailyfresh
c218cdc3ea261b695ff00b6781ba3040f5d06eff
[ "MIT" ]
7
2021-03-30T14:18:30.000Z
2022-01-13T03:13:37.000Z
apps/user/views.py
awsbreathpanda/dailyfresh
c218cdc3ea261b695ff00b6781ba3040f5d06eff
[ "MIT" ]
null
null
null
from django.shortcuts import redirect from django.contrib.auth import authenticate, login, logout from celery_tasks.tasks import celery_send_mail from apps.user.models import User import re from django.shortcuts import render from django.views import View from utils.security import get_user_token, get_activation_link, get_user_id from django.conf import settings from django.http import HttpResponse from django.urls import reverse # Create your views here. # /user/register class RegisterView(View): def get(self, request): return render(request, 'user_register.html') def post(self, request): username = request.POST.get('username') password = request.POST.get('password') rpassword = request.POST.get('rpassword') email = request.POST.get('email') allow = request.POST.get('allow') if not all([username, password, rpassword, email, allow]): context = {'errmsg': '数据不完整'} return render(request, 'user_register.html', context=context) if password != rpassword: context = {'errmsg': '密码不一致'} return render(request, 'user_register.html', context=context) if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email): context = {'errmsg': '邮箱格式不正确'} return render(request, 'user_register.html', context=context) if allow != 'on': context = {'errmsg': '请同意天天生鲜用户协议'} try: user = User.objects.get(username=username) except User.DoesNotExist: user = None if user is not None: context = {'errmsg': '已经创建该用户名'} return render(request, 'user_register.html', context=context) user = User.objects.create_user(username, email, password) user.is_active = 0 user.save() user_token = get_user_token(user.id) activation_link = get_activation_link(settings.ACTIVATION_URL_PATH, user_token) # send email subject = '天天生鲜欢迎信息' message = '' html_message = ( '<h1>%s,欢迎您成为天天生鲜的注册会员</h1><p>请点击以下链接激活你的账户</p><br><a href="%s">%s</a>' % (username, activation_link, activation_link)) from_email = 'dailyfresh<awsbreathpanda@163.com>' recipient_list = [ 'awsbreathpanda@163.com', ] celery_send_mail.delay(subject, message, from_email, recipient_list, html_message=html_message) context = {'errmsg': '添加用户成功'} return render(request, 'user_register.html', context=context) # /user/activate/(token) class ActivateView(View): def get(self, request, token): token_bytes = token.encode('utf-8') user_id = get_user_id(token_bytes) user = User.objects.get(id=user_id) user.is_active = 1 user.save() # TODO return HttpResponse('<h1>Activate User Successfully</h1>') # /user/login class LoginView(View): def get(self, request): username = request.COOKIES.get('username') checked = 'checked' if username is None: username = '' checked = '' context = {'username': username, 'checked': checked} return render(request, 'user_login.html', context=context) def post(self, request): username = request.POST.get('username') password = request.POST.get('password') remember = request.POST.get('remember') if not all([username, password]): context = {'errmsg': '参数不完整'} return render(request, 'user_login.html', context=context) user = authenticate(request, username=username, password=password) if user is None: context = {'errmsg': '用户不存在'} return render(request, 'user_login.html', context=context) if not user.is_active: context = {'errmsg': '用户未激活'} return render(request, 'user_login.html', context=context) login(request, user) next_url = request.GET.get('next', reverse('goods:index')) response = redirect(next_url) if remember == 'on': response.set_cookie('username', username, max_age=7 * 24 * 3600) else: response.delete_cookie('username') return response # /user/ class UserInfoView(View): def get(self, request): if not request.user.is_authenticated: next_url = reverse( 'user:login') + '?next=' + request.get_full_path() return redirect(next_url) else: return render(request, 'user_center_info.html') # /user/order/(page) class UserOrderView(View): def get(self, request, page): if not request.user.is_authenticated: next_url = reverse( 'user:login') + '?next=' + request.get_full_path() return redirect(next_url) else: return render(request, 'user_center_order.html') # /user/address class UserAddressView(View): def get(self, request): if not request.user.is_authenticated: next_url = reverse( 'user:login') + '?next=' + request.get_full_path() return redirect(next_url) else: return render(request, 'user_center_site.html') # /user/logout class LogoutView(View): def get(self, request): logout(request) return redirect(reverse('goods:index'))
31.80791
83
0.59325
622
5,630
5.249196
0.226688
0.057274
0.075651
0.091577
0.375804
0.326493
0.315773
0.315773
0.259418
0.180092
0
0.006986
0.288099
5,630
176
84
31.988636
0.807635
0.025222
0
0.296875
0
0.015625
0.136571
0.040351
0
0
0
0.005682
0
1
0.070313
false
0.0625
0.085938
0.007813
0.359375
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
5b0af9dfbe74e34130cf9a393f33916249893c28
8,315
py
Python
kubernetes-the-hard-way/system/collections/ansible_collections/community/general/plugins/modules/cloud/misc/proxmox_template.py
jkroepke/homelab
ffdd849e39b52972870f5552e734fd74cb1254a1
[ "Apache-2.0" ]
5
2020-12-16T21:42:09.000Z
2022-03-28T16:04:32.000Z
kubernetes-the-hard-way/system/collections/ansible_collections/community/general/plugins/modules/cloud/misc/proxmox_template.py
jkroepke/kubernetes-the-hard-way
70fd096a04addec0777744c9731a4e3fbdc40c8f
[ "Apache-2.0" ]
null
null
null
kubernetes-the-hard-way/system/collections/ansible_collections/community/general/plugins/modules/cloud/misc/proxmox_template.py
jkroepke/kubernetes-the-hard-way
70fd096a04addec0777744c9731a4e3fbdc40c8f
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # # Copyright: Ansible Project # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: proxmox_template short_description: management of OS templates in Proxmox VE cluster description: - allows you to upload/delete templates in Proxmox VE cluster options: api_host: description: - the host of the Proxmox VE cluster type: str required: true api_user: description: - the user to authenticate with type: str required: true api_password: description: - the password to authenticate with - you can use PROXMOX_PASSWORD environment variable type: str validate_certs: description: - enable / disable https certificate verification default: 'no' type: bool node: description: - Proxmox VE node, when you will operate with template type: str required: true src: description: - path to uploaded file - required only for C(state=present) type: path template: description: - the template name - required only for states C(absent), C(info) type: str content_type: description: - content type - required only for C(state=present) type: str default: 'vztmpl' choices: ['vztmpl', 'iso'] storage: description: - target storage type: str default: 'local' timeout: description: - timeout for operations type: int default: 30 force: description: - can be used only with C(state=present), exists template will be overwritten type: bool default: 'no' state: description: - Indicate desired state of the template type: str choices: ['present', 'absent'] default: present notes: - Requires proxmoxer and requests modules on host. This modules can be installed with pip. requirements: [ "proxmoxer", "requests" ] author: Sergei Antipov (@UnderGreen) ''' EXAMPLES = ''' - name: Upload new openvz template with minimal options community.general.proxmox_template: node: uk-mc02 api_user: root@pam api_password: 1q2w3e api_host: node1 src: ~/ubuntu-14.04-x86_64.tar.gz - name: > Upload new openvz template with minimal options use environment PROXMOX_PASSWORD variable(you should export it before) community.general.proxmox_template: node: uk-mc02 api_user: root@pam api_host: node1 src: ~/ubuntu-14.04-x86_64.tar.gz - name: Upload new openvz template with all options and force overwrite community.general.proxmox_template: node: uk-mc02 api_user: root@pam api_password: 1q2w3e api_host: node1 storage: local content_type: vztmpl src: ~/ubuntu-14.04-x86_64.tar.gz force: yes - name: Delete template with minimal options community.general.proxmox_template: node: uk-mc02 api_user: root@pam api_password: 1q2w3e api_host: node1 template: ubuntu-14.04-x86_64.tar.gz state: absent ''' import os import time try: from proxmoxer import ProxmoxAPI HAS_PROXMOXER = True except ImportError: HAS_PROXMOXER = False from ansible.module_utils.basic import AnsibleModule def get_template(proxmox, node, storage, content_type, template): return [True for tmpl in proxmox.nodes(node).storage(storage).content.get() if tmpl['volid'] == '%s:%s/%s' % (storage, content_type, template)] def upload_template(module, proxmox, api_host, node, storage, content_type, realpath, timeout): taskid = proxmox.nodes(node).storage(storage).upload.post(content=content_type, filename=open(realpath, 'rb')) while timeout: task_status = proxmox.nodes(api_host.split('.')[0]).tasks(taskid).status.get() if task_status['status'] == 'stopped' and task_status['exitstatus'] == 'OK': return True timeout = timeout - 1 if timeout == 0: module.fail_json(msg='Reached timeout while waiting for uploading template. Last line in task before timeout: %s' % proxmox.node(node).tasks(taskid).log.get()[:1]) time.sleep(1) return False def delete_template(module, proxmox, node, storage, content_type, template, timeout): volid = '%s:%s/%s' % (storage, content_type, template) proxmox.nodes(node).storage(storage).content.delete(volid) while timeout: if not get_template(proxmox, node, storage, content_type, template): return True timeout = timeout - 1 if timeout == 0: module.fail_json(msg='Reached timeout while waiting for deleting template.') time.sleep(1) return False def main(): module = AnsibleModule( argument_spec=dict( api_host=dict(required=True), api_user=dict(required=True), api_password=dict(no_log=True), validate_certs=dict(type='bool', default=False), node=dict(), src=dict(type='path'), template=dict(), content_type=dict(default='vztmpl', choices=['vztmpl', 'iso']), storage=dict(default='local'), timeout=dict(type='int', default=30), force=dict(type='bool', default=False), state=dict(default='present', choices=['present', 'absent']), ) ) if not HAS_PROXMOXER: module.fail_json(msg='proxmoxer required for this module') state = module.params['state'] api_user = module.params['api_user'] api_host = module.params['api_host'] api_password = module.params['api_password'] validate_certs = module.params['validate_certs'] node = module.params['node'] storage = module.params['storage'] timeout = module.params['timeout'] # If password not set get it from PROXMOX_PASSWORD env if not api_password: try: api_password = os.environ['PROXMOX_PASSWORD'] except KeyError as e: module.fail_json(msg='You should set api_password param or use PROXMOX_PASSWORD environment variable') try: proxmox = ProxmoxAPI(api_host, user=api_user, password=api_password, verify_ssl=validate_certs) except Exception as e: module.fail_json(msg='authorization on proxmox cluster failed with exception: %s' % e) if state == 'present': try: content_type = module.params['content_type'] src = module.params['src'] template = os.path.basename(src) if get_template(proxmox, node, storage, content_type, template) and not module.params['force']: module.exit_json(changed=False, msg='template with volid=%s:%s/%s is already exists' % (storage, content_type, template)) elif not src: module.fail_json(msg='src param to uploading template file is mandatory') elif not (os.path.exists(src) and os.path.isfile(src)): module.fail_json(msg='template file on path %s not exists' % src) if upload_template(module, proxmox, api_host, node, storage, content_type, src, timeout): module.exit_json(changed=True, msg='template with volid=%s:%s/%s uploaded' % (storage, content_type, template)) except Exception as e: module.fail_json(msg="uploading of template %s failed with exception: %s" % (template, e)) elif state == 'absent': try: content_type = module.params['content_type'] template = module.params['template'] if not template: module.fail_json(msg='template param is mandatory') elif not get_template(proxmox, node, storage, content_type, template): module.exit_json(changed=False, msg='template with volid=%s:%s/%s is already deleted' % (storage, content_type, template)) if delete_template(module, proxmox, node, storage, content_type, template, timeout): module.exit_json(changed=True, msg='template with volid=%s:%s/%s deleted' % (storage, content_type, template)) except Exception as e: module.fail_json(msg="deleting of template %s failed with exception: %s" % (template, e)) if __name__ == '__main__': main()
33.26
138
0.657486
1,046
8,315
5.108031
0.209369
0.047352
0.047165
0.058394
0.457795
0.381995
0.341943
0.312371
0.273629
0.24855
0
0.010902
0.238845
8,315
249
139
33.393574
0.833307
0.022489
0
0.36019
0
0
0.463679
0.030781
0
0
0
0
0
1
0.018957
false
0.061611
0.028436
0.004739
0.07109
0.004739
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
0
0
1
5b1a34dd97d2ac3c30c9847cc931832f35fa692e
7,854
py
Python
startup/97-standard-plans.py
MikeHart85/SIX_profile_collection
f4b34add0c464006a1310375b084c63597b6baf0
[ "BSD-3-Clause" ]
null
null
null
startup/97-standard-plans.py
MikeHart85/SIX_profile_collection
f4b34add0c464006a1310375b084c63597b6baf0
[ "BSD-3-Clause" ]
null
null
null
startup/97-standard-plans.py
MikeHart85/SIX_profile_collection
f4b34add0c464006a1310375b084c63597b6baf0
[ "BSD-3-Clause" ]
null
null
null
def pol_V(offset=None): yield from mv(m1_simple_fbk,0) cur_mono_e = pgm.en.user_readback.value yield from mv(epu1.table,6) # 4 = 3rd harmonic; 6 = "testing V" 1st harmonic if offset is not None: yield from mv(epu1.offset,offset) yield from mv(epu1.phase,28.5) yield from mv(pgm.en,cur_mono_e+1) #TODO this is dirty trick. figure out how to process epu.table.input yield from mv(pgm.en,cur_mono_e) yield from mv(m1_simple_fbk,1) print('\nFinished moving the polarization to vertical.\n\tNote that the offset for epu calibration is {}eV.\n\n'.format(offset)) def pol_H(offset=None): yield from mv(m1_simple_fbk,0) cur_mono_e = pgm.en.user_readback.value yield from mv(epu1.table,5) # 2 = 3rd harmonic; 5 = "testing H" 1st harmonic if offset is not None: yield from mv(epu1.offset,offset) yield from mv(epu1.phase,0) yield from mv(pgm.en,cur_mono_e+1) #TODO this is dirty trick. figure out how to process epu.table.input yield from mv(pgm.en,cur_mono_e) yield from mv(m1_simple_fbk,1) print('\nFinished moving the polarization to horizontal.\n\tNote that the offset for epu calibration is {}eV.\n\n'.format(offset)) def m3_check(): yield from mv(m3_simple_fbk,0) sclr_enable() if pzshutter.value == 0: print('Piezo Shutter is disabled') flag = 0 if pzshutter.value == 2: print('Piezo Shutter is enabled: going to be disabled') yield from pzshutter_disable() flag = 1 temp_extslt_vg=extslt.vg.user_readback.value temp_extslt_hg=extslt.hg.user_readback.value temp_gcdiag = gcdiag.y.user_readback.value #yield from mv(qem07.averaging_time, 1) yield from mv(sclr.preset_time, 1) yield from mv(extslt.hg,10) yield from mv(extslt.vg,30) #yield from gcdiag.grid # RE-COMMENT THIS LINE 5/7/2019 #yield from rel_scan([qem07],m3.pit,-0.0005,0.0005,31, md = {'reason':'checking m3 before cff'}) yield from rel_scan([sclr],m3.pit,-0.0005,0.0005,31, md = {'reason':'checking m3'}) #yield from mv(m3.pit,peaks['cen']['gc_diag_grid']) yield from mv(m3.pit,peaks['cen']['sclr_channels_chan8']) #yield from mv(m3.pit,peaks['cen']['sclr_channels_chan2']) yield from mv(extslt.hg,temp_extslt_hg) yield from mv(extslt.vg,temp_extslt_vg) yield from mv(gcdiag.y,temp_gcdiag) yield from sleep(20) #yield from mv(m1_fbk_sp,extslt_cam.stats1.centroid.x.value) yield from mv(m3_simple_fbk_target,extslt_cam.stats1.centroid.x.value)#m3_simple_fbk_cen.value) yield from mv(m3_simple_fbk,1) if flag == 0: print('Piezo Shutter remains disabled') if flag == 1: print('Piezo Shutter is going to renabled') yield from pzshutter_enable() def m1_align_fine2(): m1x_init=m1.x.user_readback.value m1pit_init=m1.pit.user_readback.value m1pit_step=50 m1pit_start=m1pit_init-1*m1pit_step for i in range(0,5): yield from mv(m1.pit,m1pit_start+i*m1pit_step) yield from scan([qem05],m1.x,-3,3.8,35) yield from mv(m1.pit,m1pit_init) yield from mv(m1.x,m1x_init) def alignM3x(): # get the exit slit positions to return to at the end vg_init = extslt.vg.user_setpoint.value hg_init = extslt.hg.user_setpoint.value hc_init = extslt.hc.user_setpoint.value print('Saving exit slit positions for later') # get things out of the way yield from m3diag.out # read gas cell diode yield from gcdiag.grid # set detector e.g. gas cell diagnostics qem detList=[qem07] #[sclr] # set V exit slit value to get enough signal yield from mv(extslt.vg, 30) # open H slit full open yield from mv(extslt.hg, 9000) #move extslt.hs appropriately and scan m3.x yield from mv(extslt.hc,-9) yield from relative_scan(detList,m3.x,-6,6,61) yield from mv(extslt.hc,-3) yield from relative_scan(detList,m3.x,-6,6,61) yield from mv(extslt.hc,3) yield from relative_scan(detList,m3.x,-6,6,61) print('Returning exit slit positions to the inital values') yield from mv(extslt.hc,hc_init) yield from mv(extslt.vg, vg_init, extslt.hg, hg_init) def beamline_align(): yield from mv(m1_fbk,0) yield from align.m1pit yield from sleep(5) yield from m3_check() #yield from mv(m1_fbk_cam_time,0.002) #yield from mv(m1_fbk_th,1500) yield from sleep(5) yield from mv(m1_fbk_sp,extslt_cam.stats1.centroid.x.value) yield from mv(m1_fbk,1) def beamline_align_v2(): yield from mv(m1_simple_fbk,0) yield from mv(m3_simple_fbk,0) yield from mv(m1_fbk,0) yield from align.m1pit yield from sleep(5) yield from mv(m1_simple_fbk_target_ratio,m1_simple_fbk_ratio.value) yield from mv(m1_simple_fbk,1) yield from sleep(5) yield from m3_check() def xas(dets,motor,start_en,stop_en,num_points,sec_per_point): sclr_enable() sclr_set_time=sclr.preset_time.value if pzshutter.value == 0: print('Piezo Shutter is disabled') flag = 0 if pzshutter.value == 2: print('Piezo Shutter is enabled: going to be disabled') yield from pzshutter_disable() flag = 1 yield from mv(sclr.preset_time,sec_per_point) yield from scan(dets,pgm.en,start_en,stop_en,num_points) E_max = peaks['max']['sclr_channels_chan2'][0] E_com = peaks['com']['sclr_channels_chan2'] if flag == 0: print('Piezo Shutter remains disabled') if flag == 1: print('Piezo Shutter is going to renabled') yield from pzshutter_enable() yield from mv(sclr.preset_time,sclr_set_time) return E_com, E_max #TODO put this inside of rixscam def rixscam_get_threshold(Ei = None): '''Calculate the minimum and maximum threshold for RIXSCAM single photon counting (LS mode) Ei\t:\t float - incident energy (default is beamline current energy) ''' if Ei is None: Ei = pgm.en.user_readback.value t_min = 0.7987 * Ei - 97.964 t_max = 1.4907 * Ei + 38.249 print('\n\n\tMinimum value for RIXSCAM threshold (LS mode):\t{}'.format(t_min)) print('\tMaximum value for RIXSCAM threshold (LS mode):\t{}'.format(t_max)) print('\tFor Beamline Energy:\t\t\t\t{}'.format(Ei)) return t_min, t_max #TODO put this insdie of rixscam def rixscam_set_threshold(Ei=None): '''Setup the RIXSCAM.XIP plugin values for a specific energy for single photon counting and centroiding in LS mode. Ei\t:\t float - incident energy (default is beamline current energy) ''' if Ei is None: Ei = pgm.en.user_readback.value thold_min, thold_max = rixscam_get_threshold(Ei) yield from mv(rixscam.xip.beamline_energy, Ei, rixscam.xip.sum_3x3_threshold_min, thold_min, rixscam.xip.sum_3x3_threshold_max, thold_max) #TODO make official so that there is a m1_fbk device like m1fbk.setpoint m1_fbk = EpicsSignal('XF:02IDA-OP{FBck}Sts:FB-Sel', name = 'm1_fbk') m1_fbk_sp = EpicsSignal('XF:02IDA-OP{FBck}PID-SP', name = 'm1_fbk_sp') m1_fbk_th = extslt_cam.stats1.centroid_threshold #m1_fbk_pix_x = extslt_cam.stats1.centroid.x.value m1_fbk_cam_time = extslt_cam.cam.acquire_time #(mv(m1_fbk_th,1500) m1_simple_fbk = EpicsSignal('XF:02IDA-OP{M1_simp_feed}FB-Ena', name = 'm1_simple_fbk') m1_simple_fbk_target_ratio = EpicsSignal('XF:02IDA-OP{M1_simp_feed}FB-TarRat', name = 'm1_simple_fbk_target_ratio') m1_simple_fbk_ratio = EpicsSignal('XF:02IDA-OP{M1_simp_feed}FB-Ratio', name = 'm1_simple_fbk_ratio') m3_simple_fbk = EpicsSignal('XF:02IDA-OP{M3_simp_feed}FB-Ena', name = 'm3_simple_fbk') m3_simple_fbk_target = EpicsSignal('XF:02IDA-OP{M3_simp_feed}FB-Targ', name = 'm3_simple_fbk_target') m3_simple_fbk_cen = EpicsSignal('XF:02IDA-OP{M3_simp_feed}FB_inpbuf', name = 'm3_simple_fbk_cen')
37.222749
134
0.697734
1,325
7,854
3.953208
0.193962
0.127148
0.107102
0.042192
0.60252
0.537801
0.488736
0.449599
0.414662
0.358725
0
0.043218
0.192768
7,854
210
135
37.4
0.782965
0.188566
0
0.434483
0
0.013793
0.183099
0.042887
0
0
0
0.014286
0
1
0.068966
false
0
0
0
0.082759
0.103448
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
5b1ed26356ab2b3641b50b827cab69738be819bd
15,878
py
Python
datasets/imppres/imppres.py
ddhruvkr/datasets-1
66f2a7eece98d2778bd22bb5034cb7c2376032d4
[ "Apache-2.0" ]
7
2021-01-04T22:18:26.000Z
2021-07-10T09:13:29.000Z
datasets/imppres/imppres.py
ddhruvkr/datasets-1
66f2a7eece98d2778bd22bb5034cb7c2376032d4
[ "Apache-2.0" ]
null
null
null
datasets/imppres/imppres.py
ddhruvkr/datasets-1
66f2a7eece98d2778bd22bb5034cb7c2376032d4
[ "Apache-2.0" ]
3
2021-01-03T22:08:20.000Z
2021-08-12T20:09:39.000Z
# coding=utf-8 # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. """Over 25k semiautomatically generated sentence pairs illustrating well-studied pragmatic inference types. IMPPRES is an NLI dataset following the format of SNLI (Bowman et al., 2015), MultiNLI (Williams et al., 2018) and XNLI (Conneau et al., 2018), which was created to evaluate how well trained NLI models recognize several classes of presuppositions and scalar implicatures.""" from __future__ import absolute_import, division, print_function import json import os import datasets # Find for instance the citation on arxiv or on the dataset repo/website _CITATION = """\ @inproceedings{jeretic-etal-2020-natural, title = "Are Natural Language Inference Models {IMPPRESsive}? {L}earning {IMPlicature} and {PRESupposition}", author = "Jereti\v{c}, Paloma and Warstadt, Alex and Bhooshan, Suvrat and Williams, Adina", booktitle = "Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics", month = jul, year = "2020", address = "Online", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/2020.acl-main.768", doi = "10.18653/v1/2020.acl-main.768", pages = "8690--8705", abstract = "Natural language inference (NLI) is an increasingly important task for natural language understanding, which requires one to infer whether a sentence entails another. However, the ability of NLI models to make pragmatic inferences remains understudied. We create an IMPlicature and PRESupposition diagnostic dataset (IMPPRES), consisting of 32K semi-automatically generated sentence pairs illustrating well-studied pragmatic inference types. We use IMPPRES to evaluate whether BERT, InferSent, and BOW NLI models trained on MultiNLI (Williams et al., 2018) learn to make pragmatic inferences. Although MultiNLI appears to contain very few pairs illustrating these inference types, we find that BERT learns to draw pragmatic inferences. It reliably treats scalar implicatures triggered by {``}some{''} as entailments. For some presupposition triggers like {``}only{''}, BERT reliably recognizes the presupposition as an entailment, even when the trigger is embedded under an entailment canceling operator like negation. BOW and InferSent show weaker evidence of pragmatic reasoning. We conclude that NLI training encourages models to learn some, but not all, pragmatic inferences.", } """ # You can copy an official description _DESCRIPTION = """Over >25k semiautomatically generated sentence pairs illustrating well-studied pragmatic inference types. IMPPRES is an NLI dataset following the format of SNLI (Bowman et al., 2015), MultiNLI (Williams et al., 2018) and XNLI (Conneau et al., 2018), which was created to evaluate how well trained NLI models recognize several classes of presuppositions and scalar implicatures.""" _HOMEPAGE = "https://github.com/facebookresearch/Imppres" _LICENSE = "Creative Commons Attribution-NonCommercial 4.0 International Public License" # The HuggingFace dataset library don't host the datasets but only point to the original files # This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method) _URLs = {"default": "https://github.com/facebookresearch/Imppres/blob/master/dataset/IMPPRES.zip?raw=true"} class Imppres(datasets.GeneratorBasedBuilder): """Each sentence type in IMPPRES is generated according to a template that specifies the linear order of the constituents in the sentence. The constituents are sampled from a vocabulary of over 3000 lexical items annotated with grammatical features needed to ensure wellformedness. We semiautomatically generate IMPPRES using a codebase developed by Warstadt et al. (2019a) and significantly expanded for the BLiMP dataset (Warstadt et al., 2019b).""" VERSION = datasets.Version("1.1.0") # This is an example of a dataset with multiple configurations. # If you don't want/need to define several sub-sets in your dataset, # just remove the BUILDER_CONFIG_CLASS and the BUILDER_CONFIGS attributes. # If you need to make complex sub-parts in the datasets with configurable options # You can create your own builder configuration class to store attribute, inheriting from datasets.BuilderConfig # BUILDER_CONFIG_CLASS = MyBuilderConfig # You will be able to load one or the other configurations in the following list with # data = datasets.load_dataset('my_dataset', 'first_domain') # data = datasets.load_dataset('my_dataset', 'second_domain') BUILDER_CONFIGS = [ datasets.BuilderConfig( name="presupposition_all_n_presupposition", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_both_presupposition", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_change_of_state", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_cleft_existence", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_cleft_uniqueness", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_only_presupposition", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_possessed_definites_existence", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_possessed_definites_uniqueness", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="presupposition_question_presupposition", version=VERSION, description="Presuppositions are facts that the speaker takes for granted when uttering a sentence.", ), datasets.BuilderConfig( name="implicature_connectives", version=VERSION, description="Scalar implicatures are inferences which can be drawn when one member of a memorized lexical scale is uttered.", ), datasets.BuilderConfig( name="implicature_gradable_adjective", version=VERSION, description="Scalar implicatures are inferences which can be drawn when one member of a memorized lexical scale is uttered.", ), datasets.BuilderConfig( name="implicature_gradable_verb", version=VERSION, description="Scalar implicatures are inferences which can be drawn when one member of a memorized lexical scale is uttered.", ), datasets.BuilderConfig( name="implicature_modals", version=VERSION, description="Scalar implicatures are inferences which can be drawn when one member of a memorized lexical scale is uttered.", ), datasets.BuilderConfig( name="implicature_numerals_10_100", version=VERSION, description="Scalar implicatures are inferences which can be drawn when one member of a memorized lexical scale is uttered.", ), datasets.BuilderConfig( name="implicature_numerals_2_3", version=VERSION, description="Scalar implicatures are inferences which can be drawn when one member of a memorized lexical scale is uttered.", ), datasets.BuilderConfig( name="implicature_quantifiers", version=VERSION, description="Scalar implicatures are inferences which can be drawn when one member of a memorized lexical scale is uttered.", ), ] def _info(self): if ( "presupposition" in self.config.name ): # This is the name of the configuration selected in BUILDER_CONFIGS above features = datasets.Features( { "premise": datasets.Value("string"), "hypothesis": datasets.Value("string"), "trigger": datasets.Value("string"), "trigger1": datasets.Value("string"), "trigger2": datasets.Value("string"), "presupposition": datasets.Value("string"), "gold_label": datasets.ClassLabel(names=["entailment", "neutral", "contradiction"]), "UID": datasets.Value("string"), "pairID": datasets.Value("string"), "paradigmID": datasets.Value("int16") # These are the features of your dataset like images, labels ... } ) else: # This is an example to show how to have different features for "first_domain" and "second_domain" features = datasets.Features( { "premise": datasets.Value("string"), "hypothesis": datasets.Value("string"), "gold_label_log": datasets.ClassLabel(names=["entailment", "neutral", "contradiction"]), "gold_label_prag": datasets.ClassLabel(names=["entailment", "neutral", "contradiction"]), "spec_relation": datasets.Value("string"), "item_type": datasets.Value("string"), "trigger": datasets.Value("string"), "lexemes": datasets.Value("string"), # These are the features of your dataset like images, labels ... } ) return datasets.DatasetInfo( # This is the description that will appear on the datasets page. description=_DESCRIPTION, # This defines the different columns of the dataset and their types features=features, # Here we define them above because they are different between the two configurations # If there's a common (input, target) tuple from the features, # specify them here. They'll be used if as_supervised=True in # builder.as_dataset. supervised_keys=None, # Homepage of the dataset for documentation homepage=_HOMEPAGE, # License for the dataset if available license=_LICENSE, # Citation for the dataset citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLs # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files. # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive my_urls = _URLs["default"] base_config = self.config.name.split("_")[0] secondary_config = self.config.name.split(base_config + "_")[1] data_dir = os.path.join(dl_manager.download_and_extract(my_urls), "IMPPRES", base_config) return [ datasets.SplitGenerator( name=secondary_config, # These kwargs will be passed to _generate_examples gen_kwargs={ "filepath": os.path.join(data_dir, secondary_config + ".jsonl"), "split": "test", }, ) ] def _generate_examples(self, filepath, split): """ Yields examples. """ # TODO: This method will receive as arguments the `gen_kwargs` defined in the previous `_split_generators` method. # It is in charge of opening the given file and yielding (key, example) tuples from the dataset # The key is not important, it's more here for legacy reason (legacy from tfds) with open(filepath, encoding="utf-8") as f: for id_, row in enumerate(f): data = json.loads(row) if "presupposition" in self.config.name: # for k, v in data.items(): # print('{}({}): {}'.format(k, type(v), v)) # print('-'*55) if "trigger1" not in list(data.keys()): yield id_, { "premise": data["sentence1"], "hypothesis": data["sentence2"], "trigger": data["trigger"], "trigger1": "Not_In_Example", "trigger2": "Not_In_Example", "presupposition": data["presupposition"], "gold_label": data["gold_label"], "UID": data["UID"], "pairID": data["pairID"], "paradigmID": data["paradigmID"], } else: yield id_, { "premise": data["sentence1"], "hypothesis": data["sentence2"], "trigger": "Not_In_Example", "trigger1": data["trigger1"], "trigger2": data["trigger2"], "presupposition": "Not_In_Example", "gold_label": data["gold_label"], "UID": data["UID"], "pairID": data["pairID"], "paradigmID": data["paradigmID"], } else: yield id_, { "premise": data["sentence1"], "hypothesis": data["sentence2"], "gold_label_log": data["gold_label_log"], "gold_label_prag": data["gold_label_prag"], "spec_relation": data["spec_relation"], "item_type": data["item_type"], "trigger": data["trigger"], "lexemes": data["lexemes"], }
56.910394
1,197
0.634463
1,750
15,878
5.679429
0.287429
0.035919
0.040246
0.035315
0.424489
0.405876
0.377
0.369856
0.369856
0.356575
0
0.011385
0.286371
15,878
278
1,198
57.115108
0.865766
0.264643
0
0.458537
0
0.02439
0.465742
0.049211
0
0
0
0.003597
0
1
0.014634
false
0
0.02439
0
0.063415
0.004878
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
5b201dedf7625f49673a17f90219f4d165f06f5d
1,322
py
Python
app.py
juergenpointinger/status-dashboard
439c7e9b6966ff10ada4062c6b97d5088083f442
[ "MIT" ]
null
null
null
app.py
juergenpointinger/status-dashboard
439c7e9b6966ff10ada4062c6b97d5088083f442
[ "MIT" ]
null
null
null
app.py
juergenpointinger/status-dashboard
439c7e9b6966ff10ada4062c6b97d5088083f442
[ "MIT" ]
null
null
null
# Standard library imports import logging import os # Third party imports import dash import dash_bootstrap_components as dbc from flask_caching import Cache import plotly.io as pio # Local application imports from modules.gitlab import GitLab import settings # Initialize logging mechanism logging.basicConfig(level=settings.LOGLEVEL, format=settings.LOGFORMAT) logger = logging.getLogger(__name__) gl = GitLab() logger.info("Current GitLab version: {}".format(GitLab.version)) # App instance app = dash.Dash(__name__, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.title = settings.APP_NAME # App caching # CACHE_CONFIG = { # # Note that filesystem cache doesn't work on systems with ephemeral # # filesystems like Heroku. # 'CACHE_TYPE': 'filesystem', # 'CACHE_DIR': 'cache-directory', # # should be equal to maximum number of users on the app at a single time # # higher numbers will store more data in the filesystem / redis cache # 'CACHE_THRESHOLD': 200 # } CACHE_CONFIG = { # try 'filesystem' if you don't want to setup redis 'CACHE_TYPE': 'redis', 'CACHE_REDIS_URL': settings.REDIS_URL } cache = Cache() cache.init_app(app.server, config=CACHE_CONFIG) pio.templates.default = "plotly_dark"
28.12766
77
0.729955
173
1,322
5.421965
0.583815
0.035181
0
0
0
0
0
0
0
0
0
0.002775
0.1823
1,322
47
78
28.12766
0.86494
0.396369
0
0
0
0
0.09153
0
0
0
0
0
0
1
0
false
0
0.347826
0
0.347826
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
0
0
0
1
d28b98aeee69dc1cdd515a34f7751e391f42ef74
5,022
py
Python
src/main/python/smart/smartplots3_run.py
cday97/beam
7e1ab50eecaefafd04daab360f8b12bc7cab559b
[ "BSD-3-Clause-LBNL" ]
123
2017-04-06T20:17:19.000Z
2022-03-02T13:42:15.000Z
src/main/python/smart/smartplots3_run.py
cday97/beam
7e1ab50eecaefafd04daab360f8b12bc7cab559b
[ "BSD-3-Clause-LBNL" ]
2,676
2017-04-26T20:27:27.000Z
2022-03-31T16:39:53.000Z
src/main/python/smart/smartplots3_run.py
cday97/beam
7e1ab50eecaefafd04daab360f8b12bc7cab559b
[ "BSD-3-Clause-LBNL" ]
60
2017-04-06T20:14:32.000Z
2022-03-30T20:10:53.000Z
import pandas as pd import smartplots3_setup def createSetup(name,expansion_factor,percapita_factor,plot_size,settings): plt_setup_smart={ 'name': name, 'expansion_factor':expansion_factor, 'percapita_factor':percapita_factor, 'scenarios_itr': [], 'scenarios_id':[], 'scenarios_year':[], 'plot_size': plot_size, 'bottom_labels': [], 'top_labels': [], 'plots_folder': "makeplots3" } plt_setup_smart['name']=name plt_setup_smart['expansion_factor']=expansion_factor plt_setup_smart['plot_size']=plot_size plt_setup_smart['scenarios_year']=[] plt_setup_smart['scenarios_id']=[] plt_setup_smart['scenarios_itr']=[] plt_setup_smart['top_labels']=[] for (scenarios_year,scenarios_id,scenarios_itr,bottom_label,top_label) in settings: plt_setup_smart['scenarios_year'].append(scenarios_year) plt_setup_smart['scenarios_id'].append(scenarios_id) plt_setup_smart['scenarios_itr'].append(scenarios_itr) plt_setup_smart['top_labels'].append(top_label) plt_setup_smart['bottom_labels'].append(bottom_label) return plt_setup_smart def createSettingRow(scenarios_year,scenarios_id,scenarios_itr,bottom_label,top_label): return (scenarios_year,scenarios_id,scenarios_itr,bottom_label,top_label) scenarios_lables = { "Base_CL_CT": "Base0", "Base_STL_STT_BAU": "Base2", "Base_STL_STT_VTO": "Base3", "Base_LTL_LTT_BAU": "Base5", "Base_LTL_LTT_VTO": "Base6", "A_STL_STT_BAU": "A2", "A_STL_STT_VTO": "A3", "B_LTL_LTT_BAU": "B5", "B_LTL_LTT_VTO": "B6", "C_LTL_LTT_BAU": "C5", "C_LTL_LTT_VTO": "C6" } output_folder = "/home/ubuntu/git/jupyter/data/28thOct2019" # Base_CL_CT # A_STL_STT_BAU settings=[] settings.append(createSettingRow(2010,1,15,scenarios_lables["Base_CL_CT"], "")) settings.append(createSettingRow(2025,6,15,scenarios_lables["A_STL_STT_BAU"], "")) settings.append(createSettingRow(2025,7,15,scenarios_lables["A_STL_STT_VTO"], "")) settings.append(createSettingRow(2040,8,15,scenarios_lables["B_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,9,15,scenarios_lables["B_LTL_LTT_VTO"], "")) settings.append(createSettingRow(2040,10,15,scenarios_lables["C_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,11,15,scenarios_lables["C_LTL_LTT_VTO"], "")) plt_setup_smart3 = createSetup('7scenarios', (7.75/0.315) * 27.0 / 21.3, 27.0/21.3, (8, 4.5), settings) #smartplots3_setup.pltRealizedModeSplitByTrips(plt_setup_smart3, output_folder) #smartplots3_setup.pltModeSplitInPMTPerCapita(plt_setup_smart3, output_folder) #smartplots3_setup.pltAveragePersonSpeed_allModes(plt_setup_smart3, output_folder) #smartplots3_setup.pltAveragePersonSpeed_car(plt_setup_smart3, output_folder) #smartplots3_setup.pltModeSplitInVMT(plt_setup_smart3, output_folder) #smartplots3_setup.pltRHEmptyPooled(plt_setup_smart3, output_folder) #smartplots3_setup.pltRHWaitTime(plt_setup_smart3, output_folder) #smartplots3_setup.pltLdvTechnologySplitInVMT(plt_setup_smart3, output_folder) settings=[] settings.append(createSettingRow(2010,1,15,scenarios_lables["Base_CL_CT"], "")) settings.append(createSettingRow(2025,2,15,scenarios_lables["Base_STL_STT_BAU"], "")) settings.append(createSettingRow(2025,3,15,scenarios_lables["Base_STL_STT_VTO"], "")) settings.append(createSettingRow(2040,4,15,scenarios_lables["Base_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,5,15,scenarios_lables["Base_LTL_LTT_VTO"], "")) settings.append(createSettingRow(2025,6,15,scenarios_lables["A_STL_STT_BAU"], "")) settings.append(createSettingRow(2025,7,15,scenarios_lables["A_STL_STT_VTO"], "")) settings.append(createSettingRow(2040,8,15,scenarios_lables["B_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,9,15,scenarios_lables["B_LTL_LTT_VTO"], "")) settings.append(createSettingRow(2040,10,15,scenarios_lables["C_LTL_LTT_BAU"], "")) settings.append(createSettingRow(2040,11,15,scenarios_lables["C_LTL_LTT_VTO"], "")) plt_setup_smart3_base = createSetup('11scenarios', (7.75/0.315) * 27.0 / 21.3, 27.0/21.3, (10, 4.5), settings) smartplots3_setup.pltEnergyPerCapita(plt_setup_smart3_base, output_folder) smartplots3_setup.pltRealizedModeSplitByTrips(plt_setup_smart3_base, output_folder) smartplots3_setup.pltModeSplitInPMTPerCapita(plt_setup_smart3_base, output_folder) smartplots3_setup.pltAveragePersonSpeed_allModes(plt_setup_smart3_base, output_folder) smartplots3_setup.pltAveragePersonSpeed_car(plt_setup_smart3_base, output_folder) smartplots3_setup.pltModeSplitInVMT(plt_setup_smart3_base, output_folder) smartplots3_setup.pltRHEmptyPooled(plt_setup_smart3_base, output_folder) smartplots3_setup.pltRHWaitTime(plt_setup_smart3_base, output_folder) smartplots3_setup.pltLdvTechnologySplitInVMT(plt_setup_smart3_base, output_folder) #smartplots3_setup.pltMEP(plt_setup_smart3, output_folder, [15071,21151,22872,29014,27541,36325,45267]) smartplots3_setup.tableSummary(plt_setup_smart3_base, output_folder)
50.727273
110
0.788331
669
5,022
5.497758
0.158445
0.076128
0.079935
0.121805
0.781403
0.730288
0.677814
0.587004
0.392877
0.312398
0
0.058913
0.080645
5,022
99
111
50.727273
0.737708
0.142174
0
0.207792
0
0
0.176868
0.009542
0
0
0
0
0
1
0.025974
false
0
0.025974
0.012987
0.077922
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d29646348f53744d285a4ab6a2096da4edb810a8
2,612
py
Python
examples/home-assistant/custom_components/evacalor/config_flow.py
fredericvl/pyevacalor
37a3d96f867efffdec4457f11119977e6e887b8a
[ "Apache-2.0" ]
2
2020-10-25T15:42:03.000Z
2021-01-06T10:25:58.000Z
examples/home-assistant/custom_components/evacalor/config_flow.py
fredericvl/pyevacalor
37a3d96f867efffdec4457f11119977e6e887b8a
[ "Apache-2.0" ]
2
2021-01-06T09:24:58.000Z
2021-02-13T21:12:02.000Z
examples/home-assistant/custom_components/evacalor/config_flow.py
fredericvl/pyevacalor
37a3d96f867efffdec4457f11119977e6e887b8a
[ "Apache-2.0" ]
null
null
null
"""Config flow for Eva Calor.""" from collections import OrderedDict import logging import uuid from pyevacalor import ( # pylint: disable=redefined-builtin ConnectionError, Error as EvaCalorError, UnauthorizedError, evacalor, ) import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from .const import CONF_UUID, DOMAIN _LOGGER = logging.getLogger(__name__) def conf_entries(hass): """Return the email tuples for the domain.""" return set( entry.data[CONF_EMAIL] for entry in hass.config_entries.async_entries(DOMAIN) ) class EvaCalorConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Eva Calor Config Flow handler.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL def _entry_in_configuration_exists(self, user_input) -> bool: """Return True if config already exists in configuration.""" email = user_input[CONF_EMAIL] if email in conf_entries(self.hass): return True return False async def async_step_user(self, user_input=None): """User initiated integration.""" errors = {} if user_input is not None: # Validate user input email = user_input[CONF_EMAIL] password = user_input[CONF_PASSWORD] if self._entry_in_configuration_exists(user_input): return self.async_abort(reason="device_already_configured") try: gen_uuid = str(uuid.uuid1()) evacalor(email, password, gen_uuid) except UnauthorizedError: errors["base"] = "unauthorized" except ConnectionError: errors["base"] = "connection_error" except EvaCalorError: errors["base"] = "unknown_error" if "base" not in errors: return self.async_create_entry( title=DOMAIN, data={ CONF_EMAIL: email, CONF_PASSWORD: password, CONF_UUID: gen_uuid, }, ) else: user_input = {} data_schema = OrderedDict() data_schema[vol.Required(CONF_EMAIL, default=user_input.get(CONF_EMAIL))] = str data_schema[ vol.Required(CONF_PASSWORD, default=user_input.get(CONF_PASSWORD)) ] = str return self.async_show_form( step_id="user", data_schema=vol.Schema(data_schema), errors=errors )
31.095238
87
0.616003
281
2,612
5.483986
0.33452
0.064244
0.025308
0.033744
0.092148
0
0
0
0
0
0
0.001101
0.304364
2,612
83
88
31.46988
0.847001
0.07925
0
0.032787
0
0
0.036596
0.010638
0
0
0
0
0
1
0.032787
false
0.081967
0.131148
0
0.311475
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d296cec19b3a1e77f406394741a977e6895ca59f
392
py
Python
PYTHON_Code/TestGUI.py
ROBO-BEV/BARISTO
0e87d79966efc111cc38c1a1cf22e2d8ee18c350
[ "CC-BY-3.0", "MIT" ]
8
2018-03-12T04:52:28.000Z
2021-05-19T19:37:01.000Z
PYTHON_Code/TestGUI.py
ROBO-BEV/BARISTO
0e87d79966efc111cc38c1a1cf22e2d8ee18c350
[ "CC-BY-3.0", "MIT" ]
null
null
null
PYTHON_Code/TestGUI.py
ROBO-BEV/BARISTO
0e87d79966efc111cc38c1a1cf22e2d8ee18c350
[ "CC-BY-3.0", "MIT" ]
1
2018-01-30T09:43:36.000Z
2018-01-30T09:43:36.000Z
from tkinter import * window0 = Tk() window0.geometry('960x540') #tk.iconbitmap(default='ROBO_BEV_LOGO.ico') window0.title("BARISTO") photo = PhotoImage(file="Page1.png") widget = Label(window0, image=photo) widget.photo = photo widget = Label(window0, text="10", fg="white", font=("Source Sans Pro",50)) #widget = Label(window0, text="9", fg="white") widget.pack() window0.mainloop()
19.6
75
0.709184
54
392
5.111111
0.648148
0.119565
0.195652
0.15942
0
0
0
0
0
0
0
0.054286
0.107143
392
19
76
20.631579
0.734286
0.221939
0
0
0
0
0.149007
0
0
0
0
0
0
1
0
false
0
0.1
0
0.1
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d2992c7176a1b65595e782d6603b030801317e72
2,662
py
Python
Sindri/Properties.py
mrcsbrn/TCC_software
17a5335aed17d4740c3bbd0ef828b0fc5dcea1da
[ "MIT" ]
11
2019-10-17T02:01:51.000Z
2022-03-17T17:39:34.000Z
Sindri/Properties.py
mrcsbrn/TCC_software
17a5335aed17d4740c3bbd0ef828b0fc5dcea1da
[ "MIT" ]
2
2019-07-25T22:16:16.000Z
2020-03-28T01:59:59.000Z
Sindri/Properties.py
mrcsbrn/TCC_software
17a5335aed17d4740c3bbd0ef828b0fc5dcea1da
[ "MIT" ]
5
2019-07-15T18:19:36.000Z
2021-12-24T08:06:24.000Z
from __future__ import annotations from constants import DBL_EPSILON class DeltaProp(object): def __init__(self, cp: float, h: float, s: float, g: float, u: float, a: float): self.Cp = cp self.H = h self.S = s self.G = g self.U = u self.A = a def subtract(self, dp2: DeltaProp) -> DeltaProp: cp = self.Cp - dp2.Cp h = self.H - dp2.H s = self.S - dp2.S g = self.G - dp2.G u = self.U - dp2.U a = self.A - dp2.A return DeltaProp(cp, h, s, g, u, a) def isEqual(self, dp2: DeltaProp, tol=1e-5) -> bool: if ( self._relAbsErr(self.Cp, dp2.Cp) < tol and self._relAbsErr(self.H, dp2.H) < tol and self._relAbsErr(self.S, dp2.S) < tol and self._relAbsErr(self.G, dp2.G) < tol and self._relAbsErr(self.U, dp2.U) < tol and self._relAbsErr(self.A, dp2.A) < tol ): return True return False def _relAbsErr(self, x: float, y: float) -> float: if abs(x) < DBL_EPSILON: return abs(x - y) return abs((x - y) / x) class VaporPressure(object): """ Class containing information about the vapor pressure of a single substance system. """ def __init__(self): self.EOS = 0 self.AW = 0 self.LK = 0 self.Antoine = 0 self.AntonieLog = 0 def setEOS(self, v: float): self.EOS = v def setAW(self, v: float): self.AW = v def setLK(self, v: float): self.LK = v def setAntoine(self, v: float, log=""): self.Antoine = v self.AntonieLog = log def getAWerr(self) -> float: return self._relError(self.EOS, self.AW) def getLKerr(self) -> float: return self._relError(self.EOS, self.LK) def getAntoineerr(self) -> float: return self._relError(self.EOS, self.Antoine) def _relError(self, _x: float, _y: float) -> float: if abs(_x) < DBL_EPSILON: return _x - _y return (_x - _y) / _x class Props(object): def __init__(self): self.P = 0 self.T = 0 self.Z = 0 self.V = 0 self.rho = 0 self.Pvp = 0 self.Fugacity = 0 self.Props = 0 self.IGProps = 0 self.log = "" def setRho(self, v: float): self.rho = v def setPvp(self, v: VaporPressure): self.Pvp = v def setProps(self, v: DeltaProp): self.Props = v def setIGProps(self, v: DeltaProp): self.IGProps = v def setIGProps(self, v: float): self.Fugacity = v
24.422018
87
0.531555
369
2,662
3.731707
0.203252
0.047204
0.074074
0.068991
0.256354
0.145243
0.145243
0.145243
0.062455
0.062455
0
0.017331
0.349737
2,662
108
88
24.648148
0.778163
0.03118
0
0.024691
0
0
0
0
0
0
0
0
0
1
0.234568
false
0
0.024691
0.037037
0.419753
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
0
0
0
1
d29e853085f1e22d6f5c45806ff223b5999daf1d
315
py
Python
notebooks/datasets.py
jweill-aws/jupyterlab-data-explorer
3db8eed9562f35d2b0e44370cf22f32ac9ffbc4d
[ "BSD-3-Clause" ]
173
2019-01-04T05:18:08.000Z
2022-03-28T11:15:30.000Z
notebooks/datasets.py
jweill-aws/jupyterlab-data-explorer
3db8eed9562f35d2b0e44370cf22f32ac9ffbc4d
[ "BSD-3-Clause" ]
115
2019-01-04T01:09:41.000Z
2022-03-24T01:07:00.000Z
notebooks/datasets.py
jweill-aws/jupyterlab-data-explorer
3db8eed9562f35d2b0e44370cf22f32ac9ffbc4d
[ "BSD-3-Clause" ]
34
2019-06-12T16:46:53.000Z
2022-02-01T08:41:40.000Z
# # @license BSD-3-Clause # # Copyright (c) 2019 Project Jupyter Contributors. # Distributed under the terms of the 3-Clause BSD License. import IPython.display import pandas def output_url(url): IPython.display.publish_display_data( {"application/x.jupyter.relative-dataset-urls+json": [url]} )
21
67
0.730159
42
315
5.404762
0.714286
0.061674
0
0
0
0
0
0
0
0
0
0.022727
0.161905
315
14
68
22.5
0.837121
0.403175
0
0
0
0
0.263736
0.263736
0
0
0
0
0
1
0.166667
false
0
0.333333
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
0
0
1
0
0
0
0
1
d2ab49c4b3562bad12874570d0c5751dda4cf3e6
1,194
py
Python
tests/settings.py
josemarimanio/django-adminlte2-templates
d39ab5eaec674c4725015fe43fc93e74dce78a6e
[ "MIT" ]
10
2020-03-21T10:50:11.000Z
2022-03-04T08:36:43.000Z
tests/settings.py
josemarimanio/django-adminlte2-templates
d39ab5eaec674c4725015fe43fc93e74dce78a6e
[ "MIT" ]
6
2020-06-06T08:48:29.000Z
2021-06-10T18:49:35.000Z
tests/settings.py
josemarimanio/django-adminlte2-templates
d39ab5eaec674c4725015fe43fc93e74dce78a6e
[ "MIT" ]
1
2021-09-14T02:00:43.000Z
2021-09-14T02:00:43.000Z
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '!t_(11ght0&nmb&$tf4to=gdg&u$!hsm3@)c6dzp=zdc*c9zci' # nosec INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'adminlte2_templates', 'tests', ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ROOT_URLCONF = 'tests.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [os.path.join(BASE_DIR, 'tests/templates')], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'adminlte2_templates.context_processors.template', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.MD5PasswordHasher', ]
23.88
74
0.629816
118
1,194
6.211864
0.5
0.141883
0.092769
0.040928
0.090041
0
0
0
0
0
0
0.012834
0.216918
1,194
49
75
24.367347
0.771123
0.004188
0
0
0
0
0.518955
0.385004
0
0
0
0
0
1
0
false
0.051282
0.025641
0
0.025641
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d2af35f5ecd1284185b97cd7fd48a1dabdbf319d
1,714
py
Python
data_input.py
zpcore/OnePass
fc102fae172c617535d4661bfa99a0302cbe09db
[ "MIT" ]
null
null
null
data_input.py
zpcore/OnePass
fc102fae172c617535d4661bfa99a0302cbe09db
[ "MIT" ]
null
null
null
data_input.py
zpcore/OnePass
fc102fae172c617535d4661bfa99a0302cbe09db
[ "MIT" ]
null
null
null
import json import string, sys from random import * class Token: def __init__(self): self.company, self.website, self.email, self.username, self.password = None, None, None, None, None def get_input(self): while(self.company in (None,'')): self.company = input('Account Association:') if(self.company in (None,'')): print('Account Association cannot be null, try again.') self.website = input('Website linked to the account:') self.email = input('Email linked to the account:') # while(self.email in (None,'')): # self.email = input('Registered Email:') # if(self.email in (None,'')): # print('Email cannot be null, try again.') while(self.username in (None,'')): self.username = input('Username:') if(self.username in (None,'')): print('Username cannot be null, try again.') while(self.password in (None,'')): select = input('Random generate a password for you? Type Y or N. ').strip().lower() if(select in ('y','yes')): characters = string.ascii_letters + string.punctuation + string.digits low_bound, up_bound = 10, 20 password = "".join(choice(characters) for x in range(randint(low_bound, up_bound))) self.password = password print('auto generated password:'+self.password) elif(select in ('n','no')): self.password = input('Password:') if(self.password in (None,'')): print('Password cannot be null, try again.') else: print('Incorrect choice. Try again.') class MyEncoder(json.JSONEncoder): def default(self, obj): if not isinstance(obj, Token): return super().default(obj) return obj.__dict__ # tok = Token() # tok.get_input() # print(json.dumps(tok, cls=MyEncoder))
32.339623
101
0.656943
232
1,714
4.788793
0.340517
0.043204
0.039604
0.054005
0.088209
0.052205
0.052205
0
0
0
0
0.002865
0.185531
1,714
53
102
32.339623
0.79298
0.124854
0
0
0
0
0.214334
0
0
0
0
0
0
1
0.083333
false
0.25
0.083333
0
0.277778
0.138889
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
0
0
1
d2c4507ff5f2b0e60108a433da49147fd8f6e6c4
3,008
py
Python
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/doc_fragments/nios.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
17
2017-06-07T23:15:01.000Z
2021-08-30T14:32:36.000Z
ansible/ansible/plugins/doc_fragments/nios.py
SergeyCherepanov/ansible
875711cd2fd6b783c812241c2ed7a954bf6f670f
[ "MIT" ]
9
2017-06-25T03:31:52.000Z
2021-05-17T23:43:12.000Z
ansible/ansible/plugins/doc_fragments/nios.py
SergeyCherepanov/ansible
875711cd2fd6b783c812241c2ed7a954bf6f670f
[ "MIT" ]
3
2018-05-26T21:31:22.000Z
2019-09-28T17:00:45.000Z
# -*- coding: utf-8 -*- # Copyright: (c) 2015, Peter Sprygada <psprygada@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = r''' options: provider: description: - A dict object containing connection details. type: dict suboptions: host: description: - Specifies the DNS host name or address for connecting to the remote instance of NIOS WAPI over REST - Value can also be specified using C(INFOBLOX_HOST) environment variable. type: str required: true username: description: - Configures the username to use to authenticate the connection to the remote instance of NIOS. - Value can also be specified using C(INFOBLOX_USERNAME) environment variable. type: str password: description: - Specifies the password to use to authenticate the connection to the remote instance of NIOS. - Value can also be specified using C(INFOBLOX_PASSWORD) environment variable. type: str validate_certs: description: - Boolean value to enable or disable verifying SSL certificates - Value can also be specified using C(INFOBLOX_SSL_VERIFY) environment variable. type: bool default: no aliases: [ ssl_verify ] http_request_timeout: description: - The amount of time before to wait before receiving a response - Value can also be specified using C(INFOBLOX_HTTP_REQUEST_TIMEOUT) environment variable. type: int default: 10 max_retries: description: - Configures the number of attempted retries before the connection is declared usable - Value can also be specified using C(INFOBLOX_MAX_RETRIES) environment variable. type: int default: 3 wapi_version: description: - Specifies the version of WAPI to use - Value can also be specified using C(INFOBLOX_WAP_VERSION) environment variable. - Until ansible 2.8 the default WAPI was 1.4 type: str default: '2.1' max_results: description: - Specifies the maximum number of objects to be returned, if set to a negative number the appliance will return an error when the number of returned objects would exceed the setting. - Value can also be specified using C(INFOBLOX_MAX_RESULTS) environment variable. type: int default: 1000 notes: - "This module must be run locally, which can be achieved by specifying C(connection: local)." - Please read the :ref:`nios_guide` for more detailed information on how to use Infoblox with Ansible. '''
35.809524
104
0.635306
359
3,008
5.261838
0.428969
0.03388
0.050821
0.059291
0.285866
0.233457
0.220222
0.220222
0.141874
0.099524
0
0.01068
0.31516
3,008
83
105
36.240964
0.906311
0.069814
0
0.351351
0
0.027027
0.973863
0.051557
0
0
0
0
0
1
0
false
0.040541
0
0
0.027027
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
0
0
0
0
0
0
1
d2d415b3f1a1db25737dd9e6b40de2eb5823d384
325
py
Python
DjangoTry/venv/Lib/site-packages/django_select2/__init__.py
PavelKoksharov/QR-BOOK
8b05cecd7a3cffcec281f2e17da398ad9e4c5de5
[ "MIT" ]
null
null
null
DjangoTry/venv/Lib/site-packages/django_select2/__init__.py
PavelKoksharov/QR-BOOK
8b05cecd7a3cffcec281f2e17da398ad9e4c5de5
[ "MIT" ]
null
null
null
DjangoTry/venv/Lib/site-packages/django_select2/__init__.py
PavelKoksharov/QR-BOOK
8b05cecd7a3cffcec281f2e17da398ad9e4c5de5
[ "MIT" ]
null
null
null
""" This is a Django_ integration of Select2_. The application includes Select2 driven Django Widgets and Form Fields. .. _Django: https://www.djangoproject.com/ .. _Select2: https://select2.org/ """ from django import get_version if get_version() < '3.2': default_app_config = "django_select2.apps.Select2AppConfig"
23.214286
71
0.750769
43
325
5.465116
0.744186
0.085106
0
0
0
0
0
0
0
0
0
0.02847
0.135385
325
13
72
25
0.807829
0.593846
0
0
0
0
0.317073
0.292683
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
d2d4cdab7ece6cb0f6e54ac92797ae4e32cdf266
673
py
Python
Sorting/bubble.py
Krylovsentry/Algorithms
0cd236f04dc065d5247a6f274bb3db503db591b0
[ "MIT" ]
1
2016-08-21T13:01:42.000Z
2016-08-21T13:01:42.000Z
Sorting/bubble.py
Krylovsentry/Algorithms
0cd236f04dc065d5247a6f274bb3db503db591b0
[ "MIT" ]
null
null
null
Sorting/bubble.py
Krylovsentry/Algorithms
0cd236f04dc065d5247a6f274bb3db503db591b0
[ "MIT" ]
null
null
null
# O(n ** 2) def bubble_sort(slist, asc=True): need_exchanges = False for iteration in range(len(slist))[:: -1]: for j in range(iteration): if asc: if slist[j] > slist[j + 1]: need_exchanges = True slist[j], slist[j + 1] = slist[j + 1], slist[j] else: if slist[j] < slist[j + 1]: need_exchanges = True slist[j], slist[j + 1] = slist[j + 1], slist[j] if not need_exchanges: return slist return slist print(bubble_sort([8, 1, 13, 34, 5, 2, 21, 3, 1], False)) print(bubble_sort([1, 2, 3, 4, 5, 6]))
32.047619
67
0.473997
95
673
3.284211
0.336842
0.230769
0.134615
0.153846
0.371795
0.371795
0.371795
0.371795
0.371795
0.371795
0
0.062802
0.384844
673
20
68
33.65
0.690821
0.013373
0
0.352941
0
0
0
0
0
0
0
0
0
1
0.058824
false
0
0
0
0.176471
0.117647
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
0
0
0
1
d2dfc266c6056fe94eecb550bf60b54a02eaa933
470
py
Python
setup.py
colineRamee/UAM_simulator_scitech2021
0583f5ce195cf1ec4f6919d6523fa39851c419fc
[ "MIT" ]
1
2021-02-04T15:57:03.000Z
2021-02-04T15:57:03.000Z
setup.py
colineRamee/UAM_simulator_scitech2021
0583f5ce195cf1ec4f6919d6523fa39851c419fc
[ "MIT" ]
null
null
null
setup.py
colineRamee/UAM_simulator_scitech2021
0583f5ce195cf1ec4f6919d6523fa39851c419fc
[ "MIT" ]
2
2021-02-04T04:41:08.000Z
2022-03-01T16:18:14.000Z
from setuptools import setup setup( name='uam_simulator', version='1.0', description='A tool to simulate different architectures for UAM traffic management', author='Coline Ramee', author_email='coline.ramee@gatech.edu', packages=['uam_simulator'], install_requires=['numpy', 'scikit-learn', 'gurobipy'] ) # If installing from source the package name is gurobipy, if installing with conda it's gurobi, but when importing it's still gurobipy
36.153846
134
0.734043
63
470
5.412698
0.761905
0.070381
0.117302
0
0
0
0
0
0
0
0
0.005076
0.161702
470
12
135
39.166667
0.860406
0.280851
0
0
0
0
0.470238
0.068452
0
0
0
0
0
1
0
true
0
0.1
0
0.1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
1
d2e52be160ba41f3c7d6be5212d1c7221d94eb66
3,211
py
Python
tests/groups/family/test_pseudo_dojo.py
mbercx/aiida-pseudo
070bdfa37d30674e1f83bf6d14987aa977426d92
[ "MIT" ]
null
null
null
tests/groups/family/test_pseudo_dojo.py
mbercx/aiida-pseudo
070bdfa37d30674e1f83bf6d14987aa977426d92
[ "MIT" ]
2
2021-09-21T11:28:55.000Z
2021-09-21T12:13:48.000Z
tests/groups/family/test_pseudo_dojo.py
mbercx/aiida-pseudo
070bdfa37d30674e1f83bf6d14987aa977426d92
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # pylint: disable=unused-argument,pointless-statement """Tests for the `PseudoDojoFamily` class.""" import pytest from aiida_pseudo.data.pseudo import UpfData, Psp8Data, PsmlData, JthXmlData from aiida_pseudo.groups.family import PseudoDojoConfiguration, PseudoDojoFamily def test_type_string(clear_db): """Verify the `_type_string` class attribute is correctly set to the corresponding entry point name.""" assert PseudoDojoFamily._type_string == 'pseudo.family.pseudo_dojo' # pylint: disable=protected-access def test_pseudo_types(): """Test the `PseudoDojoFamily.pseudo_types` method.""" assert PseudoDojoFamily.pseudo_types == (UpfData, PsmlData, Psp8Data, JthXmlData) def test_default_configuration(): """Test the `PseudoDojoFamily.default_configuration` class attribute.""" assert isinstance(PseudoDojoFamily.default_configuration, PseudoDojoConfiguration) def test_valid_configurations(): """Test the `PseudoDojoFamily.valid_configurations` class attribute.""" valid_configurations = PseudoDojoFamily.valid_configurations assert isinstance(valid_configurations, tuple) for entry in valid_configurations: assert isinstance(entry, PseudoDojoConfiguration) def test_get_valid_labels(): """Test the `PseudoDojoFamily.get_valid_labels` class method.""" valid_labels = PseudoDojoFamily.get_valid_labels() assert isinstance(valid_labels, tuple) for entry in valid_labels: assert isinstance(entry, str) def test_format_configuration_label(): """Test the `PseudoDojoFamily.format_configuration_label` class method.""" configuration = PseudoDojoConfiguration('0.4', 'PBE', 'SR', 'standard', 'psp8') assert PseudoDojoFamily.format_configuration_label(configuration) == 'PseudoDojo/0.4/PBE/SR/standard/psp8' def test_constructor(): """Test that the `PseudoDojoFamily` constructor validates the label.""" with pytest.raises(ValueError, match=r'the label `.*` is not a valid PseudoDojo configuration label'): PseudoDojoFamily() with pytest.raises(ValueError, match=r'the label `.*` is not a valid PseudoDojo configuration label'): PseudoDojoFamily(label='nc-sr-04_pbe_standard_psp8') label = PseudoDojoFamily.format_configuration_label(PseudoDojoFamily.default_configuration) family = PseudoDojoFamily(label=label) assert isinstance(family, PseudoDojoFamily) @pytest.mark.usefixtures('clear_db') def test_create_from_folder(filepath_pseudos): """Test the `PseudoDojoFamily.create_from_folder` class method.""" family = PseudoDojoFamily.create_from_folder( filepath_pseudos('upf'), 'PseudoDojo/0.4/PBE/SR/standard/psp8', pseudo_type=UpfData ) assert isinstance(family, PseudoDojoFamily) @pytest.mark.usefixtures('clear_db') def test_create_from_folder_duplicate(filepath_pseudos): """Test that `PseudoDojoFamily.create_from_folder` raises for duplicate label.""" label = 'PseudoDojo/0.4/PBE/SR/standard/psp8' PseudoDojoFamily(label=label).store() with pytest.raises(ValueError, match=r'the PseudoDojoFamily `.*` already exists'): PseudoDojoFamily.create_from_folder(filepath_pseudos('upf'), label)
40.64557
110
0.766116
360
3,211
6.636111
0.252778
0.071578
0.057765
0.01172
0.277941
0.254918
0.246965
0.154039
0.154039
0.154039
0
0.006435
0.128932
3,211
78
111
41.166667
0.847694
0.236064
0
0.142857
0
0
0.149167
0.065
0
0
0
0
0.238095
1
0.214286
false
0
0.071429
0
0.285714
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
0
0
0
1
d2f56951f340d9aa264e8c54df9fedc28d30df30
1,832
py
Python
src/nucleotide/component/linux/gcc/atom/rtl.py
dmilos/nucleotide
aad5d60508c9e4baf4888069284f2cb5c9fd7c55
[ "Apache-2.0" ]
1
2020-09-04T13:00:04.000Z
2020-09-04T13:00:04.000Z
src/nucleotide/component/linux/gcc/atom/rtl.py
dmilos/nucleotide
aad5d60508c9e4baf4888069284f2cb5c9fd7c55
[ "Apache-2.0" ]
1
2020-04-10T01:52:32.000Z
2020-04-10T09:11:29.000Z
src/nucleotide/component/linux/gcc/atom/rtl.py
dmilos/nucleotide
aad5d60508c9e4baf4888069284f2cb5c9fd7c55
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python2 # Copyright 2015 Dejan D. M. Milosavljevic # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import platform import nucleotide import nucleotide.component import nucleotide.component.function def _linux_RTL_LINKFLAGS( P_data ): I_flag = '' #if( 'dynamic' == P_data['type'] ): # I_flag += 'D' if( 'static' == P_data['type'] ): I_flag += '-static' return [ I_flag ] atom_linux_RTL = { 'platform' : { 'host' : 'Linux', 'guest' : 'Linux' }, 'cc' : { 'vendor': 'FSF', 'name' : 'gcc', 'version': 'X' }, 'config' : { 'LINKFLAGS' : _linux_RTL_LINKFLAGS }, 'name' :'RTL', 'class': [ 'RTL', 'linux:RTL' ] } class RTL: def __init__(self): pass @staticmethod def extend( P_option ): nucleotide.component.function.extend( P_option, 'A:linux:RTL', atom_linux_RTL ) atom_linux_RTL['platform']['host'] = 'X'; nucleotide.component.function.extend( P_option, 'x:linux:RTL', atom_linux_RTL ) atom_linux_RTL['platform']['guest'] = 'X'; nucleotide.component.function.extend( P_option, 'y:linux:RTL', atom_linux_RTL ) @staticmethod def check(): pass
27.343284
104
0.60917
225
1,832
4.813333
0.475556
0.088643
0.066482
0.078486
0.256694
0.186519
0.149584
0.073869
0.073869
0
0
0.006706
0.267467
1,832
66
105
27.757576
0.800298
0.357533
0
0.102564
0
0
0.14569
0
0
0
0
0
0
1
0.102564
false
0.051282
0.128205
0
0.282051
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d2f65b3512d928c10cc32ae1efdfb3cff693d569
876
py
Python
python/moderation_text_token_demo.py
huaweicloud/huaweicloud-sdk-moderation
fa7cfda017a71ec8abf3afc57a0e476dd7508167
[ "Apache-2.0" ]
8
2019-06-04T06:24:54.000Z
2022-01-29T13:16:53.000Z
python/moderation_text_token_demo.py
huaweicloud/huaweicloud-sdk-moderation
fa7cfda017a71ec8abf3afc57a0e476dd7508167
[ "Apache-2.0" ]
4
2021-12-14T21:21:03.000Z
2022-01-04T16:34:33.000Z
python/moderation_text_token_demo.py
huaweicloud/huaweicloud-sdk-moderation
fa7cfda017a71ec8abf3afc57a0e476dd7508167
[ "Apache-2.0" ]
8
2019-08-12T02:18:03.000Z
2021-11-30T10:39:23.000Z
# -*- coding:utf-8 -*- from moderation_sdk.gettoken import get_token from moderation_sdk.moderation_text import moderation_text from moderation_sdk.utils import init_global_env if __name__ == '__main__': # Services currently support North China-Beijing(cn-north-4),China East-Shanghai1(cn-east-3), CN-Hong Kong(ap-southeast-1),AP-Singapore(ap-southeast-3) init_global_env('cn-north-4') # # access moderation text enhance,posy data by token # user_name = '******' password = '******' account_name = '******' # the same as user_name in commonly use token = get_token(user_name, password, account_name) # call interface use the text result = moderation_text(token, '666666luo聊请+110亚砷酸钾六位qq,fuck666666666666666', 'content', ['ad', 'politics', 'porn', 'abuse', 'contraband', 'flood']) print(result)
38.086957
155
0.680365
111
876
5.144144
0.567568
0.098074
0.089317
0.073555
0.112084
0.112084
0
0
0
0
0
0.043417
0.184932
876
22
156
39.818182
0.756303
0.326484
0
0
0
0
0.206186
0.073883
0
0
0
0
0
1
0
false
0.166667
0.25
0
0.25
0.083333
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
0
0
1
d2fb7f6e9f85db6c80048daaef30c307b92d98da
2,145
py
Python
community_codebook/eda.py
etstieber/ledatascifi-2022
67bc56a60ec498c62ceba03e0b6b9ae8f3fc7fd9
[ "MIT" ]
null
null
null
community_codebook/eda.py
etstieber/ledatascifi-2022
67bc56a60ec498c62ceba03e0b6b9ae8f3fc7fd9
[ "MIT" ]
3
2022-01-30T18:34:22.000Z
2022-02-10T15:48:48.000Z
community_codebook/eda.py
etstieber/ledatascifi-2022
67bc56a60ec498c62ceba03e0b6b9ae8f3fc7fd9
[ "MIT" ]
14
2022-01-26T10:45:19.000Z
2022-03-28T15:59:56.000Z
############################################################### # # This function is... INSUFFICIENT. It was developed as an # illustration of EDA lessons in the 2021 class. It's quick and # works well. # # Want a higher grade version of me? Then try pandas-profiling: # https://github.com/pandas-profiling/pandas-profiling # ############################################################### def insufficient_but_starting_eda(df,cat_vars_list=None): ''' Parameters ---------- df : DATAFRAME cat_vars_list : LIST, optional A list of strings containing variable names in the dataframe for variables where you want to see the number of unique values and the 10 most common values. Likely used for categorical values. Returns ------- None. It simply prints. Description ------- This function will print a MINIMUM amount of info about a new dataframe. You should ****look**** at all this output below and consider the data exploration and cleaning questions from https://ledatascifi.github.io/ledatascifi-2021/content/03/02e_eda_golden.html#member Also LOOK at more of the data manually. Then write up anything notable you observe. TIP: put this function in your codebook to reuse easily. PROTIP: Improve this function (better outputs, better formatting). FEATURE REQUEST: optionally print the nunique and top 10 values under the describe matrix FEATURE REQUEST: optionally print more stats (percentiles) ''' print(df.head(), '\n---') print(df.tail(), '\n---') print(df.columns, '\n---') print("The shape is: ",df.shape, '\n---') print("Info:",df.info(), '\n---') # memory usage, name, dtype, and # of non-null obs (--> # of missing obs) per variable print(df.describe(), '\n---') # summary stats, and you can customize the list! if cat_vars_list != None: for var in cat_vars_list: print(var,"has",df[var].nunique(),"values and its top 10 most common are:") print(df[var].value_counts().head(10), '\n---')
35.75
124
0.607459
278
2,145
4.636691
0.535971
0.027153
0.034135
0.023274
0
0
0
0
0
0
0
0.012063
0.22704
2,145
59
125
36.355932
0.76538
0.632634
0
0
0
0
0.18664
0
0
0
0
0
0
1
0.090909
false
0
0
0
0.090909
0.727273
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
0
0
1
0
1
960dcc8a44c5847743443e7deb1bcd0169e59d72
469
py
Python
flags.py
oaxiom/glbase3
9d3fc1efaad58ffb97e5b8126c2a96802daf9bac
[ "MIT" ]
8
2019-06-11T02:13:20.000Z
2022-02-22T09:27:23.000Z
flags.py
JackNg88/glbase3
4af190d06b89ef360dcba201d9e4e81f41ef8379
[ "MIT" ]
6
2020-12-18T15:08:14.000Z
2021-05-22T00:31:57.000Z
flags.py
JackNg88/glbase3
4af190d06b89ef360dcba201d9e4e81f41ef8379
[ "MIT" ]
2
2020-05-06T04:27:03.000Z
2022-02-22T09:28:25.000Z
""" flags.py . should be renamed helpers... . This file is scheduled for deletion """ """ valid accessory tags: "any_tag": {"code": "code_insert_as_string"} # execute arbitrary code to construct this key. "dialect": csv.excel_tab # dialect of the file, default = csv, set this to use tsv. or sniffer "skip_lines": number # number of lines to skip at the head of the file. "skiptill": skip until I see the first instance of <str> """ # lists of format-specifiers.
23.45
94
0.712154
74
469
4.432432
0.716216
0.030488
0.054878
0
0
0
0
0
0
0
0
0
0.17484
469
19
95
24.684211
0.847545
0.228145
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
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
1
960deebf26b738896cbcd2ee2bd2d46605e19141
2,106
py
Python
packages/jet_bridge/jet_bridge/app.py
goncalomi/jet-bridge
ed968ac3407affdc99059faafb86ec67ac995838
[ "MIT" ]
2
2020-04-18T14:34:44.000Z
2020-04-18T14:34:47.000Z
packages/jet_bridge/jet_bridge/app.py
goncalomi/jet-bridge
ed968ac3407affdc99059faafb86ec67ac995838
[ "MIT" ]
null
null
null
packages/jet_bridge/jet_bridge/app.py
goncalomi/jet-bridge
ed968ac3407affdc99059faafb86ec67ac995838
[ "MIT" ]
null
null
null
import os import tornado.ioloop import tornado.web from jet_bridge.handlers.temporary_redirect import TemporaryRedirectHandler from jet_bridge_base import settings as base_settings from jet_bridge_base.views.api import ApiView from jet_bridge_base.views.image_resize import ImageResizeView from jet_bridge_base.views.file_upload import FileUploadView from jet_bridge_base.views.message import MessageView from jet_bridge_base.views.model import ModelViewSet from jet_bridge_base.views.model_description import ModelDescriptionView from jet_bridge_base.views.register import RegisterView from jet_bridge_base.views.reload import ReloadView from jet_bridge_base.views.sql import SqlView from jet_bridge import settings, media from jet_bridge.handlers.view import view_handler from jet_bridge.handlers.not_found import NotFoundHandler from jet_bridge.router import Router def make_app(): router = Router() router.register('/api/models/(?P<model>[^/]+)/', view_handler(ModelViewSet)) urls = [ (r'/', TemporaryRedirectHandler, {'url': "/api/"}), (r'/register/', view_handler(RegisterView)), (r'/api/', view_handler(ApiView)), (r'/api/register/', view_handler(RegisterView)), (r'/api/model_descriptions/', view_handler(ModelDescriptionView)), (r'/api/sql/', view_handler(SqlView)), (r'/api/messages/', view_handler(MessageView)), (r'/api/file_upload/', view_handler(FileUploadView)), (r'/api/image_resize/', view_handler(ImageResizeView)), (r'/api/reload/', view_handler(ReloadView)), (r'/media/(.*)', tornado.web.StaticFileHandler, {'path': settings.MEDIA_ROOT}), ] urls += router.urls if settings.MEDIA_STORAGE == media.MEDIA_STORAGE_FILE: urls.append((r'/media/(.*)', tornado.web.StaticFileHandler, {'path': settings.MEDIA_ROOT})) return tornado.web.Application( handlers=urls, debug=settings.DEBUG, default_handler_class=NotFoundHandler, template_path=os.path.join(base_settings.BASE_DIR, 'templates'), autoreload=settings.DEBUG )
39
99
0.738367
259
2,106
5.787645
0.266409
0.070047
0.130087
0.113409
0.257505
0.15477
0.072048
0.072048
0.072048
0
0
0
0.143875
2,106
53
100
39.735849
0.831392
0
0
0
0
0
0.094967
0.025166
0
0
0
0
0
1
0.022727
false
0
0.409091
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
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
9610832f6a592c17ec9781319d909b5b964100ab
15,186
py
Python
mwtab/mwschema.py
MoseleyBioinformaticsLab/mwtab
1bc1e3715538348b29a5760a9c3184fe04f568a6
[ "BSD-3-Clause-Clear" ]
7
2018-02-02T07:50:20.000Z
2021-03-14T22:46:58.000Z
mwtab/mwschema.py
MoseleyBioinformaticsLab/mwtab
1bc1e3715538348b29a5760a9c3184fe04f568a6
[ "BSD-3-Clause-Clear" ]
2
2019-02-14T08:38:54.000Z
2020-02-19T08:08:02.000Z
mwtab/mwschema.py
MoseleyBioinformaticsLab/mwtab
1bc1e3715538348b29a5760a9c3184fe04f568a6
[ "BSD-3-Clause-Clear" ]
1
2019-10-12T23:38:44.000Z
2019-10-12T23:38:44.000Z
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ mwtab.mwschema ~~~~~~~~~~~~~~ This module provides schema definitions for different sections of the ``mwTab`` Metabolomics Workbench format. """ import sys from schema import Schema, Optional, Or if sys.version_info.major == 2: str = unicode metabolomics_workbench_schema = Schema( { "VERSION": str, "CREATED_ON": str, Optional("STUDY_ID"): str, Optional("ANALYSIS_ID"): str, Optional("PROJECT_ID"): str, Optional("HEADER"): str, Optional("DATATRACK_ID"): str } ) project_schema = Schema( { "PROJECT_TITLE": str, Optional("PROJECT_TYPE"): str, "PROJECT_SUMMARY": str, "INSTITUTE": str, Optional("DEPARTMENT"): str, Optional("LABORATORY"): str, "LAST_NAME": str, "FIRST_NAME": str, "ADDRESS": str, "EMAIL": str, "PHONE": str, Optional("FUNDING_SOURCE"): str, Optional("PROJECT_COMMENTS"): str, Optional("PUBLICATIONS"): str, Optional("CONTRIBUTORS"): str, Optional("DOI"): str } ) study_schema = Schema( { "STUDY_TITLE": str, Optional("STUDY_TYPE"): str, "STUDY_SUMMARY": str, "INSTITUTE": str, Optional("DEPARTMENT"): str, Optional("LABORATORY"): str, "LAST_NAME": str, "FIRST_NAME": str, "ADDRESS": str, "EMAIL": str, "PHONE": str, Optional("NUM_GROUPS"): str, Optional("TOTAL_SUBJECTS"): str, Optional("NUM_MALES"): str, Optional("NUM_FEMALES"): str, Optional("STUDY_COMMENTS"): str, Optional("PUBLICATIONS"): str, # assumed Optional("SUBMIT_DATE"): str # assumed } ) subject_schema = Schema( { "SUBJECT_TYPE": str, "SUBJECT_SPECIES": str, Optional("TAXONOMY_ID"): str, Optional("GENOTYPE_STRAIN"): str, Optional("AGE_OR_AGE_RANGE"): str, Optional("WEIGHT_OR_WEIGHT_RANGE"): str, Optional("HEIGHT_OR_HEIGHT_RANGE"): str, Optional("GENDER"): str, Optional("HUMAN_RACE"): str, Optional("HUMAN_ETHNICITY"): str, Optional("HUMAN_TRIAL_TYPE"): str, Optional("HUMAN_LIFESTYLE_FACTORS"): str, Optional("HUMAN_MEDICATIONS"): str, Optional("HUMAN_PRESCRIPTION_OTC"): str, Optional("HUMAN_SMOKING_STATUS"): str, Optional("HUMAN_ALCOHOL_DRUG_USE"): str, Optional("HUMAN_NUTRITION"): str, Optional("HUMAN_INCLUSION_CRITERIA"): str, Optional("HUMAN_EXCLUSION_CRITERIA"): str, Optional("ANIMAL_ANIMAL_SUPPLIER"): str, Optional("ANIMAL_HOUSING"): str, Optional("ANIMAL_LIGHT_CYCLE"): str, Optional("ANIMAL_FEED"): str, Optional("ANIMAL_WATER"): str, Optional("ANIMAL_INCLUSION_CRITERIA"): str, Optional("CELL_BIOSOURCE_OR_SUPPLIER"): str, Optional("CELL_STRAIN_DETAILS"): str, Optional("SUBJECT_COMMENTS"): str, Optional("CELL_PRIMARY_IMMORTALIZED"): str, Optional("CELL_PASSAGE_NUMBER"): str, Optional("CELL_COUNTS"): str, Optional("SPECIES_GROUP"): str } ) subject_sample_factors_schema = Schema( [ { "Subject ID": str, "Sample ID": str, "Factors": dict, Optional("Additional sample data"): { Optional("RAW_FILE_NAME"): str, Optional(str): str } } ] ) collection_schema = Schema( { "COLLECTION_SUMMARY": str, Optional("COLLECTION_PROTOCOL_ID"): str, Optional("COLLECTION_PROTOCOL_FILENAME"): str, Optional("COLLECTION_PROTOCOL_COMMENTS"): str, Optional("SAMPLE_TYPE"): str, # assumed optional due to large number of files without Optional("COLLECTION_METHOD"): str, Optional("COLLECTION_LOCATION"): str, Optional("COLLECTION_FREQUENCY"): str, Optional("COLLECTION_DURATION"): str, Optional("COLLECTION_TIME"): str, Optional("VOLUMEORAMOUNT_COLLECTED"): str, Optional("STORAGE_CONDITIONS"): str, Optional("COLLECTION_VIALS"): str, Optional("STORAGE_VIALS"): str, Optional("COLLECTION_TUBE_TEMP"): str, Optional("ADDITIVES"): str, Optional("BLOOD_SERUM_OR_PLASMA"): str, Optional("TISSUE_CELL_IDENTIFICATION"): str, Optional("TISSUE_CELL_QUANTITY_TAKEN"): str } ) treatment_schema = Schema( { "TREATMENT_SUMMARY": str, Optional("TREATMENT_PROTOCOL_ID"): str, Optional("TREATMENT_PROTOCOL_FILENAME"): str, Optional("TREATMENT_PROTOCOL_COMMENTS"): str, Optional("TREATMENT"): str, Optional("TREATMENT_COMPOUND"): str, Optional("TREATMENT_ROUTE"): str, Optional("TREATMENT_DOSE"): str, Optional("TREATMENT_DOSEVOLUME"): str, Optional("TREATMENT_DOSEDURATION"): str, Optional("TREATMENT_VEHICLE"): str, Optional("ANIMAL_VET_TREATMENTS"): str, Optional("ANIMAL_ANESTHESIA"): str, Optional("ANIMAL_ACCLIMATION_DURATION"): str, Optional("ANIMAL_FASTING"): str, Optional("ANIMAL_ENDP_EUTHANASIA"): str, Optional("ANIMAL_ENDP_TISSUE_COLL_LIST"): str, Optional("ANIMAL_ENDP_TISSUE_PROC_METHOD"): str, Optional("ANIMAL_ENDP_CLINICAL_SIGNS"): str, Optional("HUMAN_FASTING"): str, Optional("HUMAN_ENDP_CLINICAL_SIGNS"): str, Optional("CELL_STORAGE"): str, Optional("CELL_GROWTH_CONTAINER"): str, Optional("CELL_GROWTH_CONFIG"): str, Optional("CELL_GROWTH_RATE"): str, Optional("CELL_INOC_PROC"): str, Optional("CELL_MEDIA"): str, Optional("CELL_ENVIR_COND"): str, Optional("CELL_HARVESTING"): str, Optional("PLANT_GROWTH_SUPPORT"): str, Optional("PLANT_GROWTH_LOCATION"): str, Optional("PLANT_PLOT_DESIGN"): str, Optional("PLANT_LIGHT_PERIOD"): str, Optional("PLANT_HUMIDITY"): str, Optional("PLANT_TEMP"): str, Optional("PLANT_WATERING_REGIME"): str, Optional("PLANT_NUTRITIONAL_REGIME"): str, Optional("PLANT_ESTAB_DATE"): str, Optional("PLANT_HARVEST_DATE"): str, Optional("PLANT_GROWTH_STAGE"): str, Optional("PLANT_METAB_QUENCH_METHOD"): str, Optional("PLANT_HARVEST_METHOD"): str, Optional("PLANT_STORAGE"): str, Optional("CELL_PCT_CONFLUENCE"): str, Optional("CELL_MEDIA_LASTCHANGED"): str } ) sampleprep_schema = Schema( { "SAMPLEPREP_SUMMARY": str, Optional("SAMPLEPREP_PROTOCOL_ID"): str, Optional("SAMPLEPREP_PROTOCOL_FILENAME"): str, Optional("SAMPLEPREP_PROTOCOL_COMMENTS"): str, Optional("PROCESSING_METHOD"): str, Optional("PROCESSING_STORAGE_CONDITIONS"): str, Optional("EXTRACTION_METHOD"): str, Optional("EXTRACT_CONCENTRATION_DILUTION"): str, Optional("EXTRACT_ENRICHMENT"): str, Optional("EXTRACT_CLEANUP"): str, Optional("EXTRACT_STORAGE"): str, Optional("SAMPLE_RESUSPENSION"): str, Optional("SAMPLE_DERIVATIZATION"): str, Optional("SAMPLE_SPIKING"): str, Optional("ORGAN"): str, Optional("ORGAN_SPECIFICATION"): str, Optional("CELL_TYPE"): str, Optional("SUBCELLULAR_LOCATION"): str } ) chromatography_schema = Schema( { Optional("CHROMATOGRAPHY_SUMMARY"): str, "CHROMATOGRAPHY_TYPE": str, "INSTRUMENT_NAME": str, "COLUMN_NAME": str, Optional("FLOW_GRADIENT"): str, Optional("FLOW_RATE"): str, Optional("COLUMN_TEMPERATURE"): str, Optional("METHODS_FILENAME"): str, Optional("SOLVENT_A"): str, Optional("SOLVENT_B"): str, Optional("METHODS_ID"): str, Optional("COLUMN_PRESSURE"): str, Optional("INJECTION_TEMPERATURE"): str, Optional("INTERNAL_STANDARD"): str, Optional("INTERNAL_STANDARD_MT"): str, Optional("RETENTION_INDEX"): str, Optional("RETENTION_TIME"): str, Optional("SAMPLE_INJECTION"): str, Optional("SAMPLING_CONE"): str, Optional("ANALYTICAL_TIME"): str, Optional("CAPILLARY_VOLTAGE"): str, Optional("MIGRATION_TIME"): str, Optional("OVEN_TEMPERATURE"): str, Optional("PRECONDITIONING"): str, Optional("RUNNING_BUFFER"): str, Optional("RUNNING_VOLTAGE"): str, Optional("SHEATH_LIQUID"): str, Optional("TIME_PROGRAM"): str, Optional("TRANSFERLINE_TEMPERATURE"): str, Optional("WASHING_BUFFER"): str, Optional("WEAK_WASH_SOLVENT_NAME"): str, Optional("WEAK_WASH_VOLUME"): str, Optional("STRONG_WASH_SOLVENT_NAME"): str, Optional("STRONG_WASH_VOLUME"): str, Optional("TARGET_SAMPLE_TEMPERATURE"): str, Optional("SAMPLE_LOOP_SIZE"): str, Optional("SAMPLE_SYRINGE_SIZE"): str, Optional("RANDOMIZATION_ORDER"): str, Optional("CHROMATOGRAPHY_COMMENTS"): str } ) analysis_schema = Schema( { "ANALYSIS_TYPE": str, Optional("LABORATORY_NAME"): str, Optional("OPERATOR_NAME"): str, Optional("DETECTOR_TYPE"): str, Optional("SOFTWARE_VERSION"): str, Optional("ACQUISITION_DATE"): str, Optional("ANALYSIS_PROTOCOL_FILE"): str, Optional("ACQUISITION_PARAMETERS_FILE"): str, Optional("PROCESSING_PARAMETERS_FILE"): str, Optional("DATA_FORMAT"): str, # not specified in mwTab specification (assumed) Optional("ACQUISITION_ID"): str, Optional("ACQUISITION_TIME"): str, Optional("ANALYSIS_COMMENTS"): str, Optional("ANALYSIS_DISPLAY"): str, Optional("INSTRUMENT_NAME"): str, Optional("INSTRUMENT_PARAMETERS_FILE"): str, Optional("NUM_FACTORS"): str, Optional("NUM_METABOLITES"): str, Optional("PROCESSED_FILE"): str, Optional("RANDOMIZATION_ORDER"): str, Optional("RAW_FILE"): str, } ) ms_schema = Schema( { "INSTRUMENT_NAME": str, "INSTRUMENT_TYPE": str, "MS_TYPE": str, "ION_MODE": str, "MS_COMMENTS": str, # changed to required Optional("CAPILLARY_TEMPERATURE"): str, Optional("CAPILLARY_VOLTAGE"): str, Optional("COLLISION_ENERGY"): str, Optional("COLLISION_GAS"): str, Optional("DRY_GAS_FLOW"): str, Optional("DRY_GAS_TEMP"): str, Optional("FRAGMENT_VOLTAGE"): str, Optional("FRAGMENTATION_METHOD"): str, Optional("GAS_PRESSURE"): str, Optional("HELIUM_FLOW"): str, Optional("ION_SOURCE_TEMPERATURE"): str, Optional("ION_SPRAY_VOLTAGE"): str, Optional("IONIZATION"): str, Optional("IONIZATION_ENERGY"): str, Optional("IONIZATION_POTENTIAL"): str, Optional("MASS_ACCURACY"): str, Optional("PRECURSOR_TYPE"): str, Optional("REAGENT_GAS"): str, Optional("SOURCE_TEMPERATURE"): str, Optional("SPRAY_VOLTAGE"): str, Optional("ACTIVATION_PARAMETER"): str, Optional("ACTIVATION_TIME"): str, Optional("ATOM_GUN_CURRENT"): str, Optional("AUTOMATIC_GAIN_CONTROL"): str, Optional("BOMBARDMENT"): str, Optional("CDL_SIDE_OCTOPOLES_BIAS_VOLTAGE"): str, Optional("CDL_TEMPERATURE"): str, Optional("DATAFORMAT"): str, Optional("DESOLVATION_GAS_FLOW"): str, Optional("DESOLVATION_TEMPERATURE"): str, Optional("INTERFACE_VOLTAGE"): str, Optional("IT_SIDE_OCTOPOLES_BIAS_VOLTAGE"): str, Optional("LASER"): str, Optional("MATRIX"): str, Optional("NEBULIZER"): str, Optional("OCTPOLE_VOLTAGE"): str, Optional("PROBE_TIP"): str, Optional("RESOLUTION_SETTING"): str, Optional("SAMPLE_DRIPPING"): str, Optional("SCAN_RANGE_MOVERZ"): str, Optional("SCANNING"): str, Optional("SCANNING_CYCLE"): str, Optional("SCANNING_RANGE"): str, Optional("SKIMMER_VOLTAGE"): str, Optional("TUBE_LENS_VOLTAGE"): str, Optional("MS_RESULTS_FILE"): Or(str, dict) } ) nmr_schema = Schema( { "INSTRUMENT_NAME": str, "INSTRUMENT_TYPE": str, "NMR_EXPERIMENT_TYPE": str, Optional("NMR_COMMENTS"): str, Optional("FIELD_FREQUENCY_LOCK"): str, Optional("STANDARD_CONCENTRATION"): str, "SPECTROMETER_FREQUENCY": str, Optional("NMR_PROBE"): str, Optional("NMR_SOLVENT"): str, Optional("NMR_TUBE_SIZE"): str, Optional("SHIMMING_METHOD"): str, Optional("PULSE_SEQUENCE"): str, Optional("WATER_SUPPRESSION"): str, Optional("PULSE_WIDTH"): str, Optional("POWER_LEVEL"): str, Optional("RECEIVER_GAIN"): str, Optional("OFFSET_FREQUENCY"): str, Optional("PRESATURATION_POWER_LEVEL"): str, Optional("CHEMICAL_SHIFT_REF_CPD"): str, Optional("TEMPERATURE"): str, Optional("NUMBER_OF_SCANS"): str, Optional("DUMMY_SCANS"): str, Optional("ACQUISITION_TIME"): str, Optional("RELAXATION_DELAY"): str, Optional("SPECTRAL_WIDTH"): str, Optional("NUM_DATA_POINTS_ACQUIRED"): str, Optional("REAL_DATA_POINTS"): str, Optional("LINE_BROADENING"): str, Optional("ZERO_FILLING"): str, Optional("APODIZATION"): str, Optional("BASELINE_CORRECTION_METHOD"): str, Optional("CHEMICAL_SHIFT_REF_STD"): str, Optional("BINNED_INCREMENT"): str, Optional("BINNED_DATA_NORMALIZATION_METHOD"): str, Optional("BINNED_DATA_PROTOCOL_FILE"): str, Optional("BINNED_DATA_CHEMICAL_SHIFT_RANGE"): str, Optional("BINNED_DATA_EXCLUDED_RANGE"): str } ) data_schema = Schema( [ { Or("Metabolite", "Bin range(ppm)", only_one=True): str, Optional(str): str, }, ] ) extended_schema = Schema( [ { "Metabolite": str, Optional(str): str, "sample_id": str }, ] ) ms_metabolite_data_schema = Schema( { "Units": str, "Data": data_schema, "Metabolites": data_schema, Optional("Extended"): extended_schema } ) nmr_binned_data_schema = Schema( { "Units": str, "Data": data_schema } ) section_schema_mapping = { "METABOLOMICS WORKBENCH": metabolomics_workbench_schema, "PROJECT": project_schema, "STUDY": study_schema, "ANALYSIS": analysis_schema, "SUBJECT": subject_schema, "SUBJECT_SAMPLE_FACTORS": subject_sample_factors_schema, "COLLECTION": collection_schema, "TREATMENT": treatment_schema, "SAMPLEPREP": sampleprep_schema, "CHROMATOGRAPHY": chromatography_schema, "MS": ms_schema, "NM": nmr_schema, "MS_METABOLITE_DATA": ms_metabolite_data_schema, "NMR_METABOLITE_DATA": ms_metabolite_data_schema, "NMR_BINNED_DATA": nmr_binned_data_schema, }
34.049327
94
0.61965
1,506
15,186
5.942895
0.23838
0.325698
0.026816
0.009385
0.119777
0.088045
0.054525
0.04581
0.027039
0.027039
0
0.000262
0.247004
15,186
445
95
34.125843
0.782422
0.021204
0
0.080097
0
0
0.35165
0.115219
0
0
0
0
0
1
0
false
0.002427
0.004854
0
0.004854
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
0
0
0
1
9616936f76e77083ea419e018de9e5eaec39224e
4,715
py
Python
test.py
chdre/noise-randomized
c803fd6c6fd641a0b1c0f4880920584a647587bc
[ "MIT" ]
null
null
null
test.py
chdre/noise-randomized
c803fd6c6fd641a0b1c0f4880920584a647587bc
[ "MIT" ]
null
null
null
test.py
chdre/noise-randomized
c803fd6c6fd641a0b1c0f4880920584a647587bc
[ "MIT" ]
3
2021-10-05T09:01:51.000Z
2021-10-05T09:37:06.000Z
import unittest class PerlinTestCase(unittest.TestCase): def test_perlin_1d_range(self): from noise import pnoise1 for i in range(-10000, 10000): x = i * 0.49 n = pnoise1(x) self.assertTrue(-1.0 <= n <= 1.0, (x, n)) def test_perlin_1d_octaves_range(self): from noise import pnoise1 for i in range(-1000, 1000): for o in range(10): x = i * 0.49 n = pnoise1(x, octaves=o + 1) self.assertTrue(-1.0 <= n <= 1.0, (x, n)) def test_perlin_1d_base(self): from noise import pnoise1 self.assertEqual(pnoise1(0.5), pnoise1(0.5, base=0)) self.assertNotEqual(pnoise1(0.5), pnoise1(0.5, base=5)) self.assertNotEqual(pnoise1(0.5, base=5), pnoise1(0.5, base=1)) def test_perlin_2d_range(self): from noise import pnoise2 for i in range(-10000, 10000): x = i * 0.49 y = -i * 0.67 n = pnoise2(x, y) self.assertTrue(-1.0 <= n <= 1.0, (x, y, n)) def test_perlin_2d_octaves_range(self): from noise import pnoise2 for i in range(-1000, 1000): for o in range(10): x = -i * 0.49 y = i * 0.67 n = pnoise2(x, y, octaves=o + 1) self.assertTrue(-1.0 <= n <= 1.0, (x, n)) def test_perlin_2d_base(self): from noise import pnoise2 x, y = 0.73, 0.27 self.assertEqual(pnoise2(x, y), pnoise2(x, y, base=0)) self.assertNotEqual(pnoise2(x, y), pnoise2(x, y, base=5)) self.assertNotEqual(pnoise2(x, y, base=5), pnoise2(x, y, base=1)) def test_perlin_3d_range(self): from noise import pnoise3 for i in range(-10000, 10000): x = -i * 0.49 y = i * 0.67 z = -i * 0.727 n = pnoise3(x, y, z) self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, n)) def test_perlin_3d_octaves_range(self): from noise import pnoise3 for i in range(-1000, 1000): x = i * 0.22 y = -i * 0.77 z = -i * 0.17 for o in range(10): n = pnoise3(x, y, z, octaves=o + 1) self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, n)) def test_perlin_3d_base(self): from noise import pnoise3 x, y, z = 0.1, 0.7, 0.33 self.assertEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=0)) self.assertNotEqual(pnoise3(x, y, z), pnoise3(x, y, z, base=5)) self.assertNotEqual(pnoise3(x, y, z, base=5), pnoise3(x, y, z, base=1)) class SimplexTestCase(unittest.TestCase): def test_randomize(self): from noise import randomize self.assertTrue(randomize(4096,23490)) def test_simplex_2d_range(self): from noise import snoise2 for i in range(-10000, 10000): x = i * 0.49 y = -i * 0.67 n = snoise2(x, y) self.assertTrue(-1.0 <= n <= 1.0, (x, y, n)) def test_simplex_2d_octaves_range(self): from noise import snoise2 for i in range(-1000, 1000): for o in range(10): x = -i * 0.49 y = i * 0.67 n = snoise2(x, y, octaves=o + 1) self.assertTrue(-1.0 <= n <= 1.0, (x, n)) def test_simplex_3d_range(self): from noise import snoise3 for i in range(-10000, 10000): x = i * 0.31 y = -i * 0.7 z = i * 0.19 n = snoise3(x, y, z) self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, n)) def test_simplex_3d_octaves_range(self): from noise import snoise3 for i in range(-1000, 1000): x = -i * 0.12 y = i * 0.55 z = i * 0.34 for o in range(10): n = snoise3(x, y, z, octaves=o + 1) self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, o+1, n)) def test_simplex_4d_range(self): from noise import snoise4 for i in range(-10000, 10000): x = i * 0.88 y = -i * 0.11 z = -i * 0.57 w = i * 0.666 n = snoise4(x, y, z, w) self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, w, n)) def test_simplex_4d_octaves_range(self): from noise import snoise4 for i in range(-1000, 1000): x = -i * 0.12 y = i * 0.55 z = i * 0.34 w = i * 0.21 for o in range(10): n = snoise4(x, y, z, w, octaves=o + 1) self.assertTrue(-1.0 <= n <= 1.0, (x, y, z, w, o+1, n)) if __name__ == '__main__': unittest.main()
32.972028
79
0.487381
723
4,715
3.095436
0.096819
0.028597
0.025469
0.135836
0.842717
0.692136
0.630027
0.567471
0.567471
0.529491
0
0.126785
0.376034
4,715
142
80
33.204225
0.633923
0
0
0.495868
0
0
0.001697
0
0
0
0
0
0.181818
1
0.132231
false
0
0.140496
0
0.289256
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
961e5e18627878c209a335c0392cc2286e8803ad
323
py
Python
Asap-3.8.4/Projects/NanoparticleMC/misc/viewatomsmc.py
auag92/n2dm
03403ef8da303b79478580ae76466e374ec9da60
[ "MIT" ]
1
2021-10-19T11:35:34.000Z
2021-10-19T11:35:34.000Z
Asap-3.8.4/Projects/NanoparticleMC/misc/viewatomsmc.py
auag92/n2dm
03403ef8da303b79478580ae76466e374ec9da60
[ "MIT" ]
null
null
null
Asap-3.8.4/Projects/NanoparticleMC/misc/viewatomsmc.py
auag92/n2dm
03403ef8da303b79478580ae76466e374ec9da60
[ "MIT" ]
3
2016-07-18T19:22:48.000Z
2021-07-06T03:06:42.000Z
import ase from ase import Atoms from ase.atom import Atom import sys from ase.visualize import view import pickle f = open(sys.argv[1],'r') #The .amc file p = pickle.load(f) positions = p['atomspositions'] atms = Atoms() for p0 in positions: a = Atom('Au',position=p0) atms.append(a) atms.center(vacuum=2) view(atms)
17
40
0.721362
56
323
4.160714
0.571429
0.090129
0
0
0
0
0
0
0
0
0
0.014545
0.148607
323
18
41
17.944444
0.832727
0.040248
0
0
0
0
0.055016
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
961e930045b962f6aec047adbd1d0fd8f14a977a
453
py
Python
bot_settings_example.py
nikmedoed/BalanceBot
731e6d09d71bbf8d7802d0b42a570947343d3ce6
[ "MIT" ]
null
null
null
bot_settings_example.py
nikmedoed/BalanceBot
731e6d09d71bbf8d7802d0b42a570947343d3ce6
[ "MIT" ]
null
null
null
bot_settings_example.py
nikmedoed/BalanceBot
731e6d09d71bbf8d7802d0b42a570947343d3ce6
[ "MIT" ]
null
null
null
# это dev среда TELEGRAM_TOKEN = "..." RELATIVE_CHAT_IDS = [ "...", '...'] TEXT = { "bot_info": ('Привет, я бот, который отвечает за равномерное распределение участников по комнатам.\n\n' 'Нажми кнопку, если готов сменить комнату'), "get_link": "Получить рекомендацию", "new_room": "Ваша новая комната\n%s", "nothing_to_change": "На данный момент ничего менять не требуется" } def logger(*message): print(message)
30.2
107
0.655629
56
453
5.160714
0.946429
0
0
0
0
0
0
0
0
0
0
0
0.200883
453
15
108
30.2
0.798343
0.028698
0
0
0
0
0.601367
0
0
0
0
0
0
1
0.090909
false
0
0
0
0.090909
0.090909
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
824a4f6bf20408ed367c7e9a67c9b62aea2ab1c0
7,611
py
Python
sweetpea/tests/test_encoding_diagram.py
anniecherk/sweetpea-py
23dbad99a9213ff764ec207b456cf5d002707fd0
[ "MIT" ]
1
2018-05-06T03:54:06.000Z
2018-05-06T03:54:06.000Z
sweetpea/tests/test_encoding_diagram.py
anniecherk/sweetpea-py
23dbad99a9213ff764ec207b456cf5d002707fd0
[ "MIT" ]
5
2018-09-18T02:15:17.000Z
2018-12-05T20:02:24.000Z
sweetpea/tests/test_encoding_diagram.py
anniecherk/sweetpea-py
23dbad99a9213ff764ec207b456cf5d002707fd0
[ "MIT" ]
null
null
null
import pytest import operator as op from sweetpea import fully_cross_block from sweetpea.primitives import Factor, DerivedLevel, WithinTrial, Transition, Window from sweetpea.encoding_diagram import __generate_encoding_diagram color = Factor("color", ["red", "blue"]) text = Factor("text", ["red", "blue"]) con_level = DerivedLevel("con", WithinTrial(op.eq, [color, text])) inc_level = DerivedLevel("inc", WithinTrial(op.ne, [color, text])) con_factor = Factor("congruent?", [con_level, inc_level]) color_repeats_factor = Factor("color repeats?", [ DerivedLevel("yes", Transition(lambda colors: colors[0] == colors[1], [color])), DerivedLevel("no", Transition(lambda colors: colors[0] != colors[1], [color])) ]) text_repeats_factor = Factor("text repeats?", [ DerivedLevel("yes", Transition(lambda colors: colors[0] == colors[1], [text])), DerivedLevel("no", Transition(lambda colors: colors[0] != colors[1], [text])) ]) design = [color, text, con_factor] crossing = [color, text] blk = fully_cross_block(design, crossing, []) def test_generate_encoding_diagram(): assert __generate_encoding_diagram(blk) == "\ ----------------------------------------------\n\ | Trial | color | text | congruent? |\n\ | # | red blue | red blue | con inc |\n\ ----------------------------------------------\n\ | 1 | 1 2 | 3 4 | 5 6 |\n\ | 2 | 7 8 | 9 10 | 11 12 |\n\ | 3 | 13 14 | 15 16 | 17 18 |\n\ | 4 | 19 20 | 21 22 | 23 24 |\n\ ----------------------------------------------\n" def test_generate_encoding_diagram_with_transition(): block = fully_cross_block([color, text, color_repeats_factor], [color, text], []) assert __generate_encoding_diagram(block) == "\ --------------------------------------------------\n\ | Trial | color | text | color repeats? |\n\ | # | red blue | red blue | yes no |\n\ --------------------------------------------------\n\ | 1 | 1 2 | 3 4 | |\n\ | 2 | 5 6 | 7 8 | 17 18 |\n\ | 3 | 9 10 | 11 12 | 19 20 |\n\ | 4 | 13 14 | 15 16 | 21 22 |\n\ --------------------------------------------------\n" def test_generate_encoding_diagram_with_constraint_and_multiple_transitions(): block = fully_cross_block([color, text, con_factor, color_repeats_factor, text_repeats_factor], [color, text], []) assert __generate_encoding_diagram(block) == "\ -------------------------------------------------------------------------------\n\ | Trial | color | text | congruent? | color repeats? | text repeats? |\n\ | # | red blue | red blue | con inc | yes no | yes no |\n\ -------------------------------------------------------------------------------\n\ | 1 | 1 2 | 3 4 | 5 6 | | |\n\ | 2 | 7 8 | 9 10 | 11 12 | 25 26 | 31 32 |\n\ | 3 | 13 14 | 15 16 | 17 18 | 27 28 | 33 34 |\n\ | 4 | 19 20 | 21 22 | 23 24 | 29 30 | 35 36 |\n\ -------------------------------------------------------------------------------\n" def test_generate_encoding_diagram_with_constraint_and_multiple_transitions_in_different_order(): block = fully_cross_block([text_repeats_factor, color, color_repeats_factor, text, con_factor], [color, text], []) assert __generate_encoding_diagram(block) == "\ -------------------------------------------------------------------------------\n\ | Trial | text repeats? | color | color repeats? | text | congruent? |\n\ | # | yes no | red blue | yes no | red blue | con inc |\n\ -------------------------------------------------------------------------------\n\ | 1 | | 1 2 | | 3 4 | 5 6 |\n\ | 2 | 25 26 | 7 8 | 31 32 | 9 10 | 11 12 |\n\ | 3 | 27 28 | 13 14 | 33 34 | 15 16 | 17 18 |\n\ | 4 | 29 30 | 19 20 | 35 36 | 21 22 | 23 24 |\n\ -------------------------------------------------------------------------------\n" def test_generate_encoding_diagram_with_windows(): color3 = Factor("color3", ["red", "blue", "green"]) yes_fn = lambda colors: colors[0] == colors[1] == colors[2] no_fn = lambda colors: not yes_fn(colors) color3_repeats_factor = Factor("color3 repeats?", [ DerivedLevel("yes", Window(yes_fn, [color3], 3, 1)), DerivedLevel("no", Window(no_fn, [color3], 3, 1)) ]) block = fully_cross_block([color3_repeats_factor, color3, text], [color3, text], []) assert __generate_encoding_diagram(block) == "\ ---------------------------------------------------------\n\ | Trial | color3 repeats? | color3 | text |\n\ | # | yes no | red blue green | red blue |\n\ ---------------------------------------------------------\n\ | 1 | | 1 2 3 | 4 5 |\n\ | 2 | | 6 7 8 | 9 10 |\n\ | 3 | 31 32 | 11 12 13 | 14 15 |\n\ | 4 | 33 34 | 16 17 18 | 19 20 |\n\ | 5 | 35 36 | 21 22 23 | 24 25 |\n\ | 6 | 37 38 | 26 27 28 | 29 30 |\n\ ---------------------------------------------------------\n" def test_generate_encoding_diagram_with_window_with_stride(): congruent_bookend = Factor("congruent bookend?", [ DerivedLevel("yes", Window(lambda colors, texts: colors[0] == texts[0], [color, text], 1, 3)), DerivedLevel("no", Window(lambda colors, texts: colors[0] == texts[0], [color, text], 1, 3)) ]) block = fully_cross_block([color, text, congruent_bookend], [color, text], []) assert __generate_encoding_diagram(block) == "\ ------------------------------------------------------\n\ | Trial | color | text | congruent bookend? |\n\ | # | red blue | red blue | yes no |\n\ ------------------------------------------------------\n\ | 1 | 1 2 | 3 4 | 17 18 |\n\ | 2 | 5 6 | 7 8 | |\n\ | 3 | 9 10 | 11 12 | |\n\ | 4 | 13 14 | 15 16 | 19 20 |\n\ ------------------------------------------------------\n" congruent_bookend = Factor("congruent bookend?", [ DerivedLevel("yes", Window(lambda colors, texts: colors[0] == texts[0], [color, text], 2, 2)), DerivedLevel("no", Window(lambda colors, texts: colors[0] == texts[0], [color, text], 2, 2)) ]) block = fully_cross_block([color, text, congruent_bookend], [color, text], []) assert __generate_encoding_diagram(block) == "\ ------------------------------------------------------\n\ | Trial | color | text | congruent bookend? |\n\ | # | red blue | red blue | yes no |\n\ ------------------------------------------------------\n\ | 1 | 1 2 | 3 4 | |\n\ | 2 | 5 6 | 7 8 | 17 18 |\n\ | 3 | 9 10 | 11 12 | |\n\ | 4 | 13 14 | 15 16 | 19 20 |\n\ ------------------------------------------------------\n"
48.170886
102
0.411247
785
7,611
3.830573
0.123567
0.068839
0.107083
0.067509
0.618557
0.591952
0.542401
0.532757
0.481543
0.446625
0
0.076106
0.307713
7,611
157
103
48.477707
0.494591
0
0
0.412698
0
0
0.021025
0
0
0
0
0
0.055556
1
0.047619
false
0
0.039683
0
0.087302
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
824adf7af953a3787b6ad72eca002b2f5fa3b943
297
py
Python
Source_Code/Python/ConductedTest/case_generator.py
fenglwh/instruments
7886158d1ed97fe6bfe372a55f4fca107e834311
[ "MIT" ]
null
null
null
Source_Code/Python/ConductedTest/case_generator.py
fenglwh/instruments
7886158d1ed97fe6bfe372a55f4fca107e834311
[ "MIT" ]
3
2018-09-21T00:57:21.000Z
2018-09-21T01:49:40.000Z
Source_Code/Python/ConductedTest/case_generator.py
fenglwh/instruments
7886158d1ed97fe6bfe372a55f4fca107e834311
[ "MIT" ]
null
null
null
import json from labinstrument.SS.CMW500.CMW500_WIFI.CMW500_WIFI import * if __name__ == '__main__': new_config_name='emm' new_config=CMW_WIFI(17).get_parameters() config=json.load(open('config.txt')) config[new_config_name]=new_config json.dump(config,open('config.txt','w'))
33
61
0.737374
44
297
4.568182
0.5
0.179104
0.129353
0
0
0
0
0
0
0
0
0.041985
0.117845
297
9
62
33
0.725191
0
0
0
0
0
0.107383
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
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
0
0
0
1
8267a45960a2743e88617d4dc273ba1a2f8b4aea
1,231
py
Python
app.py
iio1989/oshite
dd95eced2630929705670aaf23be5f35df3b9737
[ "OLDAP-2.3" ]
null
null
null
app.py
iio1989/oshite
dd95eced2630929705670aaf23be5f35df3b9737
[ "OLDAP-2.3" ]
1
2020-09-24T05:15:00.000Z
2020-09-24T05:17:06.000Z
app.py
iio1989/oshite
dd95eced2630929705670aaf23be5f35df3b9737
[ "OLDAP-2.3" ]
null
null
null
from flask import Flask, render_template, request, redirect, url_for, Markup import app_helper as apHelp app = Flask(__name__) @app.route('/') def root(): return render_template('home.html') # click convetBtn. get HttpParam. @app.route('/post', methods=['GET', 'POST']) def post(): if request.method == 'POST': input_kana = request.form['input_kana'] converted_input_list = apHelp.getConvetedStr_kanaToOshite(input_kana) # rendering for home.html. return render_template('home.html', input_kana=input_kana, converted_input_list=converted_input_list, fileType= apHelp.FILE_TYPE) else: # error redirect. return redirect(url_for('home')) # click homeBtn from header. @app.route('/home', methods=['GET', 'POST']) def home(): return render_template('home.html') # click aboutBtn from header. @app.route('/about', methods=['GET', 'POST']) def about(): return render_template('about.html') # click historyBtn from header. @app.route('/history', methods=['GET', 'POST']) def history(): return render_template('history.html') if __name__ == '__main__': app.run(debug=True)
30.775
77
0.645004
147
1,231
5.170068
0.353742
0.110526
0.131579
0.089474
0.194737
0.086842
0
0
0
0
0
0
0.215272
1,231
40
78
30.775
0.786749
0.127539
0
0.071429
0
0
0.11985
0
0
0
0
0
0
1
0.178571
false
0
0.071429
0.142857
0.464286
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
0
0
0
1
826e7e8ce0638e411f4ad1445cfe2c06fdbae9c6
936
py
Python
sigmod2021-exdra-p523/experiments/code/other/l2svm.py
damslab/reproducibility
f7804b2513859f7e6f14fa7842d81003d0758bf8
[ "Apache-2.0" ]
4
2021-12-10T17:20:26.000Z
2021-12-27T14:38:40.000Z
sigmod2021-exdra-p523/experiments/code/other/l2svm.py
damslab/reproducibility
f7804b2513859f7e6f14fa7842d81003d0758bf8
[ "Apache-2.0" ]
null
null
null
sigmod2021-exdra-p523/experiments/code/other/l2svm.py
damslab/reproducibility
f7804b2513859f7e6f14fa7842d81003d0758bf8
[ "Apache-2.0" ]
null
null
null
import numpy as np import argparse from sklearn.svm import LinearSVR from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.datasets import make_regression parser = argparse.ArgumentParser() parser.add_argument('-x', '--datapath', type=str, required=True) parser.add_argument('-y', '--labels', type=str, required=True) parser.add_argument('-v', '--verbose', type=bool, default=False) parser.add_argument('-o', '--outputpath', type=str, required=True) args = parser.parse_args() X = np.load(args.datapath, allow_pickle=True) y = np.load(args.labels, allow_pickle=True) # http://scikit-learn.sourceforge.net/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC regr = make_pipeline(StandardScaler(), LinearSVR(verbose=args.verbose, tol = 1e-5, max_iter = 30)) regr.fit(X,y) np.savetxt(args.outputpath, regr.named_steps['linearsvr'].coef_, delimiter=",")
36
111
0.766026
130
936
5.415385
0.476923
0.0625
0.096591
0.080966
0.102273
0.102273
0.102273
0
0
0
0
0.004678
0.086538
936
25
112
37.44
0.818713
0.115385
0
0
0
0
0.069259
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
8275090a0a26b9725fd053645507a75767690bfa
6,656
py
Python
dumbai.py
CapKenway/dumbai
affa89663c980177d6c1e0fef9bda7978032da4d
[ "Unlicense" ]
null
null
null
dumbai.py
CapKenway/dumbai
affa89663c980177d6c1e0fef9bda7978032da4d
[ "Unlicense" ]
null
null
null
dumbai.py
CapKenway/dumbai
affa89663c980177d6c1e0fef9bda7978032da4d
[ "Unlicense" ]
null
null
null
import sys from pprint import pprint import os #--------------------------------------------------------------------------# class CsPP(): def __init__(self, domains): self.domains = domains self.maindict = {} self.keyitems = [] pass def check_if(self): emptylist = [] for domainkey in list(self.domains.keys()): if not domainkey in list(self.maindict.keys()): emptylist.append(domainkey) for listitem in emptylist: self.maindict[listitem] = list(self.domains.values())[1] pass def not_belonging(self, key, lister): templist = [] maindomain = self.domains[key] for item in maindomain: if not item in lister: templist.append(item) self.maindict[key] = templist pass def belonging(self, key, lister): self.maindict.__setitem__(key, lister) pass def get_one_up(self, values): self.keyitems.insert(self.keyitems.index(values[0]), values[1]) def get_one_down(self, values): self.keyitems.reverse() self.keyitems.insert(self.keyitems.index(values[1]), values[0]) self.keyitems.reverse() def not_working_together(self, first, second): firstlist = self.maindict[first] secondlist = self.maindict[second] for item in firstlist: if item in secondlist: firstlist.remove(item) self.maindict[first] = firstlist def backtrack(self, maindict, what_want = '', conditions = [], starter = ''): csp_back = CsPP_Backend(domains = maindict, what_want = what_want, conditions = conditions, starter = starter) return csp_back._backtrack() pass def left_to_right(self, maindict, path): to_do = [] pathkeys = list(path.keys()) pathvalues = list(path.values()) mainkeys = list(maindict.keys()) mainvalues = list(maindict.values()) keylist = [] for key, values in zip(pathkeys, pathvalues): keylist.append(key) if len(values) > 1: to_do.append(values[1:]) if len(to_do) != 0: for i in range(0, len(to_do)): popped = to_do.pop(i) keylist.append(popped) for item in keylist: if keylist.count(item) > 1: keylist.remove(item) if type(item) == list: keylist.remove(item) valuestodict = [] for key in keylist: if type(key) != list: valuestodict.append(maindict[key]) else: keylist.remove(key) returndict = dict((key, values) for key, values in zip(keylist, valuestodict)) forprune = CsPP_Backend() pruned = forprune._prune(returndict) return pruned def right_to_left(self, maindict, path): tempkeys = list(path.keys()) tempvalues = list(path.values()) tempvalues.reverse() tempkeys.reverse() i = 0 flag = False templist = [] removeditems = [] indexes = [] i = 0 templist.append(tempkeys[0]) for key in tempkeys: for n in range(i, len(tempvalues)): flag = False for u in range(0, len(tempvalues[n])): if len(tempvalues)!= 0 and key == tempvalues[n][u]: i = n templist.append(tempkeys[n]) flag = True break if flag: break for item in templist: if templist.count(item) > 1: templist.remove(item) dictvalues = [] for tempval in templist: dictvalues.append(maindict[tempval]) availdict = dict((key, val) for key, val in zip(templist, dictvalues)) removedvalues = [] for key in list(maindict.keys()): if not key in list(availdict.keys()): removeditems.append(key) removedvalues.append(maindict[key]) removeddict = dict((key, val) for key, val in zip(removeditems, removedvalues)) forprune = CsPP_Backend() pruned = forprune._prune(availdict) for key in list(removeddict.keys()): pruned[key] = [] return pruned pass #--------------------------------------------------------------------------# class CsPP_Backend(): def __init__(self, *args, **kwargs): self.domains = kwargs.get('domains') self.conditions = kwargs.get('conditions') self.what_want = kwargs.get('what_want') self.starter = kwargs.get('starter') pass def _backtrack(self): if self.what_want == 'mrv': return self._highest_constraint(self.domains, self.starter) elif self.what_want == 'lcv': return self._minimum_constraint(self.domains, self.starter) else: return self.domains def _minimum_constraint(self, domains, starter = ''): low_constraint = None if starter != '': yet_lowest = len(domains[starter]) else: yet_lowest = len(domains[list(domains.keys())[0]]) for key, val in zip(list(domains.keys()), list(domains.values())): if yet_lowest > len(val): yet_lowest = len(val) low_constraint = key return low_constraint pass def _highest_constraint(self, domains, starter = ''): high_constraint = None if starter != '': yet_highest = len(domains[starter]) else: yet_highest = len(domains[list(domains.keys())[0]]) for key, val in zip(list(domains.keys()), list(domains.values())): if yet_highest < len(val): yet_highest = len(val) high_constraint = key return high_constraint pass def _prune(self, domains): emptydict = {} pruneditems = [] for key, value in zip(list(domains.keys()), list(domains.values())): for val in value: if val in pruneditems: continue emptydict.__setitem__(key, val) pruneditems.append(val) break for key in list(domains.keys()): if not key in list(emptydict.keys()): emptydict.__setitem__(key, []) return emptydict #--------------------------------------------------------------------------#
35.404255
118
0.526292
690
6,656
4.965217
0.169565
0.038529
0.02627
0.012843
0.18418
0.126386
0.093695
0.069761
0.04495
0.04495
0
0.004077
0.336689
6,656
188
119
35.404255
0.771914
0.033353
0
0.201183
0
0
0.006066
0
0
0
0
0
0
1
0.088757
false
0.053254
0.017751
0
0.171598
0.005917
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
0
0
1
8288331b93be5bebcd8bf3d2c82ccd107597d65b
1,067
py
Python
ApendixI-Games/StacklessPSP-2.5.2_R1/pspsnd.py
MelroLeandro/Matematica-Discreta-para-Hackers-ipnyb
1f9ca7db685733a3df924db1269bd852acf27602
[ "MIT" ]
null
null
null
ApendixI-Games/StacklessPSP-2.5.2_R1/pspsnd.py
MelroLeandro/Matematica-Discreta-para-Hackers-ipnyb
1f9ca7db685733a3df924db1269bd852acf27602
[ "MIT" ]
1
2019-08-16T12:59:01.000Z
2019-08-18T06:36:47.000Z
ApendixI-Games/StacklessPSP-2.5.2_R1/pspsnd.py
MelroLeandro/Matematica-Discreta-para-Hackers-ipnyb
1f9ca7db685733a3df924db1269bd852acf27602
[ "MIT" ]
null
null
null
"""Wrapper for pygame, which exports the PSP Python API on non-PSP systems.""" __author__ = "Per Olofsson, <MagerValp@cling.gu.se>" import pygame pygame.init() _vol_music = 255 _vol_sound = 255 def setMusicVolume(vol): global _vol_music if vol >= 0 and vol <= 255: _vol_music = vol pygame.mixer.music.set_volume(_vol_music / 255.0) def setSndFxVolume(vol): global _vol_sound if vol >= 0 and vol <= 255: _vol_sound = vol class Music: def __init__(self, filename, maxchan=128, loop=False): self._loop = loop pygame.mixer.music.load(filename) pygame.mixer.music.set_volume(_vol_music / 255.0) def start(self): if self._loop: pygame.mixer.music.play(-1) else: pygame.mixer.music.play() def stop(self): pygame.mixer.music.stop() class Sound: def __init__(self, filename): self._snd = pygame.mixer.Sound(filename) def start(self): self._snd.set_volume(_vol_sound / 255.0) self._snd.play()
21.34
78
0.62418
145
1,067
4.331034
0.337931
0.122611
0.152866
0.028662
0.184713
0.184713
0.184713
0.127389
0.127389
0.127389
0
0.038168
0.263355
1,067
49
79
21.77551
0.760814
0.067479
0
0.1875
0
0
0.037412
0.023256
0
0
0
0
0
1
0.21875
false
0
0.03125
0
0.3125
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
0
0
0
1
828ccbf87f380dbc253cd5ac125a944fc9a7bd55
4,262
py
Python
src/commercetools/services/types.py
BramKaashoek/commercetools-python-sdk
4a4191d7816c921401b782d8ae37626cb32791a1
[ "MIT" ]
null
null
null
src/commercetools/services/types.py
BramKaashoek/commercetools-python-sdk
4a4191d7816c921401b782d8ae37626cb32791a1
[ "MIT" ]
null
null
null
src/commercetools/services/types.py
BramKaashoek/commercetools-python-sdk
4a4191d7816c921401b782d8ae37626cb32791a1
[ "MIT" ]
null
null
null
import typing from commercetools import schemas, types from commercetools.services import abstract from commercetools.typing import OptionalListStr __all__ = ["TypeService"] class TypeDeleteSchema(abstract.AbstractDeleteSchema): pass class TypeQuerySchema(abstract.AbstractQuerySchema): pass class TypeService(abstract.AbstractService): def get_by_id(self, id: str, expand: OptionalListStr = None) -> types.Type: query_params = {} if expand: query_params["expand"] = expand return self._client._get(f"types/{id}", query_params, schemas.TypeSchema) def get_by_key(self, key: str, expand: OptionalListStr = None) -> types.Type: query_params = {} if expand: query_params["expand"] = expand return self._client._get(f"types/key={key}", query_params, schemas.TypeSchema) def query( self, where: OptionalListStr = None, sort: OptionalListStr = None, expand: OptionalListStr = None, limit: int = None, offset: int = None, ) -> types.TypePagedQueryResponse: params = TypeQuerySchema().dump( { "where": where, "sort": sort, "expand": expand, "limit": limit, "offset": offset, } ) return self._client._get("types", params, schemas.TypePagedQueryResponseSchema) def create( self, draft: types.TypeDraft, expand: OptionalListStr = None ) -> types.Type: query_params = {} if expand: query_params["expand"] = expand return self._client._post( "types", query_params, draft, schemas.TypeDraftSchema, schemas.TypeSchema ) def update_by_id( self, id: str, version: int, actions: typing.List[types.TypeUpdateAction], expand: OptionalListStr = None, *, force_update: bool = False, ) -> types.Type: query_params = {} if expand: query_params["expand"] = expand update_action = types.TypeUpdate(version=version, actions=actions) return self._client._post( endpoint=f"types/{id}", params=query_params, data_object=update_action, request_schema_cls=schemas.TypeUpdateSchema, response_schema_cls=schemas.TypeSchema, force_update=force_update, ) def update_by_key( self, key: str, version: int, actions: typing.List[types.TypeUpdateAction], expand: OptionalListStr = None, *, force_update: bool = False, ) -> types.Type: query_params = {} if expand: query_params["expand"] = expand update_action = types.TypeUpdate(version=version, actions=actions) return self._client._post( endpoint=f"types/key={key}", params=query_params, data_object=update_action, request_schema_cls=schemas.TypeUpdateSchema, response_schema_cls=schemas.TypeSchema, force_update=force_update, ) def delete_by_id( self, id: str, version: int, expand: OptionalListStr = None, *, force_delete: bool = False, ) -> types.Type: params = {"version": version} if expand: params["expand"] = expand query_params = TypeDeleteSchema().dump(params) return self._client._delete( endpoint=f"types/{id}", params=query_params, response_schema_cls=schemas.TypeSchema, force_delete=force_delete, ) def delete_by_key( self, key: str, version: int, expand: OptionalListStr = None, *, force_delete: bool = False, ) -> types.Type: params = {"version": version} if expand: params["expand"] = expand query_params = TypeDeleteSchema().dump(params) return self._client._delete( endpoint=f"types/key={key}", params=query_params, response_schema_cls=schemas.TypeSchema, force_delete=force_delete, )
30.22695
87
0.585171
408
4,262
5.914216
0.164216
0.086614
0.082884
0.041442
0.707833
0.673021
0.673021
0.653129
0.648156
0.648156
0
0
0.316987
4,262
140
88
30.442857
0.828925
0
0
0.68
0
0
0.041764
0
0
0
0
0
0
1
0.064
false
0.016
0.032
0
0.184
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
8299ba8eed08b051c1bd7e22979a2992369a89ff
4,398
py
Python
forge/mock_handle.py
ujjwalsh/pyforge
454d7df39f6d6cc7531d3f87e7b7f7d83ae6e66e
[ "BSD-3-Clause" ]
7
2015-01-01T18:40:53.000Z
2021-10-20T14:13:08.000Z
forge/mock_handle.py
ujjwalsh/pyforge
454d7df39f6d6cc7531d3f87e7b7f7d83ae6e66e
[ "BSD-3-Clause" ]
6
2016-03-31T16:40:30.000Z
2020-12-23T07:24:53.000Z
forge/mock_handle.py
ujjwalsh/pyforge
454d7df39f6d6cc7531d3f87e7b7f7d83ae6e66e
[ "BSD-3-Clause" ]
9
2016-03-31T15:21:29.000Z
2021-03-20T06:29:09.000Z
from .handle import ForgeHandle class MockHandle(ForgeHandle): def __init__(self, forge, mock, behave_as_instance=True): super(MockHandle, self).__init__(forge) self.mock = mock self.behaves_as_instance = behave_as_instance self._attributes = {} self._is_hashable = False self._is_setattr_enabled_in_replay = False def is_hashable(self): return self._is_hashable def enable_hashing(self): self._is_hashable = True def disable_hashing(self): self._is_hashable = False def enable_setattr_during_replay(self): self._is_setattr_enabled_in_replay = True def disable_setattr_during_replay(self): self._is_setattr_enabled_in_replay = False def is_setattr_enabled_in_replay(self): return self._is_setattr_enabled_in_replay def has_attribute(self, attr): return False def get_attribute(self, attr): if self.forge.attributes.has_attribute(self.mock, attr): return self.forge.attributes.get_attribute(self.mock, attr) if self.has_nonmethod_class_member(attr): return self.get_nonmethod_class_member(attr) if self.has_method(attr): return self.get_method(attr) raise AttributeError("%s has no attribute %r" % (self.mock, attr)) def set_attribute(self, attr, value, caller_info): if self.forge.is_recording() or self.is_setattr_enabled_in_replay(): self._set_attribute(attr, value) else: self._set_attribute_during_replay(attr, value, caller_info) def expect_setattr(self, attr, value): return self.forge.queue.push_setattr(self.mock, attr, value, caller_info=self.forge.debug.get_caller_info()) def _set_attribute_during_replay(self, attr, value, caller_info): self.forge.queue.pop_matching_setattr(self.mock, attr, value, caller_info) self._set_attribute(attr, value) def _set_attribute(self, attr, value): self.forge.attributes.set_attribute(self.mock, attr, value) def has_method(self, attr): return self.forge.stubs.has_initialized_method_stub(self.mock, attr) or self._has_method(attr) def _has_method(self, name): raise NotImplementedError() def has_nonmethod_class_member(self, name): raise NotImplementedError() def get_nonmethod_class_member(self, name): raise NotImplementedError() def get_method(self, name): returned = self.forge.stubs.get_initialized_method_stub_or_none(self.mock, name) if returned is None: real_method = self._get_real_method(name) if not self.forge.is_recording(): self._check_unrecorded_method_getting(name) returned = self._construct_stub(name, real_method) self._bind_if_needed(name, returned) self.forge.stubs.add_initialized_method_stub(self.mock, name, returned) self._set_method_description(returned, name) elif self.forge.is_replaying() and not returned.__forge__.has_recorded_calls(): self._check_getting_method_stub_without_recorded_calls(name, returned) return returned def _set_method_description(self, method, name): method.__forge__.set_description("%s.%s" % ( self.describe(), name )) def _construct_stub(self, name, real_method): return self.forge.create_method_stub(real_method) def _check_unrecorded_method_getting(self, name): raise NotImplementedError() def _check_getting_method_stub_without_recorded_calls(self, name, stub): raise NotImplementedError() def _get_real_method(self, name): raise NotImplementedError() def handle_special_method_call(self, name, args, kwargs, caller_info): self._check_special_method_call(name, args, kwargs) return self.get_method(name).__forge__.handle_call(args, kwargs, caller_info) def _check_special_method_call(self, name, args, kwargs): raise NotImplementedError() def is_callable(self): raise NotImplementedError() def _bind_if_needed(self, name, method_stub): bind_needed, bind_target = self._is_binding_needed(name, method_stub) if bind_needed: method_stub.__forge__.bind(bind_target) def _is_binding_needed(self, name, method_stub): raise NotImplementedError()
48.32967
116
0.705548
561
4,398
5.131907
0.156863
0.043765
0.075026
0.037513
0.365405
0.261549
0.172282
0.118791
0.092393
0.035429
0
0
0.208504
4,398
90
117
48.866667
0.827061
0
0
0.168539
0
0
0.006139
0
0
0
0
0
0
1
0.314607
false
0
0.011236
0.067416
0.460674
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
0
0
0
1
82a2aae9ea64aaa7fb4b9cb2856b242dd76d5578
239
py
Python
scripts/plotRUC.py
akrherz/radcomp
d44459f72891c6e1a92b61488e08422383b000d1
[ "Apache-2.0" ]
3
2015-04-18T22:23:27.000Z
2016-05-12T11:24:32.000Z
scripts/plotRUC.py
akrherz/radcomp
d44459f72891c6e1a92b61488e08422383b000d1
[ "Apache-2.0" ]
4
2016-09-30T15:04:46.000Z
2022-03-05T13:32:40.000Z
scripts/plotRUC.py
akrherz/radcomp
d44459f72891c6e1a92b61488e08422383b000d1
[ "Apache-2.0" ]
4
2015-04-18T22:23:57.000Z
2017-05-07T15:23:37.000Z
import matplotlib.pyplot as plt import netCDF4 import numpy nc = netCDF4.Dataset("data/ructemps.nc") data = nc.variables["tmpc"][17, :, :] nc.close() (fig, ax) = plt.subplots(1, 1) ax.imshow(numpy.flipud(data)) fig.savefig("test.png")
17.071429
40
0.698745
37
239
4.513514
0.648649
0
0
0
0
0
0
0
0
0
0
0.028436
0.117155
239
13
41
18.384615
0.763033
0
0
0
0
0
0.117155
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
82a4a9f7dd1ed9b3be8582ffaccf49c75f0cf8a6
3,031
py
Python
tools/draw_cal_lr_ablation.py
twangnh/Calibration_mrcnn
e5f3076cefbe35297a403a753bb57e11503db818
[ "Apache-2.0" ]
87
2020-07-24T01:28:39.000Z
2021-08-29T08:40:18.000Z
tools/draw_cal_lr_ablation.py
twangnh/Calibration_mrcnn
e5f3076cefbe35297a403a753bb57e11503db818
[ "Apache-2.0" ]
3
2020-09-27T12:59:28.000Z
2022-01-06T13:14:08.000Z
tools/draw_cal_lr_ablation.py
twangnh/Calibration_mrcnn
e5f3076cefbe35297a403a753bb57e11503db818
[ "Apache-2.0" ]
20
2020-09-05T04:37:19.000Z
2021-12-13T02:25:48.000Z
import matplotlib import matplotlib.pyplot as plt import numpy as np import math from matplotlib.ticker import FormatStrFormatter from matplotlib import scale as mscale from matplotlib import transforms as mtransforms # z = [0,0.1,0.3,0.9,1,2,5] z = [7.8, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1230] # thick = [20,40,20,60,37,32,21]ax1.set_xscale('log') # thick=[15.4, 18.2, 18.7, 19.2, 19.4, 19.5, 19.9, 20.1, 20.4, 20.5, 20.6, 20.7, 20.8, 20.7, 20.7, 20.6, 20.6, 20.6, 20.5, 20.5, 19.8] mrcnn=[17.7, 19.8, 20.0, 19.9, 20.2, 19.5, 19.1, 19.1] x_ticks = [0.001, 0.002, 0.004, 0.008, 0.01, 0.02, 0.04, 0.08] # plt.plot([1.0],[44.8], 'D', color = 'black') # plt.plot([0],[35.9], 'D', color = 'red') # plt.plot([1.0],[56.8], 'D', color = 'black') fig = plt.figure(figsize=(8,5)) ax1 = fig.add_subplot(111) matplotlib.rcParams.update({'font.size': 20}) ax1.plot(x_ticks, mrcnn, linestyle='dashed', marker='o', linewidth=2, c='k', label='mrcnn-r50-ag') # ax1.plot(z, htc, marker='o', linewidth=2, c='g', label='htc') # ax1.plot([1e-4],[15.4], 'D', color = 'green') # ax1.plot([1230],[19.8], 'D', color = 'red') plt.xlabel('calibration lr', size=16) plt.ylabel('bAP', size=16) # plt.gca().set_xscale('custom') ax1.set_xscale('log') ax1.set_xticks(x_ticks) # from matplotlib.ticker import ScalarFormatter # ax1.xaxis.set_major_formatter(ScalarFormatter()) # plt.legend(['calibration lr'], loc='best') plt.minorticks_off() plt.grid() plt.savefig('calibration_lr.eps', format='eps', dpi=1000) plt.show() # import numpy as np # import matplotlib.pyplot as plt # from scipy.interpolate import interp1d # y1=[35.9, 43.4, 46.1, 49.3, 50.3, 51.3, 51.4, 49.9, 49.5, 48.5, 44.8] # y2=[40.5, 48.2, 53.9 , 56.9, 57.8, 59.2, 58.3, 57.9, 57.5, 57.2, 56.8] # y3=[61.5, 61.5, 61.5, 61.5, 61.5, 61.5, 61.5, 61.5, 61.5, 61.5, 61.5] # x = np.linspace(0, 1, num=11, endpoint=True) # # f1 = interp1d(x, y1, kind='cubic') # f2 = interp1d(x, y2, kind='cubic') # f3 = interp1d(x, y3, kind='cubic') # xnew = np.linspace(0, 1, num=101, endpoint=True) # plt.plot(xnew, f3(xnew), '--', color='fuchsia') # plt.plot(xnew, f1(xnew), '--', color='blue') # plt.plot(xnew, f2(xnew), '--', color='green') # # plt.plot([0],[40.5], 'D', color = 'red') # plt.plot([1.0],[44.8], 'D', color = 'black') # plt.plot([0],[35.9], 'D', color = 'red') # plt.plot([1.0],[56.8], 'D', color = 'black') # plt.plot(x, y3, 'o', color = 'fuchsia') # plt.plot(x, y1, 'o', color = 'blue') # plt.plot(x, y2, 'o', color = 'green') # plt.plot([0],[40.5], 'D', color = 'red') # plt.plot([1.0],[44.8], 'D', color = 'black') # plt.plot([0],[35.9], 'D', color = 'red') # plt.plot([1.0],[56.8], 'D', color = 'black') # plt.legend(['teacher','0.25x', '0.5x', 'full-feature-imitation', 'only GT supervison'], loc='best') # plt.xlabel('Thresholding factor') # plt.ylabel('mAP') # plt.title('Resulting mAPs of varying thresholding factors') # #plt.legend(['0.5x']) # # plt.savefig('varying_thresh.eps', format='eps', dpi=1000) # plt.show()
35.244186
134
0.61069
575
3,031
3.196522
0.302609
0.064744
0.027203
0.032644
0.282916
0.192057
0.18988
0.161589
0.161589
0.161589
0
0.159909
0.12933
3,031
85
135
35.658824
0.536567
0.680633
0
0
0
0
0.076336
0
0
0
0
0
0
1
0
false
0
0.318182
0
0.318182
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
0
0
0
1