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
9fa9b9a2508774b622073aec9a477c8353758d80
1,188
py
Python
tests/test_data_models.py
haihabi/GenerativeCRB
d53c01bec7214bb087fbe17dba241e12eb60858e
[ "MIT" ]
null
null
null
tests/test_data_models.py
haihabi/GenerativeCRB
d53c01bec7214bb087fbe17dba241e12eb60858e
[ "MIT" ]
null
null
null
tests/test_data_models.py
haihabi/GenerativeCRB
d53c01bec7214bb087fbe17dba241e12eb60858e
[ "MIT" ]
null
null
null
import unittest import torch import data_model as dm import normflowpy as nf from experiments import constants def generate_model_dict(): return {constants.DIM: 4, constants.THETA_MIN: 0.3, constants.THETA_MAX: 10, constants.SIGMA_N: 0.1, } class FlowToCRBTest(unittest.TestCase): def run_model_check(self, model_enum): model = dm.get_model(model_enum, generate_model_dict()) self.assertTrue(str(4) in model.name) # Check that dim size in model name self.assertTrue(model.__class__.__name__ in model.name) # Check that class name is in model flow = model.get_optimal_model() self.assertTrue(isinstance(flow, nf.NormalizingFlowModel)) crb_value = model.crb(2.0) self.assertTrue(isinstance(crb_value, torch.Tensor)) def test_flow_linear(self): self.run_model_check(dm.ModelType.Linear) def test_gaussian_variance(self): self.run_model_check(dm.ModelType.GaussianVariance) def test_mult_1_3(self): self.run_model_check(dm.ModelType.Pow1Div3Gaussian) def test_mult_3(self): self.run_model_check(dm.ModelType.Pow3Gaussian)
32.108108
100
0.70202
161
1,188
4.919255
0.36646
0.050505
0.082071
0.080808
0.214646
0.164141
0.164141
0.083333
0
0
0
0.017076
0.211279
1,188
36
101
33
0.828175
0.056397
0
0
1
0
0
0
0
0
0
0
0.142857
1
0.214286
false
0
0.178571
0.035714
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
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
9fa9e56b663a8787279c9b910d19d9a32f11bba2
15,310
py
Python
neutronclient/tests/unit/test_auth.py
asadoughi/python-neutronclient
2026ffdc6c82135b64b3ccd569a4a442e170ca53
[ "Apache-2.0" ]
1
2016-07-16T09:36:02.000Z
2016-07-16T09:36:02.000Z
neutronclient/tests/unit/test_auth.py
ntt-sic/python-neutronclient
a8c5c650ea7d51461c6311fb477b733b2f7c36a0
[ "Apache-2.0" ]
null
null
null
neutronclient/tests/unit/test_auth.py
ntt-sic/python-neutronclient
a8c5c650ea7d51461c6311fb477b733b2f7c36a0
[ "Apache-2.0" ]
null
null
null
# Copyright 2012 NEC Corporation # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # vim: tabstop=4 shiftwidth=4 softtabstop=4 import copy import httplib2 import json import uuid import mox import testtools from neutronclient import client from neutronclient.common import exceptions from neutronclient.common import utils USERNAME = 'testuser' TENANT_NAME = 'testtenant' TENANT_ID = 'testtenantid' PASSWORD = 'password' AUTH_URL = 'authurl' ENDPOINT_URL = 'localurl' ENDPOINT_OVERRIDE = 'otherurl' TOKEN = 'tokentoken' REGION = 'RegionTest' KS_TOKEN_RESULT = { 'access': { 'token': {'id': TOKEN, 'expires': '2012-08-11T07:49:01Z', 'tenant': {'id': str(uuid.uuid1())}}, 'user': {'id': str(uuid.uuid1())}, 'serviceCatalog': [ {'endpoints_links': [], 'endpoints': [{'adminURL': ENDPOINT_URL, 'internalURL': ENDPOINT_URL, 'publicURL': ENDPOINT_URL, 'region': REGION}], 'type': 'network', 'name': 'Neutron Service'} ] } } ENDPOINTS_RESULT = { 'endpoints': [{ 'type': 'network', 'name': 'Neutron Service', 'region': REGION, 'adminURL': ENDPOINT_URL, 'internalURL': ENDPOINT_URL, 'publicURL': ENDPOINT_URL }] } class CLITestAuthKeystone(testtools.TestCase): # Auth Body expected when using tenant name auth_type = 'tenantName' def setUp(self): """Prepare the test environment.""" super(CLITestAuthKeystone, self).setUp() self.mox = mox.Mox() self.client = client.HTTPClient(username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION) self.addCleanup(self.mox.VerifyAll) self.addCleanup(self.mox.UnsetStubs) def test_get_token(self): self.mox.StubOutWithMock(self.client, "request") res200 = self.mox.CreateMock(httplib2.Response) res200.status = 200 self.client.request( AUTH_URL + '/tokens', 'POST', body=mox.StrContains(self.auth_type), headers=mox.IsA(dict) ).AndReturn((res200, json.dumps(KS_TOKEN_RESULT))) self.client.request( mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) ).AndReturn((res200, '')) self.mox.ReplayAll() self.client.do_request('/resource', 'GET') self.assertEqual(self.client.endpoint_url, ENDPOINT_URL) self.assertEqual(self.client.auth_token, TOKEN) def test_refresh_token(self): self.mox.StubOutWithMock(self.client, "request") self.client.auth_token = TOKEN self.client.endpoint_url = ENDPOINT_URL res200 = self.mox.CreateMock(httplib2.Response) res200.status = 200 res401 = self.mox.CreateMock(httplib2.Response) res401.status = 401 # If a token is expired, neutron server retruns 401 self.client.request( mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) ).AndReturn((res401, '')) self.client.request( AUTH_URL + '/tokens', 'POST', body=mox.IsA(str), headers=mox.IsA(dict) ).AndReturn((res200, json.dumps(KS_TOKEN_RESULT))) self.client.request( mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) ).AndReturn((res200, '')) self.mox.ReplayAll() self.client.do_request('/resource', 'GET') def test_get_endpoint_url(self): self.mox.StubOutWithMock(self.client, "request") self.client.auth_token = TOKEN res200 = self.mox.CreateMock(httplib2.Response) res200.status = 200 self.client.request( mox.StrContains(AUTH_URL + '/tokens/%s/endpoints' % TOKEN), 'GET', headers=mox.IsA(dict) ).AndReturn((res200, json.dumps(ENDPOINTS_RESULT))) self.client.request( mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) ).AndReturn((res200, '')) self.mox.ReplayAll() self.client.do_request('/resource', 'GET') def test_use_given_endpoint_url(self): self.client = client.HTTPClient( username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION, endpoint_url=ENDPOINT_OVERRIDE) self.assertEqual(self.client.endpoint_url, ENDPOINT_OVERRIDE) self.mox.StubOutWithMock(self.client, "request") self.client.auth_token = TOKEN res200 = self.mox.CreateMock(httplib2.Response) res200.status = 200 self.client.request( mox.StrContains(ENDPOINT_OVERRIDE + '/resource'), 'GET', headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) ).AndReturn((res200, '')) self.mox.ReplayAll() self.client.do_request('/resource', 'GET') self.assertEqual(self.client.endpoint_url, ENDPOINT_OVERRIDE) def test_get_endpoint_url_other(self): self.client = client.HTTPClient( username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION, endpoint_type='otherURL') self.mox.StubOutWithMock(self.client, "request") self.client.auth_token = TOKEN res200 = self.mox.CreateMock(httplib2.Response) res200.status = 200 self.client.request( mox.StrContains(AUTH_URL + '/tokens/%s/endpoints' % TOKEN), 'GET', headers=mox.IsA(dict) ).AndReturn((res200, json.dumps(ENDPOINTS_RESULT))) self.mox.ReplayAll() self.assertRaises(exceptions.EndpointTypeNotFound, self.client.do_request, '/resource', 'GET') def test_get_endpoint_url_failed(self): self.mox.StubOutWithMock(self.client, "request") self.client.auth_token = TOKEN res200 = self.mox.CreateMock(httplib2.Response) res200.status = 200 res401 = self.mox.CreateMock(httplib2.Response) res401.status = 401 self.client.request( mox.StrContains(AUTH_URL + '/tokens/%s/endpoints' % TOKEN), 'GET', headers=mox.IsA(dict) ).AndReturn((res401, '')) self.client.request( AUTH_URL + '/tokens', 'POST', body=mox.IsA(str), headers=mox.IsA(dict) ).AndReturn((res200, json.dumps(KS_TOKEN_RESULT))) self.client.request( mox.StrContains(ENDPOINT_URL + '/resource'), 'GET', headers=mox.ContainsKeyValue('X-Auth-Token', TOKEN) ).AndReturn((res200, '')) self.mox.ReplayAll() self.client.do_request('/resource', 'GET') def test_url_for(self): resources = copy.deepcopy(KS_TOKEN_RESULT) endpoints = resources['access']['serviceCatalog'][0]['endpoints'][0] endpoints['publicURL'] = 'public' endpoints['internalURL'] = 'internal' endpoints['adminURL'] = 'admin' catalog = client.ServiceCatalog(resources) # endpoint_type not specified url = catalog.url_for(attr='region', filter_value=REGION) self.assertEqual('public', url) # endpoint type specified (3 cases) url = catalog.url_for(attr='region', filter_value=REGION, endpoint_type='adminURL') self.assertEqual('admin', url) url = catalog.url_for(attr='region', filter_value=REGION, endpoint_type='publicURL') self.assertEqual('public', url) url = catalog.url_for(attr='region', filter_value=REGION, endpoint_type='internalURL') self.assertEqual('internal', url) # endpoint_type requested does not exist. self.assertRaises(exceptions.EndpointTypeNotFound, catalog.url_for, attr='region', filter_value=REGION, endpoint_type='privateURL') # Test scenario with url_for when the service catalog only has publicURL. def test_url_for_only_public_url(self): resources = copy.deepcopy(KS_TOKEN_RESULT) catalog = client.ServiceCatalog(resources) # Remove endpoints from the catalog. endpoints = resources['access']['serviceCatalog'][0]['endpoints'][0] del endpoints['internalURL'] del endpoints['adminURL'] endpoints['publicURL'] = 'public' # Use publicURL when specified explicitly. url = catalog.url_for(attr='region', filter_value=REGION, endpoint_type='publicURL') self.assertEqual('public', url) # Use publicURL when specified explicitly. url = catalog.url_for(attr='region', filter_value=REGION) self.assertEqual('public', url) # Test scenario with url_for when the service catalog only has adminURL. def test_url_for_only_admin_url(self): resources = copy.deepcopy(KS_TOKEN_RESULT) catalog = client.ServiceCatalog(resources) endpoints = resources['access']['serviceCatalog'][0]['endpoints'][0] del endpoints['internalURL'] del endpoints['publicURL'] endpoints['adminURL'] = 'admin' # Use publicURL when specified explicitly. url = catalog.url_for(attr='region', filter_value=REGION, endpoint_type='adminURL') self.assertEqual('admin', url) # But not when nothing is specified. self.assertRaises(exceptions.EndpointTypeNotFound, catalog.url_for, attr='region', filter_value=REGION) def test_endpoint_type(self): resources = copy.deepcopy(KS_TOKEN_RESULT) endpoints = resources['access']['serviceCatalog'][0]['endpoints'][0] endpoints['internalURL'] = 'internal' endpoints['adminURL'] = 'admin' endpoints['publicURL'] = 'public' # Test default behavior is to choose public. self.client = client.HTTPClient( username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION) self.client._extract_service_catalog(resources) self.assertEqual(self.client.endpoint_url, 'public') # Test admin url self.client = client.HTTPClient( username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION, endpoint_type='adminURL') self.client._extract_service_catalog(resources) self.assertEqual(self.client.endpoint_url, 'admin') # Test public url self.client = client.HTTPClient( username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION, endpoint_type='publicURL') self.client._extract_service_catalog(resources) self.assertEqual(self.client.endpoint_url, 'public') # Test internal url self.client = client.HTTPClient( username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION, endpoint_type='internalURL') self.client._extract_service_catalog(resources) self.assertEqual(self.client.endpoint_url, 'internal') # Test url that isn't found in the service catalog self.client = client.HTTPClient( username=USERNAME, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION, endpoint_type='privateURL') self.assertRaises(exceptions.EndpointTypeNotFound, self.client._extract_service_catalog, resources) def test_strip_credentials_from_log(self): def verify_no_credentials(kwargs): return ('REDACTED' in kwargs['body']) and ( self.client.password not in kwargs['body']) def verify_credentials(body): return 'REDACTED' not in body and self.client.password in body self.mox.StubOutWithMock(self.client, "request") self.mox.StubOutWithMock(utils, "http_log_req") res200 = self.mox.CreateMock(httplib2.Response) res200.status = 200 utils.http_log_req(mox.IgnoreArg(), mox.IgnoreArg(), mox.Func( verify_no_credentials)) self.client.request( mox.IsA(str), mox.IsA(str), body=mox.Func(verify_credentials), headers=mox.IgnoreArg() ).AndReturn((res200, json.dumps(KS_TOKEN_RESULT))) utils.http_log_req(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) self.client.request( mox.IsA(str), mox.IsA(str), headers=mox.IsA(dict) ).AndReturn((res200, '')) self.mox.ReplayAll() self.client.do_request('/resource', 'GET') class CLITestAuthKeystoneWithId(CLITestAuthKeystone): # Auth Body expected when using tenant Id auth_type = 'tenantId' def setUp(self): """Prepare the test environment.""" super(CLITestAuthKeystoneWithId, self).setUp() self.client = client.HTTPClient(username=USERNAME, tenant_id=TENANT_ID, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION) class CLITestAuthKeystoneWithIdandName(CLITestAuthKeystone): # Auth Body expected when using tenant Id auth_type = 'tenantId' def setUp(self): """Prepare the test environment.""" super(CLITestAuthKeystoneWithIdandName, self).setUp() self.client = client.HTTPClient(username=USERNAME, tenant_id=TENANT_ID, tenant_name=TENANT_NAME, password=PASSWORD, auth_url=AUTH_URL, region_name=REGION)
37.52451
79
0.602482
1,568
15,310
5.739158
0.142219
0.065563
0.039671
0.028114
0.756973
0.729303
0.695966
0.687076
0.669852
0.623514
0
0.015796
0.288766
15,310
407
80
37.616708
0.810635
0.09693
0
0.663265
0
0
0.090738
0
0
0
0
0
0.064626
1
0.054422
false
0.044218
0.030612
0.006803
0.112245
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
9fac1f748968d9d8f776e72e18bfa9ae886fb300
3,170
py
Python
tests/numpy_unit_testing/test_function_binary_operator_true_divide.py
jiajiaxu123/Orca
e86189e70c1d0387816bb98b8047a6232fbda9df
[ "Apache-2.0" ]
20
2019-12-02T11:49:12.000Z
2021-12-24T19:34:32.000Z
tests/numpy_unit_testing/test_function_binary_operator_true_divide.py
jiajiaxu123/Orca
e86189e70c1d0387816bb98b8047a6232fbda9df
[ "Apache-2.0" ]
null
null
null
tests/numpy_unit_testing/test_function_binary_operator_true_divide.py
jiajiaxu123/Orca
e86189e70c1d0387816bb98b8047a6232fbda9df
[ "Apache-2.0" ]
5
2019-12-02T12:16:22.000Z
2021-10-22T02:27:47.000Z
import unittest from setup.settings import * from numpy.testing import * from pandas.util.testing import * import numpy as np import dolphindb_numpy as dnp import pandas as pd import orca class FunctionTruedivideTest(unittest.TestCase): @classmethod def setUpClass(cls): # connect to a DolphinDB server orca.connect(HOST, PORT, "admin", "123456") def test_function_math_binary_true_divide_scalar(self): self.assertEqual(dnp.true_divide(1.2 + 1j, 1.2 - 1j), np.true_divide(1.2 + 1j, 1.2 - 1j)) self.assertEqual(dnp.true_divide(0.5, 9), np.true_divide(0.5, 9)) self.assertEqual(dnp.true_divide(-1, 8.5), np.true_divide(-1, 8.5)) self.assertEqual(dnp.true_divide(1, 4), np.true_divide(1, 4)) self.assertEqual(dnp.true_divide(1, -5), np.true_divide(1, -5)) self.assertEqual(dnp.true_divide(0, 9), np.true_divide(0, 9)) self.assertEqual(dnp.isnan(dnp.true_divide(dnp.nan, -5)), True) self.assertEqual(np.isnan(np.true_divide(dnp.nan, -5)), True) def test_function_math_binary_true_divide_list(self): lst1 = [1, 2, 3] lst2 = [4, 6, 9] assert_array_equal(dnp.true_divide(lst1, lst2), np.true_divide(lst1, lst2)) def test_function_math_binary_true_divide_array_with_scalar(self): npa = np.array([1, 2, 3]) dnpa = dnp.array([1, 2, 3]) assert_array_equal(dnp.true_divide(dnpa, 1), np.true_divide(npa, 1)) assert_array_equal(dnp.true_divide(dnpa, dnp.nan), np.true_divide(npa, np.nan)) assert_array_equal(dnp.true_divide(1, dnpa), np.true_divide(1, npa)) def test_function_math_binary_true_divide_array_with_array(self): npa1 = np.array([1, 2, 3]) npa2 = np.array([4, 6, 9]) dnpa1 = dnp.array([1, 2, 3]) dnpa2 = dnp.array([4, 6, 9]) assert_array_equal(dnp.true_divide(dnpa1, dnpa2), np.true_divide(npa1, npa2)) def test_function_math_binary_true_divide_array_with_array_param_out(self): npa1 = np.array([1, 2, 3]) npa2 = np.array([4, 6, 9]) npa = np.zeros(shape=(1, 3)) dnpa1 = dnp.array([1, 2, 3]) dnpa2 = dnp.array([4, 6, 9]) dnpa = dnp.zeros(shape=(1, 3)) np.true_divide(npa1, npa2, out=npa) dnp.true_divide(dnpa1, dnpa2, out=dnpa) assert_array_equal(dnpa, npa) def test_function_math_binary_true_divide_array_with_series(self): npa = np.array([1, 2, 3]) dnpa = dnp.array([1, 2, 3]) ps = pd.Series([4, 6, 9]) os = orca.Series([4, 6, 9]) assert_series_equal(dnp.true_divide(dnpa, os).to_pandas(), np.true_divide(npa, ps)) assert_series_equal(dnp.true_divide(os, dnpa).to_pandas(), np.true_divide(ps, npa)) def test_function_math_binary_true_divide_array_with_dataframe(self): npa = np.array([1, 2, 3]) dnpa = dnp.array([1, 2, 3]) pdf = pd.DataFrame({'A': [4, 6, 9]}) odf = orca.DataFrame({'A': [4, 6, 9]}) # TODO: orca true_divide bug # assert_frame_equal(odf.true_divide(dnpa, axis=0).to_pandas(), pdf.true_divide(npa, axis=0)) if __name__ == '__main__': unittest.main()
39.625
101
0.643218
503
3,170
3.821074
0.161034
0.208117
0.101457
0.041623
0.622268
0.516129
0.362123
0.291363
0.272633
0.218002
0
0.054248
0.209148
3,170
79
102
40.126582
0.712405
0.046688
0
0.229508
0
0
0.006958
0
0
0
0
0.012658
0.262295
1
0.131148
false
0
0.131148
0
0.278689
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
1
0
0
0
0
0
0
0
0
0
0
2
9fbc462d704378fb13b5f3d14d7cb984d4a7c69e
660
py
Python
Level1/Lessons64061/minari.py
StudyForCoding/ProgrammersLevel
dc957b1c02cc4383a93b8cbf3d739e6c4d88aa25
[ "MIT" ]
null
null
null
Level1/Lessons64061/minari.py
StudyForCoding/ProgrammersLevel
dc957b1c02cc4383a93b8cbf3d739e6c4d88aa25
[ "MIT" ]
null
null
null
Level1/Lessons64061/minari.py
StudyForCoding/ProgrammersLevel
dc957b1c02cc4383a93b8cbf3d739e6c4d88aa25
[ "MIT" ]
1
2021-04-05T07:35:59.000Z
2021-04-05T07:35:59.000Z
```python def solution(board,moves): basket=[] answer=[] for move in moves: for i in range(len(board)): # range(len(board)) 에 있는 인형갯수만큼 반복 if board[i][move-1]>0: # board[][] 안에 인형이 존재할 때에만 실행하도록 basket.append(board[i][move-1]) board[i][move-1]=0 # board[][] 초기화 break else: pass if len(basket)>=2 and basket[len(basket)-1]==basket[len(basket)-2]: #다음 move로 이동하기 전, basket에 들어있는 인형의 종류 두개가 같은지 확인 basket.pop(-1) basket.pop(-1) answer.append(i) return len(answer)*2 #사라지는 인형의 갯수는 answer*2 ```
31.428571
75
0.509091
94
660
3.574468
0.5
0.053571
0.089286
0.098214
0.10119
0.10119
0
0
0
0
0
0.027907
0.348485
660
20
76
33
0.753488
0.219697
0
0.111111
0
0
0
0
0
0
0
0
0
0
null
null
0.055556
0
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
4c80ff310733bd5d3259086a59e004736e492ea2
1,520
py
Python
tests/integration/test_integration_article.py
pwitab/visma
ffa6698738fcc1be9de727e7fe77cce30310f830
[ "BSD-3-Clause" ]
5
2018-08-10T19:12:48.000Z
2021-07-08T12:43:24.000Z
tests/integration/test_integration_article.py
pwitab/visma
ffa6698738fcc1be9de727e7fe77cce30310f830
[ "BSD-3-Clause" ]
16
2018-06-17T18:51:05.000Z
2021-01-10T10:44:36.000Z
tests/integration/test_integration_article.py
pwitab/visma
ffa6698738fcc1be9de727e7fe77cce30310f830
[ "BSD-3-Clause" ]
3
2019-03-05T15:01:13.000Z
2021-06-15T14:35:37.000Z
import pytest from visma.api import VismaClientException from visma.models import Article, ArticleAccountCoding, Unit class TestCRUDArticle: @pytest.fixture() def article(self): article = Article.objects.all()[0] yield article @pytest.fixture() def coding(self): coding = ArticleAccountCoding.objects.all()[0] yield coding @pytest.fixture() def unit(self): unit = Unit.objects.all()[0] yield unit def test_list_articles(self): articles = Article.objects.all() assert len(articles) is not 0 def test_create_article(self, coding, unit): # article = Article(number=100, name='test article', coding_id=coding.id, unit_id=unit.id) # article.save() # assert article.id is not None # Since we cannot delete articles we don't want to keep on creating new ones. pass def test_read_article(self, article): read_article = Article.objects.get(article.id) assert read_article.id == article.id def test_update_article(self, article): article.net_price = 50 article.save() updated_article = Article.objects.get(article.id) assert updated_article.net_price == 50 updated_article.net_price = 10 updated_article.save() def test_delete_article(self, article): # Not allowed # TODO: raise more explaining exception with pytest.raises(VismaClientException): article.delete()
25.762712
98
0.651316
184
1,520
5.266304
0.347826
0.05676
0.074303
0.049536
0.080495
0.080495
0.080495
0
0
0
0
0.011535
0.258553
1,520
58
99
26.206897
0.84827
0.170395
0
0.088235
0
0
0
0
0
0
0
0.017241
0.088235
1
0.235294
false
0.029412
0.088235
0
0.352941
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
1
0
0
0
0
0
0
0
2
4c9bc3f10c76957588e5e8306a910512d15f845e
1,410
py
Python
scraper/storage_spiders/halobuyvn.py
chongiadung/choinho
d2a216fe7a5064d73cdee3e928a7beef7f511fd1
[ "MIT" ]
null
null
null
scraper/storage_spiders/halobuyvn.py
chongiadung/choinho
d2a216fe7a5064d73cdee3e928a7beef7f511fd1
[ "MIT" ]
10
2020-02-11T23:34:28.000Z
2022-03-11T23:16:12.000Z
scraper/storage_spiders/halobuyvn.py
chongiadung/choinho
d2a216fe7a5064d73cdee3e928a7beef7f511fd1
[ "MIT" ]
3
2018-08-05T14:54:25.000Z
2021-06-07T01:49:59.000Z
# Auto generated by generator.py. Delete this line if you make modification. from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor XPATH = { 'name' : "//div[@class='product-name']/h1", 'price' : "//div[@class='span8']/div[@class='price-box']/p[@class='special-price']/span[2] | //div[@class='span8']/div[@class='price-box']/span/span[@class='price']", 'category' : "//div[@class='col-main']/div/ul/li/a | //ul[@class='breadcrumb hidden-phone']/li/a", 'description' : "//div[@class='box-collateral box-description']", 'images' : "//div[@class='product-img-box span4']/p//a/@href | //div[@class='more-views']/ul/li/a/@href", 'canonical' : "//link[@rel='canonical']/@href", 'base_url' : "", 'brand' : "" } name = 'halobuy.vn' allowed_domains = ['halobuy.vn'] start_urls = ['http://halobuy.vn/'] tracking_url = '' sitemap_urls = [''] sitemap_rules = [('', 'parse_item')] sitemap_follow = [] rules = [ Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+.html'], deny=['/thiet-bi-so','/gia-dung','/me-va-be','/the-thao','/du-lich','/qua-tang','/thiet-bi-cham-soc-suc-khoe','\?p=\d+']), 'parse_item'), Rule(LinkExtractor(allow=['/thiet-bi-so','/gia-dung','/me-va-be','/the-thao','/du-lich','/qua-tang','/thiet-bi-cham-soc-suc-khoe','\?p=\d+'], deny=['www\.halobuy\.vn','limit=','dir=','oder=']), 'parse'), #Rule(LinkExtractor(), 'parse_item_and_links'), ]
52.222222
207
0.619149
198
1,410
4.348485
0.5
0.083624
0.034843
0.037166
0.218351
0.218351
0.218351
0.150987
0.150987
0.150987
0
0.005495
0.096454
1,410
26
208
54.230769
0.67033
0.085106
0
0
1
0.130435
0.607615
0.327117
0
0
0
0
0
1
0
false
0
0.086957
0
0.086957
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
4cadcda3bac884ab250a8ab928b7b959bbc5ce4c
333
py
Python
monitor/nagios_check.py
caoghui/python
ca36be7d47bb8abe0561eef1e364a1edcae05088
[ "MIT" ]
null
null
null
monitor/nagios_check.py
caoghui/python
ca36be7d47bb8abe0561eef1e364a1edcae05088
[ "MIT" ]
null
null
null
monitor/nagios_check.py
caoghui/python
ca36be7d47bb8abe0561eef1e364a1edcae05088
[ "MIT" ]
null
null
null
import sys import json import base64 status = sys.argv[1] if status.lower() == "warnig": print('Status is WARN') exit(1) elif status.lower() == 'critical': print('Status is CRITICAL') exit(2) elif status.lower() == 'unknown': print('Status is UNKNOWN') exit(3) else: print('Status is OK') exit(0)
15.857143
34
0.618619
47
333
4.382979
0.468085
0.213592
0.252427
0
0
0
0
0
0
0
0
0.027027
0.222222
333
20
35
16.65
0.76834
0
0
0
0
0
0.247734
0
0
0
0
0
0
1
0
false
0
0.1875
0
0.1875
0.25
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
4cb312593753b7aa0dbd1194d0ea52750711b7d9
2,298
py
Python
src/application/model/matkaroute.py
arpejupe/matkanaattori
d255a05baa1f856bc3f0a0254fe8af5c7b0fb91d
[ "BSD-3-Clause" ]
null
null
null
src/application/model/matkaroute.py
arpejupe/matkanaattori
d255a05baa1f856bc3f0a0254fe8af5c7b0fb91d
[ "BSD-3-Clause" ]
null
null
null
src/application/model/matkaroute.py
arpejupe/matkanaattori
d255a05baa1f856bc3f0a0254fe8af5c7b0fb91d
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from urllib import urlencode from xml.etree import ElementTree from requests import get from datetime import datetime from pytz import timezone matka_api = "http://api.matka.fi/?" matka_api_timezone = timezone("Europe/Helsinki") api_user = "matkanaattori" api_pass = "ties532soa" class MatkaException(Exception): pass class MatkaRoute(object): # a: start point # b: destination point # time: date and time of departure/arrival # timemode: time is 1: the time of departure, 2: the time of arrival # show: number of valid routing results # walkspeed: walking speeds 1,2,3,4,5 def __init__(self, a, b, time, walkspeed, timemode="2", show="1"): self.start_point = a self.end_point = b self.time = time.astimezone(matka_api_timezone) self.walkspeed = walkspeed self.timemode = timemode self.show = show self.departure_time = self.getRouteDepartureTime() def getRoute(self): params = urlencode({ "a": self.start_point, "b": self.end_point, "time": self.time.strftime("%H%M"), "date": self.time.strftime("%Y%m%d"), "timemode": self.timemode, "show": self.show, "walkspeed": self.walkspeed, "user": api_user, "pass": api_pass }) request = get(matka_api + params, stream=True) if request.status_code is 200: request.raw.decode_content = True return ElementTree.iterparse(request.raw) else: raise MatkaException("Routing not available") def getRouteDepartureTime(self): for elem,routeData in self.getRoute(): if routeData.tag == "ERROR": raise MatkaException(routeData.text) elif routeData.tag == "DEPARTURE": departure_date = routeData.attrib["date"] departure_time = routeData.attrib["time"] datetimeObject = datetime.strptime(departure_date + departure_time, "%Y%m%d%H%M") return matka_api_timezone.localize(datetimeObject) if __name__ == '__main__': route = MatkaRoute("3597369,6784330", "3392009,6686355", datetime.now(matka_api_timezone), "2") print route.departure_time
35.353846
99
0.627067
267
2,298
5.254682
0.400749
0.034212
0.045617
0
0
0
0
0
0
0
0
0.02658
0.263272
2,298
64
100
35.90625
0.802126
0.104003
0
0
0
0
0.098489
0
0
0
0
0
0
0
null
null
0.06
0.1
null
null
0.02
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
4cb84140a51272538c65d31e97df90e33e4ff301
354
py
Python
model/fiz_contact.py
ol6a/training
1eaaf751ff7bc0cf46ad1e32330d988c1a700da1
[ "Apache-2.0" ]
null
null
null
model/fiz_contact.py
ol6a/training
1eaaf751ff7bc0cf46ad1e32330d988c1a700da1
[ "Apache-2.0" ]
null
null
null
model/fiz_contact.py
ol6a/training
1eaaf751ff7bc0cf46ad1e32330d988c1a700da1
[ "Apache-2.0" ]
null
null
null
class Fiz_contact: def __init__(self, lastname, firstname, middlename, email, telephone, password, confirmpassword): self.lastname=lastname self.firstname=firstname self.middlename=middlename self.email=email self.telephone=telephone self.password=password self.confirmpassword=confirmpassword
35.4
101
0.70904
34
354
7.235294
0.382353
0.097561
0
0
0
0
0
0
0
0
0
0
0.220339
354
9
102
39.333333
0.891304
0
0
0
0
0
0
0
0
0
0
0
0
1
0.111111
false
0.333333
0
0
0.222222
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
1
0
0
0
0
0
2
4cc29d6c2c7572e3d56f021b79147757d89d9e20
4,212
py
Python
setup.py
aricci10/superpose3d
36844b156d27d0f3c4a50757fe48f7a4d903f85e
[ "MIT" ]
null
null
null
setup.py
aricci10/superpose3d
36844b156d27d0f3c4a50757fe48f7a4d903f85e
[ "MIT" ]
null
null
null
setup.py
aricci10/superpose3d
36844b156d27d0f3c4a50757fe48f7a4d903f85e
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from setuptools import setup setup( name='superpose3d', packages=['superpose3d'], description='Diamond\'s 1988 rotational superposition algorithm (+scale tranforms)', long_description='''Register 3-D point clouds using rotation, translation, and scale transformations. ## Usage ``` def Superpose3D(X, # <-- Nx3 array of coords for the "frozen" point cloud x, # <-- Nx3 array of coords for the "mobile" point cloud # ---- optional arguments: ---- w = None, # optional weights for the calculation of RMSD allow_rescale=False, # attempt to rescale mobile point cloud? report_quaternion=False) # report rotation angle and axis? ``` Superpose3D() takes two ordered lists (or numpy arrays) of xyz coordinates (*of the same length*, **N**) representing points in a point cloud (**X** and **x**). Treating them as rigid objects, "Superpose3D()" attempts to superimpose them using **rotations**, **translations**, and (optionally) **scale** transformations in order to minimize the root-mean-squared-distance (RMSD) between corresponding points from either point cloud, where RMSD is defined as: ``` RMSD = sqrt( (Σ_n w[n] * Σ_i |X[n][i] - (Σ_j c*R[i][j]*x[n][j] + T[i])|^2) / (Σ_n w[n]) ) ``` If *w=None*, equal weights are used. In that case: ``` RMSD = sqrt( (Σ_n Σ_i |X[n][i] - (Σ_j c*R[i][j]*x[n][j] + T[i])|^2) / N ) ``` ...where: ``` R = a rotation matrix (a 3x3 numpy array representing the rotation. |R|=1) T = a translation vector (a 1-D numpy array containing x,y,z displacements) c = a scalar (a number, 1 by default) ``` This function returns a 4-tuple containing the optimal values of: ``` (RMSD, R, T, c) ``` If the rotation angle and axis are needed, then set the *report_quaternion* argument to *True*. In that case, the function will return this 4-tuple instead: ``` (RMSD, q, T, c) ``` ...where *q* is the [quaternion corresponding to rotation *R*](https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation), from which the rotation angle and rotation axis can be easily determined. This function implements a more general variant of the method from this paper: R. Diamond, (1988) "A Note on the Rotational Superposition Problem", Acta Cryst. A44, pp. 211-216. This version has been augmented slightly to support scale transformations. (I.E. multiplication by scalars. This can be useful for the registration of two different annotated volumetric 3-D images of the same object taken at different magnifications.) Note that if you enable scale transformations (i.e. if *allow_rescale=True*), you should be wary if the function returns a negative **c** value. Negative **c** values correspond to inversions (reflections). For this reason, if you are using this function to compare the conformations of molecules, you should probably set *allow_rescale=False*. This will prevent matching a molecule with its stereoisomer. Note: A C++ version of this repository is available at https://github.com/jewettaij/superpose3d_cpp ''', long_description_content_type='text/markdown', author='Andrew Jewett', author_email='jewett.aij@gmail.com', url='https://github.com/jewettaij/superpose3d', download_url='https://github.com/jewettaij/superpose3d/archive/v1.0.1.zip', version='1.0.1', install_requires=[ 'numpy', ], keywords=['registration', '3d', 'structure-comparison', 'molecular-structure', 'clem'], license='MIT', classifiers=['Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Environment :: Console', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX :: Linux', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.8', 'Topic :: Scientific/Engineering'], zip_safe=True, include_package_data=True )
39.364486
408
0.66548
570
4,212
4.87193
0.463158
0.018005
0.03601
0.024847
0.068419
0.056176
0.029528
0.012964
0.012964
0.012964
0
0.015663
0.211776
4,212
106
409
39.735849
0.820783
0.004986
0
0.146341
0
0
0.843399
0.027692
0
0
0
0
0
1
0
true
0
0.012195
0
0.012195
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
1
0
0
0
0
0
0
2
4cccd7d1f2855b57b5553b54acf96bb9e987eb7f
292
py
Python
studio/urls.py
mrashidov/ColdWaterWebSite
0d52860e8bb21f77aec744e3891364957ac75399
[ "MIT" ]
null
null
null
studio/urls.py
mrashidov/ColdWaterWebSite
0d52860e8bb21f77aec744e3891364957ac75399
[ "MIT" ]
null
null
null
studio/urls.py
mrashidov/ColdWaterWebSite
0d52860e8bb21f77aec744e3891364957ac75399
[ "MIT" ]
null
null
null
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^task$', views.ShowTask.as_view(), name='show_task'), url(r'^task/add/$', views.AddTask.as_view(),name='add_task'), url(r'^(?P<slug>[\w\-]+)$', views.ShowTask.as_view(), name='show'), ]
29.2
71
0.619863
43
292
4.093023
0.488372
0.068182
0.170455
0.215909
0.306818
0.306818
0
0
0
0
0
0
0.14726
292
9
72
32.444444
0.706827
0
0
0
0
0
0.195205
0
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
4cd722ff9dd1a9f34e8ee2680df4379e934645c7
207
py
Python
{{cookiecutter.project_name}}/resources/admin.py
phalt/cookicutter-django-api
01c7ffea8805a05e704819d21f20fe48cec436c0
[ "BSD-3-Clause" ]
16
2015-04-04T20:50:00.000Z
2017-08-18T19:18:02.000Z
{{cookiecutter.project_name}}/resources/admin.py
phalt/cookicutter-django-api
01c7ffea8805a05e704819d21f20fe48cec436c0
[ "BSD-3-Clause" ]
null
null
null
{{cookiecutter.project_name}}/resources/admin.py
phalt/cookicutter-django-api
01c7ffea8805a05e704819d21f20fe48cec436c0
[ "BSD-3-Clause" ]
4
2015-04-24T03:51:50.000Z
2020-02-10T13:47:02.000Z
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ( BaseModel ) classes = [BaseModel] for c in classes: admin.site.register(c)
13.8
39
0.705314
27
207
5.222222
0.703704
0
0
0
0
0
0
0
0
0
0
0.005988
0.193237
207
14
40
14.785714
0.838323
0.101449
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.375
0
0.375
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
4ce5ee6ba6e39b98743bd5a01fdada0a46b8373a
89
py
Python
config/airflow_config_property.py
ranjeettyadav/ranjeettyadav
13325501bc8abc27f352d2b6e3cbe9b8dd321232
[ "MIT" ]
null
null
null
config/airflow_config_property.py
ranjeettyadav/ranjeettyadav
13325501bc8abc27f352d2b6e3cbe9b8dd321232
[ "MIT" ]
null
null
null
config/airflow_config_property.py
ranjeettyadav/ranjeettyadav
13325501bc8abc27f352d2b6e3cbe9b8dd321232
[ "MIT" ]
null
null
null
project_dm = 'dmgcp-ingestion-poc' location = 'US' bq_connection_id= 'my_gcp_connection'
22.25
37
0.786517
13
89
5
0.923077
0
0
0
0
0
0
0
0
0
0
0
0.089888
89
3
38
29.666667
0.802469
0
0
0
0
0
0.426966
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
4ce7dce48f6457b8561f7776f1bda9d9903b5e23
792
py
Python
application/account/forms.py
fgronqvist/votingbooth
45d8505e2380f3f49938b8a7b8343e6a067a86d8
[ "Unlicense" ]
null
null
null
application/account/forms.py
fgronqvist/votingbooth
45d8505e2380f3f49938b8a7b8343e6a067a86d8
[ "Unlicense" ]
2
2018-10-03T15:59:05.000Z
2018-10-21T19:08:07.000Z
application/account/forms.py
fgronqvist/votingbooth
45d8505e2380f3f49938b8a7b8343e6a067a86d8
[ "Unlicense" ]
null
null
null
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, validators from wtforms.fields.html5 import EmailField class RegisterForm(FlaskForm): firstname = StringField(u"Firstname", [validators.Length(min=2, max=256)]) lastname = StringField(u"Lastname", [validators.length(min=2, max=256)]) email = EmailField(u"Email", [validators.InputRequired(), validators.Email()]) password = PasswordField(u"Password", [validators.InputRequired(), validators.EqualTo('passwordb')]) passwordb = PasswordField(u"Confirm password") class Meta: csrf = False class LoginForm(FlaskForm): email = StringField(u"Email", [validators.InputRequired(), validators.Email()]) password = PasswordField(u"Password", [validators.InputRequired()])
46.588235
104
0.736111
83
792
7.012048
0.385542
0.158076
0.170103
0.068729
0.42268
0.42268
0.333333
0.333333
0.333333
0.333333
0
0.01312
0.133838
792
17
105
46.588235
0.835277
0
0
0
0
0
0.08575
0
0
0
0
0
0
1
0
false
0.285714
0.214286
0
0.928571
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
980e6c10d5ee3bf2bd644b6f6b236ff8581231c5
1,164
py
Python
src/analyzer/token.py
betoSolares/minicomp
4fb05b94acdf085135924c717a470fe518e462ff
[ "MIT" ]
1
2020-08-18T16:02:38.000Z
2020-08-18T16:02:38.000Z
src/analyzer/token.py
betoSolares/minicomp
4fb05b94acdf085135924c717a470fe518e462ff
[ "MIT" ]
27
2020-08-18T17:06:50.000Z
2020-11-21T19:07:22.000Z
src/analyzer/token.py
betoSolares/minicomp
4fb05b94acdf085135924c717a470fe518e462ff
[ "MIT" ]
3
2020-08-24T13:54:23.000Z
2020-10-15T02:20:07.000Z
class Token: def __init__(self, word, line, start, finish, category, reason=None): self.__word__ = word self.__line__ = line self.__start__ = start self.__finish__ = finish self.__category__ = category self.__reason__ = reason @property def word(self): return self.__word__ @word.setter def word(self, word): self.__word__ = word @property def line(self): return self.__line__ @line.setter def line(self, line): self.__line__ = line @property def start(self): return self.__start__ @start.setter def start(self, start): self.__start__ = start @property def finish(self): return self.__finish__ @finish.setter def finish(self, finish): self.__finish__ = finish @property def category(self): return self.__category__ @category.setter def category(self, category): self.__category__ = category @property def reason(self): return self.__reason__ @reason.setter def reason(self, reason): self.__reason__ = reason
20.421053
73
0.607388
126
1,164
5.007937
0.119048
0.104596
0.133122
0
0
0
0
0
0
0
0
0
0.305842
1,164
56
74
20.785714
0.780941
0
0
0.409091
0
0
0
0
0
0
0
0
0
1
0.295455
false
0
0
0.136364
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
1
0
0
0
1
0
0
0
2
981a4012f0e9207383228850425145d6abe23671
168
py
Python
constants/nodetype.py
vladzaharia/meshnet
87a48c678094870cc273f4940f122e899eb1f5e1
[ "MIT" ]
1
2021-02-16T05:29:03.000Z
2021-02-16T05:29:03.000Z
constants/nodetype.py
vladzaharia/meshnet
87a48c678094870cc273f4940f122e899eb1f5e1
[ "MIT" ]
1
2021-02-16T06:23:08.000Z
2021-02-16T06:23:08.000Z
constants/nodetype.py
vladzaharia/meshnet
87a48c678094870cc273f4940f122e899eb1f5e1
[ "MIT" ]
null
null
null
# Node types TYPE_NODE = b'\x10' TYPE_NODE_NR = b'\x11' # Gateway types TYPE_GATEWAY = b'\x20' TYPE_GATEWAY_TIME = b'\x21' # Special types TYPE_PROVISIONING = b'\xFF'
16.8
27
0.714286
28
168
4.035714
0.5
0.238938
0
0
0
0
0
0
0
0
0
0.055944
0.14881
168
10
28
16.8
0.734266
0.22619
0
0
0
0
0.15748
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e21f915c5f29fa2f88567990fe37ec71534110ac
129
py
Python
demo/cat.py
zbentley/useful-bash
d1d9f4bde3d53564c037f6ef18e0bbaa2144ffa3
[ "MIT" ]
5
2017-07-27T13:50:15.000Z
2021-08-14T18:52:52.000Z
demo/cat.py
zbentley/useful-bash
d1d9f4bde3d53564c037f6ef18e0bbaa2144ffa3
[ "MIT" ]
1
2020-09-18T18:04:29.000Z
2020-09-19T23:02:28.000Z
demo/cat.py
zbentley/useful-bash
d1d9f4bde3d53564c037f6ef18e0bbaa2144ffa3
[ "MIT" ]
1
2020-09-19T23:15:25.000Z
2020-09-19T23:15:25.000Z
#!/usr/bin/env python import sys with open(sys.argv[1], 'r') as f: for line in f.readlines(): sys.stdout.write(line)
21.5
33
0.627907
23
129
3.521739
0.826087
0
0
0
0
0
0
0
0
0
0
0.009709
0.20155
129
5
34
25.8
0.776699
0.155039
0
0
0
0
0.009259
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e24c0ec2c106545bbb10756e5231705f8b4872ad
203
py
Python
Curso_em_video/Mundo_1/exercicios/ex012.py
TCGamer123/python
82ad1f84b52d6cc7253fb4c5522ae8389824930a
[ "MIT" ]
1
2022-03-08T13:29:59.000Z
2022-03-08T13:29:59.000Z
Curso_em_video/Mundo_1/exercicios/ex012.py
TCGamer123/python
82ad1f84b52d6cc7253fb4c5522ae8389824930a
[ "MIT" ]
null
null
null
Curso_em_video/Mundo_1/exercicios/ex012.py
TCGamer123/python
82ad1f84b52d6cc7253fb4c5522ae8389824930a
[ "MIT" ]
null
null
null
preço = float(input('Digite o preço do produto: R$')) d = preço * 0.05 vD = preço - d print('Valor original R${:.2f}, desconto de 5% é igual à R${:.2f}, seu novo preço é R${:.2f}'.format(preço, d, vD))
33.833333
115
0.62069
39
203
3.230769
0.641026
0.071429
0
0
0
0
0
0
0
0
0
0.041916
0.17734
203
6
115
33.833333
0.712575
0
0
0
0
0.25
0.558824
0
0
0
0
0
0
1
0
false
0
0
0
0
0.25
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e25e27a47f5510c4ab4d334a3f28637aba126e3c
888
py
Python
src/Phidget22/Encoding.py
MikaSoftware/mikathing
60621b01e2fcbeefe2181a58fb0f6104115d1ae6
[ "BSD-3-Clause" ]
1
2021-11-23T09:02:46.000Z
2021-11-23T09:02:46.000Z
Phidget22/Encoding.py
keysie/phidget-python-interface
ebf392fe6d8d25bd5c178edbf095cf29e0daa4af
[ "MIT" ]
null
null
null
Phidget22/Encoding.py
keysie/phidget-python-interface
ebf392fe6d8d25bd5c178edbf095cf29e0daa4af
[ "MIT" ]
1
2020-02-26T12:43:12.000Z
2020-02-26T12:43:12.000Z
import sys import ctypes class Encoding: # Unknown - the default value IR_ENCODING_UNKNOWN = 1 # Space encoding, or Pulse Distance Modulation IR_ENCODING_SPACE = 2 # Pulse encoding, or Pulse Width Modulation IR_ENCODING_PULSE = 3 # Bi-Phase, or Manchester encoding IR_ENCODING_BIPHASE = 4 # RC5 - a type of Bi-Phase encoding IR_ENCODING_RC5 = 5 # RC6 - a type of Bi-Phase encoding IR_ENCODING_RC6 = 6 @classmethod def getName(self, val): if val == self.IR_ENCODING_UNKNOWN: return "IR_ENCODING_UNKNOWN" if val == self.IR_ENCODING_SPACE: return "IR_ENCODING_SPACE" if val == self.IR_ENCODING_PULSE: return "IR_ENCODING_PULSE" if val == self.IR_ENCODING_BIPHASE: return "IR_ENCODING_BIPHASE" if val == self.IR_ENCODING_RC5: return "IR_ENCODING_RC5" if val == self.IR_ENCODING_RC6: return "IR_ENCODING_RC6" return "<invalid enumeration value>"
27.75
47
0.748874
134
888
4.69403
0.298507
0.286169
0.085851
0.104928
0.282989
0.101749
0.101749
0.101749
0
0
0
0.019126
0.175676
888
31
48
28.645161
0.840164
0.242117
0
0
0
0
0.193694
0
0
0
0
0
0
1
0.041667
false
0
0.083333
0
0.708333
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
e272629bf1764e47dd0429ebae5dabad29cdb7f2
1,258
py
Python
tools/harness/tests/aos_tests.py
Frankie8472/advanced-operating-systems
bff03e668c76886781e5fdb24dfab5880f79941d
[ "MIT" ]
5
2020-06-12T11:47:21.000Z
2022-02-27T14:39:05.000Z
tools/harness/tests/aos_tests.py
Frankie8472/advanced-operating-systems
bff03e668c76886781e5fdb24dfab5880f79941d
[ "MIT" ]
3
2020-06-04T20:11:26.000Z
2020-07-26T23:16:33.000Z
tools/harness/tests/aos_tests.py
Frankie8472/advanced-operating-systems
bff03e668c76886781e5fdb24dfab5880f79941d
[ "MIT" ]
3
2020-06-12T18:06:29.000Z
2022-03-13T17:19:02.000Z
########################################################################## # Copyright (c) 2009, ETH Zurich. # All rights reserved. # # This file is distributed under the terms in the attached LICENSE file. # If you do not find this file, copies can be found by writing to: # ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. ########################################################################## import re, tests, barrelfish from common import TestCommon from results import PassFailResult @tests.add_test class AosTest(TestCommon): '''Base class for AOS tests''' name = "aos_test" def get_modules(self, build, machine): m = barrelfish.BootModules(self, prefix="armv8/sbin/") m.set_boot_driver("boot_armv8_generic") m.set_cpu_driver("cpu_imx8x") m.add_module("init", ["g:ira0=4096"]) return m def get_finish_string(self): return "<grading> TEST" def process_data(self, testdir, rawiter): # the test passed iff the last line is the finish string lastline = '' for line in rawiter: if re.match("<grading>\s*TEST\s*ira\s*PASSED", line): return PassFailResult(True) return PassFailResult(False)
34.944444
80
0.59062
154
1,258
4.733766
0.623377
0.024691
0
0
0
0
0
0
0
0
0
0.016983
0.204293
1,258
35
81
35.942857
0.711289
0.27663
0
0
0
0
0.141333
0.041333
0
0
0
0
0
1
0.15
false
0.2
0.15
0.05
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
e2770fdbc3011a18fb2c25303fdd40f81c8ec0d1
6,421
py
Python
c_comp/nodes.py
Commodoreprime/Command-Block-Assembly
b54c2afee3ea7bdfddfe619b9b207ce30d160e45
[ "MIT" ]
223
2017-05-10T18:27:44.000Z
2022-03-06T22:44:18.000Z
c_comp/nodes.py
Commodoreprime/Command-Block-Assembly
b54c2afee3ea7bdfddfe619b9b207ce30d160e45
[ "MIT" ]
25
2017-12-07T15:37:37.000Z
2021-02-05T14:28:59.000Z
c_comp/nodes.py
Commodoreprime/Command-Block-Assembly
b54c2afee3ea7bdfddfe619b9b207ce30d160e45
[ "MIT" ]
30
2017-12-07T15:16:36.000Z
2022-03-16T03:29:59.000Z
class Node: props = () def __init__(self, **kwargs): for prop in kwargs: if prop not in self.props: raise Exception('Invalid property %r, allowed only: %s' % (prop, self.props)) self.__dict__[prop] = kwargs[prop] for prop in self.props: if prop not in self.__dict__: self.__dict__[prop] = None self.attrs = {} def print_node(self, indent=0, indent_size=4,extra=0): s = self.__class__.__name__ s += '(\n' i = ' ' * (indent+indent_size) for prop in self.props: s += i + prop + ' = ' s += self._print_val(self.__dict__[prop], indent+indent_size, indent_size, (len(prop) + 3) - indent_size) s += '\n' s += (' ' * (indent + extra)) + ')' return s def _print_val(self, val, indent, indent_size,extra=0): if isinstance(val, Node): return val.print_node(indent+indent_size,indent_size,extra) elif type(val) == list: s = '[\n' i = ' ' * (indent+indent_size) for e in val: s += i + self._print_val(e, indent, indent_size) s += ',\n' s += (' ' * (indent+extra)) + ']' return s else: return str(val) class Statement(Node): pass class Expression(Node): pass class EmptyStatement(Statement): pass EmptyStatement.INSTANCE = EmptyStatement() class FunctionDeclaration(Statement): props = ('type', 'decl', 'body') class Declaration(Statement): props = ('type', 'init') class ParamDeclaration(Node): props = ('type', 'decl') class StructTypeRef(Node): props = ('name',) class DeclarationSpecifier(Node): props = ('store', 'qual', 'type') class InitSpec(Node): props = ('decl', 'val') class DeclaratorSpec(Node): props = ('pointer_depth', 'name_spec') class ArrayDeclSpec(Node): props = ('name', 'dim') class FuncDeclSpec(Node): props = ('name', 'params') class VarArgs(Node): pass VarArgs.INSTANCE = VarArgs() class StructSpec(Node): props = ('name', 'decl') class StructMemberDecl(Node): props = ('spec', 'decl') class MemberReference(Node): props = ('child', 'idx', 'name') class TypeName(Node): props = ('type', 'spec') class LabelledStmt(Statement): props = ('label', 'stmt') class WhileStmt(Statement): props = ('cond', 'body') class DoWhileStmt(Statement): props = ('body', 'cond') class ForStmt(Statement): props = ('init', 'cond', 'after', 'body') class IfStmt(Statement): props = ('cond', 'true', 'false') class SwitchStmt(Statement): props = ('expr', 'cases') class ContinueStmt(Statement): pass ContinueStmt.INSTANCE = ContinueStmt() class BreakStmt(Statement): pass BreakStmt.INSTANCE = BreakStmt() class ReturnStmt(Statement): props = ('expr',) class GotoStmt(Statement): props = ('label',) class CaseStmt(Statement): props = ('choice', 'body') class SyncStmt(Statement): pass class ExpressionStmt(Statement): props = ('expr',) class SizeofExpr(Expression): props = ('expr',) class ConditionalExpr(Expression): props = ('cond', 'true', 'false') class FunctionCallExpr(Expression): props = ('ref', 'args') class IdentifierExpr(Expression): props = ('val',) class AssignmentExpr(Expression): props = ('left', 'right') class AssignmentOperatorExpr(Expression): props = ('left', 'op', 'right') class UnaryExpr(Expression): props = ('op', 'expr') class BinaryOperatorExpr(Expression): props = ('left', 'op', 'right') class IncrementExpr(Expression): props = ('dir', 'post', 'expr') class MemberAccessExpr(Expression): props = ('expr', 'prop', 'deref') class ArraySubscriptExpr(Expression): props = ('expr', 'sub') class Literal(Expression): props = ('val',) class IntLiteral(Literal): pass class StringLiteral(Literal): pass class Pragma(Node): props = ('val',) class Token: class Type: IDENTIFIER = 'identifier' OPERATOR = 'operator' NUMBER = 'number' STRING = 'string' def __init__(self, val, type=None): self.val = val self.type = type or Token.Type.OPERATOR def __str__(self): return 'Token(%r, %s)' % (self.val, self.type) class Keyword(Token): REGISTRY = {} def __init__(self, val): super().__init__(val, Token.Type.IDENTIFIER) Keyword.REGISTRY[val] = self Token.EOF = Token('<eof>') Token.OPEN_PAREN = Token('(') Token.CLOSE_PAREN = Token(')') Token.OPEN_BRACE = Token('{') Token.CLOSE_BRACE = Token('}') Token.OPEN_SQUARE = Token('[') Token.CLOSE_SQUARE = Token(']') Token.COMMA = Token(',') Token.SEMICOLON = Token(';') Token.QUESTION = Token('?') Token.COLON = Token(':') Token.DOT = Token('.') Token.ARROW = Token('->') Token.VARARG = Token('...') Token.OP_ASSIGN = Token('=') Token.OP_MUL_ASSIGN = Token('*=') Token.OP_DIV_ASSIGN = Token('/=') Token.OP_MOD_ASSIGN = Token('%=') Token.OP_PLUS_ASSIGN = Token('+=') Token.OP_MINUS_ASSIGN = Token('-=') Token.OP_LSHIFT_ASSIGN = Token('<<=') Token.OP_RSHIFT_ASSIGN = Token('>>=') Token.OP_AND_ASSIGN = Token('&=') Token.OP_XOR_ASSIGN = Token('^=') Token.OP_OR_ASSIGN = Token('|=') Token.OP_PLUS = Token('+') Token.OP_PLUS_PLUS = Token('++') Token.OP_MINUS = Token('-') Token.OP_MINUS_MINUS = Token('--') Token.OP_STAR = Token('*') Token.OP_DIV = Token('/') Token.OP_MOD = Token('%') Token.OP_AND = Token('&') Token.OP_OR = Token('|') Token.OP_AND_AND = Token('&&') Token.OP_OR_OR = Token('||') Token.OP_XOR = Token('^') Token.OP_NOT = Token('!') Token.OP_BITNOT = Token('~') Token.OP_SHIFT_LEFT = Token('<<') Token.OP_SHIFT_RIGHT = Token('>>') Token.OP_EQUAL = Token('==') Token.OP_NOT_EQUAL = Token('!=') Token.OP_LESS_THAN = Token('<') Token.OP_LESS_OR_EQUAL = Token('<=') Token.OP_GREATER_THAN = Token('>') Token.OP_GREATER_OR_EQUAL = Token('>=') Keyword.DO = Keyword('do') Keyword.WHILE = Keyword('while') Keyword.FOR = Keyword('for') Keyword.IF = Keyword('if') Keyword.ELSE = Keyword('else') Keyword.SIZEOF = Keyword('sizeof') Keyword.SYNC = Keyword('sync') Keyword.SWITCH = Keyword('switch') Keyword.CASE = Keyword('case') Keyword.DEFAULT = Keyword('default') Keyword.GOTO = Keyword('goto') Keyword.CONTINUE = Keyword('continue') Keyword.BREAK = Keyword('break') Keyword.RETURN = Keyword('return') Keyword.CONST = Keyword('const') Keyword.STATIC = Keyword('static') Keyword.TYPEDEF = Keyword('typedef') Keyword.STRUCT = Keyword('struct')
31.47549
86
0.634636
763
6,421
5.175623
0.225426
0.113953
0.100279
0.050139
0.103064
0.042542
0.026842
0.0157
0.0157
0
0
0.000954
0.183928
6,421
203
87
31.630542
0.752672
0
0
0.036145
0
0
0.090498
0
0
0
0
0
0
1
0.036145
false
0.054217
0
0.006024
0.590361
0.03012
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
e278e8c7930da117f96d8cb6f36e05b643813f57
1,487
py
Python
src/web/settings.py
iwwxiong/fastapi-box
3be11a6c0451467c9cac09b9a9c59ad509bb834e
[ "MIT" ]
8
2021-02-24T11:28:57.000Z
2022-02-11T08:58:39.000Z
src/web/settings.py
iwwxiong/fastapi-box
3be11a6c0451467c9cac09b9a9c59ad509bb834e
[ "MIT" ]
null
null
null
src/web/settings.py
iwwxiong/fastapi-box
3be11a6c0451467c9cac09b9a9c59ad509bb834e
[ "MIT" ]
null
null
null
import os from pydantic import BaseSettings class AppSettings(BaseSettings): debug: bool = False time_zone: str = "Asia/Shanghai" logger_level: str = "INFO" logger_formatter: str = "%(asctime)s [%(name)s] %(funcName)s[line:%(lineno)d] %(levelname)-7s: %(message)s" secret_key: str = "1@3$5^7*9)" class DatabaseSettings(BaseSettings): _db_port = os.getenv("POSTGRESQL_PORT") or "5432" _db_password = os.getenv("REDIS_PASSWORD") or "password" fastapi_uri: str = f"postgresql+asyncpg://postgres:{_db_password}@fastapi-postgresql:{_db_port}/fastapi" class RedisSettings(BaseSettings): _redis_port = os.getenv("REDIS_PORT") or "6379" _redis_password = os.getenv("REDIS_PASSWORD") or "password" fastapi_redis_uri: str = f"redis://:{_redis_password}@fastapi-redis:{_redis_port}/0?encoding=utf-8" class DataFileSettings(BaseSettings): basedir: str = "/app/web/data" runtimedir: str = "/app/runtimedir" class Settings(AppSettings, DatabaseSettings, RedisSettings, DataFileSettings): pass settings = Settings() env = os.getenv("FASTAPI_ENV") print(f"FASTAPI_ENV = {env}") if env == "development": from settings_dev import settings as dev_settings for k, v in dev_settings: if hasattr(settings, k): setattr(settings, k, v) elif env == "test": from settings_test import settings as test_settings for k, v in test_settings: if hasattr(settings, k): setattr(settings, k, v)
29.74
111
0.696032
194
1,487
5.154639
0.402062
0.04
0.039
0.042
0.208
0.178
0.178
0.178
0.086
0
0
0.013019
0.173504
1,487
49
112
30.346939
0.800651
0
0
0.117647
0
0.029412
0.276395
0.122394
0
0
0
0
0
1
0
false
0.147059
0.117647
0
0.647059
0.029412
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
e288295cb9e018ae0fba4c6ba89f7da0720d2b7a
2,692
py
Python
jsonfile.py
jason0x43/jcalfred
66e5b3d1ffc7529aeda925695b8fb32fd7fa383c
[ "MIT" ]
6
2015-05-08T19:52:04.000Z
2020-10-21T14:56:32.000Z
jsonfile.py
jason0x43/jcalfred
66e5b3d1ffc7529aeda925695b8fb32fd7fa383c
[ "MIT" ]
1
2016-05-25T19:10:07.000Z
2016-05-25T19:10:07.000Z
jsonfile.py
jason0x43/jcalfred
66e5b3d1ffc7529aeda925695b8fb32fd7fa383c
[ "MIT" ]
null
null
null
import logging import json import os.path LOG = logging.getLogger(__name__) class JsonFile(object): def __init__(self, path, default_data=None, ignore_errors=False, header=None): '''Construct a new JsonFile. Parameters ---------- default_data : dict This is a dictionary of data to initialize the JsonFile with. Any data already present in the file will override this data. ignore_errors : boolean Set to True to ignore errors when loading data from an existing file. header : string A comment header to include with the file. This should be a string or a list of strings. Necessary comment tags will be added automatically. ''' self._data = {} self._path = path self._header = header if os.path.exists(path): try: with open(path, 'rt') as cfile: lines = [n for n in cfile.readlines() if not n.strip().startswith('//')] self._data = json.loads(''.join(lines)) except ValueError: if ignore_errors: LOG.warn('ignoring corrupt JsonFile %s', path) self._data = {} else: LOG.warn('corrupt JsonFile %s', path) raise elif default_data: self._data = default_data self._save() def __contains__(self, key): return key in self._data def __getitem__(self, key): return self._data.get(key, None) def __delitem__(self, key): del self._data[key] self._save() def __setitem__(self, key, value): self._data[key] = value self._save() def __iter__(self): return self._data.__iter__() def iterkeys(self): return self._data.__iter__() def items(self): return self._data.items() @property def path(self): return self._path @property def header(self): return self._header @header.setter def header(self, value): self._header = value self._save() def get(self, key, default=None): return self._data.get(key, default) def _save(self): with open(self._path, 'wt') as cfile: if self.header: if not isinstance(self.header, (list, tuple)): self.header = self.header.split('\n') for line in self.header: cfile.write('// {0}\n'.format(line)) json.dump(self._data, cfile, indent=2)
27.752577
78
0.540862
310
2,692
4.480645
0.36129
0.074874
0.050396
0.038877
0.064795
0.035997
0
0
0
0
0
0.001168
0.36367
2,692
96
79
28.041667
0.809691
0.175706
0
0.16129
0
0
0.029886
0
0
0
0
0
0
1
0.209677
false
0
0.048387
0.129032
0.403226
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
e28edceaeb28b473911c6cbe149b7885fa3fc75c
531
py
Python
lp_mongodb/loaders/loader.py
TechLaProvence/lp_mongodb
723e7a9599442405e915fa26c361e337c80784a9
[ "MIT" ]
null
null
null
lp_mongodb/loaders/loader.py
TechLaProvence/lp_mongodb
723e7a9599442405e915fa26c361e337c80784a9
[ "MIT" ]
null
null
null
lp_mongodb/loaders/loader.py
TechLaProvence/lp_mongodb
723e7a9599442405e915fa26c361e337c80784a9
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # thumbor imaging service # https://github.com/TechLaProvence/lp_mongodb # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2011 figarocms dhardy@figarocms.fr from tornado.concurrent import return_future from lp_mongodb.storages.mongo_storage import Storage from thumbor.context import Context from thumbor.config import Config @return_future def load(context, path, callback): storage = Storage(context) callback(storage.get(path))
26.55
53
0.781544
72
531
5.694444
0.652778
0.043902
0
0
0
0
0
0
0
0
0
0.010593
0.111111
531
20
54
26.55
0.858051
0.442561
0
0
0
0
0
0
0
0
0
0
0
1
0.125
false
0
0.5
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
e29976708d7430c0f899314db03ca3391999d114
310
py
Python
1313decompressRunLength.py
vkaushik189/ltcode_solutions
035a74ee51d636989aa183e16c6ebb81dfccf74c
[ "MIT" ]
null
null
null
1313decompressRunLength.py
vkaushik189/ltcode_solutions
035a74ee51d636989aa183e16c6ebb81dfccf74c
[ "MIT" ]
null
null
null
1313decompressRunLength.py
vkaushik189/ltcode_solutions
035a74ee51d636989aa183e16c6ebb81dfccf74c
[ "MIT" ]
null
null
null
class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: de = [] for i in range(0, len(nums), 2): pair = [] pair.append(nums[i]) pair.append(nums[i + 1]) arr = [nums[i + 1]] * nums[i] de += arr return de
28.181818
62
0.448387
39
310
3.564103
0.538462
0.143885
0.201439
0.215827
0
0
0
0
0
0
0
0.021505
0.4
310
10
63
31
0.725806
0
0
0
0
0
0
0
0
0
0
0
0
1
0.1
false
0
0
0
0.3
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e299cca2abbc2b500fc05b59b682135e9c4e7a88
4,060
py
Python
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/lib/schemas/user.py
thecoderstudio/cookiecutter-pyramid-api
b3122c0d98be7179bcf726c6527096c0327d7bb7
[ "MIT" ]
null
null
null
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/lib/schemas/user.py
thecoderstudio/cookiecutter-pyramid-api
b3122c0d98be7179bcf726c6527096c0327d7bb7
[ "MIT" ]
1
2021-12-17T15:10:21.000Z
2021-12-17T15:10:21.000Z
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/lib/schemas/user.py
thecoderstudio/cookiecutter-pyramid-api
b3122c0d98be7179bcf726c6527096c0327d7bb7
[ "MIT" ]
1
2021-03-01T14:27:10.000Z
2021-03-01T14:27:10.000Z
from marshmallow import (fields, post_load, Schema, validate, validates, validates_schema, ValidationError) from {{cookiecutter.project_slug}}.lib.hash import compare_plaintext_to_hash, hash_plaintext from {{cookiecutter.project_slug}}.models.user import User, get_user_by_email_address MIN_PASSWORD_LENGTH = 8 class UserSchema(Schema): id = fields.UUID(dump_only=True) email_address = fields.Email(required=True) password = fields.Str(required=True, load_only=True, validate=validate.Length(min=MIN_PASSWORD_LENGTH)) verified = fields.Bool(dump_only=True) @validates('email_address') def check_if_email_unique(self, value): if get_user_by_email_address(value): raise ValidationError( "A user with this email address already exists." ) def hash_password(self, data, **kwargs): data['password_hash'], data['password_salt'] = hash_plaintext( data.pop('password') ) return data class CreateUserSchema(UserSchema): @post_load def create_user(self, data, **kwargs): return User(**self.hash_password(data)) class UpdateUserSchema(UserSchema): current_password = fields.Str(load_only=True) verification_token = fields.Str(load_only=True) def __init__( self, user: User = None, requires_current_password: bool = True, *args, **kwargs ): super().__init__(*args, **kwargs) self.context['user'] = user self.context['requires_current_password'] = requires_current_password @validates_schema def validate_current_password_if_required(self, data, **kwargs): if (not data.get('password') or not self.context['requires_current_password']): return try: current_password = data['current_password'] except KeyError: raise ValidationError( "This field is required when setting a new password", 'current_password' ) self.validate_current_password(current_password) def validate_current_password(self, current_password): context_user = self.context['user'] if not compare_plaintext_to_hash( current_password, context_user.password_hash, context_user.password_salt ): raise ValidationError( "Given password is incorrect", 'current_password' ) @validates('verification_token') def validate_verification_token(self, token): context_user = self.context['user'] if context_user.verified: raise ValidationError("This user is already verified.") verification_token = context_user.active_verification_token try: if compare_plaintext_to_hash(token, verification_token.token_hash, verification_token.token_salt): verification_token.used = True return except AttributeError: # No token, continue to raise pass raise ValidationError("The given token is incorrect or expired.") @post_load def hash_password(self, data, **kwargs): try: return super().hash_password(data) except KeyError: # No password, which is fine since it's not required. return data @post_load def set_verified(self, data, **kwargs): if data.pop('verification_token', None): data['verified'] = True return data class VerifyUserSchema(Schema): def __init__(self, user: User = None, *args, **kwargs): super().__init__(*args, **kwargs) self.context['user'] = user @validates_schema def check_if_already_verified(self, data, **kwargs): if self.context['user'].verified: raise ValidationError("This user is already verified.")
32.222222
92
0.624384
431
4,060
5.617169
0.220418
0.092937
0.034696
0.027261
0.241223
0.158612
0.092524
0.092524
0.092524
0.092524
0
0.000346
0.288177
4,060
125
93
32.48
0.83737
0.019458
0
0.329897
0
0
0.110608
0.012569
0
0
0
0
0
0
null
null
0.268041
0.030928
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
e29fa79eca53178795185c5b18107d7e3a5c1a43
349
py
Python
luftdaten/exceptions.py
lrubaszewski/python-luftdaten
69c29f4ee0ac6e8e8749eee44102d1b513cf5cd5
[ "MIT" ]
5
2018-02-08T12:39:19.000Z
2019-08-16T11:23:23.000Z
luftdaten/exceptions.py
lrubaszewski/python-luftdaten
69c29f4ee0ac6e8e8749eee44102d1b513cf5cd5
[ "MIT" ]
6
2017-12-26T16:58:20.000Z
2020-03-31T06:54:18.000Z
luftdaten/exceptions.py
lrubaszewski/python-luftdaten
69c29f4ee0ac6e8e8749eee44102d1b513cf5cd5
[ "MIT" ]
9
2017-12-26T15:29:13.000Z
2020-03-30T18:12:08.000Z
"""Exceptions for the Luftdaten Wrapper.""" class LuftdatenError(Exception): """General LuftdatenError exception occurred.""" pass class LuftdatenConnectionError(LuftdatenError): """When a connection error is encountered.""" pass class LuftdatenNoDataAvailable(LuftdatenError): """When no data is available.""" pass
17.45
52
0.716332
32
349
7.8125
0.6875
0.184
0
0
0
0
0
0
0
0
0
0
0.17765
349
19
53
18.368421
0.87108
0.421203
0
0.5
0
0
0
0
0
0
0
0
0
1
0
true
0.5
0
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
1
0
0
0
0
0
2
e29fe3df8dc5516581790a80c10fc304c7ec7af2
215
py
Python
training/191210/123.py
SOOIN-KIM/lab-python
4b85dc11c76e2d4f89be0d01864f9f61f3c6e2cc
[ "MIT" ]
null
null
null
training/191210/123.py
SOOIN-KIM/lab-python
4b85dc11c76e2d4f89be0d01864f9f61f3c6e2cc
[ "MIT" ]
null
null
null
training/191210/123.py
SOOIN-KIM/lab-python
4b85dc11c76e2d4f89be0d01864f9f61f3c6e2cc
[ "MIT" ]
null
null
null
from sklearn.metrics import r2_score y_true = [3, -0.5, 2, 7] y_pred = [2.5, 0.0, 2, 8] r2=r2_score(y_true, y_pred) print(r2) y_true = [5,6,7,8] y_pred = [-100,524,-1,3] r2=r2_score(y_true, y_pred) print(r2) r2_
15.357143
36
0.651163
52
215
2.461538
0.384615
0.15625
0.1875
0.28125
0.40625
0.40625
0.40625
0.40625
0.40625
0
0
0.169399
0.148837
215
14
37
15.357143
0.530055
0
0
0.4
0
0
0
0
0
0
0
0
0
1
0
false
0
0.1
0
0.1
0.2
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e2b210571dd44806899488b6c2d460b54d183385
349
py
Python
authentik/lib/utils/errors.py
BeryJu/passbook
350f0d836580f4411524614f361a76c4f27b8a2d
[ "MIT" ]
15
2020-01-05T09:09:57.000Z
2020-11-28T05:27:39.000Z
authentik/lib/utils/errors.py
BeryJu/passbook
350f0d836580f4411524614f361a76c4f27b8a2d
[ "MIT" ]
302
2020-01-21T08:03:59.000Z
2020-12-04T05:04:57.000Z
authentik/lib/utils/errors.py
BeryJu/passbook
350f0d836580f4411524614f361a76c4f27b8a2d
[ "MIT" ]
3
2020-03-04T08:21:59.000Z
2020-08-01T20:37:18.000Z
"""error utils""" from traceback import format_tb TRACEBACK_HEADER = "Traceback (most recent call last):\n" def exception_to_string(exc: Exception) -> str: """Convert exception to string stackrace""" # Either use passed original exception or whatever we have return TRACEBACK_HEADER + "".join(format_tb(exc.__traceback__)) + str(exc)
31.727273
78
0.73639
46
349
5.369565
0.673913
0.064777
0.137652
0
0
0
0
0
0
0
0
0
0.154728
349
10
79
34.9
0.837288
0.30659
0
0
0
0
0.155844
0
0
0
0
0
0
1
0.25
false
0
0.25
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
e2b2765478729a29e2e169e61178953a74d6c9a5
967
py
Python
atlas/foundations_sdk/src/foundations/helpers/queued.py
DeepLearnI/atlas
8aca652d7e647b4e88530b93e265b536de7055ed
[ "Apache-2.0" ]
296
2020-03-16T19:55:00.000Z
2022-01-10T19:46:05.000Z
atlas/foundations_sdk/src/foundations/helpers/queued.py
DeepLearnI/atlas
8aca652d7e647b4e88530b93e265b536de7055ed
[ "Apache-2.0" ]
57
2020-03-17T11:15:57.000Z
2021-07-10T14:42:27.000Z
atlas/foundations_sdk/src/foundations/helpers/queued.py
DeepLearnI/atlas
8aca652d7e647b4e88530b93e265b536de7055ed
[ "Apache-2.0" ]
38
2020-03-17T21:06:05.000Z
2022-02-08T03:19:34.000Z
_QUEUED_JOBS_KEY = 'projects:global:jobs:queued' _ARCHIVED_JOBS_KEY = 'projects:global:jobs:archived' def list_jobs(redis): return {job_id.decode() for job_id in redis.smembers(_QUEUED_JOBS_KEY)} def remove_jobs(redis, job_id_project_mapping): for job_id, project_name in job_id_project_mapping.items(): redis.srem(_QUEUED_JOBS_KEY, job_id) redis.srem('project:{}:jobs:queued'.format(project_name), job_id) def job_project_names(redis, list_of_job_ids): return {job_id: _job_project_name(redis, job_id) for job_id in list_of_job_ids} def _job_project_name(redis, job_id): project_name = redis.get('jobs:{}:project'.format(job_id)) if project_name: return project_name.decode() def add_jobs_to_archive(redis, list_of_job_ids): for job_id in list_of_job_ids: redis.sadd(_ARCHIVED_JOBS_KEY, job_id) def list_archived_jobs(redis): return {job_id.decode() for job_id in redis.smembers(_ARCHIVED_JOBS_KEY)}
37.192308
83
0.761117
159
967
4.188679
0.201258
0.12012
0.06006
0.06006
0.411411
0.285285
0.213213
0.213213
0.147147
0.147147
0
0
0.134436
967
26
84
37.192308
0.795699
0
0
0
0
0
0.096174
0.080662
0
0
0
0
0
1
0.315789
false
0
0
0.157895
0.526316
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
2c341aa50389e1550ffc2517e153f369b8431dd7
381
py
Python
15-more-types/mysum.py
SeirousLee/example-code-2e
81ec1669a4b8fd098db44a78a3d551287eec7bc9
[ "MIT" ]
990
2019-03-21T21:17:34.000Z
2022-03-31T00:55:07.000Z
15-more-types/mysum.py
FerMatPy/example-code-2e
980f75032685921e08d5200513a261e83ef5f858
[ "MIT" ]
17
2019-12-18T18:00:05.000Z
2022-01-12T14:23:47.000Z
15-more-types/mysum.py
FerMatPy/example-code-2e
980f75032685921e08d5200513a261e83ef5f858
[ "MIT" ]
276
2019-04-06T12:32:00.000Z
2022-03-29T11:50:47.000Z
import functools import operator from collections.abc import Iterable from typing import overload, Union, TypeVar T = TypeVar('T') S = TypeVar('S') # <1> @overload def sum(it: Iterable[T]) -> Union[T, int]: ... # <2> @overload def sum(it: Iterable[T], /, start: S) -> Union[T, S]: ... # <3> def sum(it, /, start=0): # <4> return functools.reduce(operator.add, it, start)
25.4
64
0.64042
57
381
4.280702
0.45614
0.07377
0.098361
0.131148
0.204918
0.204918
0
0
0
0
0
0.015823
0.170604
381
14
65
27.214286
0.756329
0.03937
0
0.166667
0
0
0.00554
0
0
0
0
0
0
1
0.25
false
0
0.333333
0.083333
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
1
0
0
0
0
2
2c4d517cd55c0652efb772faaec52634d1b76f2f
376
py
Python
pipeline/reach-es-extractor/refparse/utils/__init__.py
wellcometrust/reach
1aa42c7d8aaf0a91d033af8448a33f37563b0365
[ "MIT" ]
11
2019-11-04T08:24:00.000Z
2021-12-16T23:11:47.000Z
pipeline/reach-es-extractor/refparse/utils/__init__.py
wellcometrust/reach
1aa42c7d8aaf0a91d033af8448a33f37563b0365
[ "MIT" ]
274
2019-10-30T15:37:17.000Z
2021-03-25T16:13:36.000Z
pipeline/reach-es-extractor/refparse/utils/__init__.py
wellcometrust/reference-parser
1aa42c7d8aaf0a91d033af8448a33f37563b0365
[ "MIT" ]
3
2019-11-12T13:38:14.000Z
2020-04-16T07:49:04.000Z
from .parse import structure_reference from .fuzzy_match import FuzzyMatcher from .file_manager import FileManager from .serialiser import serialise_matched_reference, serialise_reference from .exact_match import ExactMatcher __all__ = [ structure_reference, FuzzyMatcher, FileManager, serialise_matched_reference, serialise_reference, ExactMatcher ]
25.066667
72
0.81383
39
376
7.461538
0.435897
0.123711
0.171821
0.233677
0.295533
0
0
0
0
0
0
0
0.148936
376
14
73
26.857143
0.909375
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.384615
0
0.384615
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
1
0
0
0
0
2
2c543d7182008c5df004271e7ae10351c224c8a5
2,522
py
Python
statinf/ml/activations.py
florianfelice/pleas
c25374f36b781ac726bbbc6da21a559499844594
[ "MIT" ]
6
2019-11-24T01:29:57.000Z
2021-01-28T16:24:54.000Z
statinf/ml/activations.py
florianfelice/pleas
c25374f36b781ac726bbbc6da21a559499844594
[ "MIT" ]
null
null
null
statinf/ml/activations.py
florianfelice/pleas
c25374f36b781ac726bbbc6da21a559499844594
[ "MIT" ]
6
2019-11-22T10:40:37.000Z
2020-10-31T13:59:19.000Z
import numpy as np import jax.numpy as jnp from jax import lax from jax.scipy.special import expit # Default activation functions def sigmoid(x): """Sigmoid activation function. :param x: Input value :type x: :obj:`float` or :obj:`numpy.array` :return: Sigmoid activated value: :math:`sigmoid(x) = \\dfrac{1}{1 + e^{-x}}` :rtype: :obj:`float` """ return expit(x) def relu(x): """Rectified Linear Unit activation function. :param x: Input value :type x: :obj:`float` or :obj:`numpy.array` :return: Activated value: :math:`\\mathrm{relu}(x) = \\max(0, x)` :rtype: :obj:`float` """ return jnp.maximum(0, x) def elu(x, alpha=1.): """Exponential Linear Unit activation function. :param x: Input value :type x: :obj:`float` or :obj:`numpy.array` :formula: .. math:: \\mathrm{elu}(x) = \\begin{cases} x, & x > 0\\\\ \\alpha \\left(e^{x} - 1\\right), & x \\le 0 \\end{cases} :return: Activated value. :rtype: :obj:`float` """ safe_x = jnp.where(x > 0, 0., x) return jnp.where(x > 0, x, alpha * jnp.expm1(safe_x)) def tanh(x): """Hyperbolic tangent activation function. :param x: Input value :type x: :obj:`float` or :obj:`numpy.array` :return: Activated value: :math:`\\tanh(x)` :rtype: :obj:`float` """ return jnp.log(x) def softplus(x): """Softplus activation function. :param x: Input value :type x: :obj:`float` or :obj:`numpy.array` :return: Activated value: :math:`\\mathrm{softplus}(x) = \\log(1 + e^{-x})` :rtype: :obj:`float` """ return jnp.log(1 + jnp.exp(-x)) def softmax(x, axis=-1): """Softmax activation function. :param x: Input value :type x: :obj:`float` or :obj:`numpy.array` :return: Activated value: :math:`\\mathrm{softmax}(x) = \\frac{\\exp(x_i)}{\\sum_j \\exp(x_j)}` :rtype: :obj:`float` """ un_normalized = jnp.exp(x - lax.stop_gradient(x.max(axis, keepdims=True))) return un_normalized / un_normalized.sum(axis, keepdims=True) def logit(x, weights, bias=0): """Logistic function :param x: Input value :type x: numpy.array :param weights: Vector of weights :math:`\\beta` :type weights: numpy.array :param bias: Vector of bias :math:`\\epsilon`, defaults to 0. :type bias: numpy.array :return: Logistic transformation: :math:`\\mathrm{logit}(x, \\beta) = \\dfrac{1}{1 + e^{-x \\beta}}` :rtype: float """ return 1 / (1 + np.exp(-x.dot(weights) + bias))
25.474747
130
0.600714
362
2,522
4.160221
0.232044
0.063745
0.065073
0.088313
0.434927
0.424967
0.409695
0.339973
0.339973
0.339973
0
0.010558
0.21134
2,522
98
131
25.734694
0.746606
0.637193
0
0
0
0
0
0
0
0
0
0
0
1
0.35
false
0
0.2
0
0.9
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
2c8fefcc1cd7b12e6c4a468980052f0c5a0a2783
1,469
py
Python
evaluation.py
rdedo099/HonoursProject2021
94c61218371587fd4dd9dacaa5e8f0ce7f44875d
[ "MIT" ]
null
null
null
evaluation.py
rdedo099/HonoursProject2021
94c61218371587fd4dd9dacaa5e8f0ce7f44875d
[ "MIT" ]
null
null
null
evaluation.py
rdedo099/HonoursProject2021
94c61218371587fd4dd9dacaa5e8f0ce7f44875d
[ "MIT" ]
null
null
null
from sklearn import metrics from prettytable import PrettyTable def evaluate_clustering(name, X, true_labels, pred_labels): homogeneity = metrics.homogeneity_score(true_labels, pred_labels) completeness = metrics.completeness_score(true_labels, pred_labels) v_measure = metrics.v_measure_score(true_labels, pred_labels) adj_rand_score = metrics.adjusted_rand_score(true_labels, pred_labels) norm_mutual_score = metrics.normalized_mutual_info_score(true_labels, pred_labels) fowlkes_m = metrics.fowlkes_mallows_score(true_labels, pred_labels) #silhouette = metrics.silhouette_score(X, pred_labels, metric='euclidean') return [name, "{:.2f}".format(homogeneity), "{:.2f}".format(completeness), "{:.2f}".format(v_measure), "{:.2f}".format(adj_rand_score), "{:.2f}".format(norm_mutual_score), "{:.2f}".format(fowlkes_m)] def tabulate_results(results): t = PrettyTable(['Name', 'Homogeneity', 'Completeness', 'V Measure', 'Adj Rand Score', 'Norm Mutual Score', 'Fowlkes Mallows']) for result in results: t.add_row(result) print(t) def tab_results(header, results): t = PrettyTable(header) for result in results: t.add_row(result) print(t) def evaluate_vmeasure(true_labels, pred_labels): return metrics.v_measure_score(true_labels, pred_labels) def evaluate_fm(true_labels, pred_labels): return metrics.fowlkes_mallows_score(true_labels, pred_labels)
39.702703
203
0.733833
190
1,469
5.368421
0.247368
0.117647
0.15098
0.215686
0.396078
0.298039
0.247059
0.247059
0.078431
0.078431
0
0.004804
0.149762
1,469
37
204
39.702703
0.811849
0.049694
0
0.25
0
0
0.084527
0
0
0
0
0
0
1
0.208333
false
0
0.083333
0.083333
0.416667
0.083333
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
2c90e3fa15866252a877bac9622e4131af1c6c34
1,585
py
Python
db_model.py
jose-marquez89/cryptovest
e0f04e3cbaa01f2de969ed17462052b23328fff8
[ "MIT" ]
null
null
null
db_model.py
jose-marquez89/cryptovest
e0f04e3cbaa01f2de969ed17462052b23328fff8
[ "MIT" ]
null
null
null
db_model.py
jose-marquez89/cryptovest
e0f04e3cbaa01f2de969ed17462052b23328fff8
[ "MIT" ]
null
null
null
import os import pymysql from dotenv import load_dotenv from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import Column, BigInteger, String, Float, ForeignKey def load_engine(): """Create the database engine""" load_dotenv() DB_UNAME = os.environ["DB_UNAME"] DB_PWORD = os.environ["DB_PWORD"] DB_HOST = os.environ["DB_HOST"] DB_NAME = os.environ["DB_NAME"] engine = create_engine(f'mysql+pymysql://{DB_UNAME}:{DB_PWORD}@{DB_HOST}/{DB_NAME}') return engine Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(BigInteger, primary_key=True, nullable=False) name = Column(String(32), unique=True) password = Column(String(32)) transaction = relationship("Ledger") def __repr__(self): return "<User(name={}, password={}>".format(self.name, self.password) class Ledger(Base): __tablename__ = 'ledger' # TODO: add standardized columns based on coinbase csv id = Column(BigInteger, primary_key=True, nullable=False) source = Column(String(20)) asset = Column(String(20)) txn_type = Column(String(20)) amount = Column(Float) price_at_txn = Column(Float) user_id = Column(BigInteger, ForeignKey('user.id'), nullable=False) def __repr__(self): return "<Ledger(asset={}, amount={}, user_id={})>".format(self.asset, self.amount,self.user_id) if __name__ == "__main__": engine = load_engine() Base.metadata.create_all(engine)
28.303571
103
0.694006
203
1,585
5.157635
0.334975
0.028653
0.042025
0.026743
0.08596
0.08596
0.08596
0.08596
0
0
0
0.007675
0.177918
1,585
55
104
28.818182
0.795856
0.050473
0
0.105263
0
0
0.124083
0.038025
0
0
0
0.018182
0
1
0.078947
false
0.052632
0.184211
0.052632
0.736842
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
2ccdb0b6487145d0f81802a42afd953383cafac6
525
py
Python
ex23.py
PhyuAye/Python_exercises-1
3a4049d7af5d0bb3a13b89f3040c9e26a888fea6
[ "MIT" ]
null
null
null
ex23.py
PhyuAye/Python_exercises-1
3a4049d7af5d0bb3a13b89f3040c9e26a888fea6
[ "MIT" ]
null
null
null
ex23.py
PhyuAye/Python_exercises-1
3a4049d7af5d0bb3a13b89f3040c9e26a888fea6
[ "MIT" ]
1
2018-06-26T08:29:44.000Z
2018-06-26T08:29:44.000Z
import sys script, input_encoding, error = sys.argv def main(language_file, encoding, errors): line = language_file.readline() if line: print_line(line, encoding, errors) return main(language_file, encoding, errors) def print_line(line, encoding, errors): next_lang = line.strip() raw_bytes = next_lang.encode(encoding, errors=errors) cooked_string = raw_bytes.decode(encoding, errors=errors) print(raw_bytes, "<===>", cooked_string) languages = open("languages.txt", encoding="utf-8") main(languages, input_encoding, error)
35
57
0.777143
74
525
5.324324
0.418919
0.213198
0.091371
0.121827
0.28934
0
0
0
0
0
0
0.002096
0.091429
525
14
58
37.5
0.823899
0
0
0
0
0
0.04381
0
0
0
0
0
0
0
null
null
0
0.071429
null
null
0.214286
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
e2c91d72449fad349a8ca2ab17e151f78840d950
1,961
py
Python
x509_3_validation_certs.py
askpatrickw/azure_iot_x509_helpers
2bb9f1722f8e018786fcc05589adf40f7597bfab
[ "Unlicense" ]
null
null
null
x509_3_validation_certs.py
askpatrickw/azure_iot_x509_helpers
2bb9f1722f8e018786fcc05589adf40f7597bfab
[ "Unlicense" ]
null
null
null
x509_3_validation_certs.py
askpatrickw/azure_iot_x509_helpers
2bb9f1722f8e018786fcc05589adf40f7597bfab
[ "Unlicense" ]
null
null
null
""" Generate Validation Certificate bases on Azure IoT Hub Verification Code Based on sample code from the cryptography library docs: https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate """ import datetime from pathlib import Path from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography import x509 from cryptography.x509.oid import NameOID from config import AZURE_IOT_VERIFICATION_CODE, COMPANY_INFO, PASSPHRASE, PATH_TO_CERTS, VALID_DAYS for key_name in PASSPHRASE.keys(): pem_data = open(f"{PATH_TO_CERTS}{key_name}/key.pem", "rb").read() key = serialization.load_pem_private_key(pem_data, PASSPHRASE[key_name]) issuer = x509.Name( [ x509.NameAttribute(NameOID.COUNTRY_NAME, COMPANY_INFO['COUNTRY']), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, COMPANY_INFO['STATE']), x509.NameAttribute(NameOID.LOCALITY_NAME, COMPANY_INFO['CITY']), x509.NameAttribute(NameOID.ORGANIZATION_NAME, COMPANY_INFO['NAME']), ] ) subject = x509.Name( [x509.NameAttribute(NameOID.COMMON_NAME, AZURE_IOT_VERIFICATION_CODE[key_name]),] ) cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(issuer) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(datetime.datetime.utcnow()) .not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=VALID_DAYS) ) .sign(key, hashes.SHA256()) ) path = Path(f"{PATH_TO_CERTS}{key_name}") path.mkdir(parents=True, exist_ok=True) filename = f"{path}/validation_certificate.pem" with open(filename, "wb") as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) print(f"{key_name.capitalize()} Validation Cert: {filename}")
36.314815
99
0.704233
239
1,961
5.564854
0.401674
0.031579
0.090226
0.04812
0.133835
0.028571
0
0
0
0
0
0.024406
0.18511
1,961
53
100
37
0.807885
0.113208
0
0
1
0
0.095898
0.065858
0
0
0
0
0
1
0
false
0.075
0.175
0
0.175
0.025
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
2
e2cc67d619fea277f8b31087d0bb55dfe4a8d619
308
py
Python
execicios/ex019/sorteio.py
Israel97f/Exercicios-de-Python
5d3054187977deeb3fadbd7bb1cdee035c609a61
[ "MIT" ]
null
null
null
execicios/ex019/sorteio.py
Israel97f/Exercicios-de-Python
5d3054187977deeb3fadbd7bb1cdee035c609a61
[ "MIT" ]
null
null
null
execicios/ex019/sorteio.py
Israel97f/Exercicios-de-Python
5d3054187977deeb3fadbd7bb1cdee035c609a61
[ "MIT" ]
null
null
null
import random a1 = str(input(' diga o nome do aluno 1 ')) a2 = str(input(' diga o nome do aluno 2 ')) a3 = str(input(' diga o nome do aluno 3 ')) a4 = str(input(' diga o nome do aluno 4 ')) lista = [a1, a2, a3, a4] escolhido = random.choice(lista) print('O aluno soteado é o aluno {}'.format(escolhido))
25.666667
55
0.646104
56
308
3.553571
0.428571
0.160804
0.241206
0.261307
0.482412
0.482412
0.482412
0
0
0
0
0.04878
0.201299
308
11
56
28
0.760163
0
0
0
0
0
0.402597
0
0
0
0
0
0
1
0
false
0
0.125
0
0.125
0.125
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e2d0f35a2efdab82ab362a625cfe59a0e847406a
1,914
py
Python
getAddrFromOS.py
OpenAddressesUK/OSSpatialResearch
a0156278f35330088c6e8f89cbf32601444872d3
[ "MIT" ]
1
2015-05-13T10:52:22.000Z
2015-05-13T10:52:22.000Z
getAddrFromOS.py
OpenAddressesUK/OSSpatialResearch
a0156278f35330088c6e8f89cbf32601444872d3
[ "MIT" ]
null
null
null
getAddrFromOS.py
OpenAddressesUK/OSSpatialResearch
a0156278f35330088c6e8f89cbf32601444872d3
[ "MIT" ]
null
null
null
# # Open addresses Spatial Research # Display Candidate Address Components From OS Open Map & Open Roads # # # Version 1.0 (Python) in progress # Author John Murray # Licence MIT # # Purpose Display Candidate Address Components # import MySQLdb import collections import sys # Database configuration username = "****" password = "********" hostname = "********" database = "****" if len(sys.argv) != 3: print "Invalid arguments. Usage is 'python getAddrFromOS.py postcode buffer'" sys.exit() else: postcode = sys.argv[1] buf_size = int(sys.argv[2]) dbConn = MySQLdb.connect(host=hostname,user=username,passwd=password,db=database) cur = dbConn.cursor() query = "SELECT `name1`,`formOfWay`,`length`,`formsPart`,ST_DISTANCE(`GEOMETRY`,(SELECT `GEOMETRY`FROM `gaz_opennames` WHERE `OS_ID` = '"+postcode+"')) AS `Distance` FROM `spa_roadlink` WHERE `ID` IN (SELECT `ID` FROM `spa_roadlink` WHERE ST_INTERSECTS(`GEOMETRY`,(SELECT ST_BUFFER(`GEOMETRY`,"+str(buf_size)+") FROM `gaz_opennames` WHERE `OS_ID` = '"+postcode+"'))) ORDER BY `Distance`" cur.execute(query) data = cur.fetchall() streets = [] print "Postcode: "+postcode[0:-3]+" "+postcode[-3:] print for d in data: if d[3] != '': for s in d[3].split(","): query = "SELECT `NAME1`, `TYPE`, `LOCAL_TYPE`, `POSTCODE_DISTRICT`, `POPULATED_PLACE`, `DISTRICT_BOROUGH`, `COUNTY_UNITARY`, `REGION`, `COUNTRY`, `RELATED_SPATIAL_OBJECT` FROM `gaz_opennames` WHERE `OS_ID` = '"+s+"'" cur.execute(query) for d1 in cur.fetchall(): if d1[0] not in streets: print "Street: "+d1[0] print "Settlement: "+d1[4] print "District: "+d1[5] print "County: "+d1[6] print "Distance: "+str(d[4]) print streets.extend([d1[0]])
33
387
0.603448
230
1,914
4.934783
0.469565
0.018502
0.042291
0.055507
0.080176
0.080176
0.05815
0
0
0
0
0.017796
0.236677
1,914
57
388
33.578947
0.759069
0.133229
0
0.114286
0
0.085714
0.419708
0.090024
0
0
0
0
0
0
null
null
0.057143
0.085714
null
null
0.257143
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
e2de0a9341a0679887e57b9901b796e25b230e85
327
py
Python
python_exercises/Curso_em_video/ex011.py
Matheus-IT/lang-python-related
dd2e5d9b9f16d3838ba1670fdfcba1fa3fe305e9
[ "MIT" ]
null
null
null
python_exercises/Curso_em_video/ex011.py
Matheus-IT/lang-python-related
dd2e5d9b9f16d3838ba1670fdfcba1fa3fe305e9
[ "MIT" ]
null
null
null
python_exercises/Curso_em_video/ex011.py
Matheus-IT/lang-python-related
dd2e5d9b9f16d3838ba1670fdfcba1fa3fe305e9
[ "MIT" ]
null
null
null
b = float(input('\033[36mQual a largura da parede? \033[m')) h = float(input('\033[32mQual a altura da parede? \033[m')) a = b * h print('\033[36mSua parede tem dimensão {} x {} e sua área é de {:.3f}m².\033[m'.format(b, h, a)) print('\033[32mPara pintar essa parede, você precisará de {}L de tinta.\033[m'.format(a / 2))
54.5
97
0.642202
62
327
3.387097
0.548387
0.07619
0.12381
0.114286
0
0
0
0
0
0
0
0.127737
0.16208
327
5
98
65.4
0.638686
0
0
0
0
0.2
0.68323
0
0
0
0
0
0
1
0
false
0
0
0
0
0.4
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
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e2e7e55d22649bca4fb42e3ec2dfab9577ef8761
786
py
Python
keepercommander/plugins/windows/windows.py
Mkn-yskz/Commandy
e360306f41112534ae71102658f560fd974a1f45
[ "MIT" ]
151
2015-11-02T02:04:46.000Z
2022-01-20T00:07:01.000Z
keepercommander/plugins/windows/windows.py
Mkn-yskz/Commandy
e360306f41112534ae71102658f560fd974a1f45
[ "MIT" ]
145
2015-12-31T00:11:35.000Z
2022-03-31T19:13:54.000Z
keepercommander/plugins/windows/windows.py
Mkn-yskz/Commandy
e360306f41112534ae71102658f560fd974a1f45
[ "MIT" ]
73
2015-10-30T00:53:10.000Z
2022-03-30T03:50:53.000Z
# -*- coding: utf-8 -*- # _ __ # | |/ /___ ___ _ __ ___ _ _ ® # | ' </ -_) -_) '_ \/ -_) '_| # |_|\_\___\___| .__/\___|_| # |_| # # Keeper Commander # Copyright 2015 Keeper Security Inc. # Contact: ops@keepersecurity.com # import logging import subprocess import re def rotate(record, newpassword): """ Grab any required fields from the record """ i = subprocess.call(["net", "user", record.login, newpassword], shell=True) if i == 0: logging.info('Password changed successfully') record.password = newpassword return True logging.error('Password change failed') return True def adjust(newpassword): # the characters below mess with windows command line return re.sub('[<>&|]', '', newpassword)
22.457143
79
0.603053
77
786
5.688312
0.701299
0.045662
0
0
0
0
0
0
0
0
0
0.010169
0.249364
786
34
80
23.117647
0.730508
0.414758
0
0.153846
0
0
0.144796
0
0
0
0
0
0
1
0.153846
false
0.538462
0.230769
0.076923
0.615385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
e2fa28ba790d57d8d11a1525236c74ab08efcf00
14,930
py
Python
Lib/site-packages/hackedit/app/forms/main_window_ui.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
null
null
null
Lib/site-packages/hackedit/app/forms/main_window_ui.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
20
2021-05-03T18:02:23.000Z
2022-03-12T12:01:04.000Z
Lib/site-packages/hackedit/app/forms/main_window_ui.py
fochoao/cpython
3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9
[ "bzip2-1.0.6", "0BSD" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/Users/Colin/Documents/hackedit/data/forms/main_window.ui' # # Created by: PyQt5 UI code generator 5.6 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(778, 575) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/icons/hackedit.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setDockOptions(QtWidgets.QMainWindow.AnimatedDocks) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.gridLayout = QtWidgets.QGridLayout(self.centralwidget) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setSpacing(0) self.gridLayout.setObjectName("gridLayout") self.stackedWidget = QtWidgets.QStackedWidget(self.centralwidget) self.stackedWidget.setObjectName("stackedWidget") self.page_edit = QtWidgets.QWidget() self.page_edit.setObjectName("page_edit") self.verticalLayout = QtWidgets.QVBoxLayout(self.page_edit) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName("verticalLayout") self.tabs = SplittableCodeEditTabWidget(self.page_edit) self.tabs.setObjectName("tabs") self.verticalLayout.addWidget(self.tabs) self.stackedWidget.addWidget(self.page_edit) self.page_empty = QtWidgets.QWidget() self.page_empty.setObjectName("page_empty") self.gridLayout_2 = QtWidgets.QGridLayout(self.page_empty) self.gridLayout_2.setContentsMargins(0, 0, 0, 0) self.gridLayout_2.setObjectName("gridLayout_2") spacerItem = QtWidgets.QSpacerItem(20, 171, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.gridLayout_2.addItem(spacerItem, 0, 1, 1, 1) spacerItem1 = QtWidgets.QSpacerItem(193, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem1, 1, 0, 1, 1) spacerItem2 = QtWidgets.QSpacerItem(192, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.gridLayout_2.addItem(spacerItem2, 1, 2, 1, 1) self.label = QtWidgets.QLabel(self.page_empty) self.label.setObjectName("label") self.gridLayout_2.addWidget(self.label, 1, 1, 1, 1) spacerItem3 = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.gridLayout_2.addItem(spacerItem3, 2, 1, 1, 1) self.stackedWidget.addWidget(self.page_empty) self.gridLayout.addWidget(self.stackedWidget, 0, 0, 1, 1) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 778, 27)) self.menubar.setObjectName("menubar") self.mnu_file = QtWidgets.QMenu(self.menubar) self.mnu_file.setObjectName("mnu_file") self.mnu_view = QtWidgets.QMenu(self.menubar) self.mnu_view.setObjectName("mnu_view") self.mnu_windows = QtWidgets.QMenu(self.mnu_view) self.mnu_windows.setObjectName("mnu_windows") self.mnu_help = QtWidgets.QMenu(self.menubar) self.mnu_help.setObjectName("mnu_help") self.mnu_edit = QtWidgets.QMenu(self.menubar) self.mnu_edit.setObjectName("mnu_edit") self.menuActive_editor = QtWidgets.QMenu(self.mnu_edit) icon = QtGui.QIcon.fromTheme("accessories-text-editor") self.menuActive_editor.setIcon(icon) self.menuActive_editor.setObjectName("menuActive_editor") self.menuTools = QtWidgets.QMenu(self.menubar) self.menuTools.setObjectName("menuTools") MainWindow.setMenuBar(self.menubar) self.toolBarFile = QtWidgets.QToolBar(MainWindow) self.toolBarFile.setObjectName("toolBarFile") MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBarFile) self.action_open = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("folder") self.action_open.setIcon(icon) self.action_open.setShortcutContext(QtCore.Qt.WindowShortcut) self.action_open.setObjectName("action_open") self.action_save = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("document-save") self.action_save.setIcon(icon) self.action_save.setObjectName("action_save") self.action_save_as = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("document-save-as") self.action_save_as.setIcon(icon) self.action_save_as.setObjectName("action_save_as") self.action_close = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("window-close") self.action_close.setIcon(icon) self.action_close.setObjectName("action_close") self.action_quit = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("application-exit") self.action_quit.setIcon(icon) self.action_quit.setObjectName("action_quit") self.action_preferences = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("preferences-system") self.action_preferences.setIcon(icon) self.action_preferences.setObjectName("action_preferences") self.action_about = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("help-about") self.action_about.setIcon(icon) self.action_about.setObjectName("action_about") self.action_help = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("system-help") self.action_help.setIcon(icon) self.action_help.setObjectName("action_help") self.action_new = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("document-new") self.action_new.setIcon(icon) self.action_new.setObjectName("action_new") self.action_report_bug = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("tools-report-bug") self.action_report_bug.setIcon(icon) self.action_report_bug.setObjectName("action_report_bug") self.action_save_all = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("document-save-all") self.action_save_all.setIcon(icon) self.action_save_all.setObjectName("action_save_all") self.action_check_for_update = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("system-software-update") self.action_check_for_update.setIcon(icon) self.action_check_for_update.setObjectName("action_check_for_update") self.a_fullscreen = QtWidgets.QAction(MainWindow) self.a_fullscreen.setCheckable(True) self.a_fullscreen.setChecked(False) icon = QtGui.QIcon.fromTheme("view-fullscreen") self.a_fullscreen.setIcon(icon) self.a_fullscreen.setObjectName("a_fullscreen") self.a_menu = QtWidgets.QAction(MainWindow) self.a_menu.setCheckable(True) self.a_menu.setChecked(False) self.a_menu.setObjectName("a_menu") self.action_open_file = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("document-open") self.action_open_file.setIcon(icon) self.action_open_file.setObjectName("action_open_file") self.a_print = QtWidgets.QAction(MainWindow) icon = QtGui.QIcon.fromTheme("document-print") self.a_print.setIcon(icon) self.a_print.setObjectName("a_print") self.mnu_file.addAction(self.action_new) self.mnu_file.addAction(self.action_open_file) self.mnu_file.addAction(self.action_open) self.mnu_file.addSeparator() self.mnu_file.addAction(self.action_save) self.mnu_file.addAction(self.action_save_as) self.mnu_file.addAction(self.action_save_all) self.mnu_file.addSeparator() self.mnu_file.addAction(self.a_print) self.mnu_file.addSeparator() self.mnu_file.addAction(self.action_close) self.mnu_file.addSeparator() self.mnu_file.addAction(self.action_quit) self.mnu_view.addAction(self.a_fullscreen) self.mnu_view.addAction(self.a_menu) self.mnu_view.addSeparator() self.mnu_view.addAction(self.mnu_windows.menuAction()) self.mnu_help.addAction(self.action_help) self.mnu_help.addAction(self.action_about) self.mnu_help.addSeparator() self.mnu_help.addAction(self.action_report_bug) self.mnu_help.addSeparator() self.mnu_help.addAction(self.action_check_for_update) self.mnu_edit.addAction(self.menuActive_editor.menuAction()) self.mnu_edit.addSeparator() self.mnu_edit.addAction(self.action_preferences) self.menubar.addAction(self.mnu_file.menuAction()) self.menubar.addAction(self.mnu_edit.menuAction()) self.menubar.addAction(self.menuTools.menuAction()) self.menubar.addAction(self.mnu_view.menuAction()) self.menubar.addAction(self.mnu_help.menuAction()) self.toolBarFile.addAction(self.action_new) self.toolBarFile.addAction(self.action_open_file) self.toolBarFile.addAction(self.action_open) self.toolBarFile.addSeparator() self.toolBarFile.addAction(self.action_save) self.toolBarFile.addAction(self.action_save_as) self.retranslateUi(MainWindow) self.stackedWidget.setCurrentIndex(1) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "HackEdit")) self.label.setText(_translate("MainWindow", "<html><head/><body><p align=\"center\"><span style=\" font-size:18pt;\">Open a document</span></p><hr/><ul style=\"margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;\"><li style=\" margin-top:12px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-style:italic;\">File &gt; Open File</span> (<span style=\" font-style:italic;\">Ctrl+O</span>)</li><li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-style:italic;\">Goto &gt; Goto anything</span> (<span style=\" font-style:italic;\">Ctrl+P</span>) and type to open file from any open project</li><li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Use the project tree view</li></ul><ul style=\"margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px; -qt-list-indent: 1;\"><li style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Drag and drop files here</li></ul></body></html>")) self.mnu_file.setTitle(_translate("MainWindow", "Fi&le")) self.mnu_view.setTitle(_translate("MainWindow", "&View")) self.mnu_windows.setToolTip(_translate("MainWindow", "The list of windows")) self.mnu_windows.setTitle(_translate("MainWindow", "&Windows")) self.mnu_help.setTitle(_translate("MainWindow", "?")) self.mnu_edit.setTitle(_translate("MainWindow", "E&dit")) self.menuActive_editor.setToolTip(_translate("MainWindow", "Active editor actions")) self.menuActive_editor.setTitle(_translate("MainWindow", "&Active editor")) self.menuTools.setTitle(_translate("MainWindow", "&Tools")) self.toolBarFile.setWindowTitle(_translate("MainWindow", "FileToolBar")) self.action_open.setText(_translate("MainWindow", "&Open project")) self.action_open.setToolTip(_translate("MainWindow", "Open a project")) self.action_open.setShortcut(_translate("MainWindow", "Ctrl+O")) self.action_save.setText(_translate("MainWindow", "&Save")) self.action_save.setToolTip(_translate("MainWindow", "Save current editor")) self.action_save.setShortcut(_translate("MainWindow", "Ctrl+S")) self.action_save_as.setText(_translate("MainWindow", "Sa&ve as")) self.action_save_as.setToolTip(_translate("MainWindow", "Save current editor as")) self.action_save_as.setShortcut(_translate("MainWindow", "Ctrl+Alt+S")) self.action_close.setText(_translate("MainWindow", "&Close window")) self.action_close.setShortcut(_translate("MainWindow", "Ctrl+Shift+Q")) self.action_quit.setText(_translate("MainWindow", "&Quit")) self.action_quit.setToolTip(_translate("MainWindow", "Quit application")) self.action_quit.setShortcut(_translate("MainWindow", "Ctrl+Q")) self.action_preferences.setText(_translate("MainWindow", "&Preferences")) self.action_preferences.setToolTip(_translate("MainWindow", "Edit preferences")) self.action_preferences.setShortcut(_translate("MainWindow", "Ctrl+,")) self.action_about.setText(_translate("MainWindow", "&About")) self.action_about.setToolTip(_translate("MainWindow", "About HackEdit")) self.action_help.setText(_translate("MainWindow", "&Help")) self.action_help.setToolTip(_translate("MainWindow", "Get some help")) self.action_new.setText(_translate("MainWindow", "&New")) self.action_new.setToolTip(_translate("MainWindow", "Create a new file/project")) self.action_new.setShortcut(_translate("MainWindow", "Ctrl+N")) self.action_report_bug.setText(_translate("MainWindow", "&Report an issue...")) self.action_report_bug.setToolTip(_translate("MainWindow", "Create an issue (report a bug/enhancement)")) self.action_save_all.setText(_translate("MainWindow", "Save a&ll")) self.action_save_all.setToolTip(_translate("MainWindow", "Save all editors")) self.action_save_all.setShortcut(_translate("MainWindow", "Ctrl+Shift+S")) self.action_check_for_update.setText(_translate("MainWindow", "&Check for update")) self.a_fullscreen.setText(_translate("MainWindow", "&Toggle fullscreen")) self.a_fullscreen.setToolTip(_translate("MainWindow", "Toggle fullscreen")) self.a_menu.setText(_translate("MainWindow", "Toggle &menu")) self.a_menu.setToolTip(_translate("MainWindow", "Show/Hide menu bar")) self.action_open_file.setText(_translate("MainWindow", "Open &file")) self.action_open_file.setToolTip(_translate("MainWindow", "Open a file")) self.a_print.setText(_translate("MainWindow", "&Print")) from pyqode.core.widgets import SplittableCodeEditTabWidget
61.950207
1,233
0.709779
1,749
14,930
5.885077
0.136078
0.087438
0.031283
0.035752
0.380453
0.29282
0.214806
0.159429
0.132129
0.109783
0
0.010229
0.161889
14,930
240
1,234
62.208333
0.812355
0.01507
0
0.026316
1
0.004386
0.145394
0.011362
0
0
0
0
0
1
0.008772
false
0
0.008772
0
0.02193
0.026316
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
e2fd92287732d912730a455c577004d7bf52e164
1,314
py
Python
order/models.py
divyesh1099/badboystyle
f4fec0858b43e14f0e1f173261f363d4262c28ea
[ "MIT" ]
null
null
null
order/models.py
divyesh1099/badboystyle
f4fec0858b43e14f0e1f173261f363d4262c28ea
[ "MIT" ]
null
null
null
order/models.py
divyesh1099/badboystyle
f4fec0858b43e14f0e1f173261f363d4262c28ea
[ "MIT" ]
null
null
null
from django.db import models import uuid from product.models import Product from django.contrib.auth.models import User # Create your models here. class Order(models.Model): generated_order_id = models.CharField(max_length=100, default=uuid.uuid4, unique=True) products = models.ManyToManyField(Product, related_name='product_of_order') user = models.ForeignKey(User, on_delete=models.CASCADE) payment_method = models.CharField(max_length=1000) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) address = models.TextField() city = models.CharField(max_length=1000) state = models.CharField(max_length=1000) zip = models.PositiveBigIntegerField() phonenumber = models.PositiveBigIntegerField() amount = models.PositiveIntegerField() dispatched = models.BooleanField() dispatched_timestamp = models.DateTimeField(auto_now_add=True) delivered = models.BooleanField() delivered_timestamp = models.DateTimeField(auto_now_add=True) paid = models.BooleanField() cancelled = models.BooleanField(default=False) active = models.BooleanField(default=True) class Meta: ordering = ['-date'] def __unicode__(self): return self.name def __str__(self): return str(self.id)
32.85
91
0.739726
154
1,314
6.123377
0.454545
0.09544
0.076352
0.101803
0.178155
0.089077
0.089077
0
0
0
0
0.014572
0.164384
1,314
39
92
33.692308
0.844262
0.018265
0
0
1
0
0.016317
0
0
0
0
0
0
1
0.066667
false
0
0.133333
0.066667
0.966667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
e2ff3ce76141b539b88b724b3e32501df66e17ca
6,161
py
Python
campfire/components/models/publications/Post.py
Camper-CoolDie/campfire.py
bc90f004a6f086c18d4f46e9a7679ead96feca1f
[ "MIT" ]
null
null
null
campfire/components/models/publications/Post.py
Camper-CoolDie/campfire.py
bc90f004a6f086c18d4f46e9a7679ead96feca1f
[ "MIT" ]
null
null
null
campfire/components/models/publications/Post.py
Camper-CoolDie/campfire.py
bc90f004a6f086c18d4f46e9a7679ead96feca1f
[ "MIT" ]
null
null
null
from ...reqs import publications from .. import main class Post(main._all["publication"]): """ Имитирует объект поста. """ __slots__ = ( "pages", "best_comment", "rubric_id", "rubric_name" ) def __init__(self, content): """ Создать класс Post. content: :class:`dict` Словарь, который сервер Campfire отправляет для создания объекта поста. """ super(Post, self).__init__(content) self.pages = content["jsonDB"]["J_PAGES"] # list::dict if content["bestComment"] != None: self.best_comment = main._all["comment"](content["bestComment"]) else: self.best_comment = None self.rubric_id = content["rubricId"] self.rubric_name = content["rubricName"] @staticmethod def get(post_id: int): """ Создать класс Post с помощью его идентификатора. post_id: :class:`int` Идентификатор поста. Возвращает :class:`Post` Объект поста. """ return Post(publications.get_post(post_id)) @staticmethod def get_from_feed(offset: int = 0, languages: list = [2], subscribes: bool = False, *, important: int = False): """ Получить посты из ленты. offset: :class:`int` Дата создания последнего поста в миллисекундах. languages: :class:`list[int]` Лист с языками, которые будут иметь посты из ленты. subscribes: :class:`bool` Если значение верно, то посты из ленты будут из категории "Подписки". important: :class:`bool` Только важные посты. Возвращает :class:`list[Post]` Посты из ленты. """ posts = publications.get_posts_from_feed(offset, languages, subscribes, important) return [ Post(post) for post in posts ] # Self-actions def change_fandom(self, fandom_id: int, fandom_lang: int = 2): """ Изменить фэндом поста. fandom_id: :class:`int` Идентификатор фэндома. fandom_lang: :class:`int` Язык фэндома. """ return publications.post_change_fandom(self.id, "", fandom_id, fandom_lang) def to_drafts(self): """ Отправить пост в черновики. """ return publications.post_to_drafts(self.id) def close(self): """ Закрыть пост. """ return publications.post_close(self.id) def no_close(self): """ Открыть пост. """ return publications.post_close_no(self.id) def set_multilingual(self): """ Сделать пост мультиязычным. """ return publications.post_set_multilingual(self.id) def unset_multilingual(self): """ Сделать пост не мультиязычным. """ return publications.post_unset_multilingual(self.id) def notify_followers(self): """ Уведомить подписчиков. """ return publications.post_notify_followers(self.id) def pin_to_account(self): """ Закрепить пост в своём профиле. """ return publications.post_pin_to_account(self.id) # Moderator def moderator_close(self, comment: str): """ Закрыть пост. comment: :class:`str` Комментарий к модераторскому действию. """ return publications.moderator_post_close(self.id, comment) def moderator_no_close(self, comment: str): """ Открыть пост. comment: :class:`str` Комментарий к модераторскому действию. """ return publications.moderator_post_close_no(self.id, comment) def moderator_unset_multilingual(self, comment: str): """ Сделать пост не мультиязычным. comment: :class:`str` Комментарий к модераторскому действию. """ return publications.moderator_post_unset_multilingual(self.id, comment) def moderator_set_important(self, comment: str, important: bool = True): """ Пометить/убрать метку важности с поста. comment: :class:`str` Комментарий к модераторскому действию. important: :class:`bool` Убрать или поставить метку важности. """ return publications.moderator_post_set_important(self.id, comment, important) def moderator_to_drafts(self, comment: str): """ Отправить пост в черновики. comment: :class:`str` Комментарий к модераторскому действию. """ return publications.moderator_post_to_drafts(self.id, comment) def moderator_pin_to_fandom(self, comment: str): """ Закрепить пост в фэндоме. comment: :class:`str` Комментарий к модераторскому действию. """ return publications.moderator_post_pin_to_fandom(self.id, self.fandom_id, self.fandom_lang, comment) def admin_change_fandom(self, comment: str, fandom_id: int, fandom_lang: int = 2): """ Изменить фэндом поста. comment: :class:`str` Комментарий к модераторскому действию. fandom_id: :class:`int` Идентификатор фэндома. fandom_lang: :class:`int` Язык фэндома. """ return publications.post_change_fandom(self.id, comment, fandom_id, fandom_lang) def admin_make_moderator(self, comment: str): """ Сделать автора поста модератором в фэндоме. comment: :class:`str` Комментарий к модераторскому действию. """ return publications.admin_post_make_moderator(self.id, comment) main._all["post"] = Post
27.382222
115
0.558513
598
6,161
5.571906
0.229097
0.086435
0.059424
0.062425
0.355942
0.270708
0.270708
0.270708
0.239796
0.239796
0
0.000998
0.349132
6,161
225
116
27.382222
0.829925
0.309365
0
0.034483
0
0
0.033725
0
0
0
0
0
0
1
0.327586
false
0
0.103448
0
0.775862
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
3915f2af8263e59a99c7a8c508220c1dd51ea0ed
995
py
Python
hstrat/test/test_helpers/test_is_nonincreasing.py
mmore500/hstrat
7fedcf3a7203e1e6c99ac16f4ec43ad160da3e6c
[ "MIT" ]
null
null
null
hstrat/test/test_helpers/test_is_nonincreasing.py
mmore500/hstrat
7fedcf3a7203e1e6c99ac16f4ec43ad160da3e6c
[ "MIT" ]
3
2022-02-28T17:33:57.000Z
2022-02-28T21:41:33.000Z
hstrat/test/test_helpers/test_is_nonincreasing.py
mmore500/hstrat
7fedcf3a7203e1e6c99ac16f4ec43ad160da3e6c
[ "MIT" ]
null
null
null
import unittest from hstrat.helpers import is_nonincreasing class TestIsNondecreasing(unittest.TestCase): # tests can run independently _multiprocess_can_split_ = True def test_empty(self): assert is_nonincreasing([]) def test_singleton(self): assert is_nonincreasing(['a']) assert is_nonincreasing([0]) assert is_nonincreasing([1]) def test_nondecreasing(self): assert is_nonincreasing(reversed([ *range(10), ])) assert is_nonincreasing(reversed([ 0, *range(10), ])) assert is_nonincreasing(reversed([ 0, 0, *range(10), *range(9,18), ])) def test_decreasing(self): assert not is_nonincreasing([ -1, 0, ]) assert not is_nonincreasing(reversed([ *range(10), *range(2), ])) if __name__ == '__main__': unittest.main()
22.111111
46
0.548744
95
995
5.473684
0.4
0.288462
0.282692
0.144231
0.244231
0.142308
0.142308
0
0
0
0
0.029231
0.346734
995
44
47
22.613636
0.770769
0.027136
0
0.428571
0
0
0.009317
0
0
0
0
0
0.257143
1
0.114286
false
0
0.057143
0
0.228571
0
0
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
3916b6e22cde8396683b52bfab98fb85a404ecf8
2,745
py
Python
flowder/utils.py
amir-khakshour/flowder
d4560b2faea300bb2a4815f13815085215ef7019
[ "MIT" ]
3
2016-06-20T18:33:18.000Z
2019-11-10T11:52:27.000Z
flowder/utils.py
amir-khakshour/flowder
d4560b2faea300bb2a4815f13815085215ef7019
[ "MIT" ]
null
null
null
flowder/utils.py
amir-khakshour/flowder
d4560b2faea300bb2a4815f13815085215ef7019
[ "MIT" ]
null
null
null
import csv import re import netifaces as ni from twisted.internet import defer from twisted.names import client from pygear.logging import log from pygear.core.six.moves.urllib.parse import urlparse, urljoin from .interfaces import ITaskStorage csv.register_dialect('pipes', delimiter='|') client_callback_schemes = ['http', 'https'] default_scheme = 'http' client_scheme_re = re.compile(r'^(%s)' % '|'.join(client_callback_schemes)) ip_re = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") ip_scheme_re = re.compile(r"^(%s)://(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})" % '|'.join(client_callback_schemes)) def get_tasks_db(config, app): return app.getComponent(ITaskStorage) def prepare_url(url): if not client_scheme_re.match(url): url = default_scheme + url return url def get_interface_ip(eth): eth = ni.ifaddresses(eth) return eth[2][0]['addr'] @defer.inlineCallbacks def parse_clients_list(file_path): trusted_clients = None # @TODO create a service to read trusted clients from DB try: trusted_clients = open(file_path, 'r').readlines() trusted_clients = map(lambda c: c.replace('\n', ''), trusted_clients) except IOError: _clients = [] log.warn("Trusted clinets list not found.") clients_list = {} if trusted_clients: for row in csv.reader(trusted_clients, dialect='pipes', quotechar='!'): _host, _user, _pass = row if ip_re.match(_host): _ip = _host else: _host = prepare_url(_host) parsed_url = urlparse(_host) _ip = yield client.getHostByName(parsed_url.netloc) clients_list[_ip] = {'host': _host, 'user': _user, 'pass': _pass} defer.returnValue(clients_list) def get_callback_auth_details(url, trusted_clients): match = ip_scheme_re.match(url) if not match or len(match.groups()) < 2: ip = client.getHostByName(url) else: scheme, ip = match.groups() for client_ip, details in trusted_clients.iteritems(): if ip == client_ip: return details['user'], details['pass'] return None def get_serve_uri(config): rest_port = config.getint('rest_port', 4000) eth = config.get('eth', 'eth1') # private IP rest_host = 'http://%s' % (get_interface_ip(eth)) files_static_serve_path = config.get('static_serve_path', 'files') if rest_host.endswith('/'): rest_host = rest_host[:-1] base_url = '{0}:{1}/'.format(rest_host, rest_port) if not files_static_serve_path.endswith('/'): files_static_serve_path += '/' return urljoin(base_url, files_static_serve_path) def get_file_path(filename, base_path): pass
29.202128
110
0.651002
378
2,745
4.481481
0.320106
0.07438
0.014168
0.014168
0.0366
0.0366
0.014168
0.014168
0.014168
0.014168
0
0.012471
0.211293
2,745
94
111
29.202128
0.769977
0.023679
0
0.029851
0
0.029851
0.085138
0.029873
0
0
0
0.010638
0
1
0.104478
false
0.059701
0.119403
0.014925
0.313433
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
391b5631270f881e44d8df135add12b1dee89004
1,918
py
Python
src/mblib/httpclient.py
odra/mbctl
39f40842c9e62bc59162a14ea13e17b212967067
[ "MIT" ]
null
null
null
src/mblib/httpclient.py
odra/mbctl
39f40842c9e62bc59162a14ea13e17b212967067
[ "MIT" ]
null
null
null
src/mblib/httpclient.py
odra/mbctl
39f40842c9e62bc59162a14ea13e17b212967067
[ "MIT" ]
null
null
null
""" HTTP client module. """ import requests from requests.auth import HTTPBasicAuth from requests_kerberos import HTTPKerberosAuth from . import errors class KRBAuth: """ Kerberos authenticaton type. """ principal = None hostname_override = None def __init__(self, principal=None, hostname_override=None): self.principal = principal self.hostname_override = hostname_override def auth(self): params = {} if self.principal: params['principal'] = self.principal if self.hostname_override: params['hostname_override'] = self.hostname_override return HTTPKerberosAuth(**params) class BasicAuth: username = '' password = '' def __init__(self, usernae, password): self.username = username self.password = password def auth(self): return HTTPBasicAuth(self.username, self.password) class NoAuth: """ No authentication type. """ def auth(self): """ This method does nothing, just a place holder for the "authentication interface". """ return None class Client: """ A simple HTTP client to be used within the CLI code. """ base_url = None auth = None def __init__(self, base_url, auth=NoAuth()): """ Initializes the object with a base url and authentication type. Auth type can be 'basic' or 'krb' and defaults to None if no value is provided. """ self.auth = auth if base_url: self.base_url = base_url def request(self, path, method='GET', data=None, headers=None): """ Execute a request based on method parameters. Return a tuple containing the status_code and text output. """ url = f'{self.base_url}{path}' try: res = requests.request(method, url, data=data, headers=headers, auth=self.auth.auth()) except requests.exceptions.RequestException as e: raise errors.MBError(str(e)) return (res.status_code, res.text)
21.795455
92
0.679353
240
1,918
5.3125
0.370833
0.087843
0.025882
0.04549
0.051765
0
0
0
0
0
0
0
0.220021
1,918
87
93
22.045977
0.852273
0.23879
0
0.071429
0
0
0.036819
0.015464
0
0
0
0
0
1
0.166667
false
0.095238
0.095238
0.02381
0.595238
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
391b9e2db43316337b1ceff240764f306d2bb877
532
py
Python
students/K33422/Izmaylova_Anna/web_lab2/tours2/tours_app/view_create_user.py
Anna0102/ITMO_ICT_WebDevelopment_2021-2022
1a361329eabccefa5bd9f3d22e1b5dbdb950c85e
[ "MIT" ]
null
null
null
students/K33422/Izmaylova_Anna/web_lab2/tours2/tours_app/view_create_user.py
Anna0102/ITMO_ICT_WebDevelopment_2021-2022
1a361329eabccefa5bd9f3d22e1b5dbdb950c85e
[ "MIT" ]
null
null
null
students/K33422/Izmaylova_Anna/web_lab2/tours2/tours_app/view_create_user.py
Anna0102/ITMO_ICT_WebDevelopment_2021-2022
1a361329eabccefa5bd9f3d22e1b5dbdb950c85e
[ "MIT" ]
null
null
null
from django.shortcuts import render from django.views.generic.edit import CreateView from .models import Users from .forms import UserForm from django.contrib.auth.views import LoginView # представление для создания пользователя class UserCreateView(CreateView): form_class = UserForm success_url = '/users_create/' # куда перейдет сайт, когда мы успешно зарегистируемся template_name = 'users_create_form.html' # представление для входа на сайт class UserLogin(LoginView): template_name = "registration/login.html"
33.25
88
0.802632
67
532
6.268657
0.61194
0.071429
0
0
0
0
0
0
0
0
0
0
0.133459
532
16
89
33.25
0.911063
0.234962
0
0
0
0
0.14604
0.111386
0
0
0
0
0
1
0
false
0
0.454545
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
3939aa1d856a574c19f27e62b940f244af52e4da
596
py
Python
Lib/compiler/readonly/util.py
isabella232/cinder-1
428669a9a925287f192ab361226e5a8ca3fb74d9
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Lib/compiler/readonly/util.py
isabella232/cinder-1
428669a9a925287f192ab361226e5a8ca3fb74d9
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Lib/compiler/readonly/util.py
isabella232/cinder-1
428669a9a925287f192ab361226e5a8ca3fb74d9
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
from __future__ import annotations from ast import AST, Subscript, Name, Call READONLY_ANNOTATION: str = "Readonly" READONLY_CALL: str = "readonly" READONLY_FUNC: str = "readonly_func" def is_readonly_annotation(node: AST) -> bool: return ( isinstance(node, Subscript) and isinstance(node.value, Name) and node.value.id == READONLY_ANNOTATION ) def is_readonly_wrapped(node: AST) -> bool: return isinstance(node, Name) and node.id == READONLY_CALL def is_readonly_func(node: AST) -> bool: return isinstance(node, Name) and node.id == READONLY_FUNC
24.833333
62
0.714765
78
596
5.24359
0.282051
0.117359
0.095355
0.124694
0.330073
0.330073
0.254279
0.254279
0.254279
0.254279
0
0
0.187919
596
23
63
25.913043
0.845041
0
0
0
0
0
0.048658
0
0
0
0
0
0
1
0.2
false
0
0.133333
0.2
0.533333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
393bca90bdc4ef1bbf86856f262735858fce5471
681
py
Python
scale/product/apps.py
kaydoh/scale
1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee
[ "Apache-2.0" ]
121
2015-11-18T18:15:33.000Z
2022-03-10T01:55:00.000Z
scale/product/apps.py
kaydoh/scale
1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee
[ "Apache-2.0" ]
1,415
2015-12-23T23:36:04.000Z
2022-01-07T14:10:09.000Z
scale/product/apps.py
kaydoh/scale
1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee
[ "Apache-2.0" ]
66
2015-12-03T20:38:56.000Z
2020-07-27T15:28:11.000Z
"""Defines the application configuration for the product application""" from __future__ import unicode_literals from django.apps import AppConfig class ProductConfig(AppConfig): """Configuration for the product application""" name = 'product' label = 'product' verbose_name = 'Product' def ready(self): """Registers the product implementations with other applications.""" from job.configuration.data.data_file import DATA_FILE_STORE from product.configuration.product_data_file import ProductDataFileStore # Register product files for the data file store DATA_FILE_STORE['DATA_FILE_STORE'] = ProductDataFileStore()
32.428571
80
0.743025
76
681
6.460526
0.447368
0.09776
0.105906
0.105906
0.230143
0.07943
0
0
0
0
0
0
0.18649
681
20
81
34.05
0.886282
0.320117
0
0
0
0
0.080537
0
0
0
0
0
0
1
0.1
false
0
0.4
0
0.9
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
39406eb207149313aba4ec89a02427f69ca6fbfe
612
py
Python
lesson6/solution_simple_functions.py
vinaymayar/python-game-workshop
e990f51815c2080a0d702c9d90dac8e8c2a35d45
[ "MIT" ]
1
2016-10-11T19:27:08.000Z
2016-10-11T19:27:08.000Z
lesson6/solution_simple_functions.py
vinaymayar/python-game-workshop
e990f51815c2080a0d702c9d90dac8e8c2a35d45
[ "MIT" ]
null
null
null
lesson6/solution_simple_functions.py
vinaymayar/python-game-workshop
e990f51815c2080a0d702c9d90dac8e8c2a35d45
[ "MIT" ]
null
null
null
"""lesson6/solution_simple_functions.py Contains solutions for simple functions. """ # Exercise 1: Write a function that prints your name and try calling it. # Work in this file and not in the Python shell. Defining functions in # a Python shell is difficult. Remember to name your function something # that indicates its purpose. def print_my_name(): print("Vinay Mayar") print_my_name() # Exercise 2: Write a function that uses your function from Exercise 1 # to print your name 10 times. def print_my_name_ten_times(): for ctr in range(10): print_my_name() print_my_name_ten_times()
24.48
72
0.751634
98
612
4.530612
0.520408
0.078829
0.123874
0.081081
0.085586
0
0
0
0
0
0
0.015968
0.181373
612
24
73
25.5
0.870259
0.681373
0
0.285714
0
0
0.06044
0
0
0
0
0
0
1
0.285714
false
0
0
0
0.285714
0.857143
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
1
0
2
3940c721245b515751e5bd8b6c8ca3c7c862fc8d
416
py
Python
hcloud/helpers/descriptors.py
rebost/hcloud-python
148184eec3d76b6d51cb76855dff6ae305a0e165
[ "MIT" ]
1
2019-10-23T01:00:08.000Z
2019-10-23T01:00:08.000Z
hcloud/helpers/descriptors.py
rebost/hcloud-python
148184eec3d76b6d51cb76855dff6ae305a0e165
[ "MIT" ]
null
null
null
hcloud/helpers/descriptors.py
rebost/hcloud-python
148184eec3d76b6d51cb76855dff6ae305a0e165
[ "MIT" ]
1
2019-06-19T17:53:10.000Z
2019-06-19T17:53:10.000Z
# -*- coding: utf-8 -*- from dateutil.parser import isoparse class ISODateTime(object): def __init__(self, initval=None): self.val = initval def __get__(self, obj, obj_type): return self.val def __set__(self, obj, string_date): if string_date is None: self.val = None else: # 2016-01-30T23:50+00:00 self.val = isoparse(string_date)
23.111111
44
0.59375
54
416
4.277778
0.592593
0.121212
0.095238
0
0
0
0
0
0
0
0
0.058219
0.298077
416
17
45
24.470588
0.732877
0.105769
0
0
0
0
0
0
0
0
0
0
0
1
0.272727
false
0
0.090909
0.090909
0.545455
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
1a30a95b720fecbddf3339b56bb201d9cdb0ad1d
374
py
Python
src/test_main.py
kkworden/python-pipenv-bootstrap
64f846f44240a093a2a707a8c3252b913799e177
[ "MIT" ]
null
null
null
src/test_main.py
kkworden/python-pipenv-bootstrap
64f846f44240a093a2a707a8c3252b913799e177
[ "MIT" ]
null
null
null
src/test_main.py
kkworden/python-pipenv-bootstrap
64f846f44240a093a2a707a8c3252b913799e177
[ "MIT" ]
null
null
null
from unittest import mock import unittest import pytest from .main import some_func class TestMain(unittest.TestCase): @pytest.fixture(autouse=True) def _setup_service(self): self.mock_object = mock.MagicMock() def test_some_func(self): assert some_func() == 3 # def test_mock(self): # assert self.mock_object.some_method.called
20.777778
52
0.705882
50
374
5.08
0.5
0.094488
0.110236
0
0
0
0
0
0
0
0
0.003367
0.205882
374
18
52
20.777778
0.851852
0.179144
0
0
0
0
0
0
0
0
0
0
0.1
1
0.2
false
0
0.4
0
0.7
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
1a3232723908fc855045a3607bc9137c6b489fe5
875
py
Python
ndtt/mp/mpmanager.py
HMEIatJHU/neural-datalog-through-time
725e02f4edf970e63d1c4b82d71b3720fd7938ca
[ "MIT" ]
18
2020-07-01T06:25:03.000Z
2021-10-05T23:25:21.000Z
ndtt/mp/mpmanager.py
matthewhammer/neural-datalog-through-time
2e8abd33dfabe65869df5fddc44094e64aca6ca7
[ "MIT" ]
1
2021-05-21T08:53:25.000Z
2021-05-21T08:53:25.000Z
ndtt/mp/mpmanager.py
matthewhammer/neural-datalog-through-time
2e8abd33dfabe65869df5fddc44094e64aca6ca7
[ "MIT" ]
4
2020-07-15T14:06:43.000Z
2021-01-03T13:54:44.000Z
import torch from torch import nn import torch.optim as optim import torch.multiprocessing as mp import numpy as np import time class MPManager(object): def __init__(self, num_workers): """ manage a single-instruction-multiple-data (SIMD) scheme :param int num_workers: The number of processors to run. """ mp.set_start_method('spawn') # Counting the current batch size self.num_workers = num_workers # A pool of processes self.pool = mp.Pool(processes=num_workers) def run(self, function, arguments): """ :param function : the instruction :param arguments : list of things processors loop over can be anything the function works on, e.g. model + data """ output_and_grads = self.pool.map(function, arguments) return output_and_grads
28.225806
64
0.657143
114
875
4.912281
0.561404
0.089286
0.05
0
0
0
0
0
0
0
0
0
0.270857
875
30
65
29.166667
0.877743
0.355429
0
0
0
0
0.010204
0
0
0
0
0
0
1
0.142857
false
0
0.428571
0
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
1a45326720b16c2af69d18465b3b98b47482317d
451
py
Python
aggregator/migrations/0033_auto_20190118_1735.py
dipapaspyros/bdo_platform
336de07c6ed14290c54f2154117dbf90a187e4ea
[ "MIT" ]
2
2018-02-07T10:26:28.000Z
2018-09-21T09:12:58.000Z
aggregator/migrations/0033_auto_20190118_1735.py
dipapaspyros/bdo_platform
336de07c6ed14290c54f2154117dbf90a187e4ea
[ "MIT" ]
5
2018-09-21T10:40:44.000Z
2019-04-06T10:59:57.000Z
aggregator/migrations/0033_auto_20190118_1735.py
dipapaspyros/bdo_platform
336de07c6ed14290c54f2154117dbf90a187e4ea
[ "MIT" ]
3
2019-06-09T15:42:02.000Z
2022-02-14T19:50:33.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-01-18 15:35 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('aggregator', '0032_auto_20190118_1720'), ] operations = [ # migrations.RenameField( # model_name='dataset', # old_name='spatiaNorth', # new_name='spatialNorth', # ), ]
21.47619
50
0.605322
46
451
5.695652
0.826087
0
0
0
0
0
0
0
0
0
0
0.097859
0.274945
451
20
51
22.55
0.703364
0.390244
0
0
1
0
0.123596
0.086142
0
0
0
0
0
1
0
false
0
0.25
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
1a57db3282ce89ea3a9210d6d6b1d1169726fdcf
668
py
Python
hard/python3/c0084_440_k-th-smallest-in-lexicographical-order/00_leetcode_0084.py
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
hard/python3/c0084_440_k-th-smallest-in-lexicographical-order/00_leetcode_0084.py
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
hard/python3/c0084_440_k-th-smallest-in-lexicographical-order/00_leetcode_0084.py
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
3
2018-02-09T02:46:48.000Z
2021-02-20T08:32:03.000Z
# DRUNKWATER TEMPLATE(add description and prototypes) # Question Title and Description on leetcode.com # Function Declaration and Function Prototypes on leetcode.com #440. K-th Smallest in Lexicographical Order #Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n. #Note: 1 ≤ k ≤ n ≤ 109. #Example: #Input: #n: 13 k: 2 #Output: #10 #Explanation: #The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10. #class Solution: # def findKthNumber(self, n, k): # """ # :type n: int # :type k: int # :rtype: int # """ # Time Is Money
27.833333
111
0.657186
106
668
4.169811
0.603774
0.045249
0.058824
0
0
0
0
0
0
0
0
0.062257
0.230539
668
24
112
27.833333
0.791829
0.932635
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
1a58e9cd302698322742d260b397d2fbee2e8755
1,255
py
Python
app/handlers.py
zjurelinac/Bitboard
4e17d04dff92e304e45a5416d7c2f2d927974c52
[ "MIT" ]
null
null
null
app/handlers.py
zjurelinac/Bitboard
4e17d04dff92e304e45a5416d7c2f2d927974c52
[ "MIT" ]
null
null
null
app/handlers.py
zjurelinac/Bitboard
4e17d04dff92e304e45a5416d7c2f2d927974c52
[ "MIT" ]
null
null
null
import logging import traceback import peewee from flask import request from east.exceptions import * from app import app, db print('TESTING') class DummyLogger: def log(self, *args): pass def error(self, *args): pass logger = DummyLogger() # logger = logging.getLogger(__name__) @app.errorhandler(BaseAPIException) def handle_api_errors(e): logger.error('API Exception <%s>:: %s', e.name, e.description) db.rollback() return e.make_response() @app.errorhandler(peewee.DoesNotExist) def handle_peewee_doesnotexist(e): logger.error('DoesNotExist: %s' % e) db.rollback() return DoesNotExistError(str(e)).make_response() @app.errorhandler(404) def handle_404_error(e): logger.error(str(e)) return APIRouteDoesNotExist().make_response() @app.errorhandler(405) def handle_405_error(e): logger.error(str(e)) return APIMethodNotAllowed('Requested route does not support this method [%s].' % request.method).make_response() @app.errorhandler(Exception) def handle_generic_exception(e): logger.error('Generic <%s>:: %s', e.__class__.__name__, e) logger.error(traceback.format_exc()) db.rollback() return BaseAPIException(e.__class__.__name__, str(e)).make_response()
23.679245
117
0.718725
160
1,255
5.4125
0.3375
0.048499
0.083141
0.124711
0.127021
0.062356
0.062356
0
0
0
0
0.011268
0.151394
1,255
52
118
24.134615
0.801878
0.028685
0
0.189189
0
0
0.093081
0
0
0
0
0
0
1
0.189189
false
0.054054
0.162162
0
0.513514
0.027027
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
1a67b90817fbafe39b6a3a57235954cc4307f058
1,014
py
Python
locate_cell.py
NCBI-Hackathons/Cells2Image
96fa7e4b3df63b6fecc415412693040bb59ba8d1
[ "MIT" ]
null
null
null
locate_cell.py
NCBI-Hackathons/Cells2Image
96fa7e4b3df63b6fecc415412693040bb59ba8d1
[ "MIT" ]
1
2018-03-21T15:16:40.000Z
2018-03-21T17:59:01.000Z
locate_cell.py
NCBI-Hackathons/Cells2Image
96fa7e4b3df63b6fecc415412693040bb59ba8d1
[ "MIT" ]
3
2018-03-19T16:22:42.000Z
2018-03-20T16:45:27.000Z
import matplotlib.pyplot as plt import numpy as np from scipy import ndimage import time import skimage.draw import image_data import image_processing as ip if __name__ == "__main__": movgen = image_data.all_movies() for em,movie in enumerate(movgen): framegen = image_data.all_frames(movie) for ef,frame in enumerate(framegen): #imgplot = plt.imshow(frame[1,:,:]) #imgplot.set_cmap('gray') com_out = np.zeros([frame.shape[1],frame.shape[2]]) com, labels, numlabels = ip.find_food_vacuole_centroid(frame[1,:,:]) #com_out[labels==1] = 1 rr,cc = skimage.draw.circle(com[0],com[1],10) com_out[rr,cc] = 1 patch,stuff = ip.topolar(frame[0,int(com[0])-50:int(com[0])+50,int(com[1])-50:int(com[1])+50]) #plt.imshow(com_out, alpha=0.25, cmap=plt.get_cmap('Oranges')) print ef plt.imshow(patch) plt.draw() plt.pause(0.5)
28.166667
106
0.589744
146
1,014
3.938356
0.452055
0.041739
0.041739
0.031304
0.062609
0.041739
0
0
0
0
0
0.039189
0.270217
1,014
35
107
28.971429
0.737838
0.150888
0
0
0
0
0.009335
0
0
0
0
0
0
0
null
null
0
0.333333
null
null
0.047619
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
2
1a854c8245d49247df7634f7b623ae8c8ca9bc39
1,145
py
Python
TEMP_PYTHON/lruCache.py
Tianyi6679/mincemeatpy
d0003ffb419417ba49413289ff3ec7bce17423d6
[ "MIT" ]
3
2019-11-05T00:18:33.000Z
2019-11-05T09:13:38.000Z
map-reduce with caching on HDFS/TEMP_PYTHON/lruCache.py
Tianyi6679/lightweight-MapReduce
d0003ffb419417ba49413289ff3ec7bce17423d6
[ "MIT" ]
null
null
null
map-reduce with caching on HDFS/TEMP_PYTHON/lruCache.py
Tianyi6679/lightweight-MapReduce
d0003ffb419417ba49413289ff3ec7bce17423d6
[ "MIT" ]
1
2020-02-16T04:58:46.000Z
2020-02-16T04:58:46.000Z
from functools4 import lru_cache import pickle import copy class CacheData: def __init__(self, cache=None, root=None,hit=None,full=None): self.cache = cache self.root = root self.hit = hit self.full = full # @lru_cache(maxsize=16) # def fib(n): # return n # # for x in range(16): # fib(x) # print(fib.cache_info()) # # for x in range(16): # fib(x) # print(fib.cache_info()) # # result=fib.get_cache_dictionary() # result_1=fib.get_cache_1() # result_2=fib.get_cache_2() # result_3=fib.get_cache_3() # # cacheData= CacheData(result,result_1,result_2,result_3) # # # file = open('important', 'wb') # # #dump information to that file # pickle.dump(cacheData, file) # # # close the file # file.close() # # var1=copy.deepcopy(result) # var2=copy.deepcopy(result_1) # var3=copy.deepcopy(result_2) # var4=copy.deepcopy(result_3) # # # # print(var1) # print(var2) # print(result_2) # print(result_3) # fib.set_cache_dictionary(var1,var2,result_2,result_3) # #print(var1 ) # # # result10=fib.get_cache_dictionary() # # #print(fib.cache_info()) # print(result10) #for x in range(16): # fib(x) #print(fib.cache_info())
16.357143
63
0.684716
178
1,145
4.207865
0.280899
0.040053
0.073431
0.090788
0.136182
0.136182
0.136182
0.136182
0.136182
0.136182
0
0.038974
0.148472
1,145
69
64
16.594203
0.729231
0.70393
0
0
0
0
0
0
0
0
0
0
0
1
0.111111
false
0
0.333333
0
0.555556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
1a87c649fc76316f54ba7bd2a44723ae18e4d1cd
1,254
py
Python
disarm_gears/validators/array_validators.py
disarm-platform/disarm-gears
d9f747687e632102a4ef2821b33936daacb01b6c
[ "MIT" ]
null
null
null
disarm_gears/validators/array_validators.py
disarm-platform/disarm-gears
d9f747687e632102a4ef2821b33936daacb01b6c
[ "MIT" ]
11
2019-02-28T00:18:47.000Z
2020-02-22T20:36:00.000Z
disarm_gears/validators/array_validators.py
disarm-platform/disarm-gears
d9f747687e632102a4ef2821b33936daacb01b6c
[ "MIT" ]
null
null
null
import numpy as np def validate_1d_array(x, size=None): '''Validate type and dimensions of an object x.''' assert isinstance(x, np.ndarray), 'Expecting a numpy array.' assert x.ndim == 1, 'Expecting a one-dimensional array.' if size is not None: assert x.size == size, 'Array size is different from expected.' def validate_2d_array(x, n_cols=None, n_rows=None): '''Validate type and dimensions of an object x.''' assert isinstance(x, np.ndarray), 'Expecting a numpy array.' assert x.ndim == 2, 'Expecting a two-dimensional array.' if n_rows is not None: assert x.shape[0] == n_rows, 'Array size is different from expected.' if n_cols is not None: assert x.shape[1] == n_cols, 'Number of columns is different from expected.' def validate_integer_array(x): '''Validate array elements are integers.''' assert (np.round(x) == x).all(), 'Expecting an array of integers.' def validate_positive_array(x): '''Validate array elements are positive.''' assert (x > 0).all(), 'Expecting array of positive elements.' def validate_non_negative_array(x): '''Validate array elements are non-negative.''' assert (x >= 0).all(), 'Expecting array of non-negative elements.'
31.35
84
0.678628
188
1,254
4.43617
0.271277
0.058753
0.032374
0.053957
0.605516
0.586331
0.297362
0.232614
0.232614
0.232614
0
0.007968
0.199362
1,254
39
85
32.153846
0.822709
0.165072
0
0.105263
0
0
0.339216
0
0
0
0
0
0.526316
1
0.263158
false
0
0.052632
0
0.315789
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
1
0
0
0
0
0
0
0
2
1a9a080b7593d8c6b46cbb28b3da39887e1daca7
5,973
py
Python
edera/exceptions.py
thoughteer/edera
c4ddb5d8a25906c3bd773c91afb3260fc0b704f2
[ "MIT" ]
3
2018-11-27T15:45:19.000Z
2018-12-21T20:32:10.000Z
edera/exceptions.py
thoughteer/edera
c4ddb5d8a25906c3bd773c91afb3260fc0b704f2
[ "MIT" ]
18
2018-12-02T18:38:59.000Z
2020-02-05T22:09:37.000Z
edera/exceptions.py
thoughteer/edera
c4ddb5d8a25906c3bd773c91afb3260fc0b704f2
[ "MIT" ]
null
null
null
""" This module declares all custom exception classes. """ import edera.helpers class Error(Exception): """ The base class for all exceptions within Edera. """ class ExcusableError(Error): """ The base class for all "excusable" errors. They barely deserve a warning. """ class UndefinedParameterError(Error): """ You did not pass a required parameter. """ def __init__(self, name): """ Args: name (String) - the name of the parameter """ Error.__init__(self, "parameter `%s` is undefined" % name) class UnknownParameterError(Error): """ You passed an unknown parameter. """ def __init__(self, name): """ Args: name (String) - the name of the parameter """ Error.__init__(self, "passed unknown parameter `%s`" % name) class ValueQualificationError(Error): """ You passed an invalid value the a qualifier. """ def __init__(self, value, explanation): """ Args: value (Any) - the invalid value explanation (String) - what's gone wrong """ Error.__init__(self, "value %r was not qualified: %s" % (value, explanation)) class LockAcquisitionError(ExcusableError): """ We failed to acquire a lock for a key. """ def __init__(self, key): """ Args: key (String) - the key """ ExcusableError.__init__(self, "lock for key `%s` has been already acquired" % key) class LockRetentionError(ExcusableError): """ We failed to retain a lock. """ def __init__(self, key): """ Args: key (String) - the key of the lock """ ExcusableError.__init__(self, "lock for key `%s` was lost" % key) class RequisiteConformationError(Error): """ You used an invalid object as a requisite for a task. """ def __init__(self, requisite): """ Args: requisite (Any) - the invalid object """ Error.__init__(self, "cannot conform %r" % requisite) class CircularDependencyError(Error): """ You provided a graph with a cycle. Attributes: cycle (List[Any]) - the detected cycle """ def __init__(self, cycle): """ Args: cycle (List[Any]) - the detected cycle """ message = "circular dependency detected: %s ..." % edera.helpers.render(cycle) Error.__init__(self, message) self.cycle = cycle class TargetVerificationError(Error): """ Execution of your task didn't make its target come true. Attributes: task (Task) - the broken task """ def __init__(self, task): """ Args: task (Task) - the broken task """ message = "target %r of task %r is false after execution" % (task.target, task) Error.__init__(self, message) self.task = task class InvocationError(Error): """ The base class for all invocation errors within invokers. """ class ExcusableInvocationError(ExcusableError): """ The base class for all excusable invocation errors within invokers. """ class MasterSlaveInvocationError(InvocationError): """ Some of the slave workers failed for some reason. Attributes: failed_slaves (List[Worker]) - failed slave workers """ def __init__(self, failed_slaves): """ Args: failed_slaves (List[Worker]) - failed slave workers """ message = "some of the slaves failed: %s" % edera.helpers.render(failed_slaves) InvocationError.__init__(self, message) self.failed_slaves = failed_slaves class ExcusableMasterSlaveInvocationError(ExcusableInvocationError): """ Some of the slave workers stopped for some good reason. Attributes: stopped_slaves (List[Worker]) - stopped slave workers """ def __init__(self, stopped_slaves): """ Args: stopped_slaves (List[Worker]) - stopped slave workers """ message = "some of the slaves stopped: %s" % edera.helpers.render(stopped_slaves) ExcusableInvocationError.__init__(self, message) self.stopped_slaves = stopped_slaves class WorkflowExecutionError(Error): """ There were inexcusable errors during execution. Attributes: failed_tasks (List[Task]) - failed tasks """ def __init__(self, failed_tasks): """ Args: failed_tasks (List[Task]) - failed tasks """ message = "some of the tasks failed: %s" % edera.helpers.render(failed_tasks) Error.__init__(self, message) self.failed_tasks = failed_tasks class ExcusableWorkflowExecutionError(ExcusableError): """ There were excusable (and no inexcusable) errors during execution. Attributes: stopped_tasks (List[Task]) - stopped tasks """ def __init__(self, stopped_tasks): """ Args: stopped_tasks (List[Task]) - stopped tasks """ message = "some of the tasks stopped: %s" % edera.helpers.render(stopped_tasks) ExcusableError.__init__(self, message) self.stopped_tasks = stopped_tasks class WorkflowNormalizationError(Error): """ You described a workflow that cannot be normalized. """ class WorkflowTestificationError(Error): """ You provided an invalid test/stub definition. """ class StorageOperationError(Error): """ We failed to operate your storage. """ class MonitorInconsistencyError(ExcusableError): """ A checkpoint is no longer valid. This might happen when you run multiple instances of $MonitorWatcher at the same time. But it's totally fine, should be ignored. """ class ConsumptionError(Error): """ The consumer could not accept an element. """
23.702381
90
0.612925
628
5,973
5.638535
0.264331
0.054222
0.037278
0.032194
0.380966
0.258684
0.136685
0.059305
0.059305
0.040666
0
0
0.285451
5,973
251
91
23.796813
0.829663
0.365645
0
0.12069
0
0
0.121943
0
0
0
0
0
0
1
0.206897
false
0.017241
0.017241
0
0.586207
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
1ab0013a4d518f8e51ed0c4c383fca433990afad
756
py
Python
Application/Model/GridArea.py
Thomas145/PythonWebSocketsGame
6c527ab33c43e689e125211d5abc6d579ff060a9
[ "MIT" ]
null
null
null
Application/Model/GridArea.py
Thomas145/PythonWebSocketsGame
6c527ab33c43e689e125211d5abc6d579ff060a9
[ "MIT" ]
null
null
null
Application/Model/GridArea.py
Thomas145/PythonWebSocketsGame
6c527ab33c43e689e125211d5abc6d579ff060a9
[ "MIT" ]
null
null
null
from .Styles import NoStyle class GridArea: def __init__(self, position_marker): self.style = NoStyle() self.position = position_marker def reset(self): self.style = NoStyle() def current_state(self): print(self.style.display(), end="", flush=True) def grid_area_style(self): return self.style def grid_area_position(self): return self.position def open(self): return not self.style.selected() def selected(self, player): if self.style.selected() is False: if player is not None: if player.chosen_style() is not None: self.style = player.chosen_style() return True return False
22.909091
55
0.592593
90
756
4.833333
0.355556
0.144828
0.073563
0
0
0
0
0
0
0
0
0
0.31746
756
32
56
23.625
0.843023
0
0
0.090909
0
0
0
0
0
0
0
0
0
1
0.318182
false
0
0.045455
0.136364
0.636364
0.045455
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
2
1ab21cc87223f786572255bf50a065de4031a07d
2,700
py
Python
examples/pseudo/stamps/convert.py
golly-splorts/gollyx-maps
ad57b6e0665a7f2a54f2cfa31717ce152ac3d046
[ "MIT" ]
null
null
null
examples/pseudo/stamps/convert.py
golly-splorts/gollyx-maps
ad57b6e0665a7f2a54f2cfa31717ce152ac3d046
[ "MIT" ]
null
null
null
examples/pseudo/stamps/convert.py
golly-splorts/gollyx-maps
ad57b6e0665a7f2a54f2cfa31717ce152ac3d046
[ "MIT" ]
null
null
null
import os from pprint import pprint import json def main(): patterns = { "l_pentomino": '[{"30":[30,31],"31":[30],"32":[30],"33":[30]}]', "flower_pentomino": '[{"30":[31],"31":[30,31],"32":[32],"33":[31]}]', "kite_heptomino": '[{"30":[30,31],"31":[30],"32":[30,31],"33":[32]}]', "boomerang_heptomino": '[{"30":[30],"31":[30,31],"32":[30,31],"33":[33]}]', "t_heptomino": '[{"30":[30],"31":[30,31],"32":[30],"33":[31,32]}]', "lockpick_heptomino": '[{"30":[30],"31":[30],"32":[30,31,32],"33":[32]}]', "facade_heptomino": '[{"30":[30],"31":[30,32,33],"32":[30],"33":[33]}]', "raygun_heptomino": '[{"30":[30,32,33],"31":[30,31],"33":[30]}]', "broken_l_heptomino": '[{"30":[30],"31":[30],"32":[31,32,33],"33":[30]}]', "angel_heptomino": '[{"30":[30,33],"31":[30,31],"32":[32],"33":[31]}]', "sticky_heptomino": '[{"30":[30,33],"31":[30],"32":[31,32],"33":[31]}]', "reverse_f_heptomino": '[{"30":[30],"31":[31],"32":[30,31,33],"33":[31]}]', "swandive_octomino": '[{"30":[30,33],"31":[30],"32":[30,31,32],"33":[32,33]}]', "stretchydog_octomino": '[{"30":[30,32],"31":[30,31,33],"32":[30,32],"33":[33]}]', "capacitor_octomino": '[{"30":[30],"31":[30,33],"32":[30,31,33],"33":[31,33]}]', "brass_knuckles_nonomino": '[{"30":[31,32],"31":[30,31,33],"32":[30,32],"33":[31,32]}]', "mcnasty_nonomino": '[{"30":[30,32],"31":[31],"32":[30,31,32,33],"33":[31,32]}]', "octomino_oscillator": '[{"30":[30,32],"31":[32,33],"32":[30,31],"33":[31,33]}] ', } try: os.mkdir("output") except FileExistsError: pass for pattern_name, pattern in patterns.items(): print(f"Exporting pattern {pattern_name}") s = convert(pattern) fname = pattern_name + ".txt" with open(os.path.join("output", fname), "w") as f: f.write(s) def convert(s): t = "" points = [] d = json.loads(s)[0] for y in d: for x in d[y]: points.append((x, int(y))) minx = min([p[0] for p in points]) miny = min([p[1] for p in points]) new_points = [] for x, y in points: new_points.append((x - minx, y - miny)) maxx = max([p[0] for p in new_points]) maxy = max([p[1] for p in new_points]) pattern = [] for iy in range(maxy + 1): row = [] for ix in range(maxx + 1): if (ix, iy) in new_points: row.append("o") else: row.append(".") pattern.append(row) for row in pattern: t += "".join(row) t += "\n" return t if __name__ == "__main__": main()
33.75
96
0.475556
397
2,700
3.141058
0.216625
0.0834
0.10425
0.084202
0.334403
0.246191
0.136327
0.091419
0.028869
0
0
0.186124
0.225926
2,700
79
97
34.177215
0.410526
0
0
0
0
0.238095
0.472222
0.345926
0
0
0
0
0
1
0.031746
false
0.015873
0.047619
0
0.095238
0.031746
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
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
46c24f9e543823c6b0cda1b66bf196b243046c21
3,717
py
Python
tests/test_model.py
RandalJBarnes/OnekaPy
ba082f76f3f7f4394a11864623981cc876e1b253
[ "MIT" ]
null
null
null
tests/test_model.py
RandalJBarnes/OnekaPy
ba082f76f3f7f4394a11864623981cc876e1b253
[ "MIT" ]
null
null
null
tests/test_model.py
RandalJBarnes/OnekaPy
ba082f76f3f7f4394a11864623981cc876e1b253
[ "MIT" ]
null
null
null
""" Test the Model class. Notes ----- o The specific test values were computed using the MatLab code from the "Object Based Analytic Elements" project. Author ------ Dr. Randal J. Barnes Department of Civil, Environmental, and Geo- Engineering University of Minnesota Version ------- 09 May 2020 """ import numpy as np import pytest from oneka.model import Model @pytest.fixture def my_model(): base = 500.0 conductivity = 1.0 porosity = 0.25 thickness = 100.0 xo, yo = (0.0, 0.0) coef = np.array([1.0, 1.0, 1.0, 1.0, 1.0, 500.0]) wells = [ (100.0, 200.0, 1.0, 1000.0), (200.0, 100.0, 1.0, 1000.0) ] mo = Model(base, conductivity, porosity, thickness, wells, xo, yo, coef) return mo def test_model_compute_potential(my_model): x, y = [100.0, 100.0] Phi = my_model.compute_potential(x, y) assert np.isclose(Phi, 32165.8711977589, rtol=1.0e-6) def test_model_compute_head(my_model): x, y = [100.0, 100.0] head = my_model.compute_head(x, y) assert np.isclose(head, 371.658711977589, rtol=1.0e-6) def test_model_compute_discharge(my_model): x, y = [120.0, 160.0] Qx, Qy = my_model.compute_discharge(x, y) Qx_true, Qy_true = [-401.318309886184, -438.771830796713] assert np.isclose(Qx, Qx_true, rtol=1.0e-6) assert np.isclose(Qy, Qy_true, rtol=1.0e-6) def test_model_compute_velocity(my_model): x, y = [100.0, 100.0] Vx, Vy = my_model.compute_velocity(x, y) Vx_true, Vy_true = [-11.976338022763, -11.976338022763] assert np.isclose(Vx, Vx_true, rtol=1.0e-6) assert np.isclose(Vy, Vy_true, rtol=1.0e-6) x, y = [120.0, 160.0] Vx, Vy = my_model.compute_velocity(x, y) Vx_true, Vy_true = [-16.052732395447, -17.550873231869] assert np.isclose(Vx, Vx_true, rtol=1.0e-6) assert np.isclose(Vy, Vy_true, rtol=1.0e-6) def test_model_compute_fit(my_model): ev_true = np.array([[0.9916], [0.9956], [0.9422], [171.85], [165.8], [9667.8]]) x_true, y_true = [58.52, 52.76] cov_true = np.array([ [3.195e-05, -2.031e-06, -2.437e-06, 2.176e-04, -3.117e-05, -1.340e-02], [-2.031e-06, 1.917e-05, -3.666e-06, 1.282e-04, 1.297e-04, -1.121e-02], [-2.437e-06, -3.666e-06, 1.294e-05, -2.745e-05, 5.914e-05, 3.349e-03], [2.176e-04, 1.282e-04, -2.745e-05, 1.083e-02, 6.399e-04, -1.719e-01], [-3.117e-05, 1.297e-04, 5.914e-05, 6.399e-04, 7.370e-03, -6.047e-02], [-1.340e-02, -1.121e-02, 3.349e-03, -1.719e-01, -6.047e-02, 1.715e+01]]) obs = list([ [23.00, 11.00, 573.64, 0.10], [24.00, 85.00, 668.55, 0.10], [26.00, 80.00, 661.58, 0.10], [28.00, 65.00, 637.97, 0.10], [37.00, 50.00, 626.62, 0.10], [41.00, 21.00, 598.85, 0.10], [42.00, 53.00, 637.51, 0.10], [42.00, 74.00, 673.32, 0.10], [45.00, 70.00, 670.52, 0.10], [46.00, 15.00, 599.43, 0.10], [52.00, 76.00, 694.14, 0.10], [58.00, 90.00, 736.75, 0.10], [64.00, 22.00, 629.54, 0.10], [71.00, 19.00, 637.34, 0.10], [72.00, 36.00, 660.54, 0.10], [72.00, 55.00, 691.45, 0.10], [74.00, 50.00, 686.57, 0.10], [75.00, 18.00, 642.92, 0.10], [76.00, 43.00, 678.80, 0.10], [77.00, 79.00, 752.05, 0.10], [79.00, 66.00, 727.81, 0.10], [81.00, 81.00, 766.23, 0.10], [82.00, 77.00, 759.15, 0.10], [86.00, 26.00, 673.24, 0.10], [90.00, 57.00, 734.72, 0.10]]) coef_ev, coef_cov = my_model.fit_regional_flow(obs, x_true, y_true) assert np.allclose(coef_ev, ev_true, rtol=0.001) assert np.allclose(coef_cov, cov_true, rtol=0.001)
30.719008
83
0.571429
699
3,717
2.955651
0.309013
0.036302
0.058083
0.030978
0.225557
0.201355
0.192159
0.192159
0.123911
0.09971
0
0.318373
0.232715
3,717
120
84
30.975
0.406031
0.085015
0
0.135802
0
0
0
0
0
0
0
0
0.123457
1
0.074074
false
0
0.037037
0
0.123457
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
46c7b45fdc6d0c9df561c0e5dd726412c25bc59b
1,329
py
Python
tpdata/templeplus/lib/templeplus/pymod.py
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
null
null
null
tpdata/templeplus/lib/templeplus/pymod.py
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
null
null
null
tpdata/templeplus/lib/templeplus/pymod.py
edoipi/TemplePlus
f0e552289822fea908f16daa379fa568b1bd286d
[ "MIT" ]
null
null
null
import tpdp class PythonModifier(tpdp.ModifierSpec): def AddHook(self, eventType, eventKey, callbackFcn, argsTuple ): self.add_hook(eventType, eventKey, callbackFcn, argsTuple) def ExtendExisting(self, condName): self.extend_existing(condName) def AddItemForceRemoveHandler(self): # in charge of backing up condition args self.add_item_force_remove_callback() def MapToFeat(self, feat_enum, feat_list_max = -1, feat_cond_arg2 = 0): self.add_to_feat_dict(feat_enum, feat_list_max, feat_cond_arg2) # Spell related standard hooks def AddSpellCountdownStandardHook(self): # adds an ET_OnBeginRound handler that (normally) does: # If countdown expired: (<0) # 1. Float text "Spell Expired" # 2. RemoveSpell() (has case-by-case handlers for Spell_End; Temple+ adds generic handling for wall spells here) # 3. RemoveSpellMod() # Else: # Decrement count, update spell packet duration self.add_spell_countdown_standard() def AddAoESpellEndStandardHook(self): # adds a EK_S_Spell_End handler that: # 1. Ends particles for all spell objects # 2. RemoveSpellMod() self.add_aoe_spell_ender() def AddSpellDismissStandardHook(self): self.add_spell_dismiss_hook()
47.464286
122
0.696012
159
1,329
5.610063
0.584906
0.047085
0.06278
0.08296
0.042601
0
0
0
0
0
0
0.009728
0.226486
1,329
28
123
47.464286
0.857977
0.349887
0
0
0
0
0
0
0
0
0
0
0
1
0.4375
false
0
0.0625
0
0.5625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
46df810892583016f332b3bb6b66329f389547e7
189
py
Python
engine/tests/scenes/test_scenes.py
LloydTao/ecm3423-fur-effect
fefa73665b459dfd1648dca97a95e8313cf53dd5
[ "MIT" ]
null
null
null
engine/tests/scenes/test_scenes.py
LloydTao/ecm3423-fur-effect
fefa73665b459dfd1648dca97a95e8313cf53dd5
[ "MIT" ]
null
null
null
engine/tests/scenes/test_scenes.py
LloydTao/ecm3423-fur-effect
fefa73665b459dfd1648dca97a95e8313cf53dd5
[ "MIT" ]
null
null
null
import unittest from ...scenes import Scene class TestSceneMethods(unittest.TestCase): def test_scene(self): scene = Scene() if __name__ == "__main__": unittest.main()
14.538462
42
0.68254
21
189
5.714286
0.666667
0
0
0
0
0
0
0
0
0
0
0
0.206349
189
12
43
15.75
0.8
0
0
0
0
0
0.042328
0
0
0
0
0
0
1
0.142857
false
0
0.285714
0
0.571429
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
201e557f74f0335327de9be24c57129ec7d8f08b
915
py
Python
gabbi/exception.py
scottwallacesh/gabbi
5e76332ac06cd075c11477b384ad5da1d2eaa9d5
[ "Apache-2.0" ]
145
2015-01-16T23:19:35.000Z
2022-03-15T00:21:54.000Z
gabbi/exception.py
scottwallacesh/gabbi
5e76332ac06cd075c11477b384ad5da1d2eaa9d5
[ "Apache-2.0" ]
250
2015-01-02T11:20:06.000Z
2022-03-22T19:55:18.000Z
gabbi/exception.py
scottwallacesh/gabbi
5e76332ac06cd075c11477b384ad5da1d2eaa9d5
[ "Apache-2.0" ]
49
2015-01-14T16:14:52.000Z
2022-03-21T11:37:26.000Z
# # 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. """Gabbi specific exceptions.""" class GabbiDataLoadError(ValueError): """An exception to alert when data streams cannot be loaded.""" pass class GabbiFormatError(ValueError): """An exception to encapsulate poorly formed test data.""" pass class GabbiSyntaxWarning(SyntaxWarning): """A warning about syntax that is not desirable.""" pass
31.551724
75
0.742077
127
915
5.346457
0.669291
0.088365
0.038292
0.047128
0
0
0
0
0
0
0
0.005319
0.178142
915
28
76
32.678571
0.897606
0.772678
0
0.5
0
0
0
0
0
0
0
0
0
1
0
true
0.5
0
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
1
0
0
0
0
0
2
2024077dd459a76b5147e2c0b8b573e999001432
2,305
py
Python
challenge 10/Calculator.py
caroldf07/100daysofcode-python
508ad5464904193b0bd58fc73d26b21d8adc011a
[ "Apache-2.0" ]
1
2021-11-02T22:24:13.000Z
2021-11-02T22:24:13.000Z
challenge 10/Calculator.py
caroldf07/100challengesofcode-python
508ad5464904193b0bd58fc73d26b21d8adc011a
[ "Apache-2.0" ]
null
null
null
challenge 10/Calculator.py
caroldf07/100challengesofcode-python
508ad5464904193b0bd58fc73d26b21d8adc011a
[ "Apache-2.0" ]
1
2021-10-15T23:46:34.000Z
2021-10-15T23:46:34.000Z
logo = """ _____________________ | _________________ | | | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------. | |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. | | ___ ___ ___ ___ | | | ______ | || | __ | || | _____ | || | ______ | | | | 7 | 8 | 9 | | + | | | | .' ___ | | || | / \ | || | |_ _| | || | .' ___ | | | | |___|___|___| |___| | | | / .' \_| | || | / /\ \ | || | | | | || | / .' \_| | | | | 4 | 5 | 6 | | - | | | | | | | || | / ____ \ | || | | | _ | || | | | | | | |___|___|___| |___| | | | \ `.___.'\ | || | _/ / \ \_ | || | _| |__/ | | || | \ `.___.'\ | | | | 1 | 2 | 3 | | x | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | | | |___|___|___| |___| | | | | || | | || | | || | | | | | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' | | |___|___|___| |___| | '----------------' '----------------' '----------------' '----------------' |_____________________| """ print(logo) def add(x, y): return x+y def subtract(x, y): return x-y def division(x, y): if(y == 0): print("It can't divide per 0'") else: return x/y def multiply(x, y): return x*y operators = { "+": add, "-": subtract, "/": division, "*": multiply } def calculator(): x = float(input("Please enter a number: ")) keep_going = "y" while(keep_going == "y"): operator_chosen = input("Please enter the desired operation: ") y = float(input("Please enter a number: ")) calculation = operators[operator_chosen] answer = calculation(x, y) print(f"{x} {operator_chosen} {y} = {answer}") keep_going = input( f"Type 'y' to continue calculating with {answer} or type 'n' to exit: ").lower() if(keep_going == "y"): x = answer """Here we have a recursion when the user does not want to use the same answer before and it want to start a new iteration""" else: calculator() calculator()
33.897059
137
0.358351
157
2,305
3.898089
0.458599
0.029412
0.052288
0.044118
0.150327
0.133987
0
0
0
0
0
0.008497
0.336226
2,305
67
138
34.402985
0.391503
0
0
0.08
0
0.16
0.661468
0.020183
0
0
0
0
0
1
0.1
false
0
0
0.06
0.18
0.06
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
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
202fea4fea9302a54ade62e00c206ce92370b06d
401
py
Python
tests/heuristics/test_dataset_id_heuristic.py
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
2
2022-01-29T03:46:31.000Z
2022-02-14T14:06:35.000Z
tests/heuristics/test_dataset_id_heuristic.py
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
null
null
null
tests/heuristics/test_dataset_id_heuristic.py
HPI-Information-Systems/TimeEval
9b2717b89decd57dd09e04ad94c120f13132d7b8
[ "MIT" ]
null
null
null
import unittest import tests.fixtures.heuristics_fixtures as fixtures from timeeval.heuristics import DatasetIdHeuristic class TestDatasetIdHeuristic(unittest.TestCase): def test_heuristic(self): heuristic = DatasetIdHeuristic() value = heuristic(fixtures.algorithm, fixtures.dataset, fixtures.real_test_dataset_path) self.assertEqual(value, fixtures.dataset.datasetId)
33.416667
96
0.795511
41
401
7.658537
0.560976
0.095541
0
0
0
0
0
0
0
0
0
0
0.137157
401
11
97
36.454545
0.907514
0
0
0
0
0
0
0
0
0
0
0
0.125
1
0.125
false
0
0.375
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
204f616867cf52fd8d4b52f2ac16b848490278a9
902
py
Python
LeetCode/Array and Strings/20. Valid Parentheses/solution.py
Ceruleanacg/Crack-Interview
994dc0eee2f576fc543c90b82398dc8d957cdf09
[ "MIT" ]
17
2018-09-04T15:51:30.000Z
2021-06-04T08:47:07.000Z
LeetCode/Array and Strings/20. Valid Parentheses/solution.py
Ceruleanacg/Crack-Interview
994dc0eee2f576fc543c90b82398dc8d957cdf09
[ "MIT" ]
null
null
null
LeetCode/Array and Strings/20. Valid Parentheses/solution.py
Ceruleanacg/Crack-Interview
994dc0eee2f576fc543c90b82398dc8d957cdf09
[ "MIT" ]
6
2018-11-03T09:36:25.000Z
2020-05-27T17:51:08.000Z
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if not s: return True stack = [] for char in s: if char == '{' or char == '[' or char == '(': stack.append(char) else: try: c = stack.pop() if char == '}': if c != '{': return False elif char == ']': if c != '[': return False elif char == ')': if c != '(': return False except IndexError: return False if len(stack) > 0: return False else: return True print(Solution().isValid('()'))
23.736842
57
0.301552
69
902
3.942029
0.449275
0.202206
0.077206
0.143382
0.227941
0.227941
0.227941
0.227941
0.227941
0.227941
0
0.002703
0.5898
902
38
58
23.736842
0.732432
0.027716
0
0.333333
0
0
0.013002
0
0
0
0
0
0
1
0.037037
false
0
0
0
0.333333
0.037037
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
2055fa63f57d0f09cffaf4a00ba26911a5d36c1b
977
py
Python
plantcv/plantcv/hist_equalization.py
Howzit123/plantcv
b4ff6ad765da36353f40827ce3816b33d1d3596a
[ "MIT" ]
2
2021-08-20T14:56:48.000Z
2021-08-24T23:12:56.000Z
plantcv/plantcv/hist_equalization.py
Howzit123/plantcv
b4ff6ad765da36353f40827ce3816b33d1d3596a
[ "MIT" ]
null
null
null
plantcv/plantcv/hist_equalization.py
Howzit123/plantcv
b4ff6ad765da36353f40827ce3816b33d1d3596a
[ "MIT" ]
1
2020-02-27T21:22:13.000Z
2020-02-27T21:22:13.000Z
# Histogram equalization import cv2 import numpy as np import os from plantcv.plantcv import print_image from plantcv.plantcv import plot_image from plantcv.plantcv import fatal_error from plantcv.plantcv import params def hist_equalization(gray_img): """Histogram equalization is a method to normalize the distribution of intensity values. If the image has low contrast it will make it easier to threshold. Inputs: gray_img = Grayscale image data Returns: img_eh = normalized image :param gray_img: numpy.ndarray :return img_eh: numpy.ndarray """ if len(np.shape(gray_img)) == 3: fatal_error("Input image must be gray") img_eh = cv2.equalizeHist(gray_img) params.device += 1 if params.debug == 'print': print_image(img_eh, os.path.join(params.debug_outdir, str(params.device) + '_hist_equal_img.png')) elif params.debug == 'plot': plot_image(img_eh, cmap='gray') return img_eh
26.405405
113
0.711361
141
977
4.77305
0.468085
0.062407
0.106984
0.142645
0.086181
0
0
0
0
0
0
0.005168
0.207779
977
36
114
27.138889
0.864341
0.328557
0
0
0
0
0.090762
0
0
0
0
0
0
1
0.058824
false
0
0.411765
0
0.529412
0.176471
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
205949db776405b8c267e6e455da30481aae2d57
916
py
Python
crowdsourcing/permissions/user.py
Kyeongan/crowdsource-platform
af34363158ff30ebfdade4a543648bf26a3c9698
[ "MIT" ]
138
2015-04-17T20:07:12.000Z
2017-05-03T17:58:47.000Z
crowdsourcing/permissions/user.py
cescgie/crowdi
c16ab625f27915919e21f7eec93c45af551d9022
[ "MIT" ]
657
2015-04-19T04:54:51.000Z
2017-06-26T18:07:42.000Z
crowdsourcing/permissions/user.py
cescgie/crowdi
c16ab625f27915919e21f7eec93c45af551d9022
[ "MIT" ]
311
2015-04-16T19:20:55.000Z
2017-06-13T05:32:01.000Z
from rest_framework import permissions from csp import settings from rest_framework.exceptions import PermissionDenied class IsWorker(permissions.BasePermission): def has_permission(self, request, view): return request.user.profile.is_worker class IsRequester(permissions.BasePermission): def has_object_permission(self, request, view, object): return request.user.profile.is_requester class CanCreateAccount(permissions.BasePermission): def has_permission(self, request, view): if view.action == 'create' and not (request.user.is_staff or settings.REGISTRATION_ALLOWED): raise PermissionDenied(detail='We are currently in closed beta. ' 'If you\'d like an account, email support@daemo.org ' 'with a short description of what you\'d like to use Daemo for.') return True
39.826087
107
0.689956
107
916
5.813084
0.588785
0.120579
0.135048
0.149518
0.263666
0.180064
0.180064
0.180064
0
0
0
0
0.240175
916
22
108
41.636364
0.893678
0
0
0.125
0
0
0.090611
0
0
0
0
0
0
1
0.1875
false
0
0.1875
0.125
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
646a09bba433e9134052e21102c6b81a5cd88eb1
341
py
Python
src/video_store/urls.py
staab/video-store
9badfae8316ab1d33fa20fe6a17cd90ef2737f8c
[ "MIT" ]
null
null
null
src/video_store/urls.py
staab/video-store
9badfae8316ab1d33fa20fe6a17cd90ef2737f8c
[ "MIT" ]
null
null
null
src/video_store/urls.py
staab/video-store
9badfae8316ab1d33fa20fe6a17cd90ef2737f8c
[ "MIT" ]
null
null
null
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import RedirectView import store_api.urls import store_ui.urls urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include(store_api.urls.urlpatterns)), url(r'^.*$', include(store_ui.urls.urlpatterns)) ]
24.357143
55
0.73607
49
341
5.040816
0.367347
0.121457
0.097166
0.178138
0
0
0
0
0
0
0
0
0.123167
341
13
56
26.230769
0.826087
0
0
0
0
0
0.046921
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
646a4518e28de7da32a6e93047fe7e1de9aa14ed
776
py
Python
pp/samples/13_component_yaml.py
smartalecH/gdsfactory
66dfbf740704f1a6155f4812a1d9483ccf5c116c
[ "MIT" ]
16
2020-02-03T07:05:31.000Z
2021-12-29T18:40:09.000Z
pp/samples/13_component_yaml.py
smartalecH/gdsfactory
66dfbf740704f1a6155f4812a1d9483ccf5c116c
[ "MIT" ]
2
2020-01-31T20:01:40.000Z
2020-09-26T17:50:55.000Z
pp/samples/13_component_yaml.py
smartalecH/gdsfactory
66dfbf740704f1a6155f4812a1d9483ccf5c116c
[ "MIT" ]
7
2020-02-09T23:16:18.000Z
2020-10-30T03:12:04.000Z
import pp def test_mzi(): netlist = """ instances: CP1: component: mmi1x2 settings: width_mmi: 4.5 length_mmi: 10 CP2: component: mmi1x2 settings: width_mmi: 4.5 length_mmi: 5 arm_top: component: mzi_arm arm_bot: component: mzi_arm placements: arm_bot: mirror: [0,0,0,10] ports: W0: CP1,W0 E0: CP2,W0 connections: arm_bot,W0: CP1,E0 arm_top,W0: CP1,E1 CP2,E0: arm_bot,E0 CP2,E1: arm_top,E0 """ return pp.component_from_yaml(netlist) if __name__ == "__main__": c = test_mzi() pp.show(c) pp.plotgds(c)
17.636364
42
0.476804
93
776
3.709677
0.408602
0.069565
0.133333
0.162319
0.243478
0.243478
0.243478
0.243478
0.243478
0
0
0.081818
0.43299
776
43
43
18.046512
0.702273
0
0
0.285714
0
0
0.784794
0
0
0
0
0
0
1
0.028571
false
0
0.028571
0
0.085714
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
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
646b09594cd86b4fbaef8fd2c64ad439c0f79bf3
5,159
py
Python
simulated_data.py
aamcbee/AdaOja
11d2525a2123395ba8f8d6c1da3ffc1032356766
[ "BSD-3-Clause" ]
9
2019-05-30T16:50:28.000Z
2021-06-21T14:44:29.000Z
simulated_data.py
aamcbee/AdaOja
11d2525a2123395ba8f8d6c1da3ffc1032356766
[ "BSD-3-Clause" ]
null
null
null
simulated_data.py
aamcbee/AdaOja
11d2525a2123395ba8f8d6c1da3ffc1032356766
[ "BSD-3-Clause" ]
1
2019-07-16T15:05:54.000Z
2019-07-16T15:05:54.000Z
import numpy as np import scipy.linalg as la from scipy.stats import multinomial def random_multivar_normal(n, d, k, sigma=.1): ''' Generate random samples from a random multivariate normal distribution with covariance A A^T + sigma^2 I. Input: n: int, number of samples d: int, dimension of samples k: int, number of samples approximated sigma: optional float > 0, default .1, the standard deviation of the sample noise. Output: cov: d x d array, the covariance matrix for the distibution A0: d x d array, the eigenvectors we want to estimate (note the eigenvectors are columns of the array, in descending order) X: n x d array of n d-dimensional samples. ''' A0 = la.qr(np.random.rand(d, k), mode='economic')[0] cov = A0 @ A0.T + sigma**2 * np.eye(d) X = np.random.multivariate_normal(np.zeros(d), cov, size=n) return cov, A0, X def spiked_covariance(n, d, k, sigma=.1): ''' Generate random samples from a random multivariate normal distribution with covariance A D A^T + sigma^2 I. Here A is a set of k orthogonal vectors and D is a diagonal matrix with random, uniform entries, sorted and scaled so that the first entry = 1. Input: n: int, number of samples d: int, dimension of samples k: int, number of samples approximated sigma: optional float > 0, default .1, the standard deviation of the sample noise. Output: cov: d x d array, the true covariance matrix for the distibution w: d vector of the diagonal values from matrix D. A0: d x k array, the eigenvectors we want to estimate (note the eigenvectors are columns of the array, in descending order) X: n x d array of n d-dimensional samples. ''' A0 = la.qr(np.random.rand(d, k), mode='economic')[0] w = np.sort(np.random.rand(k, 1), axis=0)[::-1] w /= w.max() cov = A0 @ (w**2 * A0.T) + sigma**2 * np.eye(d) X = np.random.multivariate_normal(np.zeros(d), cov, size=n) return cov, w, A0, X def random_multinomial(n, d, trials=100, mean0 = True, scale=1): ''' Generate random samples from a random multinomial distribution with p_i ~ U(0,1). Input: n: int, number of samples d: int, dimension of samples trials: optional int, the number of trials for each sample from the multinomial distribution default is 100. mean0: optional boolean, default True. Indicates whether to normalize the samples so they are mean 0. Output: cov: d x d array, the true covariance matrix for the distribution e: d-dimensional array, the eigenvalues of the covariance matrix v: d x d array, the eigenvectors of the covariance matrix X: n x d array of n d-dimensional samples from the random_dirichlet distribution with covariance cov. ''' # Initialize p values p = np.random.rand(d) p /= p.sum() # Calculate the covariance matrix for the multinomial distribution # For large d > 10000, use multinomial.cov(d,p) if d >= 10000: cov = multinomial.cov(trials, p) else: cov = -np.outer(p, p) * trials cov[np.diag_indices(d)] = trials * p * (1-p) cov *= scale**2 # Obtain the eigenvectors of the covariance matrix. e, v = la.eigh(cov) e = e[::-1] v = v[:,::-1] # Obtain a sample from the multinomial distribution of size n X = np.random.multinomial(trials, p, n).astype(float) if mean0: # Let X have mean 0 X -= trials * p X *= scale return cov, e, v, X def random_dirichlet(n, d, mean0=True, scale=1): ''' Generate random samples from a random dirichlet distribution with a_i ~ U(0,1). Input: n: int, number of samples d: int, dimension of samples mean0: optional boolean, default True. Indicates whether to normalize the samples so they are mean 0. Output: cov: d x d array, the true covariance matrix for the distribution e: d-dimensional array, the eigenvalues of the covariance matrix v: d x d array, the eigenvectors of the covariance matrix (note the eigenvectors are columns of the array, in descending order) X: n x d array of n d-dimensional samples from the random_dirichlet distribution with covariance cov. ''' # Initialize a random set of parameters a drawn from the # uniform distribution. a = np.random.rand(d) a0 = a.sum() a_denom = a0**2 * (a0 + 1) # Obtain the covariance matrix for the dirichlet distribution. # Note that scipy doesn't currently have a builtin method for this # (I may add one myself) cov = -np.outer(a, a) / a_denom # i neq j case cov[np.diag_indices(d)] = a * (a0 - a) / a_denom # i = j case cov *= scale**2 # Obtain the eigenvectors of the covariance matrix. e, v = la.eigh(cov) e = e[::-1] v = v[:,::-1] X = np.random.dirichlet(a, n) if mean0: X -= a / a0 X *= scale return cov, e, v, X
35.826389
85
0.629773
797
5,159
4.056462
0.179423
0.018559
0.023817
0.017321
0.701516
0.634086
0.633158
0.622023
0.622023
0.622023
0
0.019412
0.281062
5,159
143
86
36.076923
0.852251
0.634231
0
0.382979
1
0
0.009969
0
0
0
0
0
0
1
0.085106
false
0
0.06383
0
0.234043
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6471f48da26ddba2df69a8c07fa52ed1ac917387
1,499
py
Python
sdk/python/pulumi_aws_native/redshift/_enums.py
AaronFriel/pulumi-aws-native
5621690373ac44accdbd20b11bae3be1baf022d1
[ "Apache-2.0" ]
29
2021-09-30T19:32:07.000Z
2022-03-22T21:06:08.000Z
sdk/python/pulumi_aws_native/redshift/_enums.py
AaronFriel/pulumi-aws-native
5621690373ac44accdbd20b11bae3be1baf022d1
[ "Apache-2.0" ]
232
2021-09-30T19:26:26.000Z
2022-03-31T23:22:06.000Z
sdk/python/pulumi_aws_native/redshift/_enums.py
AaronFriel/pulumi-aws-native
5621690373ac44accdbd20b11bae3be1baf022d1
[ "Apache-2.0" ]
4
2021-11-10T19:42:01.000Z
2022-02-05T10:15:49.000Z
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** from enum import Enum __all__ = [ 'EventSubscriptionEventCategoriesItem', 'EventSubscriptionSeverity', 'EventSubscriptionSourceType', 'EventSubscriptionStatus', 'ScheduledActionState', ] class EventSubscriptionEventCategoriesItem(str, Enum): CONFIGURATION = "configuration" MANAGEMENT = "management" MONITORING = "monitoring" SECURITY = "security" PENDING = "pending" class EventSubscriptionSeverity(str, Enum): """ Specifies the Amazon Redshift event severity to be published by the event notification subscription. """ ERROR = "ERROR" INFO = "INFO" class EventSubscriptionSourceType(str, Enum): """ The type of source that will be generating the events. """ CLUSTER = "cluster" CLUSTER_PARAMETER_GROUP = "cluster-parameter-group" CLUSTER_SECURITY_GROUP = "cluster-security-group" CLUSTER_SNAPSHOT = "cluster-snapshot" SCHEDULED_ACTION = "scheduled-action" class EventSubscriptionStatus(str, Enum): """ The status of the Amazon Redshift event notification subscription. """ ACTIVE = "active" NO_PERMISSION = "no-permission" TOPIC_NOT_EXIST = "topic-not-exist" class ScheduledActionState(str, Enum): """ The state of the scheduled action. """ ACTIVE = "ACTIVE" DISABLED = "DISABLED"
25.844828
104
0.697799
149
1,499
6.932886
0.496644
0.033882
0.029042
0.042594
0.050339
0
0
0
0
0
0
0.000838
0.204136
1,499
57
105
26.298246
0.865046
0.280187
0
0
1
0
0.314961
0.153543
0
0
0
0
0
1
0
false
0
0.033333
0
0.766667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
647401346cf10238d3f0044de0b2d66f7bc135f8
203
py
Python
python/ex034.py
deniseicorrea/Aulas-de-Python
c5bcafa34f03ea4b9c73805b58c8004bb13f70e5
[ "MIT" ]
null
null
null
python/ex034.py
deniseicorrea/Aulas-de-Python
c5bcafa34f03ea4b9c73805b58c8004bb13f70e5
[ "MIT" ]
null
null
null
python/ex034.py
deniseicorrea/Aulas-de-Python
c5bcafa34f03ea4b9c73805b58c8004bb13f70e5
[ "MIT" ]
null
null
null
salario = float(input('Qual o seu salário? R$ ')) if salario <= 1250: novo = salario + (salario * 15 / 100) else: novo = salario + (salario * 10 / 100) print(f'Seu novo salário é R${novo :.2f}.')
33.833333
49
0.610837
31
203
4
0.612903
0.177419
0.290323
0
0
0
0
0
0
0
0
0.09434
0.216749
203
6
50
33.833333
0.685535
0
0
0
0
0
0.27451
0
0
0
0
0
0
1
0
false
0
0
0
0
0.166667
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
64799d5c6f6b719d0987aca3b83297c592058a73
58
py
Python
python/testData/intentions/quotedStringDoubleSlash_after.py
jnthn/intellij-community
8fa7c8a3ace62400c838e0d5926a7be106aa8557
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
python/testData/intentions/quotedStringDoubleSlash_after.py
Cyril-lamirand/intellij-community
60ab6c61b82fc761dd68363eca7d9d69663cfa39
[ "Apache-2.0" ]
173
2018-07-05T13:59:39.000Z
2018-08-09T01:12:03.000Z
python/testData/intentions/quotedStringDoubleSlash_after.py
Cyril-lamirand/intellij-community
60ab6c61b82fc761dd68363eca7d9d69663cfa39
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
data_path = dirname(realpath(__file__)).replace("\\", '/')
58
58
0.672414
6
58
5.666667
1
0
0
0
0
0
0
0
0
0
0
0
0.051724
58
1
58
58
0.618182
0
0
0
0
0
0.050847
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
647ae795ccb2eae73a4642206f65fa6ba9dc4abe
375
py
Python
wallarm_api/core/api/triggers_api.py
Neraverin/wallarm-api-python
a033cfee28b1648f6bb7d1e531f353929b5d41c1
[ "Apache-2.0" ]
null
null
null
wallarm_api/core/api/triggers_api.py
Neraverin/wallarm-api-python
a033cfee28b1648f6bb7d1e531f353929b5d41c1
[ "Apache-2.0" ]
null
null
null
wallarm_api/core/api/triggers_api.py
Neraverin/wallarm-api-python
a033cfee28b1648f6bb7d1e531f353929b5d41c1
[ "Apache-2.0" ]
null
null
null
from wallarm_api.core.api.base_api import BaseApi from wallarm_api.core.models.trigger import Triggers class TriggersApi(BaseApi): def get_triggers(self, clientid): url = f'/v2/clients/{clientid}/triggers?denormalize=true' response = self.client.get(url) triggers = Triggers(triggers=response['triggers']) return triggers
37.5
69
0.696
45
375
5.711111
0.555556
0.085603
0.108949
0.140078
0
0
0
0
0
0
0
0.003356
0.205333
375
9
70
41.666667
0.85906
0
0
0
0
0
0.149333
0.128
0
0
0
0
0
1
0.125
false
0
0.25
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
64875676b96c2647ed1948f84397285ec47bff0c
4,289
py
Python
venv/lib/python3.6/site-packages/ansible/modules/set_fact.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
1
2020-01-22T13:11:23.000Z
2020-01-22T13:11:23.000Z
venv/lib/python3.6/site-packages/ansible/modules/set_fact.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
12
2020-02-21T07:24:52.000Z
2020-04-14T09:54:32.000Z
venv/lib/python3.6/site-packages/ansible/modules/set_fact.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2013, Dag Wieers (@dagwieers) <dag@wieers.com> # 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 = r''' --- module: set_fact short_description: Set host variable(s) and fact(s). version_added: "1.2" description: - This action allows setting variables associated to the current host. - These variables will be available to subsequent plays during an ansible-playbook run via the host they were set on. - Set C(cacheable) to C(yes) to save variables across executions using a fact cache. Variables will keep the set_fact precedence for the current run, but will used 'cached fact' precedence for subsequent ones. - Per the standard Ansible variable precedence rules, other types of variables have a higher priority, so this value may be overridden. options: key_value: description: - "The C(set_fact) module takes C(key=value) pairs or C(key: value) (YAML notation) as variables to set in the playbook scope. The 'key' is the resulting variable name and the value is, of course, the value of said variable." - You can create multiple variables at once, by supplying multiple pairs, but do NOT mix notations. required: true cacheable: description: - This boolean converts the variable into an actual 'fact' which will also be added to the fact cache, if fact caching is enabled. - Normally this module creates 'host level variables' and has much higher precedence, this option changes the nature and precedence (by 7 steps) of the variable created. U(https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable) - "This actually creates 2 copies of the variable, a normal 'set_fact' host variable with high precedence and a lower 'ansible_fact' one that is available for persistance via the facts cache plugin. This creates a possibly confusing interaction with C(meta: clear_facts) as it will remove the 'ansible_fact' but not the host variable." type: bool default: no version_added: "2.4" notes: - Because of the nature of tasks, set_fact will produce 'static' values for a variable. Unlike normal 'lazy' variables, the value gets evaluated and templated on assignment. - Some boolean values (yes, no, true, false) will always be converted to boolean type, unless C(DEFAULT_JINJA2_NATIVE) is enabled. This is done so the C(var=value) booleans, otherwise it would only be able to create strings, but it also prevents using those values to create YAML strings. Using the setting will restrict k=v to strings, but will allow you to specify string or boolean in YAML. - "To create lists/arrays or dictionary/hashes use YAML notation C(var: [val1, val2])." - Since 'cacheable' is now a module param, 'cacheable' is no longer a valid fact name. - This action does not use a connection and always executes on the controller. seealso: - module: ansible.builtin.include_vars - ref: ansible_variable_precedence description: More information related to variable precedence and which type of variable wins over others. author: - Dag Wieers (@dagwieers) ''' EXAMPLES = r''' - name: Setting host facts using key=value pairs, this format can only create strings or booleans set_fact: one_fact="something" other_fact="{{ local_var }}" - name: Setting host facts using complex arguments set_fact: one_fact: something other_fact: "{{ local_var * 2 }}" another_fact: "{{ some_registered_var.results | map(attribute='ansible_facts.some_fact') | list }}" - name: Setting facts so that they will be persisted in the fact cache set_fact: one_fact: something other_fact: "{{ local_var * 2 }}" cacheable: yes - name: Creating list and dictionary variables set_fact: one_dict: something: here other: there one_list: - a - b - c - name: Creating list and dictionary variables using 'shorthand' YAML set_fact: two_dict: {'something': here2, 'other': somewhere} two_list: [1,2,3] '''
47.655556
144
0.726743
639
4,289
4.796557
0.4241
0.022839
0.013051
0.013703
0.080914
0.0646
0.039804
0.039804
0.039804
0.026754
0
0.006975
0.197715
4,289
89
145
48.191011
0.883755
0.044533
0
0.171053
0
0.223684
0.966292
0.035662
0
0
0
0
0
1
0
false
0
0.013158
0
0.013158
0.013158
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
648835b0871fa76f3d85b2a140f67b19860ce428
114
py
Python
virgool_cloud/config-sample.py
mavahedinia/virgoolcloud
cef18e5dc85940d079c51552e8def158dff6ec88
[ "MIT" ]
1
2018-03-27T15:16:12.000Z
2018-03-27T15:16:12.000Z
virgool_cloud/config-sample.py
Mr0Null/virgoolcloud
cef18e5dc85940d079c51552e8def158dff6ec88
[ "MIT" ]
4
2021-03-18T20:18:20.000Z
2022-03-11T23:14:34.000Z
virgool_cloud/config-sample.py
mavahedinia/virgoolcloud
cef18e5dc85940d079c51552e8def158dff6ec88
[ "MIT" ]
null
null
null
bot_token = '' waiting_timeout = 5 # Seconds admin_id = "" channel_id = "" bitly_access_token = "" vars_file = ""
16.285714
29
0.675439
15
114
4.666667
0.866667
0
0
0
0
0
0
0
0
0
0
0.010638
0.175439
114
6
30
19
0.734043
0.061404
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
6496e3a04cad8fb52d2bf8ff8057483c20f1efdb
1,788
py
Python
tests/loris/parameters/api_tests.py
jpstroop/loris-redux
b5db56d5a250fdb24486afe01bad55b81761701a
[ "BSD-2-Clause" ]
7
2016-08-09T17:39:05.000Z
2016-09-26T19:37:30.000Z
tests/loris/parameters/api_tests.py
jpstroop/loris-redux
b5db56d5a250fdb24486afe01bad55b81761701a
[ "BSD-2-Clause" ]
183
2016-06-02T22:07:05.000Z
2022-03-11T23:23:01.000Z
tests/loris/parameters/api_tests.py
jpstroop/loris-redux
b5db56d5a250fdb24486afe01bad55b81761701a
[ "BSD-2-Clause" ]
1
2016-08-09T17:39:11.000Z
2016-08-09T17:39:11.000Z
from loris.parameters.api import AbstractParameter from unittest.mock import Mock import pytest class ProperImpl(AbstractParameter): def __init__(self, uri_slice, enabled_features): super(ProperImpl, self).__init__(uri_slice, enabled_features) @property def canonical(self): return "canonical version" class TestAbstractParameter(object): def test_canonical_required(self): class WithoutCanonical(AbstractParameter): def __init__(self, uri_slice, enabled_features): super(WithoutCanonical, self).__init__(uri_slice, enabled_features) with pytest.raises(TypeError) as type_error: w = WithoutCanonical("abc", (), Mock()) assert "Can't instantiate abstract class" in str(type_error.value) def test_init_required(self): class WithoutInit(AbstractParameter): @property def canonical(self): return "canonical version" with pytest.raises(TypeError) as type_error: w = WithoutInit("abc", (), Mock()) assert "Can't instantiate abstract class" in str(type_error.value) def test_init_sig_required(self): class WrongInitSig(AbstractParameter): def __init__(self): super(WrongInitSig, self).__init__() @property def canonical(self): return "canonical version" with pytest.raises(TypeError) as type_error: WrongInitSig() assert "__init__() missing 2 required positional" in str(type_error.value) def test_proper_impl(self): ProperImpl("foo", ()) def test_stuff_is_defined(self): p = ProperImpl("foo", ()) assert p.uri_slice == "foo" assert p.enabled_features == ()
32.509091
83
0.649888
190
1,788
5.821053
0.3
0.048825
0.05425
0.083183
0.533454
0.533454
0.477396
0.412297
0.377939
0.276673
0
0.000754
0.258389
1,788
54
84
33.111111
0.833333
0
0
0.390244
0
0
0.095078
0
0
0
0
0
0.121951
1
0.268293
false
0
0.073171
0.073171
0.536585
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
64ae05324f3dae6df96c35bcbece7b74feb328fc
120
py
Python
countd.py
sushmitajaiswal/PythonPrograms
d4fb1b36953185e2f8dd866798ca6965a52563a9
[ "MIT" ]
null
null
null
countd.py
sushmitajaiswal/PythonPrograms
d4fb1b36953185e2f8dd866798ca6965a52563a9
[ "MIT" ]
null
null
null
countd.py
sushmitajaiswal/PythonPrograms
d4fb1b36953185e2f8dd866798ca6965a52563a9
[ "MIT" ]
null
null
null
word=input("enter any word:") d={} for x in word: d[x]=d.get(x,0)+1 for k,v in d.items(): print(k,"occured",v,"times")
20
29
0.608333
28
120
2.607143
0.607143
0.136986
0
0
0
0
0
0
0
0
0
0.019048
0.125
120
6
30
20
0.67619
0
0
0
0
0
0.223141
0
0
0
0
0
0
1
0
false
0
0
0
0
0.166667
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
64afdabe7a49d85a55002e8219642eede03635c1
288
py
Python
score.py
salisu14/python-tut
4defc38924e064657daa46647e8979cde733f9f4
[ "MIT" ]
5
2021-04-16T01:29:21.000Z
2021-12-24T10:03:54.000Z
score.py
salisu14/python-tut
4defc38924e064657daa46647e8979cde733f9f4
[ "MIT" ]
null
null
null
score.py
salisu14/python-tut
4defc38924e064657daa46647e8979cde733f9f4
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 average = 0 score = int(input('Enter first score: ')) score += int(input('Enter second score: ')) score += int(input('Enter third score: ')) average = score / 3.0 average = round(average, 2) print(f'Total Score: {score}') print(f'Average Score: {average}')
16.941176
43
0.65625
42
288
4.5
0.452381
0.126984
0.206349
0.285714
0.243386
0
0
0
0
0
0
0.020661
0.159722
288
16
44
18
0.760331
0.072917
0
0
0
0
0.384906
0
0
0
0
0
0
1
0
false
0
0
0
0
0.25
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
64b279e328c6e5af418118b043a2d65021c5d603
1,230
py
Python
lukkari/timerange.py
JuEeHa/lukkari
699caf7686d1b060927dfdc7dac2a7452f2371d5
[ "Unlicense" ]
null
null
null
lukkari/timerange.py
JuEeHa/lukkari
699caf7686d1b060927dfdc7dac2a7452f2371d5
[ "Unlicense" ]
null
null
null
lukkari/timerange.py
JuEeHa/lukkari
699caf7686d1b060927dfdc7dac2a7452f2371d5
[ "Unlicense" ]
null
null
null
import datetime class Timerange: def __init__(self, start, length): self.start = start self.length = length def range(self): end = self.start + self.length return (self.start, end) def __contains__(self, day): delta = day - self.start return datetime.timedelta(seconds = 0) <= delta and delta < self.length def overlaps(self, other): if other.start < self.start: return other.overlaps(self) assert(self.start <= other.start) return other.start < self.start + self.length def __repr__(self): return 'Timerange(%s, %s)' % (repr(self.start), repr(self.length)) def __str__(self): start, end = (i.strftime('%H:%M') for i in self.range()) return '%s - %s' % (start, end) def __eq__(self, other): return self.start == other.start and self.length == other.length def __ne__(self, other): return not self == other def between(start, end): assert(len(start) == 2 and len(end) == 2) start_hour, start_minute = start end_hour, end_minute = end start_obj = datetime.datetime(1970, 1, 1, start_hour, start_minute) end_obj = datetime.datetime(1970, 1, 1, end_hour, end_minute) assert(end_obj - start_obj > datetime.timedelta(seconds = 0)) return Timerange(start_obj, end_obj - start_obj)
27.954545
73
0.696748
185
1,230
4.421622
0.232432
0.121027
0.055012
0.046455
0.061125
0.061125
0
0
0
0
0
0.015595
0.165854
1,230
43
74
28.604651
0.781676
0
0
0
0
0
0.023577
0
0
0
0
0
0.090909
1
0.272727
false
0
0.030303
0.090909
0.606061
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
64cfaf05b6963c5ebf29624e1caab4a4a9f80d75
839
py
Python
custom/icds/rules/util.py
kkrampa/commcare-hq
d64d7cad98b240325ad669ccc7effb07721b4d44
[ "BSD-3-Clause" ]
1
2020-05-05T13:10:01.000Z
2020-05-05T13:10:01.000Z
custom/icds/rules/util.py
kkrampa/commcare-hq
d64d7cad98b240325ad669ccc7effb07721b4d44
[ "BSD-3-Clause" ]
1
2019-12-09T14:00:14.000Z
2019-12-09T14:00:14.000Z
custom/icds/rules/util.py
MaciejChoromanski/commcare-hq
fd7f65362d56d73b75a2c20d2afeabbc70876867
[ "BSD-3-Clause" ]
5
2015-11-30T13:12:45.000Z
2019-07-01T19:27:07.000Z
from __future__ import absolute_import from __future__ import unicode_literals import pytz import re import six from corehq.util.python_compatibility import soft_assert_type_text from corehq.util.timezones.conversions import ServerTime from datetime import datetime, date def get_date(value): if isinstance(value, date): if isinstance(value, datetime): return value.date() return value if not isinstance(value, six.string_types): raise TypeError("Expected date, datetime, or string") soft_assert_type_text(value) if not re.match(r'^\d{4}-\d{2}-\d{2}', value): raise ValueError("Expected a date string") return datetime.strptime(value, '%Y-%m-%d').date() def todays_date(utc_now): return ServerTime(utc_now).user_time(pytz.timezone('Asia/Kolkata')).done().date()
27.064516
85
0.722288
117
839
4.982906
0.461538
0.036021
0.054889
0.06175
0
0
0
0
0
0
0
0.00431
0.170441
839
30
86
27.966667
0.833333
0
0
0
0
0
0.112038
0
0
0
0
0
0.095238
1
0.095238
false
0
0.380952
0.047619
0.666667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
b37b44efa43ac0b0a452bc4955eec6b97cf0f90c
6,151
py
Python
pyapns_client/exceptions.py
rissicay/pyapns_client
3e8bc035c3319e8ba0a7d84db7ba6c7f10628ea4
[ "MIT" ]
17
2019-04-03T23:13:08.000Z
2022-03-25T03:24:38.000Z
pyapns_client/exceptions.py
rissicay/pyapns_client
3e8bc035c3319e8ba0a7d84db7ba6c7f10628ea4
[ "MIT" ]
7
2021-02-28T19:13:38.000Z
2022-01-26T19:21:43.000Z
pyapns_client/exceptions.py
rissicay/pyapns_client
3e8bc035c3319e8ba0a7d84db7ba6c7f10628ea4
[ "MIT" ]
4
2021-02-23T02:07:46.000Z
2022-03-29T15:11:31.000Z
import pytz from datetime import datetime # BASE class APNSException(Exception): """ The base class for all exceptions. """ def __init__(self, status_code, apns_id): super().__init__() # The HTTP status code retuened by APNs. # A 200 value indicates that the notification was successfully sent. # For a list of other possible status codes, see table 6-4 in the Apple Local # and Remote Notification Programming Guide. self.status_code = status_code # The APNs ApnsID value from the Notification. If you didn't set an ApnsID on the # Notification, this will be a new unique UUID which has been created by APNs. self.apns_id = apns_id class APNSDeviceException(APNSException): """ Device should be flagged as potentially invalid (remove immediately in case of UnregisteredException). """ pass class APNSServerException(APNSException): """ Try again later. """ pass class APNSProgrammingException(APNSException): """ Check your code, and try again later. """ pass # CONNECTION class APNSConnectionException(APNSServerException): """ Used when a connectinon to APNS servers fails. """ def __init__(self): super().__init__(status_code=None, apns_id=None) # APNS REASONS class BadCollapseIdException(APNSProgrammingException): """ The collapse identifier exceeds the maximum allowed size. """ pass class BadDeviceTokenException(APNSDeviceException): """ The specified device token was bad. Verify that the request contains a valid token and that the token matches the environment. """ pass class BadExpirationDateException(APNSProgrammingException): """ The apns-expiration value is bad. """ pass class BadMessageIdException(APNSProgrammingException): """ The apns-id value is bad. """ pass class BadPriorityException(APNSProgrammingException): """ The apns-priority value is bad. """ pass class BadTopicException(APNSProgrammingException): """ The apns-topic was invalid. """ pass class DeviceTokenNotForTopicException(APNSDeviceException): """ The device token does not match the specified topic. """ pass class DuplicateHeadersException(APNSProgrammingException): """ One or more headers were repeated. """ pass class IdleTimeoutException(APNSServerException): """ Idle time out. """ pass class InvalidPushTypeException(APNSProgrammingException): """ The apns-push-type value is invalid. """ pass class MissingDeviceTokenException(APNSProgrammingException): """ The device token is not specified in the request :path. Verify that the :path header contains the device token. """ pass class MissingTopicException(APNSProgrammingException): """ The apns-topic header of the request was not specified and was required. The apns-topic header is mandatory when the client is connected using a certificate that supports multiple topics. """ pass class PayloadEmptyException(APNSProgrammingException): """ The message payload was empty. """ pass class TopicDisallowedException(APNSProgrammingException): """ Pushing to this topic is not allowed. """ pass class BadCertificateException(APNSProgrammingException): """ The certificate was bad. """ pass class BadCertificateEnvironmentException(APNSProgrammingException): """ The client certificate was for the wrong environment. """ pass class ExpiredProviderTokenException(APNSServerException): """ The provider token is stale and a new token should be generated. """ pass class ForbiddenException(APNSProgrammingException): """ The specified action is not allowed. """ pass class InvalidProviderTokenException(APNSProgrammingException): """ The provider token is not valid or the token signature could not be verified. """ pass class MissingProviderTokenException(APNSProgrammingException): """ No provider certificate was used to connect to APNs and Authorization header was missing or no provider token was specified. """ pass class BadPathException(APNSProgrammingException): """ The request contained a bad :path value. """ pass class MethodNotAllowedException(APNSProgrammingException): """ The specified :method was not POST. """ pass class UnregisteredException(APNSDeviceException): """ The device token is inactive for the specified topic. Expected HTTP/2 status code is 410; see Table 8-4. """ def __init__(self, status_code, apns_id, timestamp): super().__init__(status_code=status_code, apns_id=apns_id) # If the value of StatusCode is 410, this is the last time at which APNs # confirmed that the device token was no longer valid for the topic. # The value is in milliseconds (ms). self.timestamp = timestamp @property def timestamp_datetime(self): if not self.timestamp: return None return datetime.fromtimestamp(self.timestamp / 1000, tz=pytz.utc) class PayloadTooLargeException(APNSProgrammingException): """ The message payload was too large. See Creating the Remote Notification Payload for details on maximum payload size. """ pass class TooManyProviderTokenUpdatesException(APNSServerException): """ The provider token is being updated too often. """ pass class TooManyRequestsException(APNSServerException): """ Too many requests were made consecutively to the same device token. """ pass class InternalServerErrorException(APNSServerException): """ An internal server error occurred. """ pass class ServiceUnavailableException(APNSServerException): """ The service is unavailable. """ pass class ShutdownException(APNSServerException): """ The server is shutting down. """ pass
20.101307
191
0.691595
639
6,151
6.596244
0.352113
0.061922
0.044128
0.011388
0.074733
0.012811
0.012811
0
0
0
0
0.003831
0.236222
6,151
305
192
20.167213
0.893359
0.41099
0
0.382716
0
0
0
0
0
0
0
0
0
1
0.049383
false
0.382716
0.024691
0
0.518519
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
b37c7961a918b47e8c39d8b6b6cd69f43d49c54f
287
py
Python
pdf_generator/views.py
ianvieira/django-pdf-generator
65b89e0cbf9aee890336e9eb86785ce3171f82a3
[ "MIT" ]
null
null
null
pdf_generator/views.py
ianvieira/django-pdf-generator
65b89e0cbf9aee890336e9eb86785ce3171f82a3
[ "MIT" ]
null
null
null
pdf_generator/views.py
ianvieira/django-pdf-generator
65b89e0cbf9aee890336e9eb86785ce3171f82a3
[ "MIT" ]
2
2019-12-08T09:24:31.000Z
2020-09-01T12:49:42.000Z
import os from django.shortcuts import render from .settings import pdf_settings def pdf_html(request, html_key): filename = '%s.html' % html_key response = render(request, 'pdf_generator/%s' % filename) os.remove(os.path.join(pdf_settings.TEMPLATES_DIR, filename)) return response
28.7
62
0.780488
42
287
5.166667
0.52381
0.101382
0
0
0
0
0
0
0
0
0
0
0.114983
287
10
63
28.7
0.854331
0
0
0
0
0
0.079861
0
0
0
0
0
0
1
0.125
false
0
0.375
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
b3859f2b30854f47917ba9cb42b44404ed3ba402
8,035
py
Python
installation/templates/configuration/auth.py
piwaniuk/critic
28ed20bb8032d7cc5aa23de98da51e619fd84164
[ "Apache-2.0" ]
216
2015-01-05T12:48:10.000Z
2022-03-08T00:12:23.000Z
installation/templates/configuration/auth.py
piwaniuk/critic
28ed20bb8032d7cc5aa23de98da51e619fd84164
[ "Apache-2.0" ]
55
2015-02-28T12:10:26.000Z
2020-11-18T17:45:16.000Z
installation/templates/configuration/auth.py
piwaniuk/critic
28ed20bb8032d7cc5aa23de98da51e619fd84164
[ "Apache-2.0" ]
34
2015-05-02T15:15:10.000Z
2020-06-15T19:20:37.000Z
# -*- mode: python; encoding: utf-8 -*- # # Copyright 2013 Jens Lindström, Opera Software ASA # # 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. # Accepted password hash schemes. They need to be supported by the passlib # Python package; see http://packages.python.org/passlib for details. PASSWORD_HASH_SCHEMES = %(installation.config.password_hash_schemes)r # Default password hash scheme. Must be included in PASSWORD_HASH_SCHEMES. DEFAULT_PASSWORD_HASH_SCHEME = %(installation.config.default_password_hash_scheme)r # (Approximate) minimum password hash time in seconds. Higher means safer # passwords (more difficult to decrypt using brute-force) but slower sign-in # operation. MINIMUM_PASSWORD_HASH_TIME = %(installation.config.minimum_password_hash_time)r # Calibrated minimum rounds per password hash scheme. MINIMUM_ROUNDS = %(installation.config.minimum_rounds)r # External authentication providers. PROVIDERS = { # GitHub OAuth-based authentication. "github": { "enabled": %(installation.config.provider_github.enabled)r, # Allow authenticated user to create a Critic user. "allow_user_registration": %(installation.config.provider_github.allow_user_registration)r, # Verify user email addresses provided by GitHub. "verify_email_addresses": %(installation.config.provider_github.verify_email_addresses)r, # Client ID and secret. These are generated by registering an # application at https://github.com/settings/applications/new. "client_id": %(installation.config.provider_github.client_id)r, "client_secret": %(installation.config.provider_github.client_secret)r, # Bypass /createuser on first sign in, creating a user automatically. "bypass_createuser": %(installation.config.provider_github.bypass_createuser)r, # Authentication callback URI. This same URI must be provided # to GitHub when registering the application. The path # component must be "/oauth/github". "redirect_uri": %(installation.config.provider_github.redirect_uri)r }, # Google OAuth-based authentication. "google": { "enabled": %(installation.config.provider_google.enabled)r, # Allow authenticated user to create a Critic user. "allow_user_registration": %(installation.config.provider_google.allow_user_registration)r, # Verify user email addresses provided by Google. "verify_email_addresses": %(installation.config.provider_google.verify_email_addresses)r, # Client ID and secret. These are generated by creating a project at # https://cloud.google.com/console/project, and then creating an OAuth2 # client id using the project administration UI. "client_id": %(installation.config.provider_google.client_id)r, "client_secret": %(installation.config.provider_google.client_secret)r, # Bypass /createuser on first sign in, creating a user automatically. "bypass_createuser": %(installation.config.provider_google.bypass_createuser)r, # Authentication callback URI. This same URI must be provided # to Google when creating the OAuth2 client id. The path # component must be "/oauth/google". "redirect_uri": %(installation.config.provider_google.redirect_uri)r }, } # Authentication databases. DATABASES = { # Using Critic's own user database for authentication. "internal": {}, # Using an LDAP database for authentication. "ldap": { # Input fields. # # Each element is a tuple containing: # [0]: True if the field should use <input type=password> # [1]: Internal field identifier # [2]: Field label # [3]: (Optional) Longer description / help text "fields": [ (False, "username", "Username:"), (True, "password", "Password:"), ], # LDAP server URL. "url": "%(installation.config.ldap_url)s", # Use TLS when connecting to LDAP server. "use_tls": True, # Credentials field. # # Identifier of the field whose value will be used as the credentials # (e.g. password) in the bind request used for authentication. "credentials": "password", # The following two values are all interpreted as Python format strings # that can reference field values, e.g. using "%%(username)s". The input # values will have been escaped for safe usage in LDAP expressions. # LDAP search base. "search_base": "%(installation.config.ldap_search_base)s", # LDAP search filter. "search_filter": "(uid=%%(username)s)", # The following settings control if and how Critic user records are # created after successful authentication of a user. # If true, Critic user records are created automatically if # authentication succeeds but a matching record is not found. "create_user": %(installation.config.ldap_create_user)r, # User name LDAP attribute. # # This is the LDAP attribute whose value is used as the Critic username, # both when looking for an existing user record and when creating a new # one (if one isn't found.) # # If the attribute is missing or empty it will be considered an # authentication error. "username_attribute": "%(installation.config.ldap_username_attribute)s", # Full name LDAP attribute. # # This is the LDAP attribute to use as the (initial) full name when # creating a new Critic user record. It is not used if an existing user # record is found. # # If the attribute is missing or empty, the user is created with the # username as full name. "fullname_attribute": "%(installation.config.ldap_fullname_attribute)s", # Email LDAP attribute. # # This is the LDAP attribute to use as the (initial) primary email # address when creating a new Critic user record. It is not used if an # existing user record is found. # # If the attribute is missing or empty, the user is created with no # primary email address. "email_attribute": "%(installation.config.ldap_email_attribute)s", # List of required LDAP groups. # # If the list is empty, no group membership is required. "require_groups": [ # { # # Distinguished name of the required group. # "dn": "cn=SomeGroup,ou=Groups,dc=example,dc=com", # # # Group attribute containing the list of members. # "members_attribute": "memberUid", # # # Value to search for in the list of members. # # # # The value is interpreted as a Python format string, and can # # reference field values. It can also reference the # # distinguished name of the user signing in as "%%(dn)s". # "member_value": "%%(username)s", # }, ], # Maximum age of cached successful authentication attempts, in seconds. # If set to zero, caching is disabled altogether. "cache_max_age": %(installation.config.ldap_cache_max_age)r, }, } DATABASE = %(installation.config.auth_database)r ENABLE_ACCESS_TOKENS = %(installation.config.enable_access_tokens)r
41.205128
99
0.667953
987
8,035
5.339412
0.287741
0.09222
0.06907
0.042505
0.31537
0.273624
0.24592
0.24592
0.213283
0.213283
0
0.002484
0.248413
8,035
194
100
41.417526
0.870177
0.5715
0
0.042553
0
0
0.192782
0.090226
0
0
0
0
0
0
null
null
0.148936
0
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
b397b968bf5b0884131d6ce2a3bdfa2c376131cc
792
py
Python
tests/integration/test_project.py
gitter-badger/a2ml
1d9ef6657645b61c64090284ed8fadb1a68b932c
[ "Apache-2.0" ]
30
2019-07-01T13:23:27.000Z
2022-03-16T21:19:33.000Z
tests/integration/test_project.py
arita37/a2ml
3e92bede2c2ef6e63be74560cc6b904d3ec9d931
[ "Apache-2.0" ]
234
2019-07-04T13:56:15.000Z
2021-11-04T10:12:55.000Z
tests/integration/test_project.py
arita37/a2ml
3e92bede2c2ef6e63be74560cc6b904d3ec9d931
[ "Apache-2.0" ]
13
2019-07-04T14:00:34.000Z
2020-07-13T11:18:44.000Z
import pytest from a2ml.cmdl.cmdl import cmdl class TestProjectCLI(): def test_create_list_delete(self, runner, log, project): result = runner.invoke(cmdl, ['project', 'delete', 'cli-integration-test']) result = runner.invoke(cmdl, ['project', 'select', 'cli-integration-test']) assert log.messages[-1] == '[auger] Selected Project cli-integration-test' result = runner.invoke(cmdl, ['project', 'create']) assert log.messages[-1] == '[auger] Created Project cli-integration-test' result = runner.invoke(cmdl, ['project', 'list']) assert 'cli-integration-test' in str(log.messages) result = runner.invoke(cmdl, ['project', 'delete']) assert log.messages[-1] == '[auger] Deleted Project cli-integration-test'
39.6
83
0.65404
93
792
5.537634
0.322581
0.163107
0.209709
0.213592
0.570874
0.436893
0.300971
0.300971
0.209709
0
0
0.006231
0.189394
792
19
84
41.684211
0.79595
0
0
0
0
0
0.32702
0
0
0
0
0
0.307692
1
0.076923
false
0
0.153846
0
0.307692
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
b39916cb7995122f663f739553c92cd8a79865f1
4,955
py
Python
pineboolib/fllegacy/flserialport.py
juanjosepablos/pineboo
f6ce515aec6e0139821bb9c1d62536d9fb50dae4
[ "MIT" ]
null
null
null
pineboolib/fllegacy/flserialport.py
juanjosepablos/pineboo
f6ce515aec6e0139821bb9c1d62536d9fb50dae4
[ "MIT" ]
1
2017-10-30T22:00:48.000Z
2017-11-11T19:34:32.000Z
pineboolib/fllegacy/flserialport.py
juanjosepablos/pineboo
f6ce515aec6e0139821bb9c1d62536d9fb50dae4
[ "MIT" ]
1
2017-10-30T20:16:38.000Z
2017-10-30T20:16:38.000Z
"""Flserial por module.""" from PyQt5 import QtCore from pineboolib.core import decorators from typing import TYPE_CHECKING if TYPE_CHECKING: from PyQt5 import QtSerialPort # type: ignore [attr-defined] class BaudRateType(object): """BaudRateType class.""" BAUD50: int = -1 BAUD75: int = -1 BAUD110: int = -1 BAUD134: int = -1 BAUD150: int = -1 BAUD200: int = -1 BAUD300: int = -1 BAUD600: int = -1 BAUD1200: int = 1200 BAUD1800: int = -1 BAUD2400: int = 2400 BAUD4800: int = 4800 BAUD9600: int = 9600 BAUD14400: int = -1 BAUD19200: int = 19200 BAUD38400: int = 38400 BAUD56000: int = -1 BAUD57600: int = 57600 BAUD76800: int = -1 BAUD115200: int = 115200 BAUD128000: int = -1 BAUD256000: int = -1 class DataBitsType(object): """DataBitsType class.""" DATA_5: int = 5 DATA_6: int = 6 DATA_7: int = 7 DATA_8: int = 8 class ParityType(object): """ParityType class.""" PAR_NONE: int = 0 PAR_EVEN: int = 2 PAR_ODD: int = 3 PAR_SPACE: int = 4 PAR_MARK: int = 5 class StopBitType(object): """StopBitType class.""" STOP_1: int = 1 STOP_1_5: int = 3 STOP_2: int = 2 class FlowType(object): """FlowType class.""" FLOW_OFF: int = 0 FLOW_HARDWARE: int = 1 FLOW_XONXOFF: int = 2 class FLSerialPort(QtCore.QObject, BaudRateType, DataBitsType, ParityType, StopBitType, FlowType): """FLSerialPort class.""" _obj: "QtSerialPort.QSerialPort" def __init__(self, port_name: str) -> None: """Inicialize.""" super().__init__() if str(QtCore.QSysInfo()) == "ios": from pineboolib.q3widgets.messagebox import MessageBox MessageBox.information( None, self.tr("Opción deshabilitada"), self.tr("FLSerialPort no está disponible para IOS"), MessageBox.Ok, ) return else: from PyQt5 import QtSerialPort # type: ignore [attr-defined] # noqa: F821 self._obj = QtSerialPort.QSerialPort(port_name) def setBaudRate(self, baud_rate: int) -> None: """Set baud rate.""" self._obj.setBaudRate(baud_rate) def baudRate(self) -> int: """Return actual baud rate.""" return self._obj.baudRate() def setDataBits(self, data_bits: int) -> None: """Set data bits.""" self._obj.setDataBits(data_bits) def dataBits(self) -> int: """Return actual data bits.""" return self._obj.dataBits() def setParity(self, parity: int) -> None: """Set parity check value.""" self._obj.setParity(parity) def parity(self) -> int: """Return parity check.""" return self._obj.parity() def setStopBits(self, stop_bit: int) -> None: """Set stop bits.""" self._obj.setStopBits(stop_bit) def stopBits(self) -> int: """Return stop bits.""" return self._obj.stopBits() def setFlowControl(self, flow: int) -> None: """Set flow conrol.""" self._obj.setFlowControl(flow) def flowControl(self) -> int: """Return flow control.""" return self._obj.flowControl() def setTimeOut(self, sec: int = 0, milisec: int = 3000) -> None: """Set time out.""" time = milisec if sec: time = sec * 1000 + time self._obj.waitForBytesWritten(time) self._obj.waitForReadyRead(time) def open(self) -> bool: """Return if port is open.""" return self._obj.open() def close(self) -> bool: """Return if port is closed.""" return self._obj.close() @decorators.NotImplementedWarn def writeText(self, data: str) -> None: """Send string data.""" pass @decorators.NotImplementedWarn def getch(self) -> int: """Return int char readed from port.""" return 0 @decorators.NotImplementedWarn def putch(self, ch: int) -> int: """Send a char.""" return 0 @decorators.NotImplementedWarn def ungetch(self, ch: int) -> int: """Return unsigned char?.""" return 0 def size(self) -> int: """Return size data recceived.""" return self._obj.size() def flush(self) -> bool: """Flush data.""" return self._obj.flush() @decorators.NotImplementedWarn def readBlock(self) -> int: """Read data block.""" return 0 def writeBlock(self) -> int: """Write data block.""" return 0 def bytesAvailable(self) -> int: """Return number of bytes avalaible to read.""" return 0 def setRts(self, b: bool) -> None: """Emit RTS. signal.""" self._obj.setRequestToSend(b) def setDtr(self, b: bool) -> None: """Emit DTR signal.""" self._obj.setDataTerminalReady(b)
24.651741
98
0.578204
567
4,955
4.957672
0.310406
0.047314
0.041622
0.01921
0.102455
0.049804
0.034152
0.034152
0
0
0
0.053113
0.293239
4,955
200
99
24.775
0.749572
0.144097
0
0.108333
0
0
0.021334
0.005885
0
0
0
0
0
1
0.208333
false
0.008333
0.05
0
0.758333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
b39c43d0021d178a258b637ee9621caf69f2c4a1
230
py
Python
nsot/util/__init__.py
BunkersCo/nsot
fd45bdf63794aa3015a87855f4d7b03663fd5396
[ "Apache-2.0" ]
null
null
null
nsot/util/__init__.py
BunkersCo/nsot
fd45bdf63794aa3015a87855f4d7b03663fd5396
[ "Apache-2.0" ]
null
null
null
nsot/util/__init__.py
BunkersCo/nsot
fd45bdf63794aa3015a87855f4d7b03663fd5396
[ "Apache-2.0" ]
null
null
null
""" Utilities used across the project. """ # Core from . import core from .core import * # noqa # Stats from . import stats from .stats import * # noqa __all__ = [] __all__.extend(core.__all__) __all__.extend(stats.__all__)
13.529412
34
0.695652
30
230
4.666667
0.4
0.114286
0.171429
0
0
0
0
0
0
0
0
0
0.182609
230
16
35
14.375
0.744681
0.243478
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.571429
0
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
b3a08e780fd80323f4995b454d6b15261e415287
1,898
py
Python
minecraftQuest.py
prathimacode-hub/Toonslate-Gags
fc7868c64d8b2694f2110fe8c941a0f311127e72
[ "MIT" ]
2
2021-07-12T10:36:42.000Z
2021-07-17T04:39:20.000Z
minecraftQuest.py
prathimacode-hub/Toonslate-Gags
fc7868c64d8b2694f2110fe8c941a0f311127e72
[ "MIT" ]
null
null
null
minecraftQuest.py
prathimacode-hub/Toonslate-Gags
fc7868c64d8b2694f2110fe8c941a0f311127e72
[ "MIT" ]
2
2021-07-11T12:56:07.000Z
2021-07-14T17:40:54.000Z
# Setup opt = ["yes", "no"] directions = ["left", "right", "forward", "backward"] # Introduction name = input("What is your name, HaCKaToOnEr ?\n") print("Welcome to Toonslate island , " + name + " Let us go on a Minecraft quest!") print("You find yourself in front of a abandoned mineshaft.") print("Can you find your way to explore the shaft and find the treasure chest ?\n") # Start of game response = "" while response not in opt: response = input("Would you like to go inside the Mineshaft?\nyes/no\n") if response == "yes": print("You head into the Mineshaft. You hear grumbling sound of zombies,hissing sound of spidersand rattling of skeletons.\n") elif response == "no": print("You are not ready for this quest. Goodbye, " + name + ".") quit() else: print("I didn't understand that.\n") # Next part of game response = "" while response not in directions: print("To your left, you see a skeleton with a golden armor and a bow .") print("To your right, there is a way to go more inside the shaft.") print("There is a cobble stone wall directly in front of you.") print("Behind you is the mineshaft exit.\n") response = input("What direction would you like to move?\nleft/right/forward/backward\n") if response == "left": print(name+" was shot by an arrow. Farewell :( ") quit() elif response == "right": print("You head deeper into the mineshaft and find the treasure chest ,Kudos!!!.\n") elif response == "forward": print("You broke the stone walls and find out it was a spider spawner, spiders slain you to deeath\n") response = "" elif response == "backward": print("You leave the mineshaft un explored . Goodbye, " + name + ".") quit() else: print("I didn't understand that.\n")
43.136364
135
0.632771
271
1,898
4.431734
0.431734
0.039967
0.033306
0.029975
0.166528
0.128226
0.128226
0.074938
0.074938
0.074938
0
0
0.253952
1,898
43
136
44.139535
0.848164
0.026344
0
0.277778
0
0.055556
0.601667
0.02
0
0
0
0
0
1
0
false
0
0
0
0
0.416667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
b3ab6c36b1a0d4d101bc155cc11546266d771646
623
py
Python
test_platform/api_app/user_view.py
juxiaona/test_dev05
7a47ff51cc4afd33353323ebe10469a1a3e40e4a
[ "Apache-2.0" ]
1
2021-07-11T09:16:24.000Z
2021-07-11T09:16:24.000Z
test_platform/api_app/user_view.py
juxiaona/test_dev05
7a47ff51cc4afd33353323ebe10469a1a3e40e4a
[ "Apache-2.0" ]
1
2021-07-11T09:16:52.000Z
2021-07-11T09:16:52.000Z
test_platform/api_app/user_view.py
juxiaona/test_dev05
7a47ff51cc4afd33353323ebe10469a1a3e40e4a
[ "Apache-2.0" ]
3
2021-10-17T12:23:01.000Z
2022-02-03T02:29:05.000Z
from rest_framework import routers, serializers, viewsets from django.contrib.auth.models import User from api_app.serializer import UserSerializer # 视图类 class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # users = User.objects.all() # users_list = [] # for user in users: # user_dict = { # "url": "http://127.0.0.1/users/"+ user.id + "/", # "username": user.username, # "email": user.email, # } # users_list.append(user_dict) # # return JsonResponse({"userlist":users_list})
27.086957
62
0.626003
69
623
5.536232
0.57971
0.070681
0.073298
0
0
0
0
0
0
0
0
0.012766
0.245586
623
22
63
28.318182
0.8
0.462279
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
1
0
0
2
b3b8c9350fdcc10478be9ff8a551df1606e7ecf2
880
py
Python
controllers/portal.py
R-E-A-L-iT/odoo-proportals-module
f4f500632c7e15eb7b1e47f3c915a36a78d7e3da
[ "MIT" ]
null
null
null
controllers/portal.py
R-E-A-L-iT/odoo-proportals-module
f4f500632c7e15eb7b1e47f3c915a36a78d7e3da
[ "MIT" ]
null
null
null
controllers/portal.py
R-E-A-L-iT/odoo-proportals-module
f4f500632c7e15eb7b1e47f3c915a36a78d7e3da
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import binascii from odoo import fields, http, _ from odoo.exceptions import AccessError, MissingError, UserError from odoo.http import request from odoo.addons.payment.controllers.portal import PaymentProcessing from odoo.addons.portal.controllers.mail import _message_post_helper from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager, get_records_pager from odoo.osv import expression class CustomerPortal(CustomerPortal): @http.route(['/my/products', '/my/products/page/<int:page>'], type='http', auth="user", website=True) def products(self): company = request.env.user.partner_id.parent_id values = { 'company': company } return request.render("proportal.portal_products", values)
36.666667
106
0.744318
111
880
5.810811
0.567568
0.086822
0.065116
0.062016
0.096124
0
0
0
0
0
0
0.001348
0.156818
880
23
107
38.26087
0.867925
0.106818
0
0
0
0
0.102171
0.067688
0
0
0
0
0
1
0.0625
false
0
0.5
0
0.6875
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
b3b8fdb7ee87591bb03fea19135fb3fea98d20aa
6,222
py
Python
google/cloud/videointelligence/v1/videointelligence-v1-py/google/cloud/videointelligence/__init__.py
googleapis/googleapis-gen
d84824c78563d59b0e58d5664bfaa430e9ad7e7a
[ "Apache-2.0" ]
7
2021-02-21T10:39:41.000Z
2021-12-07T07:31:28.000Z
google/cloud/videointelligence/v1/videointelligence-v1-py/google/cloud/videointelligence/__init__.py
googleapis/googleapis-gen
d84824c78563d59b0e58d5664bfaa430e9ad7e7a
[ "Apache-2.0" ]
6
2021-02-02T23:46:11.000Z
2021-11-15T01:46:02.000Z
google/cloud/videointelligence/v1/videointelligence-v1-py/google/cloud/videointelligence/__init__.py
googleapis/googleapis-gen
d84824c78563d59b0e58d5664bfaa430e9ad7e7a
[ "Apache-2.0" ]
4
2021-01-28T23:25:45.000Z
2021-08-30T01:55:16.000Z
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from google.cloud.videointelligence_v1.services.video_intelligence_service.client import VideoIntelligenceServiceClient from google.cloud.videointelligence_v1.services.video_intelligence_service.async_client import VideoIntelligenceServiceAsyncClient from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoProgress from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoRequest from google.cloud.videointelligence_v1.types.video_intelligence import AnnotateVideoResponse from google.cloud.videointelligence_v1.types.video_intelligence import DetectedAttribute from google.cloud.videointelligence_v1.types.video_intelligence import DetectedLandmark from google.cloud.videointelligence_v1.types.video_intelligence import Entity from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentDetectionConfig from google.cloud.videointelligence_v1.types.video_intelligence import ExplicitContentFrame from google.cloud.videointelligence_v1.types.video_intelligence import FaceAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import FaceDetectionConfig from google.cloud.videointelligence_v1.types.video_intelligence import FaceFrame from google.cloud.videointelligence_v1.types.video_intelligence import FaceSegment from google.cloud.videointelligence_v1.types.video_intelligence import LabelAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionConfig from google.cloud.videointelligence_v1.types.video_intelligence import LabelFrame from google.cloud.videointelligence_v1.types.video_intelligence import LabelSegment from google.cloud.videointelligence_v1.types.video_intelligence import LogoRecognitionAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingBox from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedBoundingPoly from google.cloud.videointelligence_v1.types.video_intelligence import NormalizedVertex from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingConfig from google.cloud.videointelligence_v1.types.video_intelligence import ObjectTrackingFrame from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import PersonDetectionConfig from google.cloud.videointelligence_v1.types.video_intelligence import ShotChangeDetectionConfig from google.cloud.videointelligence_v1.types.video_intelligence import SpeechContext from google.cloud.videointelligence_v1.types.video_intelligence import SpeechRecognitionAlternative from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscription from google.cloud.videointelligence_v1.types.video_intelligence import SpeechTranscriptionConfig from google.cloud.videointelligence_v1.types.video_intelligence import TextAnnotation from google.cloud.videointelligence_v1.types.video_intelligence import TextDetectionConfig from google.cloud.videointelligence_v1.types.video_intelligence import TextFrame from google.cloud.videointelligence_v1.types.video_intelligence import TextSegment from google.cloud.videointelligence_v1.types.video_intelligence import TimestampedObject from google.cloud.videointelligence_v1.types.video_intelligence import Track from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationProgress from google.cloud.videointelligence_v1.types.video_intelligence import VideoAnnotationResults from google.cloud.videointelligence_v1.types.video_intelligence import VideoContext from google.cloud.videointelligence_v1.types.video_intelligence import VideoSegment from google.cloud.videointelligence_v1.types.video_intelligence import WordInfo from google.cloud.videointelligence_v1.types.video_intelligence import Feature from google.cloud.videointelligence_v1.types.video_intelligence import LabelDetectionMode from google.cloud.videointelligence_v1.types.video_intelligence import Likelihood __all__ = ('VideoIntelligenceServiceClient', 'VideoIntelligenceServiceAsyncClient', 'AnnotateVideoProgress', 'AnnotateVideoRequest', 'AnnotateVideoResponse', 'DetectedAttribute', 'DetectedLandmark', 'Entity', 'ExplicitContentAnnotation', 'ExplicitContentDetectionConfig', 'ExplicitContentFrame', 'FaceAnnotation', 'FaceDetectionAnnotation', 'FaceDetectionConfig', 'FaceFrame', 'FaceSegment', 'LabelAnnotation', 'LabelDetectionConfig', 'LabelFrame', 'LabelSegment', 'LogoRecognitionAnnotation', 'NormalizedBoundingBox', 'NormalizedBoundingPoly', 'NormalizedVertex', 'ObjectTrackingAnnotation', 'ObjectTrackingConfig', 'ObjectTrackingFrame', 'PersonDetectionAnnotation', 'PersonDetectionConfig', 'ShotChangeDetectionConfig', 'SpeechContext', 'SpeechRecognitionAlternative', 'SpeechTranscription', 'SpeechTranscriptionConfig', 'TextAnnotation', 'TextDetectionConfig', 'TextFrame', 'TextSegment', 'TimestampedObject', 'Track', 'VideoAnnotationProgress', 'VideoAnnotationResults', 'VideoContext', 'VideoSegment', 'WordInfo', 'Feature', 'LabelDetectionMode', 'Likelihood', )
53.637931
130
0.851013
627
6,222
8.280702
0.202552
0.09245
0.138675
0.29584
0.57473
0.57473
0.57473
0.57473
0.57473
0
0
0.01003
0.086628
6,222
115
131
54.104348
0.903572
0.09145
0
0
0
0
0.153273
0.07912
0
0
0
0
0
1
0
false
0
0.494845
0
0.494845
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
1
0
0
0
0
2
b3db0f61a48ed17e172300c3cb8606a8b731cdc4
7,477
py
Python
app/views.py
soje402/imageboard
45db024dae3fc9b2ae3e4531a4c1b59a36629692
[ "MIT" ]
null
null
null
app/views.py
soje402/imageboard
45db024dae3fc9b2ae3e4531a4c1b59a36629692
[ "MIT" ]
null
null
null
app/views.py
soje402/imageboard
45db024dae3fc9b2ae3e4531a4c1b59a36629692
[ "MIT" ]
null
null
null
# coding=utf-8 from flask import Flask, url_for, render_template, request, redirect, jsonify, session, send_file import models import json import datetime import time import md5 from werkzeug import secure_filename app = Flask(__name__) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webm', 'mp4', 'avi', 'mov', 'mpeg'] def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.template_filter('dt') def datetimee(date): return datetime.datetime.utcfromtimestamp(float(date)).strftime("""%d-%m-%Y %H:%M:%S""") @app.template_filter('log') def log(tolog): print(tolog) @app.route('/test') def test(): return render_template('test.html', date = int(time.time())) #@app.route('/<id>') #def hello_world(id=None): # if request.method == 'GET': # pass # elif resquest.method == 'POST': # pass # user = models.User.get_user('toot') # posts = models.Post.get_posts(user['username']) # for post in posts: # commentaires = models.Commentaire.get_commentaires(post['id']) # post['commentaires'] = commentaires # post['nb_com'] = len(commentaires) # return render_template('index.html', posts = posts) #mettre un champ invisible dans les form pour la redirection #l'url de la form est /login mais on sait ou on doit rediriger si le login est bon #l'url login doit être accessible en GET pour les messages d'erreurs (trop compliqués à intégrer dans le header) #!!!!!!!!!!!!!!!!!!!!! def do_login(nickname, clear_password, redirect_url): connection = False user = models.user.get_by_name(nickname) if user: hashed_pass = md5.new(clear_password).hexdigest() if hashed_pass == user['password']: connection = True if connection : session.permanent = True session['nickname'] = nickname session['password'] = clear_password else: session.clear() return redirect(redirect_url) @app.route('/login', methods=['POST']) def login(): return do_login(request.form.get('nickname'), request.form.get('password'), request.form.get('redirect')) @app.route('/register', methods=['GET', 'POST']) def register(): print(request.form) if(request.method == 'POST'): champs = [ 'nickname', 'password', 'password_confirm' ] result = validate(request.form, champs) print result if result['valid']: #résultat valide if not models.user.exist(request.form.get('nickname')): #le nickname n'existe pas déjà models.user.create(request.form.get('nickname'), md5.new(request.form.get('password')).hexdigest()) session.permanent = True session['nickname'] = request.form.get('nickname') session['password'] = request.form.get('password') print('session ajoutée') return redirect(request.form.get('redirect')) else: result['errors']['nickname'] = 'Le nickname existe déjà !'.decode('utf-8') print(result['errors']) return render_template('register.html', redirect=request.form['redirect'], form=result['form'], errors=result['errors']) return render_template('register.html') def validate(form, champs): result = {'valid': True, 'form': form, 'errors': {}} for champ in champs: result['valid'] = result['valid'] and champ_requis(form, champ, errors=result['errors']) #if(champ == 'nickname'): # result['form'][champ] = champ #else: # result['form'][champ] = '' return result def champ_requis(form, champ, errors): if form.get(champ, '') == '': errors[champ] = 'le champ {} est requis'.format(champ) return False else: return True @app.route('/threads/<thread_id>', methods=['GET']) def thread(thread_id): print('ok') return render_template('thread.html', nav = models.board.get_nav(None, thread_id), thread=models.thread.get_full(thread_id)) @app.route('/logout', methods=['POST']) def logout(): session.clear() return redirect(request.form['redirect']) @app.route('/post/<what>/<id>', methods=['POST']) def post(what, id): if(session): user = models.user.get_by_name(session['nickname']) if(user): if not(models.user.check_connect(session['nickname'], md5.new(session['password']).hexdigest())): session.clear() else: print(request.form) #uploaded_files = request.files.getlist("file[]") #next_post = models.post.get_max #for file, index in enumerate(request.files.getlist('file')): # if(file.filename != ''): # filename = secure_filename(file.filename) timestamp = int(time.time()) if(what == 'thread'): #ici vérifier les input models.thread.create( id, request.form['title'], request.form['content'], user['id'], timestamp) elif(what == 'reply'): models.post.create( id, request.form['content'], user['id'], timestamp) else: #l'utilisateur n'existe plus session.clear() return redirect(request.form['redirect']) @app.route('/boards/<boardname>', methods=['GET']) def navboard(boardname): if(session): print('session ok') if not(models.user.check_connect(session['nickname'], md5.new(session['password']).hexdigest())): session.clear() else: print('no session') return render_template( 'board.html', nav = models.board.get_nav(boardname, None), threads = models.thread.get_threads_review(boardname, 20, 3)) @app.route('/') def root(): return redirect('/boards/{}'.format(models.board.get_random_board())) #@app.route('/create_post', methods=['GET', 'POST']) #def create_post(): # champs = [ # 'titre', # 'contenu' # ] # # if request.method == 'GET': # return render_template('post.html', champs=champs, form={}, errors={}) # else: # form = request.form # result = validate(form, champs) # # if result['valid']: # user = models.User.get_user('toot') # models.Post.insert('toot', result['form']['titre'], result['form']['contenu']) # return redirect('/') # # else: # return render_template('post.html', # champs=champs, # form=result['form'], # errors=result['errors']) # # #def validate(form, champs): # result = {'valid': True, 'form': form, 'errors': {}} # for champ in champs: # result['valid'] = result['valid'] and champ_requis(form, champ, errors=result['errors']) # # return result # #def champ_requis(form, champ, errors): # if form.get(champ, None) == '': # errors[champ] = 'le champ {} est requis'.format(champ) # return False # else: # return True
35.103286
128
0.570817
830
7,477
5.063855
0.23494
0.049726
0.029979
0.016179
0.306924
0.290269
0.228884
0.207947
0.187009
0.161789
0
0.003127
0.27297
7,477
212
129
35.268868
0.770052
0.307744
0
0.235772
0
0
0.128672
0
0
0
0
0
0
0
null
null
0.089431
0.056911
null
null
0.073171
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
2
b3e388297ce0c73ba9eddb04d2d2199bfb28b6a2
11,450
py
Python
main_test.py
OniriCorpe/Motion
ee617b0f183c177e63b52fb91f52ede6eb1b1f83
[ "WTFPL" ]
null
null
null
main_test.py
OniriCorpe/Motion
ee617b0f183c177e63b52fb91f52ede6eb1b1f83
[ "WTFPL" ]
null
null
null
main_test.py
OniriCorpe/Motion
ee617b0f183c177e63b52fb91f52ede6eb1b1f83
[ "WTFPL" ]
null
null
null
#!/usr/bin/env python """ The test file to use with pytest. '(motion-venv) $ python -m pytest main_test.py' """ import main def test_calculate_date_delta(): """ Tests that the function calculate_date_delta(date_start, date_now) calculates correctly the number of days between two dates. """ assert main.calculate_date_delta("2042-12-13", "2042-12-10") == 3 assert main.calculate_date_delta("2014-02-13", "2014-02-14") == 1 assert main.calculate_date_delta("1891-03-11", "1891-03-18") == 7 assert main.calculate_date_delta("1871-03-18", "1995-02-14") == 45258 def test_agenda_format_day(): """ Tests that the function agenda_format_day( number_of_days_before, date_start, cfg_today, cfg_tomorrow, cfg_in_days,) formats properly a the string. """ assert ( main.agenda_format_day( 0, "2022-13-12", "ajd", "dem", " j", ) == "ajd" ) assert ( main.agenda_format_day( 0, "2021-05-10T13:12:00", "ajd", "dem", " j", ) == "13:12" ) assert ( main.agenda_format_day( 1, "2022-13-12", "ajd", "dem", " j", ) == "dem" ) assert ( main.agenda_format_day( 2, "2022-13-12", "ajd", "dem", " j", ) == "2 j" ) assert ( main.agenda_format_day( 3, "2022-13-12", "ajd", "dem", " j", ) == "3 j" ) def test_agenda_results(): """ Tests that the function agenda_results(data) formats correctly under all conditions. """ assert not main.agenda_results( {"results": []}, "2022-01-15", "Date", "Nom", ) assert ( main.agenda_results( { "results": [ { "properties": { "Date": { "date": { "start": "2022-12-13", "end": None, }, }, "Nom": { "title": [ { "plain_text": "test 1", } ], }, }, } ], }, "2022-12-13", "Date", "Nom", ) == [("ajd", "test 1")], ) assert ( main.agenda_results( { "results": [ { "properties": { "Date": { "date": { "start": "2022-12-13T13:12:00.000+01:00", "end": None, }, }, "Nom": { "title": [ { "plain_text": "test heure", } ], }, }, } ], }, "2022-12-13", "Date", "Nom", ) == [("13:12", "test heure")], ) assert main.agenda_results( { "results": [ { "properties": { "Date": { "date": { "start": "2022-12-08", "end": None, }, }, "Nom": { "title": [ { "plain_text": "test 1", } ], }, }, }, { "properties": { "Date": { "date": { "start": "2022-12-08T13:12:00.000+01:00", "end": None, }, }, "Nom": { "title": [ { "plain_text": "test heure 2", } ], }, }, }, { "properties": { "Date": { "date": { "start": "2022-12-09T13:12:00.000+01:00", "end": None, }, }, "Nom": { "title": [ { "plain_text": "test 3", } ], }, }, }, { "properties": { "Date": { "date": { "start": "2022-12-11", "end": "2022-12-12", }, }, "Nom": { "title": [ { "plain_text": "test 4", } ], }, }, }, { "properties": { "Date": { "date": { "start": "2022-12-12T13:00:00.000+01:00", "end": "2022-12-14T12:00:00.000+01:00", }, }, "Nom": { "title": [ { "plain_text": "test 5", } ], }, }, }, ], }, "2022-12-08", "Date", "Nom", ) == [ ("ajd", "test 1"), ("13:12", "test heure 2"), ("dem", "test 3"), ("3 j", "test 4"), ("4 j", "test 5"), ] def test_meds_results(): """ Tests that the function meds_results(data) formats correctly under all conditions. """ assert not main.meds_results({"results": []}) assert main.meds_results( { "results": [ { "properties": { "NbRefill": { "formula": {"number": 1}, }, "Nom": { "title": [ { "plain_text": "test 1", } ], }, }, } ], } ) == ["test 1 : ≥1"] assert main.meds_results( { "results": [ { "properties": { "NbRefill": { "formula": {"number": 1}, }, "Nom": { "title": [ { "plain_text": "test 1", } ], }, }, }, { "properties": { "NbRefill": { "formula": {"number": 2}, }, "Nom": { "title": [ { "plain_text": "test 2", } ], }, }, }, ] } ) == ["test 1 : ≥1", "test 2 : ≥2"] def test_int_to_tuple(): """ Tests that the function int_to_tuple() returns tuples. """ assert main.int_to_tuple(1) == (1,) assert main.int_to_tuple((2,)) == (2,) assert main.int_to_tuple((3, )) == (3,) # fmt: skip assert main.int_to_tuple((4, 5)) == (4, 5) assert main.int_to_tuple((6,7)) == (6, 7) # fmt: skip def test_generate_custom_text(): """ Tests that the function generate_custom_text() returns good data. """ assert main.generate_custom_text([], 2, 14) == "" assert main.generate_custom_text([["test not today", 2]], 1, 14) == "" assert main.generate_custom_text([["test not today tuple", (2, 3)]], 1, 14) == "" assert main.generate_custom_text([["test today", 2]], 2, 14) == "test today" assert ( main.generate_custom_text([["test today tuple", (0, 2)]], 2, 14) == "test today tuple" ) assert main.generate_custom_text([["odd", "test odd", 2]], 2, 14) == "test odd" assert ( main.generate_custom_text([["odd", "test odd tuple", (2, 5)]], 2, 14) == "test odd tuple" ) assert main.generate_custom_text([["even", "test even", 2]], 2, 15) == "test even" assert ( main.generate_custom_text([["even", "test even tuple", (2, 6)]], 2, 15) == "test even tuple" ) assert main.generate_custom_text([["even", "test not even", 2]], 2, 14) == "" assert ( main.generate_custom_text([["even", "test not even tuple", (2, 6)]], 2, 14) == "" ) assert main.generate_custom_text([["odd", "test not odd", 2]], 2, 15) == "" assert ( main.generate_custom_text([["odd", "test not odd tuple", (2, 6)]], 2, 15) == "" ) assert ( main.generate_custom_text( [["test multiple lists not today", 2], ["test multiple lists", 3]], 1, 14 ) == "" ) assert ( main.generate_custom_text( [ ["test multiple lists not today tuple", (2, 4)], ["test multiple lists 2", 3], ], 1, 14, ) == "" ) assert ( main.generate_custom_text( [["test multiple lists 1", 2], ["test multiple lists 2", 1]], 1, 14 ) == "test multiple lists 2" ) assert ( main.generate_custom_text( [["test multiple lists 1 tuple", (2, 5)], ["test multiple lists 2", 1]], 1, 14, ) == "test multiple lists 2" )
29.060914
88
0.291179
810
11,450
3.976543
0.144444
0.111767
0.106178
0.126669
0.706302
0.522509
0.453275
0.429991
0.360137
0.267308
0
0.090433
0.582795
11,450
393
89
29.13486
0.583211
0.061572
0
0.431487
0
0
0.154187
0.013657
0
0
0
0
0.110787
1
0.017493
true
0
0.002915
0
0.020408
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
2
b3eabfc5d1919b5ecce2863be161ba0e44633f43
5,955
py
Python
Project-4/python_template/mogEM.py
ybhan/Machine-Learning-Projects
80301a774247bb6ad11cccaeef54e9ec588a61b0
[ "MIT" ]
null
null
null
Project-4/python_template/mogEM.py
ybhan/Machine-Learning-Projects
80301a774247bb6ad11cccaeef54e9ec588a61b0
[ "MIT" ]
null
null
null
Project-4/python_template/mogEM.py
ybhan/Machine-Learning-Projects
80301a774247bb6ad11cccaeef54e9ec588a61b0
[ "MIT" ]
null
null
null
from kmeans import * import sys import matplotlib.pyplot as plt plt.ion() def mogEM(x, K, iters, minVary=0): """ Fits a Mixture of K Gaussians on x. Inputs: x: data with one data vector in each column. K: Number of Gaussians. iters: Number of EM iterations. minVary: minimum variance of each Gaussian. Returns: p : probabilities of clusters. mu = mean of the clusters, one in each column. vary = variances for the cth cluster, one in each column. logProbX = log-probability of data after every iteration. """ N, T = x.shape # Initialize the parameters randConst = 1 p = randConst + np.random.rand(K, 1) p = p / np.sum(p) mn = np.mean(x, axis=1).reshape(-1, 1) vr = np.var(x, axis=1).reshape(-1, 1) # Change the initializaiton with Kmeans here # -------------------- Add your code here -------------------- mu = mn + np.random.randn(N, K) * (np.sqrt(vr) / randConst) # ------------------------------------------------------------ vary = vr * np.ones((1, K)) * 2 vary = (vary >= minVary) * vary + (vary < minVary) * minVary logProbX = np.zeros((iters, 1)) # Do iters iterations of EM for i in xrange(iters): # Do the E step respTot = np.zeros((K, 1)) respX = np.zeros((N, K)) respDist = np.zeros((N, K)) logProb = np.zeros((1, T)) ivary = 1 / vary logNorm = np.log(p) - 0.5 * N * np.log(2 * np.pi) - \ 0.5 * np.sum(np.log(vary), axis=0).reshape(-1, 1) logPcAndx = np.zeros((K, T)) for k in xrange(K): dis = (x - mu[:, k].reshape(-1, 1))**2 logPcAndx[k, :] = logNorm[k] - 0.5 * \ np.sum(ivary[:, k].reshape(-1, 1) * dis, axis=0) mxi = np.argmax(logPcAndx, axis=1).reshape(1, -1) mx = np.max(logPcAndx, axis=0).reshape(1, -1) PcAndx = np.exp(logPcAndx - mx) Px = np.sum(PcAndx, axis=0).reshape(1, -1) PcGivenx = PcAndx / Px logProb = np.log(Px) + mx logProbX[i] = np.sum(logProb) print 'Iter %d logProb %.5f' % (i, logProbX[i]) # Plot log prob of data plt.figure(1) plt.clf() plt.plot(np.arange(i), logProbX[:i], 'r-') plt.title('Log-probability of data versus # iterations of EM') plt.xlabel('Iterations of EM') plt.ylabel('log P(D)') plt.draw() respTot = np.mean(PcGivenx, axis=1).reshape(-1, 1) respX = np.zeros((N, K)) respDist = np.zeros((N, K)) for k in xrange(K): respX[:, k] = np.mean(x * PcGivenx[k, :].reshape(1, -1), axis=1) respDist[:, k] = np.mean((x - mu[:, k].reshape(-1, 1))**2 * PcGivenx[k, :].reshape(1, -1), axis=1) # Do the M step p = respTot mu = respX / respTot.T vary = respDist / respTot.T vary = (vary >= minVary) * vary + (vary < minVary) * minVary return p, mu, vary, logProbX def mogLogProb(p, mu, vary, x): """Computes logprob of each data vector in x under the MoG model specified by p, mu and vary.""" K = p.shape[0] N, T = x.shape ivary = 1 / vary logProb = np.zeros(T) for t in xrange(T): # Compute log P(c)p(x|c) and then log p(x) logPcAndx = np.log(p) - 0.5 * N * np.log(2 * np.pi) \ - 0.5 * np.sum(np.log(vary), axis=0).reshape(-1, 1) \ - 0.5 * \ np.sum(ivary * (x[:, t].reshape(-1, 1) - mu) ** 2, axis=0).reshape(-1, 1) mx = np.max(logPcAndx, axis=0) logProb[t] = np.log(np.sum(np.exp(logPcAndx - mx))) + mx return logProb def q3(): iters = 10 minVary = 0.01 (inputs_train, inputs_valid, inputs_test, target_train, target_valid, target_test) = LoadData('digits.npz') # Train a MoG model with 20 components on all 600 training # vectors, with both original initialization and kmeans initialization. # ------------------- Add your code here --------------------- raw_input('Press Enter to continue.') def q4(): iters = 10 minVary = 0.01 errorTrain = np.zeros(4) errorTest = np.zeros(4) errorValidation = np.zeros(4) print(errorTrain) numComponents = np.array([2, 5, 15, 25]) T = numComponents.shape[0] (inputs_train, inputs_valid, inputs_test, target_train, target_valid, target_test) = LoadData('digits.npz') (train2, valid2, test2, target_train2, target_valid2, target_test2) = LoadData('digits.npz', True, False) (train3, valid3, test3, target_train3, target_valid3, target_test3) = LoadData('digits.npz', False, True) for t in xrange(T): K = numComponents[t] # Train a MoG model with K components for digit 2 # -------------------- Add your code here -------------------- # Train a MoG model with K components for digit 3 # -------------------- Add your code here -------------------- # Caculate the probability P(d=1|x) and P(d=2|x), # classify examples, and compute error rate # Hints: you may want to use mogLogProb function # -------------------- Add your code here -------------------- # Plot the error rate plt.clf() # -------------------- Add your code here -------------------- plt.draw() raw_input('Press Enter to continue.') def q5(): # Choose the best mixture of Gaussian classifier you have, compare this # mixture of Gaussian classifier with the neural network you implemented in # the last assignment. # Train neural network classifier. The number of hidden units should be # equal to the number of mixture components. # Show the error rate comparison. # -------------------- Add your code here -------------------- raw_input('Press Enter to continue.') if __name__ == '__main__': q3() q4() q5()
33.083333
79
0.538539
823
5,955
3.861482
0.253949
0.03776
0.04248
0.03304
0.292637
0.237885
0.228446
0.171177
0.171177
0.129012
0
0.027992
0.280101
5,955
179
80
33.268156
0.713319
0.229051
0
0.247525
0
0
0.053831
0
0
0
0
0.011173
0
0
null
null
0
0.029703
null
null
0.019802
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
1
0
0
0
0
0
0
0
0
2
b604cff0636c7f5ed2000c437822c2e55deb7a04
5,307
py
Python
model.py
NerdToMars/Fringe-pattern-denoising-based-on-deep-learning
23dea6bcd4d43568d458cb3ac748dbd5cd7d0cf2
[ "BSD-2-Clause" ]
5
2019-03-01T07:42:29.000Z
2021-04-18T16:47:06.000Z
model.py
NerdToMars/Fringe-pattern-denoising-based-on-deep-learning
23dea6bcd4d43568d458cb3ac748dbd5cd7d0cf2
[ "BSD-2-Clause" ]
null
null
null
model.py
NerdToMars/Fringe-pattern-denoising-based-on-deep-learning
23dea6bcd4d43568d458cb3ac748dbd5cd7d0cf2
[ "BSD-2-Clause" ]
5
2019-01-10T20:59:14.000Z
2020-09-15T01:33:19.000Z
""" This script demonstrates the use of a convolutional LSTM network. This network is used to predict the next frame of an artificially generated movie which contains moving squares. """ from keras.models import Sequential from keras.layers.convolutional import Conv3D from keras.layers.convolutional_recurrent import ConvLSTM2D from keras.layers.normalization import BatchNormalization import numpy as np import pylab as plt import skimage.transform import tensorflow as tf import keras import keras.backend as K import keras.layers as KL import keras.engine as KE import keras.models as KM from keras.models import * from keras.layers import * from keras.optimizers import * from keras.callbacks import ModelCheckpoint, LearningRateScheduler from keras import backend as keras def getBiConvLSTM2d(input_image,filters,kernel_size,name): L1 = KL.Bidirectional(KL.ConvLSTM2D(filters=filters, kernel_size=kernel_size,activation='relu', padding='same', return_sequences=True))(input_image) L1 = KL.BatchNormalization(name="batchNormL_"+name)(L1) return L1 def unet(inputs): conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs) conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1) pool1 = MaxPooling2D(pool_size=(2, 2))(conv1) conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1) conv2 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2) pool2 = MaxPooling2D(pool_size=(2, 2))(conv2) conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2) conv3 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3) pool3 = MaxPooling2D(pool_size=(2, 2))(conv3) conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3) conv4 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4) drop4 = Dropout(0.5)(conv4) print(conv4) pool4 = MaxPooling2D(pool_size=(2, 2))(drop4) conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4) conv5 = Conv2D(1024, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5) drop5 = Dropout(0.5)(conv5) up6 = Conv2D(512, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5)) print(drop4) print(up6) merge6 = concatenate([drop4,up6], axis = 3) conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge6) conv6 = Conv2D(512, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6) up7 = Conv2D(256, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6)) merge7 = concatenate([conv3,up7], axis = 3) conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge7) conv7 = Conv2D(256, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7) up8 = Conv2D(128, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7)) merge8 = concatenate([conv2,up8], axis = 3) conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge8) conv8 = Conv2D(128, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8) up9 = Conv2D(64, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8)) merge9 = concatenate([conv1,up9], axis = 3) conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(merge9) conv9 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9) conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9) conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9) return conv10 def LSTMUnet(): ''' Input frame, with size 8*256*256*1 numpy array ''' row = 256 col = 256 input_image = KL.Input(shape=[8, row,col,1], name="input_image") L4 = input_image for i in range(3): L4 = getBiConvLSTM2d(L4,filters=20, kernel_size=(3, 3),name='top'+str(i)) L5 = KL.Conv3D(filters=8, kernel_size=(3, 3, 8), activation='relu', padding='same', data_format='channels_last')(L4) # L5 = KL.BatchNormalization(name="batchNormL_sel5")(L5) L6 = KL.Conv3D(filters=1, kernel_size=(3, 3, 4), activation='relu', padding='same', data_format='channels_last')(L5) L6 = KL.BatchNormalization(name="batchNormL_sel5")(L6) L7 = KL.Conv3D(filters=1, kernel_size=(3, 3, 8), activation='relu', padding='same', data_format='channels_first')(L6) L7 = Reshape((row,col,1))(L7) seg = unet(L7) model = KM.Model(input_image,seg) model.compile(loss='mean_squared_error', optimizer='adadelta') return model
50.066038
152
0.679292
690
5,307
5.114493
0.224638
0.107113
0.160669
0.191272
0.534996
0.488524
0.488524
0.488524
0.461604
0.461604
0
0.065193
0.173356
5,307
105
153
50.542857
0.73923
0.052949
0
0.036145
1
0
0.107136
0
0
0
0
0
0
1
0.036145
false
0
0.216867
0
0.289157
0.036145
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2