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
e372ca50f1bbb91d278a5aa868f3b3246267b836
4,886
py
Python
python/tests/pyspark/feature/string_map_test.py
voganrc/mleap
68cbf375968d9f55acb1d673a4c2390602c0274a
[ "Apache-2.0" ]
1,401
2017-01-07T03:34:44.000Z
2022-03-31T22:17:58.000Z
python/tests/pyspark/feature/string_map_test.py
liang0/mleap
41dbde99e389873fc609083cce5d610cea9e9170
[ "Apache-2.0" ]
546
2016-12-30T19:10:55.000Z
2022-03-31T16:56:52.000Z
python/tests/pyspark/feature/string_map_test.py
liang0/mleap
41dbde99e389873fc609083cce5d610cea9e9170
[ "Apache-2.0" ]
326
2017-01-24T10:35:41.000Z
2022-03-15T15:53:17.000Z
import os import tempfile import unittest from py4j.protocol import Py4JJavaError from pyspark.ml import Pipeline from pyspark.sql import types as t from mleap.pyspark.feature.string_map import StringMap from mleap.pyspark.spark_support import SimpleSparkSerializer from tests.pyspark.lib.assertions import assert_df from tests.pyspark.lib.spark_session import spark_session INPUT_SCHEMA = t.StructType([t.StructField('key_col', t.StringType(), False), t.StructField('extra_col', t.StringType(), False)]) OUTPUT_SCHEMA = t.StructType([t.StructField('key_col', t.StringType(), False), t.StructField('extra_col', t.StringType(), False), t.StructField('value_col', t.DoubleType(), False)]) class StringMapTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.spark = spark_session() @classmethod def tearDownClass(cls): cls.spark.stop() def setUp(self): self.input = StringMapTest.spark.createDataFrame([['a', 'b']], INPUT_SCHEMA) def test_map(self): result = StringMap( labels={'a': 1.0}, inputCol='key_col', outputCol='value_col', ).transform(self.input) expected = StringMapTest.spark.createDataFrame([['a', 'b', 1.0]], OUTPUT_SCHEMA) assert_df(expected, result) def test_map_default_value(self): result = StringMap( labels={'z': 1.0}, inputCol='key_col', outputCol='value_col', handleInvalid='keep', ).transform(self.input) expected = StringMapTest.spark.createDataFrame([['a', 'b', 0.0]], OUTPUT_SCHEMA) assert_df(expected, result) def test_map_custom_default_value(self): result = StringMap( labels={'z': 1.0}, inputCol='key_col', outputCol='value_col', handleInvalid='keep', defaultValue=-1.0 ).transform(self.input) expected = StringMapTest.spark.createDataFrame([['a', 'b', -1.0]], OUTPUT_SCHEMA) assert_df(expected, result) def test_map_missing_value_error(self): with self.assertRaises(Py4JJavaError) as error: StringMap( labels={'z': 1.0}, inputCol='key_col', outputCol='value_col' ).transform(self.input).collect() self.assertIn('java.util.NoSuchElementException: Missing label: a', str(error.exception)) def test_map_from_dataframe(self): labels_df = StringMapTest.spark.createDataFrame([['a', 1.0]], 'key_col: string, value_col: double') result = StringMap.from_dataframe( labels_df=labels_df, inputCol='key_col', outputCol='value_col' ).transform(self.input) expected = StringMapTest.spark.createDataFrame([['a', 'b', 1.0]], OUTPUT_SCHEMA) assert_df(expected, result) def test_serialize_to_bundle(self): string_map = StringMap( labels={'a': 1.0}, inputCol='key_col', outputCol='value_col', ) pipeline = Pipeline(stages=[string_map]).fit(self.input) serialization_dataset = pipeline.transform(self.input) jar_file_path = _serialize_to_file(pipeline, serialization_dataset) deserialized_pipeline = _deserialize_from_file(jar_file_path) result = deserialized_pipeline.transform(self.input) expected = StringMapTest.spark.createDataFrame([['a', 'b', 1.0]], OUTPUT_SCHEMA) assert_df(expected, result) @staticmethod def test_validate_handleInvalid_ok(): StringMap(labels={}, handleInvalid='error') def test_validate_handleInvalid_bad(self): with self.assertRaises(AssertionError): StringMap(labels=None, inputCol=dict(), outputCol=None, handleInvalid='invalid') def test_validate_labels_type_fails(self): with self.assertRaises(AssertionError): StringMap(labels=None, inputCol=set(), outputCol=None) def test_validate_labels_key_fails(self): with self.assertRaises(AssertionError): StringMap(labels=None, inputCol={False: 0.0}, outputCol=None) def test_validate_labels_value_fails(self): with self.assertRaises(AssertionError): StringMap(labels=None, inputCol={'valid_key_type': 'invalid_value_type'}, outputCol=None) def _serialize_to_file(model, df_for_serializing): jar_file_path = _to_jar_file_path( os.path.join(tempfile.mkdtemp(), 'test_serialize_to_bundle-pipeline.zip')) SimpleSparkSerializer().serializeToBundle(model, jar_file_path, df_for_serializing) return jar_file_path def _to_jar_file_path(path): return "jar:file:" + path def _deserialize_from_file(path): return SimpleSparkSerializer().deserializeFromBundle(path)
36.192593
107
0.657388
548
4,886
5.633212
0.213504
0.024943
0.028507
0.077098
0.484937
0.460641
0.434726
0.434726
0.434726
0.39391
0
0.007668
0.225952
4,886
134
108
36.462687
0.808567
0
0
0.380952
0
0
0.068973
0.014327
0
0
0
0
0.114286
1
0.161905
false
0
0.095238
0.019048
0.295238
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
0
0
0
1
0
e374d42c0a5b986cfc32f92436749b7345991388
4,210
py
Python
stocks.py
nicojapas/algorithmic_trading
46b2b59253638f15858e44b4ebae39eb222a4619
[ "MIT" ]
1
2021-03-16T12:11:47.000Z
2021-03-16T12:11:47.000Z
stocks.py
nicojapas/algorithmic_trading
46b2b59253638f15858e44b4ebae39eb222a4619
[ "MIT" ]
null
null
null
stocks.py
nicojapas/algorithmic_trading
46b2b59253638f15858e44b4ebae39eb222a4619
[ "MIT" ]
1
2022-01-14T21:48:08.000Z
2022-01-14T21:48:08.000Z
#!/usr/bin/env python # coding: utf-8 # In[6]: import pandas as pd import io import requests import time import random # In[3]: # gets the hidden API keys api_key = pd.read_csv('secrets.csv').api_key.to_string().split()[1] # In[124]: # gets data using user's parameters def get_data(symbol, interval): """ Signature: get_data(symbol, period) -> 'DataFrame' Docstring: Retrieves market data for the selected symbol and period. Parameters ---------- symbol : str The name of the equity of your choice. For example: symbol=GOOGL. interval : str Time interval between two consecutive data points in the time series. The following values are supported: 1min, 5min, 15min, 30min, 60min. Returns ------- DataFrame Examples -------- >>> get_data('GOOGL', '60min') """ # main url or alphavantage and selection of features from user BASE_URL = 'https://www.alphavantage.co/query?' q = { 'function':'TIME_SERIES_INTRADAY_EXTENDED', 'symbol':symbol, 'interval':interval, 'slice':'year1month1', 'apikey':'KO4L9YMRD2VLJX8O' } df=pd.DataFrame() for y in range(1,3): for m in range(1,13): # create 'slices' of 1 month each. has to do with how the api functions q['slice'] = f'year{y}month{m}' # concatenate all user's selected values into one string q_str = "".join([i for i in [str(i) + "=" + str(q[i]) + "&" for i in q]])[:-1] # concatenate the base alphavantage url with the user's query url = BASE_URL + q_str print(url) # GET url response = requests.get(url) # read data into a pandas dataframe df=pd.concat([df, pd.read_csv(io.StringIO(response.content.decode('utf-8')))], axis=0) # because the free api has a limit of 5 calls per minute, we need to wait time.sleep(60/5) # returns a dataframe return(df) # In[125]: # auto complete function for stocks def auto_complete_stocks(x): """ Signature: auto_complete_stocks(str) -> 'json' Docstring: Makes use of the auto-completion function of Alpha Vantage API. It takes the user's input and returns a json with the coincidences. Parameters ---------- symbol : str A string containing part of the symbol or description of the equity. For example 'amaz' would return the symbol and description for AMZN stocks, etc. Returns ------- json """ BASE_URL = 'https://www.alphavantage.co/query?' url = f'https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords={x}&datatype=json&apikey={api_key}' response = requests.get(url).json() return(response) # In[ ]: # to fetch all updated stocks and ETFs supported def get_supported_stocks(): """ Signature: get_supported_stocks() -> 'DataFrame' Docstring: Retrieves the supported list of stocks and ETFs from Alpha Vantage, using their API. See https://www.alphavantage.co/ Returns ------- DataFrame Examples -------- >>> get_supported_stocks() """ BASE_URL = 'https://www.alphavantage.co/query?' url = f'https://www.alphavantage.co/query?function=LISTING_STATUS&apikey={api_key}' response = requests.get(url) x=pd.read_csv(io.StringIO(response.content.decode('utf-8'))) return(x) # In[ ]: # to fetch all updated stocks and ETFs supported # static version loading from .csv previously downloaded def get_supported_stocks_static(): """ Signature: get_supported_stocks() -> 'DataFrame' Docstring: Retrieves the supported list of stocks and ETFs from Alpha Vantage, using their API. This 'static' version loads the list from a .csv file. Returns ------- DataFrame Examples -------- >>> get_supported_stocks() """ x = pd.read_csv('data/stocks_etfs_list.csv') l1 = x['symbol'].to_list() l2 = x['name'].to_list() l3 = [str(i) + " - " + str(j) for i, j in zip(l1, l2)] return(l1, l2, l3)
24.195402
113
0.611639
555
4,210
4.56036
0.331532
0.018965
0.047412
0.052153
0.288424
0.288424
0.255235
0.214935
0.214935
0.182537
0
0.015484
0.263658
4,210
173
114
24.33526
0.800968
0.499762
0
0.116279
0
0.023256
0.246273
0.029818
0
0
0
0
0
1
0.093023
false
0
0.116279
0
0.209302
0.023256
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
e37917c4d561fd8d9c4ecc0de859e1c2d60e6398
1,834
py
Python
statdpwrapper/experiments/exp_without_pp.py
barryZZJ/dp-sniper
71a3fc06f3fc319b023bde9aad8f05b8c5a47a80
[ "MIT" ]
13
2021-03-30T15:39:35.000Z
2022-02-21T08:30:45.000Z
statdpwrapper/experiments/exp_without_pp.py
barryZZJ/dp-sniper
71a3fc06f3fc319b023bde9aad8f05b8c5a47a80
[ "MIT" ]
null
null
null
statdpwrapper/experiments/exp_without_pp.py
barryZZJ/dp-sniper
71a3fc06f3fc319b023bde9aad8f05b8c5a47a80
[ "MIT" ]
4
2021-06-30T08:37:45.000Z
2022-03-05T03:21:14.000Z
import os from dpsniper.utils.my_multiprocessing import initialize_parallel_executor from dpsniper.utils.paths import get_output_directory, set_output_directory from statdpwrapper.algorithms_ext import * from statdpwrapper.experiments.base import run_statdp from statdpwrapper.experiments.mechanism_config import statdp_mechanism_map, statdp_arguments_map,\ statdp_postprocessing_map, statdp_sensitivity_map, statdp_num_inputs_map def _get_mechanism(alg_name: str): if alg_name not in statdp_mechanism_map: raise ValueError("Unknown mechanism {}".format(alg_name)) return statdp_mechanism_map[alg_name] def run_without_postprocessing(n_processes: int, out_dir: str, alg_name: str): mechanism = _get_mechanism(alg_name) kwargs = statdp_arguments_map[alg_name] pp_config = statdp_postprocessing_map[alg_name] num_inputs = statdp_num_inputs_map[alg_name] sensitivity = statdp_sensitivity_map[alg_name] log.configure("WARNING") set_output_directory(out_dir) logs_dir = get_output_directory("logs") log_file = os.path.join(logs_dir, "original_statdp_{}_log.log".format(alg_name)) data_file = os.path.join(logs_dir, "original_statdp_{}_data.log".format(alg_name)) if os.path.exists(log_file): log.warning("removing existing log file '%s'", log_file) os.remove(log_file) if os.path.exists(data_file): log.warning("removing existing log file '%s'", data_file) os.remove(data_file) log.configure("INFO", log_file=log_file, data_file=data_file, file_level="INFO") with initialize_parallel_executor(n_processes, out_dir): # run StatDP with disabled postprocessing pp_config.disable_pp = True run_statdp(alg_name, mechanism, pp_config, num_inputs, sensitivity, kwargs) log.info("finished experiment")
41.681818
99
0.768811
255
1,834
5.164706
0.282353
0.069096
0.037965
0.027335
0.110858
0.110858
0.110858
0.110858
0
0
0
0
0.143402
1,834
43
100
42.651163
0.83832
0.021265
0
0
0
0
0.096486
0.029559
0
0
0
0
0
1
0.060606
false
0
0.181818
0
0.272727
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
0
0
0
1
0
e37a1fef8ba0d57e0296169fc7cb4fee0cc149e2
1,134
py
Python
ants/registration/symimg.py
ncullen93/ANTsPy
a4c990dcd5b7445a45ce7b366ee018c7350e7d9f
[ "Apache-2.0" ]
3
2018-06-07T19:11:47.000Z
2019-06-10T05:24:06.000Z
ants/registration/symimg.py
ncullen93/ANTsPy
a4c990dcd5b7445a45ce7b366ee018c7350e7d9f
[ "Apache-2.0" ]
null
null
null
ants/registration/symimg.py
ncullen93/ANTsPy
a4c990dcd5b7445a45ce7b366ee018c7350e7d9f
[ "Apache-2.0" ]
1
2019-04-04T06:18:44.000Z
2019-04-04T06:18:44.000Z
__all__ = ['symimg'] from tempfile import mktemp from .reflect_image import reflect_image from .interface import registration from .apply_transforms import apply_transforms from ..core import image_io as iio def symimg(img, gs=0.25): """ Symmetrize an image Example ------- >>> import ants >>> img = ants.image_read( ants.get_ants_data('r16') , 'float') >>> simg = ants.symimg(img) """ imgr = reflect_image(img, axis=0) imgavg = imgr * 0.5 + img for i in range(5): w1 = registration(imgavg, img, type_of_transform='SyN') w2 = registration(imgavg, imgr, type_of_transform='SyN') xavg = w1['warpedmovout']*0.5 + w2['warpedmovout']*0.5 nada1 = apply_transforms(img, img, w1['fwdtransforms'], compose=w1['fwdtransforms'][0]) nada2 = apply_transforms(img, img, w2['fwdtransforms'], compose=w2['fwdtransforms'][0]) wavg = (iio.image_read(nada1) + iio.image_read(nada2)) * (-0.5) wavgfn = mktemp(suffix='.nii.gz') iio.image_write(wavg, wavgfn) xavg = apply_transforms(img, imgavg, wavgfn) return xavg
27.658537
95
0.636684
147
1,134
4.755102
0.394558
0.107296
0.077253
0.051502
0
0
0
0
0
0
0
0.032805
0.220459
1,134
40
96
28.35
0.757919
0.126984
0
0
0
0
0.1
0
0
0
0
0
0
1
0.05
false
0
0.25
0
0.35
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
0
0
0
1
0
e37b5fbe24287ac8297fbe7f44ed3c806e40c97b
3,775
py
Python
src/facrecog_core.py
GaussQR/cs305-g01
06b1ad9ba2d05e7c76ee10eb053e9d091b070d6d
[ "MIT" ]
null
null
null
src/facrecog_core.py
GaussQR/cs305-g01
06b1ad9ba2d05e7c76ee10eb053e9d091b070d6d
[ "MIT" ]
null
null
null
src/facrecog_core.py
GaussQR/cs305-g01
06b1ad9ba2d05e7c76ee10eb053e9d091b070d6d
[ "MIT" ]
null
null
null
import dlib import face_recognition import glob import pickle import cv2 import numpy as np import os from PIL import Image,ImageFont, ImageDraw, ImageEnhance def add_target_faces(path): faces = {} for img in glob.glob(path + "/*.jpg"): print("encoding img...") f_image = face_recognition.load_image_file(img) x = face_recognition.face_encodings(f_image)[0] name = img.split('/')[1].split('.')[0] # if faces.get(name) is None: # faces[name] = [] faces[name] = x with open('encoded_faces.pkl', 'wb') as fp: pickle.dump(faces, fp) def load_encoded_faces(path_file='encoded_faces.pkl'): return pickle.load(open(path_file,'rb')) def identify_faces_image(img, faces, save_output=0, isfile=0): print(save_output) face_enc, name_face = list(faces.values()), list(faces.keys()) # Loading face encoding along with their names. group_img = face_recognition.load_image_file(img) if isfile == 0 else img coordinates = face_recognition.face_locations(group_img) face_encodings = face_recognition.face_encodings(group_img) src_img = Image.open(img).convert("RGB") if isfile == 0 else Image.fromarray(img).convert('RGB') draw = ImageDraw.Draw(src_img) face_in_img = [] # print(img," contains faces: ") for (c,each_encoding) in zip(coordinates,face_encodings): results = face_recognition.compare_faces(face_enc, each_encoding, 0.5) indices = [i for i, value in enumerate(results) if value == True] # Should be one # assert(len(indices) == 1) for index in indices: recog_name = name_face[index] face_in_img.append((recog_name, c)) if save_output: draw.rectangle(((c[3],c[0]), (c[1],c[2])), outline='red') draw.text((c[3]+1, c[2]-1), recog_name, font = ImageFont.truetype('arial.ttf', 160)) if save_output: if 'output' not in os.listdir(): os.mkdir('output') src_img.save('output/' + img.split('/')[-1]) return face_in_img def identify_faces_images(path_folder, faces, save_output=0): faces_in_folder = [] for img in glob.glob(path_folder + "/*.jpg"): faces_in_folder.append(identify_faces_image(img, faces, save_output)) return faces_in_folder # from google.colab.patches import cv2_imshow def identify_faces_video(path_video, faces, show_output=0): cap = cv2.VideoCapture(path_video) frate = cap.get(cv2.CAP_PROP_FPS) faces_in_video = [] i = 0 while cap.isOpened(): ret, frame = cap.read() if ret == False: break i += 1 if i % frate != 1: continue # frame = cv2.resize(frame, (0, 0), fx = 0.25, fy = 0.25) frame = np.array(frame[:, :, ::-1]) # print(frame.shape) res = identify_faces_image(frame, faces, isfile=1) #[(name, coordin)] faces_in_video.append(res) if show_output: for (name, (top, right, bottom, left)) in res: # top, right, bottom, left = map(int, [top, right, bottom, left]) # print((top, right, bottom, left)) cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) frame = frame[:, :, ::-1] cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break return faces_in_video add_target_faces('known') faces = load_encoded_faces('encoded_faces.pkl') identify_faces_video('al.mp4', faces, 1)
41.944444
115
0.614834
526
3,775
4.23384
0.292776
0.047149
0.031432
0.03233
0.092501
0.078132
0.03233
0
0
0
0
0.028441
0.245563
3,775
90
116
41.944444
0.753511
0.10702
0
0.026667
0
0
0.042508
0
0
0
0.001223
0
0
1
0.066667
false
0
0.106667
0.013333
0.226667
0.026667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
e37d41115e68a3191b6a2c67d0ba9d33fd342473
378
py
Python
pulpo_forms_example/urls.py
pulpocoders/pulpo-forms-examples
8b9121b8e323b9432d17f7fc0812405668df3b04
[ "Apache-2.0" ]
3
2015-11-05T00:23:32.000Z
2017-05-02T15:24:11.000Z
pulpo_forms_example/urls.py
pulpocoders/pulpo-forms-examples
8b9121b8e323b9432d17f7fc0812405668df3b04
[ "Apache-2.0" ]
null
null
null
pulpo_forms_example/urls.py
pulpocoders/pulpo-forms-examples
8b9121b8e323b9432d17f7fc0812405668df3b04
[ "Apache-2.0" ]
1
2015-08-01T02:03:23.000Z
2015-08-01T02:03:23.000Z
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^example/', include('pulpo_example.urls')), url(r'^pulpo/', include('pulpo_forms.urls'), name='base'), url(r'^admin/', include(admin.site.urls)), url(r'^model_field_form/$', 'pulpo_forms.views.render_form', {'instance': 'model-field-example'}), ]
29.076923
62
0.656085
50
378
4.84
0.46
0.066116
0.066116
0
0
0
0
0
0
0
0
0
0.153439
378
12
63
31.5
0.75625
0
0
0
0
0
0.359788
0.07672
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
e37dccf1196dd3e409502f652bd89e454eb6a2b8
2,903
py
Python
backup_tool/utils.py
tnoff/backup-tool
114d066b0aeaa9dab9e2594f42a520839587df20
[ "BSD-2-Clause" ]
null
null
null
backup_tool/utils.py
tnoff/backup-tool
114d066b0aeaa9dab9e2594f42a520839587df20
[ "BSD-2-Clause" ]
null
null
null
backup_tool/utils.py
tnoff/backup-tool
114d066b0aeaa9dab9e2594f42a520839587df20
[ "BSD-2-Clause" ]
null
null
null
import codecs from contextlib import contextmanager import hashlib import logging from logging.handlers import RotatingFileHandler import random import string from pathlib import Path def random_string(length=32, prefix='', suffix=''): ''' Generate random string length : Length of string prefix : Prefix to place before random characters suffix : Suffix to place after random characters ''' chars = string.ascii_lowercase + string.digits generated = "".join(random.choice(chars) for _ in range(length - len(prefix) - len(suffix))) return f'{prefix}{generated}{suffix}' @contextmanager def temp_file(directory, name=None, suffix='', delete=True): ''' Create temporary file name : Name of temporary file directory : Directory for temporary files suffix : Suffix for temporary file name ( not used if name given ) delete : Delete file after use ''' file_path = None directory = Path(directory) if not directory.exists(): directory.mkdir(parents=True) if not name: file_path = directory / random_string(suffix=suffix) else: file_path = directory / name try: if file_path: yield Path(file_path) else: yield None finally: if delete and file_path and file_path.exists(): file_path.unlink() def md5(input_file, chunksize=64*1024): ''' Get md5 base64 hash of input file ''' hash_value = hashlib.md5() with open(input_file, 'rb') as read: while True: chunk = read.read(chunksize) if not chunk: break try: hash_value.update(chunk.encode('utf-8')) except AttributeError: # File is likely binary hash_value.update(chunk) md5_value = codecs.encode(hash_value.digest(), 'base64') # This leaves "b'<hash> at beginning, so take out first two chars return str(md5_value).rstrip("\\n'")[2:] def setup_logger(name, log_file_level, logging_file=None, console_logging=True, console_logging_level=logging.INFO): ''' Setup logging ''' logger = logging.getLogger(name) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logger.setLevel(log_file_level) if logging_file is not None: fh = RotatingFileHandler(logging_file, backupCount=4, maxBytes=((2 ** 20) * 10)) fh.setLevel(log_file_level) fh.setFormatter(formatter) logger.addHandler(fh) if console_logging: sh = logging.StreamHandler() sh.setLevel(console_logging_level) sh.setFormatter(formatter) logger.addHandler(sh) return logger
31.901099
96
0.613503
338
2,903
5.159763
0.387574
0.036697
0.020642
0.022936
0
0
0
0
0
0
0
0.012165
0.292112
2,903
90
97
32.255556
0.836496
0.176369
0
0.064516
0
0
0.044329
0.011734
0
0
0
0
0
1
0.064516
false
0
0.129032
0
0.241935
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
0
0
0
1
0
e37f1a70ff938fa436f4a4d3d93cb8fdc066ba63
2,201
py
Python
chatette/parsing/lexing/rule_slot_val.py
ziligy/Chatette
014c0b0a991bf66cb69fc6a69e0f6c298974eec9
[ "MIT" ]
263
2018-09-06T14:46:29.000Z
2022-03-31T08:40:19.000Z
chatette/parsing/lexing/rule_slot_val.py
ziligy/Chatette
014c0b0a991bf66cb69fc6a69e0f6c298974eec9
[ "MIT" ]
50
2018-09-06T14:50:18.000Z
2021-11-16T03:54:27.000Z
chatette/parsing/lexing/rule_slot_val.py
ziligy/Chatette
014c0b0a991bf66cb69fc6a69e0f6c298974eec9
[ "MIT" ]
49
2018-09-18T23:15:09.000Z
2022-03-02T11:23:08.000Z
# coding: utf-8 """ Module `chatette.parsing.lexing.rule_slot_val` Contains the definition of the class that represents the lexing rule to tokenize a slot value being set within a unit rule (only for a slot). """ from chatette.parsing.lexing.lexing_rule import LexingRule from chatette.parsing.lexing import LexicalToken, TerminalType from chatette.parsing.utils import find_next_comment, SLOT_VAL_SYM class RuleSlotVal(LexingRule): def _apply_strategy(self, **kwargs): """ `kwargs` can contain a boolean with key `parsing_slot_def` that is `True` if the current text is part of a slot definition. If this boolean is not in `kwargs`, defaults to `False`. """ parsing_slot_def = kwargs.get("parsing_slot_def", False) if parsing_slot_def: while self._text[self._next_index].isspace(): self._next_index += 1 self._update_furthest_matched_index() if self._text.startswith(SLOT_VAL_SYM, self._next_index): self._tokens.append( LexicalToken(TerminalType.slot_val_marker, SLOT_VAL_SYM) ) self._next_index += 1 self._update_furthest_matched_index() while self._text[self._next_index].isspace(): self._next_index += 1 self._update_furthest_matched_index() comment_sym = find_next_comment(self._text, self._next_index) if comment_sym is not None: slot_value = \ self._text[self._next_index:comment_sym].rstrip() else: slot_value = self._text[self._next_index:].rstrip() self._tokens.append( LexicalToken(TerminalType.slot_val, slot_value) ) self._next_index += len(slot_value) self._update_furthest_matched_index() return True return False else: raise ValueError( "Tried to extract a slot value within a rule that is not " + \ "part of a slot definition." )
37.948276
78
0.598364
257
2,201
4.824903
0.311284
0.064516
0.104839
0.064516
0.385484
0.310484
0.283871
0.159677
0.159677
0.124194
0
0.002701
0.327124
2,201
57
79
38.614035
0.834571
0.174466
0
0.351351
0
0
0.055367
0
0
0
0
0
0
1
0.027027
false
0
0.081081
0
0.189189
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
0
0
0
1
0
e37fa4448f670de81c2e240c869389511aaf6b49
441
py
Python
python算法/6.5如何根据已知随机数生成函数计算新的随机数.py
RobinYaoWenbin/Python-CommonCode
1ee714541f2fd9c8b96d018d3d4eb94f4edc812a
[ "MIT" ]
12
2020-09-28T03:25:03.000Z
2022-03-20T07:44:09.000Z
python算法/6.5如何根据已知随机数生成函数计算新的随机数.py
RobinYaoWenbin/Python-CommonCode
1ee714541f2fd9c8b96d018d3d4eb94f4edc812a
[ "MIT" ]
null
null
null
python算法/6.5如何根据已知随机数生成函数计算新的随机数.py
RobinYaoWenbin/Python-CommonCode
1ee714541f2fd9c8b96d018d3d4eb94f4edc812a
[ "MIT" ]
21
2020-03-19T00:44:35.000Z
2022-01-30T03:46:18.000Z
# -*- coding: utf-8 -*- """ Created on Sun Feb 23 20:28:51 2020 @author: Administrator """ """ 已知随机数rand7()产生的随机数是整数1~7的均匀分布,如何构造rand10()函数,使其产生的随机数是整数1-10的均匀分布. """ import random def rand7(): return random.randint(1,7) def rand10(): x = 0 while True: x = (rand7() - 1) * 7 + rand7() if x <= 40: break return x % 10 + 1 if __name__ == "__main__": print(rand10())
16.961538
67
0.535147
54
441
4.222222
0.759259
0.017544
0
0
0
0
0
0
0
0
0
0.124183
0.306122
441
26
68
16.961538
0.620915
0.185941
0
0
0
0
0.031621
0
0
0
0
0
0
1
0.166667
false
0
0.083333
0.083333
0.416667
0.083333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
e380169c4e3938481f564cc3fc99e33f8bdaa725
26,432
py
Python
pytropos/internals/values/python_values/python_values.py
helq/pytropos
497ed5902e6e4912249ca0a46b477f9bfa6ae80a
[ "MIT" ]
4
2019-10-06T18:01:24.000Z
2020-07-03T05:27:35.000Z
pytropos/internals/values/python_values/python_values.py
helq/pytropos
497ed5902e6e4912249ca0a46b477f9bfa6ae80a
[ "MIT" ]
5
2021-06-07T15:50:04.000Z
2021-06-07T15:50:06.000Z
pytropos/internals/values/python_values/python_values.py
helq/pytropos
497ed5902e6e4912249ca0a46b477f9bfa6ae80a
[ "MIT" ]
null
null
null
from abc import ABC, abstractmethod from enum import Enum from functools import partial # from math import isinf from typing import Union, Optional, Any from typing import Callable, Tuple, Dict, List, Set, Type # noqa: F401 from ..builtin_values import Bool, ops_symbols from ..abstract_value import AbstractValue from ...abstract_domain import AbstractDomain from ...errors import TypeCheckLogger from .objects_ids import new_id from ...miscelaneous import Pos __all__ = ['PythonValue', 'PT', 'AbstractMutVal', 'Args'] class PT(Enum): """Python types supported in pytropos""" # Undefined = 0 Top = 1 # Bottom = 2 InConstruction = 11 class PythonValue(AbstractDomain): def __init__(self, val: Union[AbstractValue, PT] = PT.Top ) -> None: self.val = val __top = None # type: PythonValue @classmethod def top(cls) -> 'PythonValue': """Returns the Top element from the lattice: Any?""" if cls.__top is None: cls.__top = PythonValue(PT.Top) return cls.__top def is_top(self) -> 'bool': """Returns True if this object is the top of the lattice, ie, if Any?""" return self.val is PT.Top def join(self, other: 'PythonValue') -> 'PythonValue': if self.val is PT.Top or other.val is PT.Top: return PythonValue.top() assert isinstance(self.val, AbstractValue) assert isinstance(other.val, AbstractValue) if type(self.val) is type(other.val): # noqa: E721 return PythonValue(self.val.join(other.val)) return PythonValue.top() def widen_op(self, other: 'PythonValue') -> 'Tuple[PythonValue, bool]': # eg: PythonValue(Int(5)) == PythonValue(Int(5)) if self == other: return self, True # eg: PythonValue(PT.Top) and PythonValue(Int(5)) if self.val is PT.Top or other.val is PT.Top: return PythonValue.top(), False # eg: PythonValue(Float(3)) and PythonValue(Int(5)) if type(self.val) is not type(other.val): # noqa: E721 return PythonValue.top(), False assert isinstance(self.val, AbstractValue) assert isinstance(other.val, AbstractValue) # eg: PythonValue(List([3])) and PythonValue(List([3,5])) if self.__op_in_abstractvalue_overwritten(self.val.widen_op): new_val, fix = self.val.widen_op(other.val) # eg: PythonValue(Int(3)) and PythonValue(Int(5)) else: new_val = self.val.join(other.val) # TODO(helq): This is not how a widening operator is defined, actually we # compare with <= not == !!! fix = new_val == self.val return PythonValue(new_val), fix def is_mut(self) -> 'bool': """Checks if the object is mutable""" return isinstance(self.val, AbstractMutVal) @property def mut_id(self) -> 'int': """Returns id of object if it is mutable""" assert isinstance(self.val, AbstractMutVal) return self.val.mut_id def copy_mut(self, mut_heap: 'Dict[int, PythonValue]' ) -> 'PythonValue': """Copies a mutable object recursively""" assert isinstance(self.val, AbstractMutVal) if self.is_top(): return self if self.mut_id in mut_heap: return mut_heap[self.mut_id] else: new_obj = mut_heap[self.mut_id] = PythonValue(PT.InConstruction) new_obj.val = self.val.copy_mut(mut_heap) return new_obj def convert_into_top(self, converted: 'Set[int]') -> None: """Makes the underlying AbstractMutVal Top""" assert isinstance(self.val, AbstractMutVal) self.val.convert_into_top(converted) self.val = self.val.top() def new_vals_to_top( self, mut_heap: 'Dict[Tuple[str, int], Tuple[int, int, PythonValue]]', side: str ) -> None: """Makes a mutable object Top""" assert isinstance(self.val, AbstractMutVal) self.val.new_vals_to_top(mut_heap, side) def join_mut(self, other: 'PythonValue', mut_heap: 'Dict[Tuple[str, int], Tuple[int, int, PythonValue]]' ) -> 'PythonValue': """Joining two mutable PythonValues""" assert isinstance(self.val, AbstractMutVal) assert isinstance(other.val, AbstractMutVal) left_iden = ('left', self.mut_id) right_iden = ('right', other.mut_id) # Checking if we have encounter already this value if (left_iden in mut_heap) or (right_iden in mut_heap): # self and other have already been joined if (left_iden in mut_heap) and mut_heap[left_iden][1] == other.mut_id: # assert right_iden in mut_heap assert mut_heap[right_iden][0] == self.mut_id assert mut_heap[right_iden][2] is mut_heap[left_iden][2] return mut_heap[left_iden][2] # left has been already been joined with other object else: self.new_vals_to_top(mut_heap, 'left') other.new_vals_to_top(mut_heap, 'right') return PythonValue.top() if type(self.val) is not type(other.val): # noqa: E721 self.new_vals_to_top(mut_heap, 'left') other.new_vals_to_top(mut_heap, 'right') return PythonValue.top() # If the value is top the result its top if self.val.is_top(): other.new_vals_to_top(mut_heap, 'right') return PythonValue(self.val.top()) if other.val.is_top(): self.new_vals_to_top(mut_heap, 'right') return PythonValue(self.val.top()) new_obj = PythonValue(PT.InConstruction) mut_heap[left_iden] = mut_heap[right_iden] = \ (self.mut_id, other.mut_id, new_obj) new_val = self.val.join_mut(other.val, mut_heap) if new_obj.val == PT.InConstruction: new_obj.val = new_val # Notice that we don't change the value of the Object if it is not InConstruction. # If a PythonValue is not anymore in construction it means that it has been made # "top" by some call before it return new_obj # TODO(helq): This equality function is faulty (because of the underlying mutable # variables). An equality function should be defined in Store, not here, to compare # two different Stores. Similar to how `join_mut` is defined def __eq__(self, other: Any) -> 'bool': if self is other: return True if not isinstance(other, PythonValue): return False return self.val == other.val __repr_visited = set() # type: Set[int] def __repr__(self) -> str: if self.val is PT.Top: return "Top" elif self.val is PT.InConstruction: return "InConstruction" else: # self.type is PT.Top assert not isinstance(self.val, PT) if self.is_mut(): if self.mut_id in self.__repr_visited: return 'Ref' else: self.__repr_visited.add(self.mut_id) r = self.val.abstract_repr self.__repr_visited.remove(self.mut_id) return r else: return self.val.abstract_repr # TODO(helq): Improve by checking if the given parameters correspond to the arguments # the function receives, if not return Top def call(self, store: Any, args: 'Args', pos: Optional[Pos] = None) -> 'PythonValue': if self.is_top(): return PythonValue.top() # This assert is always true, it's just to keep Mypy from crying assert isinstance(self.val, AbstractValue), \ f"The type is {type(self.val)} but should have been an AbstractValue" call_method = self.val.fun_call if self.__op_in_abstractvalue_overwritten(call_method): newval = call_method(store, args, pos) # type: PythonValue assert isinstance(newval, PythonValue), "A function call didn't return a PythonValue" else: TypeCheckLogger().new_warning( "E016", f"TypeError: '{self.val.type_name}' object is not callable", pos) newval = PythonValue.top() return newval @property def attr(self) -> 'AttrsContainer': if self.is_top(): return AttrsTopContainer() # This assert is always true, it's just to keep Mypy from crying assert isinstance(self.val, AbstractValue), \ f"The type is {type(self.val)} but should have been an AbstractValue" call_method = self.val.get_attrs if self.__op_in_abstractvalue_overwritten(call_method): return call_method() # type: ignore else: return AttrsTopContainer() def subs(self, pos: 'Optional[Pos]' = None) -> 'SubscriptsContainer': if self.is_top(): return SubscriptsTopContainer() # This assert is always true, it's just to keep Mypy from crying assert isinstance(self.val, AbstractValue), \ f"The type is {type(self.val)} but should have been an AbstractValue" call_method = self.val.get_subscripts if self.__op_in_abstractvalue_overwritten(call_method): return call_method(pos) # type: ignore else: TypeCheckLogger().new_warning( "E015", f"TypeError: '{self.val.type_name}' object is not subscriptable", pos) return SubscriptsTopContainer() def __getattr__(self, name: str) -> Any: # Checking if name is add, mul, truediv if name in ops_symbols.keys(): return partial(self.operate, name) raise AttributeError(f"PythonValue has no attribute called '{name}'") @staticmethod def __op_in_abstractvalue_overwritten(method: Any) -> 'bool': """Checks whether the method (defined in AbstractValue) was overwriten or not""" notoverwritten = hasattr(method, '__qualname__') and \ method.__qualname__.split('.')[0] == "AbstractValue" return not notoverwritten # ie, True if method overwritten def operate(self, op: str, other: 'PythonValue', pos: Optional[Pos] = None) -> 'PythonValue': op_sym = ops_symbols[op] if self.val is PT.Top or other.val is PT.Top: return PythonValue.top() # This assert is always true, it's just to keep Mypy from crying assert isinstance(self.val, AbstractValue), \ f"Left type is {type(self.val)} but should have been an AbstractValue" assert isinstance(other.val, AbstractValue), \ f"Left type is {type(other.val)} but should have been an AbstractValue" # If both values have the same type use val.op_add(otherval) if type(self.val) is type(other.val): # noqa: E721 # Checking if op_add has been overwritten by the class that has been called # If it hasn't, the operation result is Top op_method = getattr(self.val, f'op_{op}') if self.__op_in_abstractvalue_overwritten(op_method): newval = op_method(other.val, pos) else: TypeCheckLogger().new_warning( "E009", f"TypeError: unsupported operand type(s) for {op_sym}: " f"'{self.val.type_name}' and '{other.val.type_name}'", pos) newval = PT.Top # If values have different type use val.op_add_OtherType(otherval) # or otherval.op_add_Type(val) else: leftOpName = "op_r{op}_{class_name}".format(op=op, class_name=type(self.val).__name__) rightOpName = "op_{op}_{class_name}".format(op=op, class_name=type(other.val).__name__) try: newval = getattr(self.val, rightOpName)(other.val, pos) except AttributeError: try: newval = getattr(other.val, leftOpName)(self.val, pos) except AttributeError: TypeCheckLogger().new_warning( "E009", f"TypeError: unsupported operand type(s) for {op_sym}: " f"'{self.val.type_name}' and '{other.val.type_name}'", pos) newval = PT.Top if newval is None: return PythonValue.top() return PythonValue(newval) def bool(self, pos: Optional[Pos] = None) -> 'PythonValue': """method documentation""" if isinstance(self.val, Bool): return self if self.val is PT.Top: return PythonValue(Bool.top()) assert isinstance(self.val, AbstractValue) op_method = self.val.op_bool if self.__op_in_abstractvalue_overwritten(op_method): bool_val = op_method(pos) # Checking bool_val is a boolean! if not isinstance(bool_val, Bool): TypeCheckLogger().new_warning( "E010", f"TypeError: __bool__ should return bool, returned {bool_val.val.type_name}", pos) return PythonValue(Bool.top()) return PythonValue(bool_val) # TODO(helq): If the operation was not defined more stuff is to be done, like # checking __len__. # More info: https://docs.python.org/3/reference/datamodel.html#object.__bool__ return PythonValue(Bool.top()) def type(self) -> str: """Returns the type of the value hold self.val""" if self.val is PT.Top: return "Top" elif self.val is PT.InConstruction: return "InConstruction" else: # self.type is PT.Top assert not isinstance(self.val, PT) return str(self.val.type_name) def __lt__(self, other: 'PythonValue') -> '__builtins__.bool': if self.is_top(): return False elif other.is_top(): return True assert isinstance(self.val, AbstractValue) assert isinstance(other.val, AbstractValue) if type(self.val) is not type(other.val): # noqa: E721 return False try: return bool(self.val < other.val) # type: ignore except TypeError: # TODO(helq): Add warning saying that comparing this two elements is not fully # supported and may be very slow pass # Two know if a value in a Lattice is bigger than the other one can do: # join(self, other) == other if isinstance(self.val, AbstractMutVal): joining = self.join_mut(other, {}).val else: joining = self.val.join(other.val) return bool(joining == other.val) class AbstractMutVal(AbstractValue): """An AbstractValue that allows mutability""" def __init__(self, children: 'Optional[Dict[Any, PythonValue]]' = None) -> None: """Init must always be called All attributes and values must be stored into `children`""" self.__mut_id = new_id() # type: int self.children = {} if children is None else children @property def mut_id(self) -> 'int': """Unique id of object""" return self.__mut_id __eq_visited = ({}, {}) # type: Tuple[Dict[int, int], Dict[int, int]] def __eq__(self, other: Any) -> bool: if self is other: return True if not isinstance(other, AbstractMutVal): return False if self.mut_id in AbstractMutVal.__eq_visited[0]: return AbstractMutVal.__eq_visited[0][self.mut_id] == other.mut_id if other.mut_id in AbstractMutVal.__eq_visited[1]: return AbstractMutVal.__eq_visited[1][other.mut_id] == self.mut_id AbstractMutVal.__eq_visited[0][self.mut_id] = other.mut_id AbstractMutVal.__eq_visited[1][other.mut_id] = self.mut_id eq = self.children == other.children del AbstractMutVal.__eq_visited[0][self.mut_id] del AbstractMutVal.__eq_visited[1][other.mut_id] return eq def convert_into_top(self, converted: 'Set[int]') -> None: """Makes all children objects connected to this into Top""" if self.mut_id in converted: return converted.add(self.mut_id) children = self.children for k, v in children.items(): if v.is_mut(): assert isinstance(v.val, AbstractMutVal) v.convert_into_top(converted) children.clear() def new_vals_to_top( self, mut_heap: 'Dict[Tuple[str, int], Tuple[int, int, PythonValue]]', side: str ) -> None: """Makes all new children objects connected to this into Top""" obj_iden = (side, self.mut_id) val_children = self.children self_topped = False if obj_iden in mut_heap: new_val = mut_heap[obj_iden][2] if not new_val.is_top(): new_val.val = PT.Top self_topped = True else: mut_heap[obj_iden] = (self.mut_id, -1, PythonValue.top()) self_topped = True if self_topped: children = dict(val_children) for k, v in children.items(): if v.is_mut(): assert isinstance(v.val, AbstractMutVal) v.val.new_vals_to_top(mut_heap, side) def copy_mut(self, mut_heap: 'Dict[int, PythonValue]') -> 'Any': """Makes a copy of the current AbstractMutVal. It must be overwritten to add stuff that is not children (PythonValue's)""" if self.is_top(): return self assert len(mut_heap) > 0 \ and self.mut_id in mut_heap, \ "copy_mut cannot be called with an empty mut_heap!" children = dict(self.children) for k, v in children.items(): if v.is_mut(): children[k] = v.copy_mut(mut_heap) cls = type(self) return cls(children=children) def join(self, other: 'Any') -> 'Any': """Join should never be called. It is strange to have an AbstractValue (AbstractDomain) which doesn't not define a `join` operation. The reason is that this class is very tightly coupled to PythonValue. PythonValue is who actually implements the functionality of joining AbstractMutVals""" raise NotImplementedError() # TODO(helq): any children that doesn't appear on both branches should produce a # warning def join_mut(self, other: 'Any', mut_heap: 'Dict[Tuple[str, int], Tuple[int, int, PythonValue]]', ) -> 'Any': """Joins both values including their children""" assert not self.is_top() and not other.is_top() assert len(mut_heap) > 0 \ and ('left', self.mut_id) in mut_heap \ and ('right', other.mut_id) in mut_heap, \ "join_mut cannot be called with an empty mut_heap!" left_children = self.children right_children = other.children new_children = {} # Dict[Any, PythonValue] # almost same code as found in store join for k in set(left_children).union(right_children): # The key is only in the left children if k not in right_children: # handling the mutable case left_val = left_children[k] if left_val.is_mut(): left_val.new_vals_to_top(mut_heap, "left") new_children[k] = PythonValue.top() # The key is only in the right store elif k not in left_children: # handling the mutable case right_val = right_children[k] if right_val.is_mut(): right_val.new_vals_to_top(mut_heap, "right") new_children[k] = PythonValue.top() # the key is only in right children else: val1 = left_children[k] val2 = right_children[k] if val1.is_mut(): if val2.is_mut(): # both (val1 and val2) are mutable new_children[k] = val1.join_mut(val2, mut_heap) else: # val1 mutable, val2 not mutable val1.new_vals_to_top(mut_heap, 'left') new_children[k] = PythonValue.top() else: if val2.is_mut(): # val1 not mutable, val2 mutable val2.new_vals_to_top(mut_heap, 'right') new_children[k] = PythonValue.top() else: # both (val1 and val2) are not mutable new_children[k] = val1.join(val2) cls = type(self) return cls(children=new_children) def get_attrs(self) -> 'AttrsContainer': if self.is_top(): return AttrsTopContainer() return AttrsMutContainer(self.type_name, self.children) class Args: def __init__( self, vals: 'Tuple[PythonValue, ...]', args: 'Optional[PythonValue]' = None, kargs: 'Optional[Dict[str, PythonValue]]' = None ) -> None: """Basic support for arguments to pass to a function""" self.vals = vals self.args = args self.kargs = kargs class AttrsContainer(ABC): """This class acts as a Dict[str, PythonValue]""" @abstractmethod def __getitem__(self, key_: 'Union[str, Tuple[str, Pos]]') -> PythonValue: raise NotImplementedError() @abstractmethod def __delitem__(self, key_: 'Union[str, Tuple[str, Pos]]') -> None: raise NotImplementedError() @abstractmethod def __setitem__(self, key_: 'Union[str, Tuple[str, Pos]]', val: PythonValue) -> None: raise NotImplementedError() class AttrsMutContainer(AttrsContainer): """This class acts as a Dict[str, PythonValue] but it's defined to access and modify AbstractMutVals Attributes: - type_name: The name of the object from which the attributes are being taken - children: Dictionary with all the references to other PythonValues - non_mut_attrs: Dictionary with all python references that are created on the spot, i.e., Not Methods! - read_only: Signals whether the attributes of the AbstractMutVal are writable""" def __init__( self, type_name: str, children: 'Dict[Any, PythonValue]', non_mut_attrs: 'Optional[Dict[Any, Callable[[], PythonValue]]]' = None, read_only: bool = False ) -> None: self.type_name = type_name self.children = children self.read_only = read_only self.non_mut_attrs = {} if non_mut_attrs is None else non_mut_attrs def __getitem__(self, key_: 'Union[str, Tuple[str, Pos]]') -> PythonValue: if not isinstance(key_, tuple): key = key_ src_pos = None # type: Optional[Pos] else: key, src_pos = key_ if key in self.non_mut_attrs: return self.non_mut_attrs[key]() try: return self.children[('attr', key)] except KeyError: TypeCheckLogger().new_warning( "E011", f"AttributeError: '{self.type_name}' object has no attribute '{key}'", src_pos) return PythonValue.top() def __setitem__(self, key_: 'Union[str, Tuple[str, Pos]]', val: PythonValue) -> None: if not isinstance(key_, tuple): key = key_ src_pos = None # type: Optional[Pos] else: key, src_pos = key_ if self.read_only or key in self.non_mut_attrs: TypeCheckLogger().new_warning( "E012", f"AttributeError: '{self.type_name}' object attribute '{key}' is read-only", src_pos) else: self.children[('attr', key)] = val def __delitem__(self, key_: 'Union[str, Tuple[str, Pos]]') -> None: if not isinstance(key_, tuple): key = key_ src_pos = None # type: Optional[Pos] else: key, src_pos = key_ if self.read_only or key in self.non_mut_attrs: TypeCheckLogger().new_warning( "E012", f"AttributeError: '{self.type_name}' object attribute '{key}' is read-only", src_pos) else: try: del self.children[('attr', key)] except KeyError: TypeCheckLogger().new_warning("E013", f"AttributeError: '{key}'", src_pos) class AttrsTopContainer(AttrsContainer): """This class acts as a Dict[str, PythonValue] that does nothing or returns PV.top()""" def __getitem__(self, key_: 'Union[str, Tuple[str, Pos]]') -> PythonValue: return PythonValue.top() def __delitem__(self, key_: 'Union[str, Tuple[str, Pos]]') -> None: pass def __setitem__(self, key_: 'Union[str, Tuple[str, Pos]]', val: PythonValue) -> None: pass class SubscriptsContainer(ABC): """This class acts as a Dict[PythonValue, PythonValue]""" @abstractmethod def __getitem__(self, key_: PythonValue) -> PythonValue: raise NotImplementedError() @abstractmethod def __delitem__(self, key_: PythonValue) -> None: raise NotImplementedError() @abstractmethod def __setitem__(self, key_: PythonValue, val: PythonValue) -> None: raise NotImplementedError() class SubscriptsTopContainer(SubscriptsContainer): """This class acts as a Dict[PythonValue, PythonValue] but returns PV.top() or does nothing""" def __getitem__(self, key_: PythonValue) -> PythonValue: return PythonValue.top() def __delitem__(self, key_: PythonValue) -> None: pass def __setitem__(self, key_: PythonValue, val: PythonValue) -> None: pass
37.019608
99
0.589967
3,229
26,432
4.64664
0.110251
0.033591
0.013796
0.011197
0.483271
0.429819
0.3751
0.356638
0.304319
0.267329
0
0.005385
0.311516
26,432
713
100
37.071529
0.819101
0.183982
0
0.505133
0
0
0.110787
0.009397
0
0
0
0.002805
0.057495
1
0.098563
false
0.010267
0.022587
0.004107
0.295688
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
0
0
0
1
0
e3819ef8cd2690861dd5dfa539b9d90716dabcd3
2,249
py
Python
datasets/utils_cifar10.py
jbinas/fortified-networks
7db626075a019a6a7d8e2cb7d3a97404a1124c69
[ "MIT" ]
5
2018-10-29T20:21:58.000Z
2021-11-19T08:58:18.000Z
datasets/utils_cifar10.py
yaya20160101/fortified-networks
7db626075a019a6a7d8e2cb7d3a97404a1124c69
[ "MIT" ]
null
null
null
datasets/utils_cifar10.py
yaya20160101/fortified-networks
7db626075a019a6a7d8e2cb7d3a97404a1124c69
[ "MIT" ]
5
2018-06-29T00:37:56.000Z
2021-05-28T04:00:55.000Z
import keras import tensorflow as tf import numpy.random as rng from keras.datasets import cifar10 from keras.utils import np_utils def data_cifar10(**kwargs): """ Preprocess CIFAR10 dataset :return: """ # These values are specific to CIFAR10 img_rows = 32 img_cols = 32 nb_classes = 10 # the data, shuffled and split between train and test sets (X_train, y_train), (X_test, y_test) = cifar10.load_data() if keras.backend.image_dim_ordering() == 'th': X_train = X_train.reshape(X_train.shape[0], 3, img_rows, img_cols) X_test = X_test.reshape(X_test.shape[0], 3, img_rows, img_cols) else: X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 3) X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 3) X_train = X_train.astype('float32') X_test = X_test.astype('float32') tpermutation = rng.permutation(X_test.shape[0]) X_test = X_test[tpermutation] y_test = y_test[tpermutation] permutation = rng.permutation(X_train.shape[0]) X_train = X_train[permutation] y_train = y_train[permutation] X_train /= 255 X_test /= 255 print('X_train shape:', X_train.shape) print(X_train.shape[0], 'train samples') print(X_test.shape[0], 'test samples') # convert class vectors to binary class matrices Y_train = np_utils.to_categorical(y_train, nb_classes) Y_test = np_utils.to_categorical(y_test, nb_classes) return X_train, Y_train, X_test, Y_test def preprocess_image(image, is_training): _HEIGHT=32 _WIDTH=32 _DEPTH=3 if is_training: """Preprocess a single image of layout [height, width, depth].""" # Resize the image to add four extra pixels on each side. image = tf.image.resize_image_with_crop_or_pad( image, _HEIGHT + 8, _WIDTH + 8) # Randomly crop a [_HEIGHT, _WIDTH] section of the image. image = tf.random_crop(image, [_HEIGHT, _WIDTH, _DEPTH]) # Randomly flip the image horizontally. image = tf.image.random_flip_left_right(image) # Subtract off the mean and divide by the variance of the pixels. image = tf.image.per_image_standardization(image) return image
29.207792
74
0.678524
339
2,249
4.235988
0.300885
0.071031
0.045961
0.033426
0.18454
0.155292
0.155292
0.134401
0.082173
0
0
0.025773
0.223655
2,249
76
75
29.592105
0.796678
0.173855
0
0
0
0
0.031126
0
0
0
0
0
0
1
0.046512
false
0
0.116279
0
0.209302
0.069767
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b4c4b1f780806fe28ac378ba5bc5176a6a833d9
763
py
Python
applications/createEVENT/SimCenterEvent.py
fmckenna/EE-UQ
a1fe96fd000aec933430bda5829c82b5743338c3
[ "BSD-2-Clause" ]
1
2019-04-30T19:38:17.000Z
2019-04-30T19:38:17.000Z
applications/createEVENT/SimCenterEvent.py
s-m-amin-ghasemi/EE-UQ
7eb42d09b59b42fd1256c6d8693cfe46e0b8034b
[ "BSD-2-Clause" ]
2
2018-09-11T01:32:27.000Z
2018-09-11T23:08:06.000Z
applications/createEVENT/SimCenterEvent.py
s-m-amin-ghasemi/EE-UQ
7eb42d09b59b42fd1256c6d8693cfe46e0b8034b
[ "BSD-2-Clause" ]
6
2018-05-14T21:45:24.000Z
2018-10-04T18:13:42.000Z
import sys from shutil import copyfile def main(): inputArgs = sys.argv #First let's process the arguments argBIM = inputArgs.index("--filenameBIM") + 1 bimFile = inputArgs[argBIM] argEVENT = inputArgs.index("--filenameEVENT") + 1 eventFile = inputArgs[argEVENT] argInputFile = inputArgs.index("--fileName") + 1 inputFile = inputArgs[argInputFile] # only copy file if --getRV, which occurs when argc == 10 argc = len(sys.argv) if (argc == 10): if (inputFile != eventFile): copyfile(inputFile, eventFile) print("Copied File: %s to %s\n",inputFile, eventFile) else: print("FIle not copied: %s to %s\n",inputFile, eventFile) if __name__== "__main__": main()
29.346154
69
0.626474
88
763
5.340909
0.5
0.153191
0.017021
0.021277
0.097872
0.097872
0
0
0
0
0
0.012238
0.250328
763
25
70
30.52
0.809441
0.116645
0
0
0
0
0.142857
0
0
0
0
0
0
1
0.052632
false
0
0.105263
0
0.157895
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b4d9675e98a4abeceff47ef0ef4214b548c119b
259
py
Python
2-mouth02/day03/exe03.py
gary-gggggg/gary
d8ba30ea4bc2b662a2d6a87d247f813e5680d63e
[ "Apache-2.0" ]
4
2021-02-01T10:28:11.000Z
2021-02-01T10:34:40.000Z
2-mouth02/day03/exe03.py
gary-gggggg/gary
d8ba30ea4bc2b662a2d6a87d247f813e5680d63e
[ "Apache-2.0" ]
null
null
null
2-mouth02/day03/exe03.py
gary-gggggg/gary
d8ba30ea4bc2b662a2d6a87d247f813e5680d63e
[ "Apache-2.0" ]
null
null
null
title=open("file.txt","w") title.write("《悯农》\n" ) title.close() sum=0 while 1: sentence=open("file.txt","a") sum+=1 if sum>4: sentence.close() break k =input("请输入句子(包括标点符号):") sentence.write(f"{k}\n") sentence.close()
17.266667
33
0.555985
39
259
3.692308
0.589744
0.111111
0.152778
0
0
0
0
0
0
0
0
0.019901
0.223938
259
14
34
18.5
0.696517
0
0
0.153846
0
0
0.166667
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b4d9f6ab5c3257761c9eb3fa1e62a13d1f8d05b
1,635
py
Python
scanplans/grid_scan.py
st3107/bluesky_scanplans
2ab126c0b7f4427a10d42cf59ea004770c433383
[ "BSD-3-Clause" ]
null
null
null
scanplans/grid_scan.py
st3107/bluesky_scanplans
2ab126c0b7f4427a10d42cf59ea004770c433383
[ "BSD-3-Clause" ]
null
null
null
scanplans/grid_scan.py
st3107/bluesky_scanplans
2ab126c0b7f4427a10d42cf59ea004770c433383
[ "BSD-3-Clause" ]
null
null
null
import bluesky.plan_stubs as bps import bluesky.plans as bp from xpdacq.beamtime import _configure_area_det from xpdacq.glbl import glbl from xpdacq.xpdacq import open_shutter_stub, close_shutter_stub from xpdacq.xpdacq_conf import xpd_configuration def acq_rel_grid_scan( dets: list, exposure: float, wait: float, start0: float, stop0: float, num0: int, start1: float, stop1: float, num1: int ): """Make a plan of two dimensional grid scan.""" area_det = xpd_configuration["area_det"] x_controller = xpd_configuration["x_controller"] y_controller = xpd_configuration["y_controller"] def per_step(detectors, step: dict, pos_cache): """ customized step to ensure shutter is open before reading at each motor point and close shutter after reading """ yield from bps.checkpoint() for motor, pos in step.items(): yield from bps.mv(motor, pos) yield from bps.sleep(wait) yield from open_shutter_stub() yield from bps.sleep(glbl["shutter_sleep"]) yield from bps.trigger_and_read(list(detectors) + list(step.keys())) yield from close_shutter_stub() plan = bp.rel_grid_scan( [area_det], x_controller, start0, stop0, num0, y_controller, start1, stop1, num1, snake_axes=True, per_step=per_step ) yield from _configure_area_det(exposure) yield from plan # below is the code to run at the beamtime # register the scanplan # ScanPlan(bt, acq_rel_grid_scan, 60, 30, -5, 5, 10, -5, 5, 10) # use bt.list() to see the index of the scanplan and use it in xrun
34.0625
76
0.688685
238
1,635
4.542017
0.394958
0.074931
0.055504
0.025902
0
0
0
0
0
0
0
0.018987
0.226911
1,635
47
77
34.787234
0.836234
0.209174
0
0
0
0
0.035686
0
0
0
0
0
0
1
0.058824
false
0
0.176471
0
0.235294
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
0
0
0
1
0
8b528bad86c27520698632ef706d6564180389c3
10,562
py
Python
helpers.py
TimHeiszwolf/NBPGravity
b054b189f5493ad8ec094786f16f5525c117a127
[ "MIT" ]
1
2022-03-08T07:16:53.000Z
2022-03-08T07:16:53.000Z
helpers.py
TimHeiszwolf/NBPGravity
b054b189f5493ad8ec094786f16f5525c117a127
[ "MIT" ]
null
null
null
helpers.py
TimHeiszwolf/NBPGravity
b054b189f5493ad8ec094786f16f5525c117a127
[ "MIT" ]
null
null
null
import numpy as np import time import matplotlib.pyplot as plt import imageio from scipy.optimize import fsolve from body import Body def get_position_from_Kepler(semimajor_axis, eccentricity, inclination, ascending_node, argument_of_periapsis, mean_anomaly, mass_orbit, G=6.67430 * 10**(-11)): """ Get the position vectors from the Keplerian coordinates First part from https://downloads.rene-schwarz.com/download/M001-Keplerian_Orbit_Elements_to_Cartesian_State_Vectors.pdf Second part from https://space.stackexchange.com/questions/19322/converting-orbital-elements-to-cartesian-state-vectors >>> position = get_position_from_Kepler(1.5*10**8, 0.0167, (5*10**(-5))*np.pi/180, 1, 1, 190*np.pi/180, 1.988435 * (10**30)) >>> position array([ 8.58449271e+07, -1.26004733e+08, -1.22449388e+02]) >>> np.linalg.norm(position) 152468174.39880842 """ mu = G * mass_orbit func = lambda EA: mean_anomaly - (EA - eccentricity * np.sin(EA)) eccentric_anomaly = fsolve(func, np.pi)[0] true_anomaly = 2 * np.arctan2(np.sqrt(1 + eccentricity) * np.sin(eccentric_anomaly / 2), np.sqrt(1 - eccentricity) * np.cos(eccentric_anomaly / 2)) radius = semimajor_axis * (1 - eccentricity * np.cos(eccentric_anomaly)) h = np.sqrt(mu * semimajor_axis * (1 - eccentricity**2)) p = semimajor_axis * (1 - eccentricity**2) Om = ascending_node w = argument_of_periapsis nu = true_anomaly r = radius i = inclination e = eccentricity x = r*(np.cos(Om)*np.cos(w+nu) - np.sin(Om)*np.sin(w+nu)*np.cos(i)) y = r*(np.sin(Om)*np.cos(w+nu) + np.cos(Om)*np.sin(w+nu)*np.cos(i)) z = r*(np.sin(i)*np.sin(w+nu)) #print(x, r, Om, w, nu, i, e, eccentric_anomaly) position = np.array([x, y, z]) xd = (x*h*e/(r*p))*np.sin(nu) - (h/r)*(np.cos(Om)*np.sin(w+nu) + np.sin(Om)*np.cos(w+nu)*np.cos(i)) yd = (x*h*e/(r*p))*np.sin(nu) - (h/r)*(np.sin(Om)*np.sin(w+nu) - np.cos(Om)*np.cos(w+nu)*np.cos(i)) zd = (x*h*e/(r*p))*np.sin(nu) - (h/r)*(np.cos(w+nu)*np.sin(i)) velocity = np.array([xd, yd, zd]) #print(velocity) return position def get_coordinates_from_Kepler(semimajor_axis, eccentricity, inclination, ascending_node, argument_of_periapsis, mean_anomaly, current_velocity, mass_orbit, G=6.67430 * 10**(-11), delta=0.001): """ Lol wtf pls kil me. >>> position, velocity = get_coordinates_from_Kepler(1.5*10**8, 0.0167, (5*10**(-5))*np.pi/180, 1, 1, 190*np.pi/180, 29300, 1.988435 * (10**30)) >>> position array([ 8.58449271e+07, -1.26004733e+08, -1.22449388e+02]) >>> velocity array([ 2.41591639e+04, 1.65778407e+04, -9.92410781e-03]) >>> np.linalg.norm(position) 152468174.39880842 >>> np.linalg.norm(velocity) 29299.999999999993 """ position = get_position_from_Kepler(semimajor_axis, eccentricity, inclination, ascending_node, argument_of_periapsis, mean_anomaly, mass_orbit, G) position_plus_delta = get_position_from_Kepler(semimajor_axis, eccentricity, inclination, ascending_node, argument_of_periapsis, mean_anomaly + delta, mass_orbit, G) delta_position = position_plus_delta - position direction_unit_vector = delta_position / np.linalg.norm(delta_position) return position, current_velocity * direction_unit_vector def ld_to_m(ld): """ Converts the input distance (or velocity) of the input from Lunar distances to meters. """ return ld * 384402 * 10**3 def au_to_m(au): """ Converts the input distance (or velocity) of the input from atronomical units to meters. """ return au * 1.495978707 * 10**11 def ly_to_m(ly): """ Converts the input distance (or velocity) of the input from light years to meters. """ return ly * 9.4607 * 10**15 def pc_to_m(pc): """ Converts the input distance (or velocity) of the input from parsec to meters. """ return pc * 3.085677581 * 10**18 def make_gif(bodies, trail_length, tick_per_frame=10, frames_per_second=5, window=[[-1, 1], [-1, 1]], name='output', axis=[0, 1], labels=False): images = [] min_trail = 0 fig = plt.figure(figsize=(16, 16)) for tick in range(0, len(bodies[0].history['time']), tick_per_frame): if bodies[0].history['time'][0] > (bodies[0].history['time'][tick] - trail_length): continue print('Rendering tick:', tick) current_time = bodies[0].history['time'][tick] x = [body.history['position'][tick][axis[0]] for body in bodies] y = [body.history['position'][tick][axis[1]] for body in bodies] colors = [body.color for body in bodies] plt.scatter(x, y, c=colors) plt.axis((window[0][0], window[0][1], window[1][0], window[1][1])) while bodies[0].history['time'][min_trail] + trail_length < current_time: min_trail = min_trail + 1 for body in bodies: if labels: x_label = body.history['position'][tick][axis[0]] y_label = body.history['position'][tick][axis[1]] plt.text(x_label, y_label, body.name) #x_trail = [body.history['position'][i][axis[0]] for i in range(tick + 1) if ((body.history['time'][i] + trail_length) >= current_time)] #y_trail = [body.history['position'][i][axis[1]] for i in range(tick + 1) if ((body.history['time'][i] + trail_length) >= current_time)] x_trail = [body.history['position'][i][axis[0]] for i in range(min_trail, tick + 1)] y_trail = [body.history['position'][i][axis[1]] for i in range(min_trail, tick + 1)] plt.plot(x_trail, y_trail, c=body.color) plt.title(name + ' time ' + str(round(current_time, 0))) plt.xlabel('grgr') plt.ylabel('grgr') image_name = name + '/' + str(tick) + '.png' plt.savefig(image_name) images.append(imageio.imread(image_name)) #plt.pause(0.0001)# Do we want this? plt.clf() print('Done rendering now saving gif.') imageio.mimwrite(name+'.gif', images, format='.gif', fps=frames_per_second) def simple_plotter(space, end_time, time_per_second, updates_per_second=2): #plt.show() lim = 1.50*10**11#max([max([abs(pos) for pos in body.position]) for body in space.bodies]) fig, ax = plt.subplots(figsize=(8, 8)) start_time = time.time() tick = 0 #print(tick, space.time) while space.time<=end_time: print(tick, space.time, round(time.time()-start_time, 2), np.linalg.norm(space.bodies[1].position - space.bodies[2].position)) time.sleep(max([0.001, tick - (time.time() - start_time)])) space.proceed_time_until(tick*time_per_second) x = [] y = [] for body in space.bodies: x.append(body.position[0]) y.append(body.position[1]) ax.clear() ax.scatter(x, y, marker='o', c='r') ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) plt.pause(0.0001) tick = tick+1/updates_per_second plt.show() def get_test_Space_simple_solar(): """ Generates a simple test Space object. It is filled with the 8 plannets of the solar system (and the moon). They are position in a way that doesn't 100% correspond to reality. """ bodies = [] mass_orbit = 1.988435 * (10**30) # The most important bodies. bodies.append(Body(np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 0.0]), 1.988435 * (10**30), 695700000, 'Sun', True, 'tab:orange')) position_earth, velocity_earth = get_coordinates_from_Kepler(1.0*1.496*10**11, 0.01671, (5*10**(-5))*np.pi/180, 0, 0, 190*np.pi/180, 29300, mass_orbit) bodies.append(Body(position_earth, velocity_earth, 5.97 * (10**24), 6371009, 'Earth', True, 'tab:blue')) position, velocity = get_coordinates_from_Kepler(384400*1000, 0.0554, 5.16*np.pi/180, 125*np.pi/180, 318.15*np.pi/180, 213*np.pi/180, 1020, bodies[1].mass) position = position + position_earth velocity = velocity + velocity_earth bodies.append(Body(position,velocity, 7.349 * (10**22), 1737400, 'Moon', True, 'darkgrey')) # Other inner plannets. position, velocity = get_coordinates_from_Kepler(0.38709893*1.496*10**11, 0.20563069, 7.00487*np.pi/180, 48.33*np.pi/180, 29.12*np.pi/180, 269*np.pi/180, 45810, mass_orbit) bodies.append(Body(position, velocity, 3.301 * (10**23), 2440000, 'Mercury', True, 'lightsteelblue')) position, velocity = get_coordinates_from_Kepler(0.72333199*1.496*10**11, 0.00677, 3.39471*np.pi/180, 76.68069*np.pi/180, 54.85*np.pi/180, 187*np.pi/180, 34790, mass_orbit) bodies.append(Body(position, velocity, 4.867 * (10**24), 6050000, 'Venus', True, 'goldenrod')) position, velocity = get_coordinates_from_Kepler(1.52366*1.496*10**11, 0.09341, 1.85061*np.pi/180, 49.57*np.pi/180, 286*np.pi/180, 349*np.pi/180, 26450, mass_orbit) bodies.append(Body(position, velocity, 6.417 * (10**23), 3390000, 'Mars', True, 'sandybrown')) # Outer planets. position_jupiter, velocity_jupiter = get_coordinates_from_Kepler(5.2033*1.496*10**11, 0.04839, 1.3053*np.pi/180, 100.556*np.pi/180, -85.80*np.pi/180, 283*np.pi/180, 13170, mass_orbit) bodies.append(Body(position_jupiter, velocity_jupiter, 1.898 * (10**27), 69950000, 'Jupiter', True, 'darkorange')) position_saturn, velocity_saturn = get_coordinates_from_Kepler(9.537*1.496*10**11, 0.0541, 2.48446*np.pi/180, 113.715*np.pi/180, -21.2831*np.pi/180, 207*np.pi/180, 91590, mass_orbit) bodies.append(Body(position_saturn, velocity_saturn, 5.683 * (10**26), 58300000, 'Saturn', True, 'navajowhite')) position_uranus, velocity_uranus = get_coordinates_from_Kepler(19.1912*1.496*10**11, 0.0471771, 0.76986*np.pi/180, 74.22988*np.pi/180, 96.73436*np.pi/180, 229*np.pi/180, 6578, mass_orbit) bodies.append(Body(position_uranus, velocity_uranus, 8.681 * (10**25), 25360000, 'Uranus', True, 'powderblue')) position_neptune, velocity_neptune = get_coordinates_from_Kepler(30.06896*1.496*10**11, 0.00858587, 1.76917*np.pi/180, 131.72169*np.pi/180, -86.75*np.pi/180, 301*np.pi/180, 5449, mass_orbit) bodies.append(Body(position_neptune, velocity_neptune, 1.024 * (10**26), 24600000, 'Neptune', True, 'dodgerblue')) return bodies if __name__ == "__main__": import doctest doctest.testmod()
44.944681
194
0.639841
1,628
10,562
4.022113
0.235872
0.023824
0.040623
0.040318
0.390959
0.321014
0.246487
0.199756
0.182804
0.170892
0
0.125369
0.197974
10,562
235
195
44.944681
0.647621
0.189074
0
0
0
0
0.037024
0
0
0
0
0
0
1
0.072
false
0
0.056
0
0.184
0.024
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b569282b5d41a4fb5d9ee37ff203ff019b8b666
10,897
py
Python
opttrack/lib/ui/edit_handlers.py
aisthesis/opttrack
17e0c7740ea43e0f07166e30d689b106d0319d0b
[ "MIT" ]
null
null
null
opttrack/lib/ui/edit_handlers.py
aisthesis/opttrack
17e0c7740ea43e0f07166e30d689b106d0319d0b
[ "MIT" ]
2
2016-03-30T02:50:31.000Z
2016-03-30T16:18:23.000Z
opttrack/lib/ui/edit_handlers.py
aisthesis/opttrack
17e0c7740ea43e0f07166e30d689b106d0319d0b
[ "MIT" ]
null
null
null
""" Copyright (c) 2015 Marshall Farrier license http://opensource.org/licenses/MIT lib/ui/handlers.py Handlers for edit menu """ from bson.codec_options import CodecOptions import datetime as dt from functools import partial import json from pymongo.errors import BulkWriteError from ..dbschema import SPREADS from ..dbtools import delete_many, find_job, getcoll, insert_many from ..dbwrapper import job from ..spreads.optspread import SPREAD_TYPES from ..spreads.optspread_factory import OptSpreadFactory from .spread_ui import SpreadUi from .utils import confirm class EditHandlers(object): def __init__(self, logger, tz): self.logger = logger self.tz = tz def add_obs(self, spread_type): spread = SpreadUi().get(spread_type) if not spread: print('\nAborting: spread NOT saved!') return True job(self.logger, partial(_saveentries, (vars(spread),), 'observe')) return True def del_obs(self, spread_type): underlying = input('Underlying: ').strip().upper() wrapped_spreads = self._get_observed({'Underlying': underlying, 'Spread_Type': spread_type}) if len(wrapped_spreads) == 0: print('\nNo {} spreads found for {}'.format(SPREAD_TYPES[spread_type], underlying)) else: self._del_obs(wrapped_spreads) return True def show_obs(self, spread_type): wrapped_spreads = self._get_observed({'Spread_Type': spread_type}) if not len(wrapped_spreads): print('\nNo {} spreads found.'.format(SPREAD_TYPES[spread_type])) for item in wrapped_spreads: print('') item['spread'].show(False, False, False) return True def add_find(self, spread_type): if _is_fromfile(): fname = input('Enter file name: ').strip() equities = _eqs_fromfile(fname) else: equities = _eqs_fromblob(input('Underlying equities (GOOGL,TSLA,FB): ')) print('Include in future scans:\n') for eq in equities: print("'{}'".format(eq)) choice = input('\nOK to proceed (y/n)? ').lower() if choice == 'y': entries = _get_find_entries(equities, spread_type) job(self.logger, partial(_saveentries, entries, 'find')) else: print('Aborting: equities NOT saved!') return True def del_find(self, spread_type): equities = _eqs_fromblob(input('Underlying equities (GOOGL,TSLA,FB): ')) print('Remove from future scans:\n') for eq in equities: print("'{}'".format(eq)) choice = input('\nOK to proceed (y/n)? ').lower() if choice == 'y': entries = _get_find_entries(equities, spread_type) job(self.logger, partial(_delentries, entries, 'find')) else: print('Aborting: equities NOT deleted!') return True def show_find(self): for spread in SPREADS: cursor = job(self.logger, partial(find_job, 'find', {'spread': spread['key']})) equities = sorted([item['eq'] for item in cursor]) print('\n{}:'.format(spread['desc'])) if len(equities) > 0: print('{} equities are being scanned'.format(len(equities))) for equity in equities: print("'{}'".format(equity)) else: print('No equities are being scanned') return True def track_single(self): entry = self._get_track_entry() self._confirmsave((entry,)) return True def track_dgb(self): print('\nTrack diagonal butterfly:') underlying = input('Underlying equity: ').strip().upper() straddleexp = self._getexpdt(input('Straddle expiration (yyyy-mm-dd): ')) straddlestrike = float(input('Straddle strike: ')) farexp = self._getexpdt(input('Far expiration (yyyy-mm-dd): ')) distance = float(input('Distance between strikes: ')) entries = _get_dgbentries(underlying, straddleexp, straddlestrike, farexp, distance) self._confirmsave(entries) return True def delete_tracked(self): entry = self._get_track_entry() self._confirmdelete(entry) return True def show_tracked(self): underlying = input('Underlying equity: ').strip().upper() job(self.logger, partial(_show_tracked, self.tz, underlying)) return True def _del_obs(self, wrapped_spreads): if len(wrapped_spreads) == 1: self._del_obs_unique(wrapped_spreads[0]) else: self._del_obs_select(wrapped_spreads) def _del_obs_unique(self, wrapped_spread): print('\nStop observing the following spread:\n') wrapped_spread['spread'].show(False, False, False) print('') if confirm(): job(self.logger, partial(_delentries, ({'_id': wrapped_spread['_id']},), 'observe')) else: print('\nAborting: spread NOT deleted!') def _del_obs_select(self, wrapped_spreads): print('Multiple {} spreads found for {}.'.format(SPREAD_TYPES[wrapped_spreads[0]['spread'].Spread_Type], wrapped_spreads[0]['spread'].Underlying)) print('Select spread to delete:') for i in range(len(wrapped_spreads)): print('\n({})'.format(i + 1)) wrapped_spreads[i]['spread'].show(False, False, False) choice = int(input('\nEnter number for spread to delete: ')) if not 0 < choice <= len(wrapped_spreads): print('\nInvalid selection!') return self._del_obs_unique(wrapped_spreads[choice - 1]) def _get_track_entry(self): entry = {} entry['Underlying'] = input('Underlying equity: ').strip().upper() entry['Opt_Type'] = _getopttype(input('Option type (c[all] or p[ut]): ')) entry['Expiry'] = self._getexpdt(input('Expiration (yyyy-mm-dd): ')) entry['Strike'] = float(input('Strike: ')) return entry def _confirmsave(self, entries): print('\nSaving the following options:') _show_track_entries(entries) choice = input('\nOK to proceed (y/n)? ').lower() if choice == 'y': job(self.logger, partial(_saveentries, entries, 'track')) else: print('Aborting: option(s) NOT saved!') def _confirmdelete(self, entry): print('\nDeleting the following option:') _show_track_entries((entry,)) choice = input('\nStop tracking this option (y/n)? ').lower() if choice == 'y': job(self.logger, partial(_delentries, (entry,), 'track')) else: print('Aborting: option NOT deleted!') def _get_observed(self, qry): spread_factory = OptSpreadFactory(self.tz) cursor = job(self.logger, partial(find_job, 'observe', qry, codec_options=CodecOptions(tz_aware=True))) wrapped_spreads = [] for item in cursor: wrapped_spreads.append({'spread': spread_factory.make(item), '_id': item['_id']}) return wrapped_spreads def _getexpdt(self, expirytxt): # on 2016-02-19 expired options were unavailable on yahoo by 7:30 pm EST return self.tz.localize(dt.datetime.strptime(expirytxt, '%Y-%m-%d')).replace(hour=19) def _getopttype(rawtxt): if rawtxt.strip().lower() in ('c', 'call'): return 'call' if rawtxt.strip().lower() in ('p', 'put'): return 'put' raise ValueError('option type must be call or put') def _show_track_entries(entries): for entry in entries: print('') _show_track_entry(entry) def _show_track_entry(entry): print('Underlying: {}'.format(entry['Underlying'])) print('Opt_Type: {}'.format(entry['Opt_Type'])) print('Expiry: {}'.format(entry['Expiry'].strftime('%Y-%m-%d'))) print('Strike: {:.2f}'.format(entry['Strike'])) def _delentries(entries, collname, logger, client): logger.info("removing {} record(s) from collection '{}'".format(len(entries), collname)) coll = getcoll(client, collname) total_deleted = 0 for entry in entries: n_deleted = delete_many(logger, coll, entry) if n_deleted < 1: logger.warn('record to be deleted not found: {}'.format(entry)) total_deleted += n_deleted if total_deleted == len(entries): msg = '{} record(s) deleted'.format(total_deleted) print(msg) else: msg = '{} records queued for deletion but {} records were deleted!'.format(len(entries), total_deleted) logger.warn(msg) print('WARNING: {}'.format(msg)) print('Did you verify that the records to be deleted were actually present?') def _saveentries(entries, collname, logger, client): msg = 'Saving {} entries'.format(len(entries)) print(msg) logger.info(msg) coll = getcoll(client, collname) try: n_inserted = insert_many(logger, coll, entries) except BulkWriteError: print('\nERROR writing to database! Entries not saved!') print('Are you trying to enter duplicate records?') else: print('{} records saved'.format(n_inserted)) def _show_tracked(tz, underlying, logger, client): c_opts = CodecOptions(tz_aware=True) trackcoll = getcoll(client, 'track', codec_options=c_opts) print('\nEntries for {}:\n'.format(underlying)) for record in trackcoll.find({'Underlying': underlying}): _show_tracked_record(tz, record) def _show_tracked_record(tz, record): print('Opt_Type: {}'.format(record['Opt_Type'])) print('Expiry: {}'.format(record['Expiry'].astimezone(tz).strftime('%Y-%m-%d'))) print('Strike: {:.2f}\n'.format(record['Strike'])) def _get_dgbentries(underlying, straddleexp, straddlestrike, farexp, distance): entries = [] farstrikes = {'call': straddlestrike + distance, 'put': straddlestrike - distance} for key in farstrikes: # straddle entries.append({'Underlying': underlying, 'Opt_Type': key, 'Expiry': straddleexp, 'Strike': straddlestrike}) # long-term spread entries.append({'Underlying': underlying, 'Opt_Type': key, 'Expiry': farexp, 'Strike': farstrikes[key]}) return entries def _is_fromfile(): if input('Get list from file, 1 equity per line (y/n)? ').strip().lower() == 'y': return True return False def _eqs_fromblob(eqblob): return sorted(map(_fmt_eq, eqblob.split(','))) def _fmt_eq(rawtxt): return rawtxt.strip().upper() def _eqs_fromfile(fname): equities = [] with open(fname, 'r') as infile: equities = infile.readlines() return sorted(map(_fmt_eq, equities)) def _get_find_entries(equities, spread_type): return [{'eq': equity, 'spread': spread_type} for equity in equities]
37.968641
112
0.623383
1,282
10,897
5.136505
0.205928
0.042521
0.019742
0.027335
0.28003
0.199696
0.145938
0.088838
0.073956
0.073956
0
0.003746
0.240525
10,897
286
113
38.101399
0.791928
0.020189
0
0.214286
0
0
0.181418
0
0
0
0
0
0
1
0.134454
false
0
0.05042
0.016807
0.289916
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
0
0
0
0
1
0
8b59bcd3a89ce1967c8f1f93333ca68f2476a3f5
6,331
py
Python
BIT_OpenDomain_QA/rerank/utils_rerank.py
rwei1218/transformers
511e100c650b3f942c432d8f71eee3ea1c0005a8
[ "Apache-2.0" ]
null
null
null
BIT_OpenDomain_QA/rerank/utils_rerank.py
rwei1218/transformers
511e100c650b3f942c432d8f71eee3ea1c0005a8
[ "Apache-2.0" ]
null
null
null
BIT_OpenDomain_QA/rerank/utils_rerank.py
rwei1218/transformers
511e100c650b3f942c432d8f71eee3ea1c0005a8
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Load Duqa labeled dataset. """ from __future__ import absolute_import, division, print_function import collections import json import logging import math from io import open from tqdm import tqdm from transformers.tokenization_bert import BasicTokenizer, whitespace_tokenize logger = logging.getLogger(__name__) class InputExample(object): """A single training/test example for simple sequence classification.""" def __init__(self, guid, text_a, text_b=None, label=None): """Constructs a InputExample.""" self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label class InputFeatures(object): """A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.label_id = label_id class DataProcessor(object): """Base class for data converters for sequence classification data sets.""" def get_train_examples(self, data_dir): """Gets a collection of `InputExample`s for the train set.""" raise NotImplementedError() def get_dev_examples(self, data_dir): """Gets a collection of `InputExample`s for the dev set.""" raise NotImplementedError() def get_labels(self): """Gets the list of labels for this data set.""" raise NotImplementedError() @classmethod def _read_json_data(cls, input_file): """Read a json file""" lines = list(open(input_file, 'r', encoding='utf8').readlines()) lines = [json.loads(line) for line in lines] return lines class DuQAProcessor(DataProcessor): """Processor for the DuReader data set:""" def get_train_examples(self, data_dir): """See base class.""" logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train_labeled.json"))) return self._create_examples(self._read_json_data(os.path.join(data_dir, "train_labeled.json")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples(self._read_json_data(os.path.join(data_dir, "dev_labeled.json")), "dev") def get_predict_examples(self, examples): """ get predict examples Args: data_file: list include many json """ return self._create_examples(examples, "infer") def get_labels(self): """ - 0:not_most_related - 1: most_related """ return [0, 1] def _create_examples(self, examples, set_type): """ here we input a example list: [ { "question_id": int, "question": string, "doc_tokens": string, "mrc_logits": float, "answer":sring, } """ examples_list = [] for id, example in enumerate(examples): guid = set_type + '-' + str(id) text_a = example['question'] text_b = example['answer'] label = 0 ## 在predict环节这里没用,只是一个tag examples_list.append( InputExample( guid=guid, text_a=text_a, text_b=text_b, label=label ) ) return examples_list def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): label_map = {label : i for i, label in enumerate(label_list)} features = [] for (ex_index, example) in tqdm(enumerate(examples), desc='loading_data'): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3) else: if len(tokens_a) > max_seq_length - 2: tokens_a = tokens_a[:(max_seq_length - 2)] tokens = ["[CLS]"] + tokens_a + ["[SEP]"] segment_ids = [0] * len(tokens) if tokens_b: tokens += tokens_b + ["[SEP]"] segment_ids += [1] * (len(tokens_b) + 1) input_ids = tokenizer.convert_tokens_to_ids(tokens) input_mask = [1] * len(input_ids) padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding input_mask += padding segment_ids += padding assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length label_id = label_map[example.label] if ex_index < 5: logger.info("*** Example ***") logger.info("guid: %s" % (example.guid)) logger.info("tokens: %s" % " ".join( [str(x) for x in tokens])) logger.info("input_ids: %s" % " ".join([str(x) for x in input_ids])) logger.info("input_mask: %s" % " ".join([str(x) for x in input_mask])) logger.info( "segment_ids: %s" % " ".join([str(x) for x in segment_ids])) logger.info("label: %s (id = %d)" % (example.label, label_id)) features.append( InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_id=label_id)) return features def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that's truncated likely contains more information than a longer sequence. while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() processors = { 'duqa': DuQAProcessor, } num_labels_task = { 'duqa': 2, }
31.655
113
0.59027
774
6,331
4.583979
0.251938
0.027058
0.027058
0.021421
0.207723
0.171082
0.159808
0.112176
0.063134
0.063134
0
0.003849
0.302322
6,331
199
114
31.81407
0.799411
0.18212
0
0.094017
0
0
0.046695
0
0
0
0
0
0.025641
1
0.111111
false
0
0.068376
0
0.273504
0.008547
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b59f06aa5c12c6a5c23df65ae4eee79a9122e69
1,973
py
Python
LanguageConstructs/DataModel/MetaProgramming/Reflection/attribute_builtins.py
ha-khan/PythonPractice
31366d0a3380b168b96cf2e90cef3960efee8a7e
[ "MIT" ]
null
null
null
LanguageConstructs/DataModel/MetaProgramming/Reflection/attribute_builtins.py
ha-khan/PythonPractice
31366d0a3380b168b96cf2e90cef3960efee8a7e
[ "MIT" ]
null
null
null
LanguageConstructs/DataModel/MetaProgramming/Reflection/attribute_builtins.py
ha-khan/PythonPractice
31366d0a3380b168b96cf2e90cef3960efee8a7e
[ "MIT" ]
null
null
null
from typing import Any class Orchestrator: # __class__ Reference to the object's class # # __dict__ Mapping that stores the writable attributes of an object or class # # __slots__ Attribute that may be defined in a class to limit the attributes its instances can have. # # def __init__(self) -> None: pass def __setattr__(self, __name: str, __value: Any) -> None: """ setattr() operator or . operator will always invoke this special method and "hook" in a check to see if setting an attribute dynamically (monkey patch) """ if __name in vars(self): raise ValueError('name: {} already set!'.format(__name)) self.__dict__[__name] = __value # causes infinite recursion # def __getattribute__(self, __name: str) -> Any: # if __name in vars(self): # return self.__dict__[__name] # return vars(self)[__name] def main(): o = Orchestrator() apply = lambda a: print('applying {}'.format(a)) # invokes __setattr__ setattr(o,'apply', apply) print('Has attribute \'apply\' is {}'.format(hasattr(o, 'apply'))) # invokes __getattr__ o_apply = getattr(o, 'apply') o_apply('deployment') print(o.__dict__ == vars(o)) print(o.__class__ == type(o)) #print(Orchestrator.__dict__) try: setattr(o,'apply', None) except ValueError as e: print(e) delete = eval('lambda a: print(\'deleting {}\'.format(a))') setattr(o, 'delete', delete) o.delete('a') try: o.delete = None except ValueError as e: print(e) try: delattr(o, 'delete') o.delete('deployment') except AttributeError as e: print(e) print(dir(o)) print(locals()) print(globals()) print(callable(Orchestrator)) print(callable(o)) print(isinstance(o, Orchestrator)) if __name__ == '__main__': main()
25.294872
104
0.601115
236
1,973
4.677966
0.402542
0.032609
0.021739
0.024457
0.081522
0.052536
0.052536
0
0
0
0
0
0.278256
1,973
77
105
25.623377
0.775281
0.303599
0
0.195122
0
0
0.107576
0
0
0
0
0
0
1
0.073171
false
0.02439
0.02439
0
0.121951
0.341463
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b5b05fdbf74764959912c9444f946a0e9f8ee11
3,524
py
Python
hard-gists/1558831/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
21
2019-07-08T08:26:45.000Z
2022-01-24T23:53:25.000Z
hard-gists/1558831/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
5
2019-06-15T14:47:47.000Z
2022-02-26T05:02:56.000Z
hard-gists/1558831/snippet.py
jjhenkel/dockerizeme
eaa4fe5366f6b9adf74399eab01c712cacaeb279
[ "Apache-2.0" ]
17
2019-05-16T03:50:34.000Z
2021-01-14T14:35:12.000Z
# [h] interpolated nudge dialog '''a simple RoboFont dialog for the famous "interpolated nudge" script''' # Interpolated Nudge for RoboFont -- Travis Kochel # http://tktype.tumblr.com/post/15254264845/interpolated-nudge-for-robofont # Interpolated Nudge -- Christian Robertson # http://betatype.com/node/18 from vanilla import * from NudgeCore import * class interpolatedNudgeDialog(object): _title = "Nudge" _button_1 = 30 _button_2 = 20 _padding = 10 _width = (_button_1 * 3) + (_padding * 2) - 2 _height = (_button_1 * 4) + (_padding * 3) - 2 _nudge = 10 def __init__(self): self.w = FloatingWindow( (self._width, self._height), self._title) self.w._up = SquareButton( (self._button_1 + self._padding - 1, self._padding, self._button_1, self._button_1), "+", callback=self._up_callback) self.w._left = SquareButton( (self._padding, self._button_1 + self._padding - 1, self._button_1, self._button_1), "-", callback=self._left_callback) self.w._right = SquareButton( ((self._button_1 * 2) + self._padding - 2, self._button_1 + (self._padding - 1), self._button_1, self._button_1), "+", callback=self._right_callback) self.w._down = SquareButton( (self._button_1 + self._padding - 1, (self._button_1 * 2) + (self._padding - 2), self._button_1, self._button_1), "-", callback=self._down_callback) # nudge size self.w._nudge_value = EditText( (self._padding, (self._button_1 * 3) + (self._padding * 2) + 5, (self._width / 2) - (self._padding * 1.5), 20), self._nudge, sizeStyle='small', readOnly=True) self.w._nudge_plus = SquareButton( (-self._padding - 20, (self._button_1 * 3) + (self._padding * 2) + 5, self._button_2, self._button_2), '+', sizeStyle='small', callback=self.nudge_plus_callback) self.w._nudge_minus = SquareButton( (-self._padding - 39, (self._button_1 * 3) + (self._padding * 2) + 5, self._button_2, self._button_2), '-', sizeStyle='small', callback=self.nudge_minus_callback) # open dialog self.w.open() def nudge_minus_callback(self, sender): _nudge = int(self.w._nudge_value.get()) - 10 if _nudge >= 0: self._nudge = _nudge self.w._nudge_value.set(self._nudge) def nudge_plus_callback(self, sender): self._nudge = int(self.w._nudge_value.get()) + 10 self.w._nudge_value.set(self._nudge) def _left_callback(self, sender): nudgeSelected((-self._nudge, 0)) def _right_callback(self, sender): nudgeSelected((self._nudge, 0)) def _up_callback(self, sender): nudgeSelected((0, self._nudge)) def _down_callback(self, sender): nudgeSelected((0, -self._nudge)) # run interpolatedNudgeDialog()
31.464286
75
0.521566
365
3,524
4.668493
0.20274
0.123239
0.109742
0.070423
0.471831
0.465376
0.454812
0.40669
0.225939
0.195423
0
0.038909
0.365494
3,524
111
76
31.747748
0.723166
0.090238
0
0.329412
0
0
0.008143
0
0
0
0
0
0
1
0.082353
false
0
0.023529
0
0.2
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b5d964924108495e0cb8ad5afc9e9b8d784d6b3
1,547
py
Python
django_query_profiler/django/db/backends/database_wrapper_mixin.py
sonej/django-query-profiler
4afe3694ded26d7ba0b435f5666e990b668d85b5
[ "BSD-3-Clause" ]
97
2020-03-03T01:20:35.000Z
2022-03-23T14:06:09.000Z
django_query_profiler/django/db/backends/database_wrapper_mixin.py
sonej/django-query-profiler
4afe3694ded26d7ba0b435f5666e990b668d85b5
[ "BSD-3-Clause" ]
24
2020-03-06T17:35:08.000Z
2022-02-09T20:06:05.000Z
django_query_profiler/django/db/backends/database_wrapper_mixin.py
sonej/django-query-profiler
4afe3694ded26d7ba0b435f5666e990b668d85b5
[ "BSD-3-Clause" ]
9
2020-03-22T18:17:09.000Z
2022-01-31T18:59:11.000Z
""" This module defines a mixin, which can be used by all implementations for all databases. All the databases have a different hierarchy of DatabaseWrapper, but all of them derive from BaseDatabaseWrapper """ from abc import ABC from typing import Optional from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.utils import CursorDebugWrapper, CursorWrapper from .cursor_wrapper_instrumentation import QueryProfilerCursorDebugWrapper, QueryProfilerCursorWrapper class QueryProfilerDatabaseWrapperMixin(BaseDatabaseWrapper, ABC): def cursor(self): cursor_wrapper = super().cursor() kwargs = dict( cursor=cursor_wrapper.cursor, db=cursor_wrapper.db, db_row_count=self.db_row_count(cursor_wrapper.cursor)) if isinstance(cursor_wrapper, CursorDebugWrapper): return QueryProfilerCursorDebugWrapper(**kwargs) elif isinstance(cursor_wrapper, CursorWrapper): return QueryProfilerCursorWrapper(**kwargs) else: raise Exception("cursor_wrapper is not of either of {CursorWrapper, CursorDebugWrapper}. Is it because of " "new version of django? Did you run the tests in the django_query_profiler - they must " "have failed") @staticmethod def db_row_count(cursor) -> Optional[int]: """ Implementation varies by database types, having it as a function allows it to be overriden """ return cursor.rowcount
39.666667
120
0.707822
169
1,547
6.378698
0.514793
0.096475
0.027829
0.037106
0
0
0
0
0
0
0
0
0.232062
1,547
38
121
40.710526
0.907407
0.188752
0
0
0
0
0.154412
0.017157
0
0
0
0
0
1
0.086957
false
0
0.217391
0
0.478261
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
0
0
0
1
0
8b620f703a95ef7c54125b1554d9a9e0de82f47e
12,330
py
Python
lib/rapi/auth/pam.py
regnauld/ganeti
c1d88461a964a5d0d89cd1ba0571429e01f0a1b5
[ "BSD-2-Clause" ]
2
2018-09-26T10:09:23.000Z
2018-09-27T07:27:06.000Z
lib/rapi/auth/pam.py
regnauld/ganeti
c1d88461a964a5d0d89cd1ba0571429e01f0a1b5
[ "BSD-2-Clause" ]
null
null
null
lib/rapi/auth/pam.py
regnauld/ganeti
c1d88461a964a5d0d89cd1ba0571429e01f0a1b5
[ "BSD-2-Clause" ]
null
null
null
# # # Copyright (C) 2015, 2016 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Module interacting with PAM performing authorization and authentication This module authenticates and authorizes RAPI users based on their credintials. Both actions are performed by interaction with PAM as a 'ganeti-rapi' service. """ import logging try: import ctypes as c # pylint: disable=F0401 import ctypes.util as util except ImportError: c = None from ganeti import constants from ganeti.errors import PamRapiAuthError import ganeti.http as http from ganeti.http.auth import HttpServerRequestAuthentication from ganeti.rapi import auth __all__ = ['PamAuthenticator'] DEFAULT_SERVICE_NAME = 'ganeti-rapi' MAX_STR_LENGTH = 100000 MAX_MSG_COUNT = 100 PAM_ENV_URI = 'GANETI_RAPI_URI' PAM_ENV_BODY = 'GANETI_REQUEST_BODY' PAM_ENV_METHOD = 'GANETI_REQUEST_METHOD' PAM_ENV_ACCESS = 'GANETI_RESOURCE_ACCESS' PAM_ABORT = 26 PAM_BUF_ERR = 5 PAM_CONV_ERR = 19 PAM_SILENT = 32768 PAM_SUCCESS = 0 PAM_PROMPT_ECHO_OFF = 1 PAM_AUTHTOK = 6 PAM_USER = 2 if c: class PamHandleT(c.Structure): """Wrapper for PamHandleT """ _fields_ = [("hidden", c.c_void_p)] def __init__(self): c.Structure.__init__(self) self.handle = 0 class PamMessage(c.Structure): """Wrapper for PamMessage """ _fields_ = [ ("msg_style", c.c_int), ("msg", c.c_char_p), ] class PamResponse(c.Structure): """Wrapper for PamResponse """ _fields_ = [ ("resp", c.c_char_p), ("resp_retcode", c.c_int), ] CONV_FUNC = c.CFUNCTYPE(c.c_int, c.c_int, c.POINTER(c.POINTER(PamMessage)), c.POINTER(c.POINTER(PamResponse)), c.c_void_p) class PamConv(c.Structure): """Wrapper for PamConv """ _fields_ = [ ("conv", CONV_FUNC), ("appdata_ptr", c.c_void_p), ] class CFunctions(object): def __init__(self): if not c: raise PamRapiAuthError("ctypes Python package is not found;" " remote API PAM authentication is not available") self.libpam = c.CDLL(util.find_library("pam")) if not self.libpam: raise PamRapiAuthError("libpam C library is not found;" " remote API PAM authentication is not available") self.libc = c.CDLL(util.find_library("c")) if not self.libc: raise PamRapiAuthError("libc C library is not found;" " remote API PAM authentication is not available") self.pam_acct_mgmt = self.libpam.pam_acct_mgmt self.pam_acct_mgmt.argtypes = [PamHandleT, c.c_int] self.pam_acct_mgmt.restype = c.c_int self.pam_authenticate = self.libpam.pam_authenticate self.pam_authenticate.argtypes = [PamHandleT, c.c_int] self.pam_authenticate.restype = c.c_int self.pam_end = self.libpam.pam_end self.pam_end.argtypes = [PamHandleT, c.c_int] self.pam_end.restype = c.c_int self.pam_get_item = self.libpam.pam_get_item self.pam_get_item.argtypes = [PamHandleT, c.c_int, c.POINTER(c.c_void_p)] self.pam_get_item.restype = c.c_int self.pam_putenv = self.libpam.pam_putenv self.pam_putenv.argtypes = [PamHandleT, c.c_char_p] self.pam_putenv.restype = c.c_int self.pam_set_item = self.libpam.pam_set_item self.pam_set_item.argtypes = [PamHandleT, c.c_int, c.c_void_p] self.pam_set_item.restype = c.c_int self.pam_start = self.libpam.pam_start self.pam_start.argtypes = [ c.c_char_p, c.c_char_p, c.POINTER(PamConv), c.POINTER(PamHandleT), ] self.pam_start.restype = c.c_int self.calloc = self.libc.calloc self.calloc.argtypes = [c.c_uint, c.c_uint] self.calloc.restype = c.c_void_p self.free = self.libc.free self.free.argstypes = [c.c_void_p] self.free.restype = None self.strndup = self.libc.strndup self.strndup.argstypes = [c.c_char_p, c.c_uint] self.strndup.restype = c.c_char_p def Authenticate(cf, pam_handle, authtok=None): """Performs authentication via PAM. Perfroms two steps: - if authtok is provided then set it with pam_set_item - call pam_authenticate """ try: authtok_copy = None if authtok: authtok_copy = cf.strndup(authtok, len(authtok)) if not authtok_copy: raise http.HttpInternalServerError("Not enough memory for PAM") ret = cf.pam_set_item(c.pointer(pam_handle), PAM_AUTHTOK, authtok_copy) if ret != PAM_SUCCESS: raise http.HttpInternalServerError("pam_set_item failed [%d]" % ret) ret = cf.pam_authenticate(pam_handle, 0) if ret == PAM_ABORT: raise http.HttpInternalServerError("pam_authenticate requested abort") if ret != PAM_SUCCESS: raise http.HttpUnauthorized("Authentication failed") except: cf.pam_end(pam_handle, ret) raise finally: if authtok_copy: cf.free(authtok_copy) def PutPamEnvVariable(cf, pam_handle, name, value): """Wrapper over pam_setenv. """ setenv = "%s=" % name if value: setenv += value ret = cf.pam_putenv(pam_handle, setenv) if ret != PAM_SUCCESS: raise http.HttpInternalServerError("pam_putenv call failed [%d]" % ret) def Authorize(cf, pam_handle, uri_access_rights, uri=None, method=None, body=None): """Performs authorization via PAM. Performs two steps: - initialize environmental variables - call pam_acct_mgmt """ try: PutPamEnvVariable(cf, pam_handle, PAM_ENV_ACCESS, uri_access_rights) PutPamEnvVariable(cf, pam_handle, PAM_ENV_URI, uri) PutPamEnvVariable(cf, pam_handle, PAM_ENV_METHOD, method) PutPamEnvVariable(cf, pam_handle, PAM_ENV_BODY, body) ret = cf.pam_acct_mgmt(pam_handle, PAM_SILENT) if ret != PAM_SUCCESS: raise http.HttpUnauthorized("Authorization failed") except: cf.pam_end(pam_handle, ret) raise def ValidateParams(username, _uri_access_rights, password, service, authtok, _uri, _method, _body): """Checks whether ValidateRequest has been called with a correct params. These checks includes: - username is an obligatory parameter - either password or authtok is an obligatory parameter """ if not username: raise http.HttpUnauthorized("Username should be provided") if not service: raise http.HttpBadRequest("Service should be proivded") if not password and not authtok: raise http.HttpUnauthorized("Password or authtok should be provided") def ValidateRequest(cf, username, uri_access_rights, password=None, service=DEFAULT_SERVICE_NAME, authtok=None, uri=None, method=None, body=None): """Checks whether it's permitted to execute an rapi request. Calls pam_authenticate and then pam_acct_mgmt in order to check whether a request should be executed. @param cf: An instance of CFunctions class containing necessary imports @param username: username @param uri_access_rights: handler access rights @param password: password @param service: a service name that will be used for the interaction with PAM @param authtok: user's authentication token (e.g. some kind of signature) @param uri: an uri of a target resource obtained from an http header @param method: http method trying to access the uri @param body: a body of an RAPI request @return: On success - authenticated user name. Throws an exception otherwise. """ ValidateParams(username, uri_access_rights, password, service, authtok, uri, method, body) def ConversationFunction(num_msg, msg, resp, _app_data_ptr): """Conversation function that will be provided to PAM modules. The function replies with a password for each message with PAM_PROMPT_ECHO_OFF style and just ignores the others. """ if num_msg > MAX_MSG_COUNT: logging.warning("Too many messages passed to conv function: [%d]", num_msg) return PAM_BUF_ERR response = cf.calloc(num_msg, c.sizeof(PamResponse)) if not response: logging.warning("calloc failed in conv function") return PAM_BUF_ERR resp[0] = c.cast(response, c.POINTER(PamResponse)) for i in range(num_msg): if msg[i].contents.msg_style != PAM_PROMPT_ECHO_OFF: continue resp.contents[i].resp = cf.strndup(password, len(password)) if not resp.contents[i].resp: logging.warning("strndup failed in conv function") for j in range(i): cf.free(c.cast(resp.contents[j].resp, c.c_void_p)) cf.free(response) return PAM_BUF_ERR resp.contents[i].resp_retcode = 0 return PAM_SUCCESS pam_handle = PamHandleT() conv = PamConv(CONV_FUNC(ConversationFunction), 0) ret = cf.pam_start(service, username, c.pointer(conv), c.pointer(pam_handle)) if ret != PAM_SUCCESS: cf.pam_end(pam_handle, ret) raise http.HttpInternalServerError("pam_start call failed [%d]" % ret) Authenticate(cf, pam_handle, authtok) Authorize(cf, pam_handle, uri_access_rights, uri, method, body) # retrieve the authorized user name puser = c.c_void_p() ret = cf.pam_get_item(pam_handle, PAM_USER, c.pointer(puser)) if ret != PAM_SUCCESS or not puser: cf.pam_end(pam_handle, ret) raise http.HttpInternalServerError("pam_get_item call failed [%d]" % ret) user_c_string = c.cast(puser, c.c_char_p) cf.pam_end(pam_handle, PAM_SUCCESS) return user_c_string.value def MakeStringC(string): """Converts a string to a valid C string. As a C side treats non-unicode strings, encode unicode string with 'ascii'. Also ensure that C string will not be longer than MAX_STR_LENGTH in order to prevent attacs based on too long buffers. """ if string is None: return None if isinstance(string, unicode): string = string.encode("ascii") if not isinstance(string, str): return None if len(string) <= MAX_STR_LENGTH: return string return string[:MAX_STR_LENGTH] class PamAuthenticator(auth.RapiAuthenticator): """Class providing an Authenticate method based on interaction with PAM. """ def __init__(self): """Checks whether ctypes has been imported. """ self.cf = CFunctions() def ValidateRequest(self, req, handler_access, _): """Checks whether a user can access a resource. This function retuns authenticated user name on success. """ username, password = HttpServerRequestAuthentication \ .ExtractUserPassword(req) authtok = req.request_headers.get(constants.HTTP_RAPI_PAM_CREDENTIAL, None) if handler_access is not None: handler_access_ = ','.join(handler_access) return ValidateRequest(self.cf, MakeStringC(username), MakeStringC(handler_access_), MakeStringC(password), MakeStringC(DEFAULT_SERVICE_NAME), MakeStringC(authtok), MakeStringC(req.request_path), MakeStringC(req.request_method), MakeStringC(req.request_body))
32.447368
79
0.701703
1,705
12,330
4.892082
0.217009
0.008632
0.009591
0.01079
0.211006
0.176837
0.13068
0.09807
0.076969
0.068097
0
0.004316
0.210706
12,330
379
80
32.532982
0.852754
0.285807
0
0.148148
0
0
0.093285
0.004995
0
0
0
0
0
1
0.050926
false
0.046296
0.041667
0
0.185185
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
0
0
0
1
0
8b666913019cd3ac664dfb714c512a8beb73daff
10,601
py
Python
mssql_backend/mssql_backend.py
Reposoft/trac-mssql
da8d8ae29ef81db39ca2d6af439d88f3d6ecfebd
[ "BSD-3-Clause" ]
1
2021-01-27T00:21:47.000Z
2021-01-27T00:21:47.000Z
mssql_backend/mssql_backend.py
Reposoft/trac-mssql
da8d8ae29ef81db39ca2d6af439d88f3d6ecfebd
[ "BSD-3-Clause" ]
1
2015-05-11T18:34:46.000Z
2017-02-12T07:07:06.000Z
mssql_backend/mssql_backend.py
Reposoft/trac-mssql
da8d8ae29ef81db39ca2d6af439d88f3d6ecfebd
[ "BSD-3-Clause" ]
1
2021-01-27T00:21:50.000Z
2021-01-27T00:21:50.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2013 MATOBA Akihiro <matobaa+trac-hacks@gmail.com> # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. from trac.core import * from trac.config import Option from trac.core import Component, implements from trac.db.api import ConnectionBase from trac.db.api import DatabaseManager from trac.db.api import IDatabaseConnector from trac.db.api import _parse_db_str, get_column_names from trac.db.api import ConnectionBase from trac.db.util import ConnectionWrapper from trac.env import IEnvironmentSetupParticipant, ISystemInfoProvider from trac.env import BackupError from trac.db import Table, Column import re try: import pymssql as pymssql has_mssql = True except ImportError: has_mssql = False # force enables this plugin in trac-admin initenv #enabled = BoolOption("components", "mssql_backend.*", "enabled") # Mapping from "abstract" SQL types to DB-specific types _type_map = { 'int64': 'bigint', 'text': 'nvarchar(512)', } # TODO: You cannot use MS Access because column name 'value' can seems not use via odbc. _column_map = { 'key': '"key"', # 'value': '"value"' } re_limit = re.compile(" LIMIT (\d+)( OFFSET (\d+))?", re.IGNORECASE) re_order_by = re.compile("ORDER BY ", re.IGNORECASE) re_where = re.compile("WHERE ", re.IGNORECASE) re_equal = re.compile("(\w+)\s*=\s*(['\w]+|\?)", re.IGNORECASE) re_isnull = re.compile("(\w+) IS NULL", re.IGNORECASE) re_select = re.compile('SELECT( DISTINCT)?( TOP)?', re.IGNORECASE) re_coalesce_equal = re.compile("(COALESCE\([^)]+\))=([^,]+)", re.IGNORECASE) class MSSQLConnector(Component): implements(IDatabaseConnector, IEnvironmentSetupParticipant, ISystemInfoProvider) required = False def __init__(self): self._mssql_version = None # ISystemInfoProvider methods def get_system_info(self): if self.required: yield 'pymssql', self._mssql_version # IDatabaseConnector methods def get_supported_schemes(self): yield ('mssql', 1) def init_db(self, path, schema=None, log=None, user=None, password=None,\ host=None, port=None, params={}): cnx = self.get_connection(path, log, user, password, host, port, params) cursor = cnx.cursor() if schema is None: from trac.db_default import schema for table in schema: for stmt in _to_sql(table): cursor.execute(stmt) cnx.commit() def get_connection(self, path, log=None, user=None, password=None, host=None, port=None, params={}): cnx = MSSQLConnection(path, log, user, password, host, port, params) return cnx # IEnvironmentSetupParticipant methods def environment_created(self): pass def environment_needs_upgrade(self): return False def upgrade_environment(self): pass def get_exceptions(self): return pymssql class MSSQLConnection(ConnectionBase, ConnectionWrapper): """Connection wrapper for MSSQL.""" poolable = True def __init__(self, path, log, user=None, password=None, host=None, port=None, params={}): if path.startswith('/'): path = path[1:] if 'host' in params: host = params['host'] cnx = pymssql.connect(database=path, user=user, password=password, host=host, port=port) self.schema = path conn = ConnectionWrapper.__init__(self, cnx, log) self._is_closed = False def cursor(self): cursor = SQLServerCursor(self.cnx.cursor(), self.log) cursor.cnx = self return cursor def rollback(self): try: self.cnx.rollback() except pymssql.ProgrammingError: self._is_closed = True def close(self): if not self._is_closed: try: self.cnx.close() except pymssql.ProgrammingError: pass # this error would mean it's already closed. So, ignore self._is_closed = True def cast(self, column, type): if type == 'signed': type = 'int' elif type == 'text': type = 'varchar(max)' return 'CAST(%s AS %s)' % (column, type) def concat(self, *args): return 'concat(%s)' % ', '.join(args) def drop_table(self, table): cursor = pymssql.cursors.Cursor(self.cnx) cursor._defer_warnings = True # ignore "Warning: Unknown table ..." cursor.execute("DROP TABLE IF EXISTS " + self.quote(table)) def get_column_names(self, table): rows = self.execute(""" SELECT column_name FROM information_schema.columns WHERE table_schema=%s AND table_name=%s """, (self.schema, table)) return [row[0] for row in rows] def get_last_id(self, cursor, table, column='id'): return cursor.lastrowid def get_table_names(self): rows = self.execute(""" SELECT table_name FROM information_schema.tables WHERE table_schema=%s""", (self.schema,)) return [row[0] for row in rows] def like(self): return 'LIKE %s' # TODO quick hacked. check me. def like_escape(self, text): return text # TODO quick hacked. check me. def prefix_match(self): return "LIKE %s ESCAPE '/'" def prefix_match_value(self, prefix): return self.like_escape(prefix) + '%' def quote(self, identifier): return '"%s"' % identifier def update_sequence(self, cursor, table, column='id'): # MSSQL handles sequence updates automagically pass def _to_sql(table): sql = ["CREATE TABLE %s (" % table.name] coldefs = [] for column in table.columns: column.name = _column_map.get(column.name, column.name) ctype = column.type.lower() ctype = _type_map.get(ctype, ctype) # for SQL Server, patch for "enum" table, value is not text, use int instead. if table.name == 'enum' and column.name == 'value': ctype = 'int' if (table.name, column.name) in [ ('wiki', 'text'), ('report', 'query'), ('report', 'description'), ('milestone', 'description'), ('version', 'description'), ]: ctype = 'nvarchar(MAX)' if (table.name, column.name) in [ ('ticket', 'description'), ('ticket_change', 'oldvalue'), ('ticket_change', 'newvalue'), ('ticket_custom', 'value'), ('session_attribute', 'value') ]: ctype = 'nvarchar(4000)' # I'm using SQL Userver 2012 Express if column.auto_increment: ctype = 'INT IDENTITY NOT NULL' # SQL Server Style # ctype = 'INT UNSIGNED NOT NULL AUTO_INCREMENT' # MySQL Style # ctype = 'SERIAL' # PGSQL Style # ctype = "integer constraint P_%s PRIMARY KEY" % table.name # SQLite Style else: # if column.name in table.key or any([column.name in index.columns for index in table.indices]): # ctype = {'ntext': 'nvarchar(255)'}.get(ctype, ctype) # SQL Server cannot use text as PK if len(table.key) == 1 and column.name in table.key: ctype += " constraint P_%s PRIMARY KEY" % table.name coldefs.append(" %s %s" % (column.name, ctype)) if len(table.key) > 1: coldefs.append(" UNIQUE (%s)" % ','.join(table.key)) sql.append(',\n'.join(coldefs) + '\n);') yield '\n'.join(sql) for index in table.indices: type_ = ('INDEX', 'UNIQUE INDEX')[index.unique] yield "CREATE %s %s_%s_idx ON %s (%s);" % (type_, table.name, '_'.join(index.columns), table.name, ','.join(index.columns)) class SQLServerCursor(object): def __init__(self, cursor, log=None): self.cursor = cursor self.log = log def __getattr__(self, name): return getattr(self.cursor, name) def __iter__(self): while True: row = self.cursor.fetchone() if not row: return yield row def execute(self, sql, args=None): if args: sql = sql % (('%s',) * len(args)) # replace __column__ IS NULL -> COALESCE(__column__, '') after ORDER BY match = re_order_by.search(sql) if match: end = match.end() for match in reversed([match for match in re_isnull.finditer(sql[end:])]): replacement = "COALESCE(%s,'')" % match.group(1) sql = sql[:end + match.start()] + replacement + sql[end + match.end():] # replace __column__ = %s -> CASE __column__ WHEN %s THEN '0' ELSE '1' END after ORDER BY match = re_order_by.search(sql) if match: end = match.end() for match in reversed([match for match in re_equal.finditer(sql[end:])]): replacement = "CASE %s WHEN %s THEN '0' ELSE '1' END" % (match.group(1), match.group(2)) sql = sql[:end + match.start()] + replacement + sql[end + match.end():] for match in reversed([match for match in re_coalesce_equal.finditer(sql[end:])]): replacement = "CASE %s WHEN %s THEN '0' ELSE '1' END" % (match.group(1), match.group(2)) sql = sql[:end + match.start()] + replacement + sql[end + match.end():] # trim duplicated columns after ORDER BY match = re_order_by.search(sql) if match: end = match.end() match = re.search("'([a-z]+)'", sql[end:]) if match: column_name = match.group(1) re_columns = re.compile("([a-z]+.)?%s,?" % column_name) order_by = ' '.join([column for column in match.string.split(' ') if not re_columns.match(column)]) self.log.debug(order_by) sql = sql[:end] + order_by # transform LIMIT clause match = re_limit.search(sql) if match: limit = match.group(1) offset = match.group(3) if not offset: # LIMIT n (without OFFSET) -> SELECT TOP n sql = match.string[:match.start()].replace("SELECT", "SELECT TOP %s" % limit) else: # LIMIT n OFFSET m -> OFFSET m ROWS FETCH NEXT n ROWS ONLY sql = match.string[:match.start()] + " OFFSET %s ROWS FETCH NEXT %s ROWS ONLY" % (offset, limit) # match = re_where.search(sql) # sql = match.string[:match.end()] + 'ROW_NUMBER() > %s, ' % limit + match.string[match.end():] # avoid error in "order by" in sub query # TODO: decide count of lines else: for match in reversed([match for match in re_select.finditer(sql) if match.group(2) == None]): sql = sql[:match.end()] + ' TOP 1000' + sql[match.end():] try: if self.log: # See [trac] debug_sql in trac.ini self.log.debug(sql) self.log.debug(args) if args: self.cursor.execute(sql, tuple(args)) else: self.cursor.execute(sql, ()) except: self.cnx.rollback() raise def executemany(self, sql, args): if not args: return sql = sql % (('%s',) * len(args[0])) try: if self.log: # See [trac] debug_sql in trac.ini self.log.debug(sql) self.log.debug(args) self.cursor.executemany(sql, args) except: self.cnx.rollback() raise
31.550595
111
0.647486
1,445
10,601
4.644983
0.221453
0.020858
0.011919
0.009684
0.247318
0.184595
0.170292
0.14854
0.141091
0.116806
0
0.005618
0.210829
10,601
335
112
31.644776
0.796677
0.186963
0
0.256198
0
0
0.123892
0.012268
0
0
0
0.002985
0
1
0.128099
false
0.041322
0.066116
0.041322
0.285124
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
0
0
0
1
0
8b668fce877fc1e0332e1fd014c47e5007f994ff
6,767
py
Python
CertifiableBayesianInference/BayesKeras/optimizers/adam.py
Hongchenglong/colab
9cc5c15abde536493cc3f12008e791caa1d00070
[ "Apache-2.0" ]
null
null
null
CertifiableBayesianInference/BayesKeras/optimizers/adam.py
Hongchenglong/colab
9cc5c15abde536493cc3f12008e791caa1d00070
[ "Apache-2.0" ]
null
null
null
CertifiableBayesianInference/BayesKeras/optimizers/adam.py
Hongchenglong/colab
9cc5c15abde536493cc3f12008e791caa1d00070
[ "Apache-2.0" ]
null
null
null
#Author: Matthew Wicker # Impliments the BayesByBackprop optimizer for BayesKeras import os import math import logging import numpy as np import tensorflow as tf import tensorflow_probability as tfp from tensorflow.keras.models import * from tensorflow.keras.layers import * from tqdm import tqdm from tqdm import trange from BayesKeras.optimizers import optimizer from BayesKeras.optimizers import losses from BayesKeras import analyzers from abc import ABC, abstractmethod # A dumb mistake on my part which needs to be factored out def softplus(x): return tf.math.softplus(x) class Adam(optimizer.Optimizer): def __init__(self): super().__init__() # I set default params for each sub-optimizer but none for the super class for # pretty obvious reasons def compile(self, keras_model, loss_fn, batch_size=64, learning_rate=0.15, decay=0.0, epochs=10, prior_mean=-1, prior_var=-1, **kwargs): super().compile(keras_model, loss_fn, batch_size, learning_rate, decay, epochs, prior_mean, prior_var, **kwargs) # Now we get into the NoisyAdam specific enrichments to the class self.beta_1 = kwargs.get('beta_1', 0.99) self.beta_2 = kwargs.get('beta_2', 0.9999) self.lam = kwargs.get('lam', 0.5) self.m = [0.0 for i in range(len(self.posterior_mean))] self.posterior_var = [tf.zeros(i.shape) for i in self.posterior_mean] return self def step(self, features, labels, lrate): alpha = lrate beta_1 = self.beta_1 beta_2 = self.beta_2 lam = self.lam posti_var = self.posterior_var posti_mean = self.posterior_mean N = float(self.batch_size) # batch size with tf.GradientTape(persistent=True) as tape: # Get the probabilities predictions = self.model(features) # Calculate the loss if(int(self.robust_train) == 0): loss = self.loss_func(labels, predictions) elif(int(self.robust_train) == 1): logit_l, logit_u = analyzers.IBP(self, features, self.model.trainable_variables, eps=self.epsilon) v1 = tf.one_hot(labels, depth=10) v2 = 1 - tf.one_hot(labels, depth=10) worst_case = tf.math.add(tf.math.multiply(v2, logit_u), tf.math.multiply(v1, logit_l)) worst_case = self.model.layers[-1].activation(worst_case) loss = self.loss_func(labels, predictions, worst_case, self.robust_lambda) #self.train_rob(labels, worst_case) elif(int(self.robust_train) == 2): features_adv = analyzers.FGSM(self, features, self.attack_loss, eps=self.epsilon, num_models=-1) # Get the probabilities worst_case = self.model(features_adv) # Calculate the loss loss = self.loss_func(labels, predictions, worst_case, self.robust_lambda) weight_gradient = tape.gradient(loss, self.model.trainable_variables) g = np.asarray(weight_gradient) sq_grad = [] for i in range(len(weight_gradient)): sq_grad.append(tf.math.multiply(weight_gradient[i],weight_gradient[i])) self.m[i] = (beta_1*self.m[i]) + ((1-beta_1)*(g[i]+((lam*posti_mean[i])/N))) posti_var[i] = (beta_2*posti_var[i]) + ((1-beta_2)*(sq_grad[i])) sq_grad = np.asarray(sq_grad); self.m = np.asarray(self.m) posti_var = np.asarray(posti_var) for i in range(len(weight_gradient)): m_ = self.m[i]/(1-beta_1) s_ = np.sqrt(posti_var[i]) + lam/N posti_mean[i] = posti_mean[i] - (alpha*(m_/s_)) self.model.set_weights(posti_mean) self.train_loss(loss) self.train_metric(labels, predictions) return posti_mean, posti_var def old_step(self, features, labels, lrate): # OPTIMIZATION PARAMETERS: alpha = lrate #self.alpha beta_1 = self.beta_1 beta_2 = self.beta_2 lam = self.lam posti_mean = self.model.get_weights() self.model.set_weights(posti_mean) with tf.GradientTape(persistent=True) as tape: # Get the probabilities predictions = self.model(features) # Calculate the loss if(int(self.robust_train) == 0): loss = self.loss_func(labels, predictions) elif(int(self.robust_train) == 1): logit_l, logit_u = analyzers.IBP(self, features, self.model.trainable_variables, eps=self.epsilon) v1 = tf.one_hot(labels, depth=10) v2 = 1 - tf.one_hot(labels, depth=10) worst_case = tf.math.add(tf.math.multiply(v2, logit_u), tf.math.multiply(v1, logit_l)) worst_case = self.model.layers[-1].activation(worst_case) loss = self.loss_func(labels, predictions, worst_case, self.robust_lambda) #self.train_rob(labels, worst_case) elif(int(self.robust_train) == 2): features_adv = analyzers.FGSM(self, features, self.attack_loss, eps=self.epsilon, num_models=-1) # Get the probabilities worst_case = self.model(features_adv) # Calculate the loss loss = self.loss_func(labels, predictions, worst_case, self.robust_lambda) weight_gradient = tape.gradient(loss, self.model.trainable_variables) g = np.asarray(weight_gradient) #print(g) sq_grad = [] for i in range(len(weight_gradient)): sq_grad.append(tf.math.multiply(weight_gradient[i],weight_gradient[i])) self.m[i] = (beta_1*self.m[i]) + ((1-beta_1)*(g[i])) self.posterior_var[i] = (beta_2*self.posterior_var[i]) + ((1-beta_2)*(sq_grad[i])) #print("sq: ", sq_grad) sq_grad = np.asarray(sq_grad); self.m = np.asarray(self.m) self.posterior_var = np.asarray(self.posterior_var) for i in range(len(weight_gradient)): m_ = self.m[i]/(1-beta_1) s_ = np.sqrt(self.posterior_var[i]) #print(alpha*(m_/s_)) self.posterior_mean[i] = self.posterior_mean[i] - (alpha*(m_/s_)) #self.model.set_weights(self.posterior_mean) self.train_loss(loss) self.train_metric(labels, predictions) return self.posterior_mean, self.posterior_var def train(self, X_train, y_train, X_test=None, y_test=None): super().train(X_train, y_train, X_test, y_test) def sample(self): return self.model.get_weights()
42.031056
114
0.612827
914
6,767
4.339168
0.181619
0.049168
0.032274
0.027231
0.642713
0.625567
0.579425
0.579425
0.570852
0.555219
0
0.016132
0.276341
6,767
160
115
42.29375
0.793751
0.100783
0
0.540541
0
0
0.002474
0
0
0
0
0
0
1
0.063063
false
0
0.126126
0.018018
0.243243
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
0
0
0
1
0
8b68b894928fc1a47949be32739e5721fad32eb5
518
py
Python
voluseg/_tools/evenly_parallelize.py
jingxlim/voluseg
41429a73a481fbffc3a15457be262ec021304b51
[ "MIT" ]
10
2019-11-05T18:49:50.000Z
2022-03-07T04:15:53.000Z
voluseg/_tools/evenly_parallelize.py
jingxlim/voluseg
41429a73a481fbffc3a15457be262ec021304b51
[ "MIT" ]
5
2021-02-09T20:32:38.000Z
2021-03-22T16:53:40.000Z
voluseg/_tools/evenly_parallelize.py
jingxlim/voluseg
41429a73a481fbffc3a15457be262ec021304b51
[ "MIT" ]
3
2019-12-09T08:30:18.000Z
2021-03-22T01:58:44.000Z
def evenly_parallelize(input_list): '''return evenly partitioned spark resilient distributed dataset (RDD)''' import numpy as np from pyspark.sql.session import SparkSession spark = SparkSession.builder.getOrCreate() sc = spark.sparkContext n_input = len(input_list) n_parts = sc.parallelize(input_list).getNumPartitions() partitions = np.floor(np.linspace(0, n_parts, n_input, endpoint=False)).astype(int) return sc.parallelize(zip(partitions, input_list)).partitionBy(n_parts)
37
87
0.747104
66
518
5.712121
0.590909
0.095491
0.106101
0
0
0
0
0
0
0
0
0.002273
0.150579
518
13
88
39.846154
0.854545
0.129344
0
0
0
0
0
0
0
0
0
0
0
1
0.111111
false
0
0.222222
0
0.444444
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
0
0
0
1
0
8b6908539193ed05f7b55115e992b2c27664607d
3,153
py
Python
deepplats/models/utils.py
GuillaumeDMMarion/deep-plats
d1f58d9fe07a7e3e7560fd4b425234fd5512da1a
[ "MIT" ]
null
null
null
deepplats/models/utils.py
GuillaumeDMMarion/deep-plats
d1f58d9fe07a7e3e7560fd4b425234fd5512da1a
[ "MIT" ]
null
null
null
deepplats/models/utils.py
GuillaumeDMMarion/deep-plats
d1f58d9fe07a7e3e7560fd4b425234fd5512da1a
[ "MIT" ]
null
null
null
"""Model helper module. """ from __future__ import annotations from typing import Union import numpy as np import torch class Scaler: """ Standardize features by removing the mean and scaling to unit variance. Accepts both torch.Tensor and numpy.ndarray. """ def __init__(self, astype="float32"): self.astype = astype self.fitted = False self.mean = None self.std = None @staticmethod def _coerce( X: Union[np.ndarray, torch.Tensor], astype: str ) -> Union[np.ndarray, torch.Tensor]: if isinstance(X, np.ndarray): return X.astype(astype).copy() elif isinstance(X, torch.Tensor): return X.type(getattr(torch, astype)).clone() def fit(self, X: Union[np.ndarray, torch.Tensor]) -> Scaler: """Extract mean and std from training.""" mean_kwargs = std_kwargs = {} if isinstance(X, torch.Tensor): mean_kwargs = dict(keepdim=True) std_kwargs = dict(unbiased=False, keepdim=True) self.mean = float(X.mean(0, **mean_kwargs)) self.std = float(X.std(0, **std_kwargs) + 1e-7) self.fitted = True return self def transform( self, X: Union[np.ndarray, torch.Tensor] ) -> Union[np.ndarray, torch.Tensor]: """Transform array.""" X = self._coerce(X, self.astype) X -= self.mean X /= self.std return X def inverse_transform( self, X: Union[np.ndarray, torch.Tensor] ) -> Union[np.ndarray, torch.Tensor]: """Transform array.""" X = self._coerce(X, self.astype) X *= self.std X += self.mean return X def fit_transform( self, X: Union[np.ndarray, torch.Tensor] ) -> Union[np.ndarray, torch.Tensor]: """Fit, then transform array.""" self.fit(X) return self.transform(X) class TimeScaler(Scaler): """Scaler specific for monotonically increasing timesteps.""" def __init__(self, astype="float32"): self.step = None super().__init__(astype=astype) @staticmethod def _extract_steps( X: Union[np.ndarray, torch.Tensor] ) -> Union[np.ndarray, torch.Tensor]: X_flat = X.flatten() steps = np.diff(X_flat) if isinstance(X, np.ndarray) else X_flat.diff() return steps def fit(self, X: Union[np.ndarray, torch.Tensor]) -> Scaler: untransformed_steps = self._extract_steps(X) assert ( np.unique(untransformed_steps).size == 1 ), "Time should be monotonically increasing." fit_res = super().fit(X) transform = super().transform(X) self.step = float(self._extract_steps(transform)[0]) return fit_res class FlattenLSTM(torch.nn.Module): """LSTM flattener""" def __init__(self, last_step: bool = True): super().__init__() self.last_step = last_step def forward(self, X: torch.Tensor) -> torch.Tensor: """Default forward method.""" out, (final_out, _) = X if self.last_step: return final_out[0] return out.flatten(1)
29.745283
79
0.598795
391
3,153
4.68798
0.255754
0.102019
0.091653
0.124386
0.30551
0.267867
0.223131
0.223131
0.223131
0.223131
0
0.005245
0.274342
3,153
105
80
30.028571
0.795892
0.104345
0
0.24
0
0
0.019544
0
0
0
0
0
0.013333
1
0.146667
false
0
0.053333
0
0.373333
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
0
0
0
1
0
8b69509f22f3cb70d7f8b98551364109fc2064fa
1,491
py
Python
test/utils/test_utils.py
Chick-star/sagemaker-xgboost-container
e06e278b3a34515f79fa73ab770b574b9aafe5f0
[ "Apache-2.0" ]
1
2021-07-10T15:08:18.000Z
2021-07-10T15:08:18.000Z
test/utils/test_utils.py
Chick-star/sagemaker-xgboost-container
e06e278b3a34515f79fa73ab770b574b9aafe5f0
[ "Apache-2.0" ]
null
null
null
test/utils/test_utils.py
Chick-star/sagemaker-xgboost-container
e06e278b3a34515f79fa73ab770b574b9aafe5f0
[ "Apache-2.0" ]
1
2020-02-07T22:41:34.000Z
2020-02-07T22:41:34.000Z
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the 'license' file accompanying this file. This file 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 __future__ import absolute_import import socket from contextlib import closing import test.utils.local_mode as localmode def files_exist(opt_ml, files): for f in files: assert localmode.file_exists(opt_ml, f), 'file {} was not created'.format(f) def predict_and_assert_response_length(data, content_type): predict_response = localmode.request(data, content_type=content_type) assert len(predict_response) == len(data) # From https://stackoverflow.com/a/45690594 def find_two_open_ports(): with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s1: s1.bind(('', 0)) s1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s2: s2.bind(('', 0)) s2.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s1.getsockname()[1], s2.getsockname()[1]
35.5
84
0.7277
220
1,491
4.795455
0.509091
0.056872
0.028436
0.043602
0.181991
0.181991
0.181991
0.181991
0.100474
0.100474
0
0.02437
0.17438
1,491
41
85
36.365854
0.832656
0.390342
0
0
0
0
0.025698
0
0
0
0
0
0.166667
1
0.166667
false
0
0.222222
0
0.444444
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
0
0
0
1
0
8b6f0fc1892ec8aa8153dba6ca257fd87d9c6c75
4,263
py
Python
Sketches/THF/3D/playground/SimpleCube.py
sparkslabs/kamaelia_orig
24b5f855a63421a1f7c6c7a35a7f4629ed955316
[ "Apache-2.0" ]
12
2015-10-20T10:22:01.000Z
2021-07-19T10:09:44.000Z
Sketches/THF/3D/playground/SimpleCube.py
sparkslabs/kamaelia_orig
24b5f855a63421a1f7c6c7a35a7f4629ed955316
[ "Apache-2.0" ]
2
2015-10-20T10:22:55.000Z
2017-02-13T11:05:25.000Z
Sketches/THF/3D/playground/SimpleCube.py
sparkslabs/kamaelia_orig
24b5f855a63421a1f7c6c7a35a7f4629ed955316
[ "Apache-2.0" ]
6
2015-03-09T12:51:59.000Z
2020-03-01T13:06:21.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # 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. # ------------------------------------------------------------------------- """\ ===================== Simple Cube component ===================== TODO """ import Axon import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from Display3D import Display3D from Util3D import * from Object3D import * class SimpleCube(Object3D): def __init__(self, **argd): super(SimpleCube, self).__init__(**argd) self.grabbed = False def setup(self): self.addListenEvents( [pygame.MOUSEMOTION, pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP ]) def draw(self): # draw faces glBegin(GL_QUADS) glColor4f(1.0,0.75,0.75,0.5) glVertex3f(1.0,1.0,1.0) glVertex3f(-1.0,1.0,1.0) glVertex3f(-1.0,-1.0,1.0) glVertex3f(1.0,-1.0,1.0) glColor4f(0.75,1.0,0.75, 0.5) glVertex3f(1.0,1.0,-1.0) glVertex3f(1.0,-1.0,-1.0) glVertex3f(-1.0,-1.0,-1.0) glVertex3f(-1.0,1.0,-1.0) glColor4f(0.75,0.75,1.0, 0.5) glVertex3f(1.0,1.0,1.0) glVertex3f(1.0,-1.0,1.0) glVertex3f(1.0,-1.0,-1.0) glVertex3f(1.0,1.0,-1.0) glColor4f(1.0,0.75,1.0, 0.5) glVertex3f(-1.0,1.0,1.0) glVertex3f(-1.0,-1.0,1.0) glVertex3f(-1.0,-1.0,-1.0) glVertex3f(-1.0,1.0,-1.0) glColor4f(0.75,1.0,1.0, 0.5) glVertex3f(1.0,1.0,1.0) glVertex3f(-1.0,1.0,1.0) glVertex3f(-1.0,1.0,-1.0) glVertex3f(1.0,1.0,-1.0) glColor4f(1.0,1.0,0.75, 0.5) glVertex3f(1.0,-1.0,1.0) glVertex3f(-1.0,-1.0,1.0) glVertex3f(-1.0,-1.0,-1.0) glVertex3f(1.0,-1.0,-1.0) glEnd() def handleEvents(self): pass #while self.dataReady("inbox"): #event = self.recv("inbox") #if event.type == pygame.MOUSEBUTTONDOWN and self.ogl_name in event.hitobjects: #if event.button in [1,3]: #self.grabbed = event.button #if event.button == 4: #self.pos.z -= 1 #if event.button == 5: #self.pos.z += 1 #if event.type == pygame.MOUSEBUTTONUP: #if event.button in [1,3]: #self.grabbed = 0 #if event.type == pygame.MOUSEMOTION: #if self.grabbed == 1: #self.rot.y += float(event.rel[0]) #self.rot.x += float(event.rel[1]) #self.rot %= 360 #if self.grabbed == 3: #self.pos.x += float(event.rel[0])/10.0 #self.pos.y -= float(event.rel[1])/10.0 if __name__=='__main__': class Bunch: pass class CubeRotator(Axon.Component.component): def main(self): while 1: yield 1 self.send( (0.1, 0.1, 0.1), "outbox") from Kamaelia.Util.Graphline import Graphline CUBEC = SimpleCube(pos=Vector(0, 0,-12), name="Center cube").activate() CUBER = SimpleCube(pos=Vector(4,0,-22), name="Right cube").activate() CUBEB = SimpleCube(pos=Vector(0,-4,-18), name="Bottom cube").activate() ROTATOR = CubeRotator().activate() ROTATOR.link((ROTATOR, "outbox"), (CUBEC, "rel_rotation")) Axon.Scheduler.scheduler.run.runThreads()
31.577778
98
0.546798
605
4,263
3.821488
0.276033
0.071799
0.067474
0.088235
0.254758
0.246107
0.232266
0.232266
0.208045
0.208045
0
0.09485
0.280319
4,263
134
99
31.813433
0.658735
0.356087
0
0.380952
0
0
0.023748
0
0
0
0
0.007463
0
1
0.079365
false
0.031746
0.142857
0
0.269841
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
0
0
0
1
0
8b72e1cc46246e65f5c4487e4423aa24c3c70e6e
8,480
py
Python
plugins/modules/waf_domain.py
schrej/ansible-collection-cloud
1fa1d18aaa06178616af17d8240e8fc5d13a370c
[ "Apache-2.0" ]
16
2020-09-22T14:45:52.000Z
2022-02-11T07:56:38.000Z
plugins/modules/waf_domain.py
schrej/ansible-collection-cloud
1fa1d18aaa06178616af17d8240e8fc5d13a370c
[ "Apache-2.0" ]
153
2020-08-20T14:00:55.000Z
2022-03-30T13:48:51.000Z
plugins/modules/waf_domain.py
schrej/ansible-collection-cloud
1fa1d18aaa06178616af17d8240e8fc5d13a370c
[ "Apache-2.0" ]
11
2020-09-01T12:21:09.000Z
2021-12-23T09:48:34.000Z
#!/usr/bin/python # 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. DOCUMENTATION = ''' --- module: waf_domain short_description: Add/Modify/Delete WAF domain extends_documentation_fragment: opentelekomcloud.cloud.otc version_added: "0.0.3" author: "Anton Sidelnikov (@anton-sidelnikov)" description: - Add/Modify/Delete WAF domain from the OTC. options: name: description: Specifies the domain name. required: true type: str certificate: description: Specifies the certificate. type: str server: description: Specifies the origin server information. Each element contains client_protocol (HTTP or HTTPS), server_protocol (HTTP or HTTPS), address (IP address or domain name), port (from 0 to 65535) type: list elements: dict proxy: description: Specifies whether a proxy is configured. type: bool sip_header_name: description: Specifies the type of the source IP header. choices: [default, cloudflare, akamai, custom] type: str sip_header_list: description: Specifies the HTTP request header for identifying the real source IP address. type: list elements: str state: description: - Should the resource be present or absent. choices: [present, absent] default: present type: str requirements: ["openstacksdk", "otcextensions"] ''' RETURN = ''' waf_domain: description: List of dictionaries describing domains matching query. type: complex returned: On Success. contains: id: description: Specifies the instance ID. type: str hostname: description: Specifies the domain name. type: str cname: description: Specifies the CNAME value. type: str sample: "efec1196267b41c399f2980ea4048517.waf.cloud.com." policy_id: description: Specifies the policy ID. type: str protect_status: description: Specifies the WAF mode. type: int access_status: description: Specifies whether a domain name is connected to WAF. type: int protocol: description: Specifies the protocol type. type: str certificate_id: description: Specifies the certificate ID. type: str server: description: Specifies the origin server information. type: dict proxy: description: Specifies whether a proxy is configured. type: bool timestamp: description: Specifies the time when a domain name is created. type: str ''' EXAMPLES = ''' # Create Domain. - waf_domain: name: test.domain.name server: - client_protocol: https server_protocol: https address: 4.3.2.1 port: 8080 proxy: False state: present # Modify Domain. - waf_domain: name: "{{ domain_name }}" certificate: "{{ cert_name }}" # Delete Domain. - waf_domain: name: "{{ domain_id }}" state: absent ''' from ansible_collections.opentelekomcloud.cloud.plugins.module_utils.otc import OTCModule class WafDomainModule(OTCModule): argument_spec = dict( name=dict(required=True, type='str'), certificate=dict(required=False), server=dict(required=False, type='list', elements='dict'), proxy=dict(required=False, type='bool'), sip_header_name=dict(required=False, choices=['default', 'cloudflare', 'akamai', 'custom']), sip_header_list=dict(required=False, type='list', elements='str'), state=dict(default='present', choices=['absent', 'present']), ) module_kwargs = dict( supports_check_mode=True ) otce_min_version = '0.9.0' def _check_server_client_protocol(self, server: list): for srv in server: if srv['client_protocol'] == 'HTTPS': return True return False def _compare_servers_list(self, old, new): pairs = zip(old, new) return any(x != y for x, y in pairs) def run(self): name_filter = self.params['name'] domain = None changed = False domain = self.conn.waf.find_domain(name_or_id=name_filter, ignore_missing=True) if domain: if not domain.server: domain = self.conn.waf.get_domain(domain.id) if self.params['state'] == 'absent': changed = False if domain: if self.ansible.check_mode: self.exit_json(changed=True) self.conn.waf.delete_domain(domain) changed = True elif self.params['state'] == 'present': query = {} certificate_filter = self.params['certificate'] server_filter = self.params['server'] proxy_filter = self.params['proxy'] sip_header_name_filter = self.params['sip_header_name'] sip_header_list_filter = self.params['sip_header_list'] if name_filter: query['name'] = name_filter if certificate_filter: try: res = self.conn.waf.find_certificate(name_or_id=certificate_filter) query['certificate_id'] = res.id except self.sdk.exceptions.ResourceNotFound: self.fail_json(msg='certificate not found.') if server_filter: for srv in server_filter: srv['client_protocol'] = srv['client_protocol'].upper() srv['server_protocol'] = srv['server_protocol'].upper() if server_filter and not domain: if self._check_server_client_protocol(server_filter): if not certificate_filter: self.fail_json(msg='certificate should by specified' ' when client_protocol is equal to HTTPS.') query['server'] = server_filter if proxy_filter and not domain: query['proxy'] = proxy_filter if not sip_header_name_filter and not sip_header_list_filter: self.fail_json(msg='sip_header_name and sip_header_list' ' should by specified when proxy is set to true.') else: query['sip_header_name'] = sip_header_name_filter query['sip_header_list'] = sip_header_list_filter if domain: mquery = {} if certificate_filter: if domain.certificate_id != query['certificate_id']: mquery['certificate_id'] = query['certificate_id'] if proxy_filter: if domain.proxy != proxy_filter: mquery['proxy'] = proxy_filter if sip_header_name_filter: if domain.sip_header_name != sip_header_name_filter: mquery['sip_header_name'] = sip_header_name_filter if sip_header_list_filter: if domain.sip_header_list != sip_header_list_filter: mquery['sip_header_list'] = sip_header_list_filter if server_filter: if self._compare_servers_list(old=domain.server, new=server_filter): mquery['server'] = server_filter if self.ansible.check_mode: self.exit_json(changed=True) domain = self.conn.waf.update_domain(domain, **mquery) self.exit( changed=True, waf_domain=domain.to_dict() ) if self.ansible.check_mode: self.exit_json(changed=True) domain = self.conn.waf.create_domain(**query) self.exit( changed=True, waf_domain=domain.to_dict() ) self.exit(changed=changed) def main(): module = WafDomainModule() module() if __name__ == '__main__': main()
33.254902
100
0.610024
964
8,480
5.186722
0.23029
0.0468
0.0644
0.0228
0.289
0.1712
0.1374
0.1118
0.0982
0.0586
0
0.007965
0.304127
8,480
254
101
33.385827
0.839349
0.063443
0
0.266355
0
0
0.420555
0.013367
0
0
0
0
0
1
0.018692
false
0
0.004673
0
0.056075
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
0
0
0
1
0
8b75a7eaacdb476c970a5cf2013b558edc778b20
10,303
py
Python
incremental_evaluation_run.py
comrob/ensgendel
4958d588a30a5bc60c6e7af5abb2b830b1265a25
[ "BSD-3-Clause" ]
null
null
null
incremental_evaluation_run.py
comrob/ensgendel
4958d588a30a5bc60c6e7af5abb2b830b1265a25
[ "BSD-3-Clause" ]
null
null
null
incremental_evaluation_run.py
comrob/ensgendel
4958d588a30a5bc60c6e7af5abb2b830b1265a25
[ "BSD-3-Clause" ]
null
null
null
import incremental_evaluation.utils as IE import incremental_evaluation.scenario_sets as SS import incremental_evaluation.visualisation_helper as VH import models.basic_predictor_interfaces import models.ensgendel_interface import incremental_evaluation.data_file_helper as DFH import os import argparse SS_MNIST012 = "mnist012" SS_MNIST197 = "mnist197" SS_MNIST_CN5 = "mnist_cn5" SS_GAUSS3 = "gauss_3" RESULTS = os.path.join("results", "incremental_evaluation_run") def datafile_path(_experiment_name, _scenario_set_name, _trial_tag): return os.path.join(RESULTS, "{}_{}_{}".format(_experiment_name, _scenario_set_name, _trial_tag)) def stat_cell_format(stats, iteration): return "{:.2f}({:.2f})".format(stats["mean"][iteration], stats["std"][iteration]) parser = argparse.ArgumentParser(description="EnsGenDel algorithm & Incremental evaluation framework.\n" "The continual learning algorithms are evaluated in predefined scenarios." "For example: [{0:[9,7]}, {0:[8], 1:[7]}] is a scenario of two tasks." "In the first task {0: [9, 7]} the predictor gets training instances of " "nines and sevens images labeled as 0. In the second task {0:[8], 1:[7]} " "the predictor gets training instances of eights labeled as 0 and " "sevens labeled as 1. Note that the sevens changed the label. After the " "second task the predictor should classify nines and eights as 0 and " "sevens as 1.\n" "The scenario is encoded into bracket-less notation in filenames, e.g., " "[{0:[9,7]}, {0:[8], 1:[7]}] -> T0x97T0x8a1x7 (any resemblance with " "hexadecimals is purely coincidental).") parser.add_argument('experiment_name', help="Experiment name which will be in file prefix.") parser.add_argument('scenario_name', help="Select the scenario. One of the following: " + str([ SS_MNIST012, SS_MNIST197, SS_MNIST_CN5, SS_GAUSS3]) + "The scenario name is appended after experiment_name.") parser.add_argument('modes', help="Series of numbers activating five modes of this application:" "1:scenario preview; 2:predictor training; 3:debug evaluation; " "4:generate csv table with evaluation stats; 5:generate accuracy plots" ";e.g., '24' trains the predictors and then generates csv table with results.") parser.add_argument('--trials', type=int, default=1, help="Number of independent runs. The trial number is appended " "in the postfix of the file.") parser.add_argument('--trials_from', type=int, default=0, help="Index of the first trial.") parser.add_argument('--scout_number', type=int, default=-1, help="Cropping the training set. Speeding up the training " "at the cost of less accuracy.") parser.add_argument("--debug", default=False, type=bool, help="Runs only light weight models. True/False") if __name__ == '__main__': args = parser.parse_args() # Experiment setup trial_tags = [i for i in range(args.trials_from, args.trials_from + args.trials)] experiment_name = args.experiment_name scout_subset = args.scout_number if args.scout_number > 0 else None scenario_set_name = args.scenario_name mode = list(map(int, args.modes)) # mode += [1] # show scenario data # mode += [2] # run predictor learning on scenarios # mode += [3] # evaluate predictors scenarios # mode += [4] # write accuracy statistics into table # mode += [5] # write accuracy statistics into table # list of predictor classes that implement the incremental_evaluation.interfaces.Predictor if args.debug: predictor_builders = [ models.basic_predictor_interfaces.SGD, models.basic_predictor_interfaces.Perceptron, ] else: predictor_builders = [ models.ensgendel_interface.Ensgendel, models.ensgendel_interface.Ensgen, models.ensgendel_interface.Ens, models.basic_predictor_interfaces.Perceptron, ] # scenario sets implementing the incremental_evaluation.interfaces.ScenarioSet if scenario_set_name == SS_MNIST012: scenario_set = SS.MnistMinimalScenarios(digits_tripplet=(0, 1, 2), debug_set=False, scout_subset=scout_subset) visualiser = VH.mnist_visualiser elif scenario_set_name == SS_MNIST197: scenario_set = SS.MnistMinimalScenarios(digits_tripplet=(1, 9, 7), debug_set=False, scout_subset=scout_subset) visualiser = VH.mnist_visualiser elif scenario_set_name == SS_MNIST_CN5: scenario_set = SS.MnistConvergentFiveScenarios(scout_subset=scout_subset) visualiser = VH.mnist_visualiser elif scenario_set_name == SS_GAUSS3: scenario_set = SS.Gauss3DMinimalScenarios(train_size=scout_subset) visualiser = VH.gauss3d_visualiser else: raise NotImplementedError(scenario_set_name) # setting up basic directories if not os.path.exists("results"): os.mkdir("results") if not os.path.exists(RESULTS): os.mkdir(RESULTS) # Pre-flight check of the scenario if 1 in mode: scenarios = scenario_set.get_scenarios() train_sam, train_sub = scenario_set.get_training_set() test_sam, test_sub = scenario_set.get_test_set() for scenario in scenarios: folder_name = "preview_{}".format(VH.scenario_into_filename(str(scenario))) folder_path = os.path.join(RESULTS, folder_name) if not os.path.exists(folder_path): os.mkdir(folder_path) VH.show_scenario(scenario, test_sam, test_sub, visualiser, save_into=folder_path) # Cycle of experiment runs for trial_tag in trial_tags: experiment_path = datafile_path(experiment_name, scenario_set_name, trial_tag) if not os.path.exists(experiment_path): os.mkdir(experiment_path) if 2 in mode: DFH.run_and_save(predictor_builders, scenario_set, experiment_path) if 3 in mode: evals = DFH.datafile_evaluation(experiment_path, { DFH.TOTAL_ACCURACY: IE.evaluate_task_total_accuracy, DFH.LOCAL_ACCURACY: IE.evaluate_task_accuracy, DFH.SUBCLASS_ACCURACY: IE.evaluate_subclass_accuracy, }) print(evals) # Stats evaluation files = [datafile_path(experiment_name, scenario_set_name, trial_tag) for trial_tag in trial_tags] portfolio = dict([(str(clazz), files) for clazz in predictor_builders]) if 4 in mode: eval_stats_total = DFH.extract_stats_for_portfolio(portfolio, over_testing_set=True, task_accuracy_type=DFH.TOTAL_ACCURACY) table = VH.stats_into_text_table(eval_stats_total, stat_cell_format, cell_join=';', row_join='\n') print(table) table_path = os.path.join(RESULTS, "{}_{}_total_accuracy.csv".format(experiment_name, scenario_set_name)) with open(table_path, "w") as fil: fil.write(table) print("Saved stats of total accuracy into {}".format(table_path)) if 5 in mode: figure_styles = [ [("color", "r"), ("marker", "o")], [("color", "g"), ("marker", "^")], [("color", "b"), ("marker", "x")], [("color", "c"), ("marker", "s")], [("color", "m"), ("marker", "d")], [("color", "y"), ("marker", "+")], [("color", "k"), ("marker", "*")], ] classifier_style = dict( [(str(clazz), dict([("label", clazz.__name__)] + figure_styles[i % len(figure_styles)])) for i, clazz in enumerate(predictor_builders)] ) eval_stats_total = DFH.extract_stats_for_portfolio(portfolio, over_testing_set=True, task_accuracy_type=DFH.TOTAL_ACCURACY) scenarios = list(eval_stats_total[list(eval_stats_total.keys())[0]].keys()) print(scenarios) for i, scenario in enumerate(scenarios): # picking subclass for tracking scenario_obj = eval(scenario) tracked_label = list(scenario_obj[0].keys())[0] tracked_subclass = scenario_obj[0][tracked_label][-1] # tracking the selected subclass label assignment def tracked_evaluation(_scen, _pred, _subs): # lambda for tracking return IE.evaluate_selected_subclass_accuracy(_scen, _pred, _subs, tracked_subclass, tracked_label) eval_stats_tracked = DFH.extract_stats_for_portfolio( portfolio, over_testing_set=True, task_accuracy_type=None, evaluator=tracked_evaluation) # titles and names _scenario_str = scenario if type(scenario) is bytes: _scenario_str = scenario.decode('ASCII') # sometimes hdf5 returns bytes instead of strings test_task = str(IE.get_perfect_task_map(scenario_obj, len(scenario_obj) - 1)) tracked_task = "{{{}: [{}]}}".format(tracked_label, tracked_subclass) title = "Scenario: {}\ntest task {}(full), tracked assignment {}(dashed)".format( _scenario_str, test_task, tracked_task) # visualisaiton fig_path = os.path.join(RESULTS, "{}_{}_{}_accuracy.pdf".format(experiment_name, scenario_set_name, VH.scenario_into_filename(_scenario_str))) VH.show_metric_evol(eval_stats_total, scenario, classifier_style, fig_path=fig_path, tracked_eval_stats=eval_stats_tracked, title=title) print("fig of scenario {} saved into {}".format(scenario, fig_path))
54.803191
119
0.625837
1,198
10,303
5.129382
0.24374
0.035801
0.029292
0.02441
0.225386
0.1738
0.138649
0.118633
0.118633
0.082343
0
0.01379
0.275066
10,303
187
120
55.096257
0.808944
0.067165
0
0.085526
0
0.019737
0.194639
0.007406
0
0
0
0
0
1
0.019737
false
0
0.052632
0.019737
0.092105
0.032895
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b76c38f1e29d8bf142d3e3373941067e32aadc6
15,792
py
Python
core/models.py
admariner/madewithwagtail
a43b3263c0f151ece4994fccd561b0575db4979f
[ "MIT" ]
null
null
null
core/models.py
admariner/madewithwagtail
a43b3263c0f151ece4994fccd561b0575db4979f
[ "MIT" ]
null
null
null
core/models.py
admariner/madewithwagtail
a43b3263c0f151ece4994fccd561b0575db4979f
[ "MIT" ]
null
null
null
import os import re from bs4 import BeautifulSoup from django.core.exceptions import ObjectDoesNotExist from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.db import models from django.db.models import Case, Count, Q, Value, When from django.utils.encoding import python_2_unicode_compatible from django.utils.html import mark_safe from modelcluster.fields import ParentalKey from modelcluster.tags import ClusterTaggableManager from taggit.models import Tag, TaggedItemBase from core import panels from core.forms import SubmitFormBuilder from core.utilities import has_recaptcha, validate_only_one_instance from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailcore.models import Page from wagtail.wagtailforms.models import AbstractEmailForm, AbstractFormField from wagtail.wagtailsearch import index from wagtailcaptcha.models import WagtailCaptchaEmailForm class IndexPage(models.Model): """ Abstract Index Page class. Declare a couple of abstract methods that should be implemented by any class implementing this 'interface'. """ def clean(self): validate_only_one_instance(self) def children(self): raise NotImplementedError("Class %s doesn't implement aMethod()" % (self.__class__.__name__)) def get_context(self, request, *args, **kwargs): raise NotImplementedError("Class %s doesn't implement aMethod()" % (self.__class__.__name__)) class Meta: abstract = True class HomePage(Page, IndexPage): """ HomePage class, inheriting from wagtailcore.Page straight away """ subpage_types = [ 'core.CompanyIndex', 'core.SubmitFormPage', ] feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = [] body = RichTextField(blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) @property def og_image(self): # Returns image and image type of feed_image, if exists image = {'image': None, 'type': None} if self.feed_image: image['image'] = self.feed_image name, extension = os.path.splitext(image['image'].file.url) image['type'] = extension[1:] return image def children(self): return self.get_children().live() def get_context(self, request, *args, **kwargs): # Get pages pages = WagtailSitePage.objects\ .live()\ .descendant_of(self)\ .order_by('-is_featured', '-latest_revision_created_at') # Filter by tag tag = request.GET.get('tag') if tag: pages = pages.filter(tags__slug__iexact=tag) # Pagination page = request.GET.get('page') paginator = Paginator(pages, 12) # Show 12 pages per page try: pages = paginator.page(page) except PageNotAnInteger: pages = paginator.page(1) except EmptyPage: pages = paginator.page(paginator.num_pages) # Update template context context = super(HomePage, self).get_context(request, *args, **kwargs) context['pages'] = pages context['tag'] = tag # Only tags used by live pages context['tags'] = Tag.objects.filter( core_pagetag_items__isnull=False, core_pagetag_items__content_object__live=True ).annotate(count=Count('core_pagetag_items')).distinct().order_by('-count', 'name') return context class Meta: verbose_name = "Home Page" content_panels = panels.HOME_PAGE_CONTENT_PANELS promote_panels = panels.WAGTAIL_PAGE_PROMOTE_PANELS class CompanyIndex(Page, IndexPage): """ HomePage class, inheriting from wagtailcore.Page straight away """ parent_types = ['core.HomePage'] subpage_types = ['core.WagtailCompanyPage'] search_fields = [] body = RichTextField(null=True, blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) show_map = models.BooleanField(default=False, help_text='Show map of companies around the world.') def children(self): return self.get_children().live() def get_context(self, request, *args, **kwargs): # Get pages. # Note: `numchild` includes draft/unpublished pages but does not create additional queries. pages = WagtailCompanyPage.objects\ .live()\ .descendant_of(self)\ .distinct()\ .order_by('-numchild', '-latest_revision_created_at') # Filter by tag tag = request.GET.get('tag') if tag: pages = pages.filter(tags__name__iexact=tag) # Pagination page = request.GET.get('page') paginator = Paginator(pages, 12) try: pages = paginator.page(page) except PageNotAnInteger: pages = paginator.page(1) except EmptyPage: pages = paginator.page(paginator.num_pages) # Update template context context = super(CompanyIndex, self).get_context(request, *args, **kwargs) context['pages'] = pages context['tag'] = tag return context class Meta: verbose_name = "Companies Index Page" content_panels = panels.WAGTAIL_COMPANY_INDEX_PAGE_CONTENT_PANELS class PageTag(TaggedItemBase): content_object = ParentalKey('core.WagtailPage', related_name='tagged_items') # Main core Page model. All main content pages inherit from this class. class WagtailPage(Page): """ Our main custom Page class. All content pages should inherit from this one. """ parent_types = ['core.HomePage'] subpage_types = ['core.WagtailPage'] is_creatable = False feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body = RichTextField(blank=True, features=['bold', 'italic', 'ol', 'ul', 'link', 'cleanhtml']) tags = ClusterTaggableManager(through=PageTag, blank=True) search_fields = [] @property def parent(self): try: return self.get_ancestors().reverse()[0] except IndexError: return None @property def child(self): for related_object in self._meta.get_all_related_objects(): if not issubclass(related_object.model, self.__class__): continue try: return getattr(self, related_object.get_accessor_name()) except ObjectDoesNotExist: pass @property def body_text(self): return BeautifulSoup(self.body, "html5lib").get_text() @property def body_excerpt(self): """ Return body text replacing end of lines (. ? ! chars) with a blank space """ return re.sub(r'([\.?!])([a-zA-Z])', r'\1 \2', self.body_text) @property def og_image(self): # Returns image and image type of feed_image or image as fallback, if exists image = {'image': None, 'type': None} if self.feed_image: image['image'] = self.feed_image name, extension = os.path.splitext(image['image'].file.url) image['type'] = extension[1:] return image class Meta: verbose_name = "Content Page" content_panels = panels.WAGTAIL_PAGE_CONTENT_PANELS promote_panels = panels.WAGTAIL_PAGE_PROMOTE_PANELS class WagtailCompanyPage(WagtailPage): """ Company page listing a bunch of site pages """ parent_types = ['core.HomePage'] subpage_types = ['core.WagtailSitePage'] SITES_ORDERING_ALPHABETICAL = 'alphabetical' SITES_ORDERING_CREATED = 'created' SITES_ORDERING_PATH = 'path' SITES_ORDERING = { SITES_ORDERING_PATH: { 'name': 'Path (i.e. manual)', 'ordering': ['-path'], }, SITES_ORDERING_ALPHABETICAL: { 'name': 'Alphabetical', 'ordering': ['title'], }, SITES_ORDERING_CREATED: { 'name': 'Created', 'ordering': ['-first_published_at'], }, } SITES_ORDERING_CHOICES = [ (key, opts['name']) for key, opts in sorted(SITES_ORDERING.items(), key=lambda k: k[1]['name']) ] company_url = models.URLField( blank=True, null=True, help_text='The URL of your site, something like "https://www.springload.co.nz"', ) github_url = models.URLField(null=True, blank=True) twitter_url = models.URLField(null=True, blank=True) location = models.CharField(max_length=128, blank=True, null=True) show_map = models.BooleanField(default=True, help_text='Show company in the map of companies around the world.') coords = models.CharField(max_length=255, blank=True, null=True) logo = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) sites_ordering = models.CharField( max_length=20, blank=False, choices=SITES_ORDERING_CHOICES, default=SITES_ORDERING_CREATED, help_text='The order the sites will be listed on the page', ) search_fields = Page.search_fields + [ index.SearchField('company_url', boost=1), index.SearchField('body_text', boost=1) ] @property def lat(self): if self.coords: return self.coords.split(",")[0].strip() else: return None @property def lon(self): if self.coords: return self.coords.split(",")[1].strip() else: return None @property def twitter_handler(self): if self.twitter_url: return "@%s" % self.twitter_url.strip('/ ').split("/")[-1] else: return None @property def github_user(self): if self.github_url: return self.github_url.strip('/ ').split("/")[-1] else: return None @property def children_count(self): return self.children().count() @property def og_image(self): # Returns image and image type of logo or feed_image as fallback, if exists image = {'image': None, 'type': None} if self.logo: image['image'] = self.logo elif self.feed_image: image['image'] = self.feed_image name, extension = os.path.splitext(image['image'].file.url) image['type'] = extension[1:] return image def children(self): user_ordering = self.SITES_ORDERING[self.sites_ordering]['ordering'] pages = WagtailSitePage.objects.live().filter(Q(path__startswith=self.path) | Q(in_cooperation_with=self)) # When ordering by `path`, the collaborations would either all be listed first or last # depending on whether the collaborator(s) page(s) was created before or after this page. # Adding an overwrite here so collaborations always appear last. if self.sites_ordering == self.SITES_ORDERING_PATH: pages = pages.annotate( is_own=Case( When(path__startswith=self.path, then=Value(True)), default_value=Value(False), output_field=models.BooleanField(), ) ).order_by('is_own', *user_ordering) # When ordering alphabetically or by creation date, # own sites and collaboration sites will be sorted together. else: pages = pages.order_by(*user_ordering) return pages def get_context(self, request, *args, **kwargs): # Get pages pages = self.children() # Pagination page = request.GET.get('page') paginator = Paginator(pages, 12) # Show 12 pages per page try: pages = paginator.page(page) except PageNotAnInteger: pages = paginator.page(1) except EmptyPage: pages = paginator.page(paginator.num_pages) # Update template context context = super(WagtailCompanyPage, self).get_context(request, *args, **kwargs) context['pages'] = pages return context @property def sites_count(self): # Note: It uses `self.numchild` which counts draft/unpublished pages but does not create additional queries. return self.get_children_count() class Meta: verbose_name = "Company Page" content_panels = panels.WAGTAIL_COMPANY_PAGE_CONTENT_PANELS settings_panels = panels.WAGTAIL_COMPANY_PAGE_SETTINGS_PANELS @python_2_unicode_compatible class WagtailSitePage(WagtailPage): """ Site page """ parent_types = ['core.WagtailCompanyPage'] subpage_types = [] is_featured = models.BooleanField( "Featured", default=False, blank=False, help_text='If enabled, this site will appear on top of the sites list of the homepage.' ) site_screenshot = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text=mark_safe( 'Use a <b>ratio</b> of <i>16:13.28</i> ' 'and a <b>size</b> of at least <i>1200x996 pixels</i> ' 'for an optimal display.' ), ) site_url = models.URLField( blank=True, null=True, help_text='The URL of your site, something like "https://www.springload.co.nz"', ) in_cooperation_with = models.ForeignKey( 'core.WagtailCompanyPage', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) search_fields = Page.search_fields + [ index.SearchField('site_url'), index.SearchField('body_text') ] @property def og_image(self): # Returns image and image type of feed_image, if exists image = {'image': None, 'type': None} if self.feed_image: image['image'] = self.feed_image elif self.site_screenshot: image['image'] = self.site_screenshot name, extension = os.path.splitext(image['image'].file.url) image['type'] = extension[1:] return image def __str__(self): if self.site_url: return '%s - %s' % (self.title, self.site_url) return self.title class Meta: verbose_name = "Site Page" content_panels = panels.WAGTAIL_SITE_PAGE_CONTENT_PANELS promote_panels = panels.WAGTAIL_SITE_PAGE_PROMOTE_PANELS class SubmitFormField(AbstractFormField): page = ParentalKey('SubmitFormPage', related_name='form_fields') class SubmitFormPage(WagtailCaptchaEmailForm if has_recaptcha() else AbstractEmailForm): """ Form page, inherits from WagtailCaptchaEmailForm if available, otherwise fallback to AbstractEmailForm """ def __init__(self, *args, **kwargs): super(SubmitFormPage, self).__init__(*args, **kwargs) # WagtailCaptcha does not respect cls.form_builder and overwrite with its own. # See https://github.com/springload/wagtail-django-recaptcha/issues/7 for more info. self.form_builder = SubmitFormBuilder parent_types = ['core.HomePage'] subpage_types = [] search_fields = [] body = RichTextField(blank=True, help_text='Edit the content you want to see before the form.') thank_you_text = RichTextField(blank=True, help_text='Set the message users will see after submitting the form.') class Meta: verbose_name = "Form Page" content_panels = panels.SUBMIT_FORM_PAGE_CONTENT_PANELS
31.967611
117
0.634435
1,806
15,792
5.378738
0.198228
0.01853
0.021001
0.014
0.462425
0.435454
0.394585
0.35979
0.352172
0.323554
0
0.004542
0.261082
15,792
493
118
32.032454
0.82792
0.116135
0
0.461972
0
0.002817
0.116539
0.008914
0
0
0
0
0
1
0.070423
false
0.002817
0.056338
0.014085
0.405634
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
0
0
0
1
0
8b790365631a765420b493cba01b292fac4bc258
475
py
Python
ArrangingCoins.py
Jcarlos0828/LeetCode-PracticeResults
73566a131629038caf2555eaf4999379227ec369
[ "MIT" ]
1
2019-06-26T22:44:16.000Z
2019-06-26T22:44:16.000Z
ArrangingCoins.py
Jcarlos0828/LeetCode-PracticeResults
73566a131629038caf2555eaf4999379227ec369
[ "MIT" ]
null
null
null
ArrangingCoins.py
Jcarlos0828/LeetCode-PracticeResults
73566a131629038caf2555eaf4999379227ec369
[ "MIT" ]
null
null
null
''' EASY 441. Arranging Coins You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. ''' class Solution: def arrangeCoins(self, n: int) -> int: rows = [0] count = 1 def recur(n, count): if n - count >= 0: rows[0] += 1 count += 1 recur(n-count+1, count) return recur(n, count) return rows[0]
26.388889
66
0.511579
67
475
3.626866
0.552239
0.098765
0.135802
0
0
0
0
0
0
0
0
0.038062
0.391579
475
18
67
26.388889
0.802768
0.309474
0
0
0
0
0
0
0
0
0
0
0
1
0.166667
false
0
0
0
0.416667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b7cf31b94df4dc51935676b554357efa86d4611
1,167
py
Python
stable_projects/predict_phenotypes/Nguyen2020_RNNAD/cbig/Nguyen2020/test_rnn.py
marielacour81/CBIG
511af756c6ddabbd3a9681ce3514b79ef5aaaf3f
[ "MIT" ]
6
2020-03-03T22:23:07.000Z
2021-11-27T06:11:02.000Z
stable_projects/predict_phenotypes/Nguyen2020_RNNAD/cbig/Nguyen2020/test_rnn.py
marielacour81/CBIG
511af756c6ddabbd3a9681ce3514b79ef5aaaf3f
[ "MIT" ]
null
null
null
stable_projects/predict_phenotypes/Nguyen2020_RNNAD/cbig/Nguyen2020/test_rnn.py
marielacour81/CBIG
511af756c6ddabbd3a9681ce3514b79ef5aaaf3f
[ "MIT" ]
2
2020-05-27T20:24:03.000Z
2021-04-14T07:51:44.000Z
# Written by Minh Nguyen and CBIG under MIT license: # https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md import unittest import torch import cbig.Nguyen2020.rnn as rnn class RnnCellTest(unittest.TestCase): """ Unit tests for recurrent cells """ def setUp(self): torch.manual_seed(0) self.in_features = 10 self.hidden_size = 20 self.batch_size = 3 self.length = 15 def test_MinimalRNNCell(self): cell = rnn.MinimalRNNCell(self.in_features, self.hidden_size) seq = torch.randn(self.length, self.batch_size, self.in_features) h_t = torch.randn(self.batch_size, self.hidden_size) for i in range(self.length): h_t = cell(seq[i], h_t) self.assertAlmostEqual(h_t.sum().item(), -3.026607, 6) def test_LssCell(self): cell = rnn.LssCell(self.in_features, self.hidden_size) seq = torch.randn(self.length, self.batch_size, self.in_features) h_t = torch.randn(self.batch_size, self.hidden_size) for i in range(self.length): h_t = cell(seq[i], h_t) self.assertAlmostEqual(h_t.sum().item(), 60.245380, 6)
33.342857
73
0.658098
171
1,167
4.339181
0.368421
0.021563
0.09434
0.091644
0.485175
0.485175
0.485175
0.485175
0.485175
0.485175
0
0.03208
0.225364
1,167
34
74
34.323529
0.788717
0.122536
0
0.333333
0
0
0
0
0
0
0
0
0.083333
1
0.125
false
0
0.125
0
0.291667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b7e0f2a1f8d7363c4a7045709aa260449c86b2e
4,816
py
Python
mysite/myapp/forms.py
MarkArren/PhotoSocial
bb401f465a464e7cf6a7fac184cef0d40e0a9525
[ "MIT" ]
null
null
null
mysite/myapp/forms.py
MarkArren/PhotoSocial
bb401f465a464e7cf6a7fac184cef0d40e0a9525
[ "MIT" ]
null
null
null
mysite/myapp/forms.py
MarkArren/PhotoSocial
bb401f465a464e7cf6a7fac184cef0d40e0a9525
[ "MIT" ]
null
null
null
from django import forms from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.core.validators import EmailValidator from . import models from .models import ProfileModel from io import BytesIO from PIL import Image, ExifTags from django.core.files import File def compressImage(image): maxWidth = 440 # Open image and get bytes imageTmp = Image.open(image).convert('RGB') imageIO = BytesIO() try: # Rotate image if 'Orientation' included in metadata # From https://stackoverflow.com/questions/13872331/rotating-an-image-with-orientation-specified-in-exif-using-python-without-pil-in for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation]=='Orientation': break exif=dict(imageTmp.getexif().items()) if exif[orientation] == 3: imageTmp=imageTmp.rotate(180, expand=True) elif exif[orientation] == 6: imageTmp=imageTmp.rotate(270, expand=True) elif exif[orientation] == 8: imageTmp=imageTmp.rotate(90, expand=True) except (AttributeError, KeyError, IndexError): pass # Get image attributes width, height = imageTmp.size newWidth = width newHeight = height # Check if if image needs to be cropped crop = False if width/height > 1.7: # Image is too wide so cut width ratio = height/9 newWidth = 16 * ratio newHeight = height crop = True print("too wide") elif width/height < 0.8: # image is too tall so cut height ratio = width / 8 newWidth = width newHeight = 10 * ratio crop = True print("too tall") if crop: # Crop left = (width - newWidth) / 2 top = (height - newHeight)/2 right = (width + newWidth)/2 bottom = (height + newHeight)/2 imageTmp = imageTmp.crop((left, top, right, bottom)) print("cropped") # Resize image ratio = maxWidth/newWidth newWidth = newWidth * ratio newHeight = newHeight * ratio imageTmp = imageTmp.resize((int(newWidth), int(newHeight))) print("resized") # Convert to bytes, save and compress imageTmp.save(imageIO, format='JPEG', optimize=True, quality=60) return File(imageIO, name=image.name) class PostForm(forms.Form): image = forms.ImageField(label="Upload Image", required=True) caption = forms.CharField(label="Caption", max_length=512, required=False, widget=forms.TextInput(attrs={'placeholder': 'Caption'})) location = forms.CharField(label="Location", max_length=50, required=False, widget=forms.TextInput(attrs={'placeholder': 'Location'})) def save(self, request): postInstance = models.PostModel() postInstance.image = compressImage(self.cleaned_data["image"]) postInstance.caption = self.cleaned_data["caption"] postInstance.location = self.cleaned_data["location"] profile = models.ProfileModel.objects.filter(user=request.user.id) postInstance.profile = profile[0] postInstance.save() return postInstance # class PostForm(ModelForm): # class meta: # model = models.PostModel # fields = ('image', 'caption', 'location') def must_be_unique_email(value): user = User.objects.filter(email=value) if len(user) > 0: raise forms.ValidationError("Email Already Exists") return value def must_be_unique_username(value): user = User.objects.filter(username=value) if len(user) > 0: raise forms.ValidationError("Username Already Exists") return value class RegistrationForm(UserCreationForm): # email = forms.EmailField( # label="Email", # required=True, # validators=[EmailValidator] # ) username = forms.CharField(label='Username', required=True, max_length=30 ) class Meta: model = User fields = ("username", "password1", "password2") def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) # user.email = self.cleaned_data["email"] if commit: user.save() return user # def __init__(self, *args, **kwargs): # super(RegistrationForm, self).__init__(*args, **kwargs) # self.fields['fullname'] = user.first_name + user.last_name class ProfileForm(ModelForm): class Meta: model = ProfileModel fields = ('profilePicture', 'fullname', 'email', 'bio') class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email') # class ProfileForm(forms.Form): # profilePicture = forms.ImageField(label="Profile Picture", required=False) # bio = forms.CharField(label="Bio", max_length=512, required=False) # def save(self, request): # profileInstance = models.PostModel() # postInstance.user = request.user # profileInstance.profilePicture = self.cleaned_data["profilePicture"] # profileInstance.bio = self.cleaned_data["bio"] # profileInstance.save() # return profileInstance
28.163743
135
0.706811
581
4,816
5.814114
0.306368
0.017762
0.026643
0.020426
0.115157
0.07164
0.052694
0.023683
0
0
0
0.013277
0.171096
4,816
170
136
28.329412
0.832916
0.269103
0
0.147059
0
0
0.072289
0
0
0
0
0
0
1
0.04902
false
0.019608
0.098039
0
0.303922
0.039216
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b80a8a516beaa5b7d7dde65eb8c098754473d58
1,442
py
Python
up/tasks/sparse/models/heads/cls_head.py
ModelTC/EOD
164bff80486e9ae6a095a97667b365c46ceabd86
[ "Apache-2.0" ]
196
2021-10-30T05:15:36.000Z
2022-03-30T18:43:40.000Z
up/tasks/sparse/models/heads/cls_head.py
ModelTC/EOD
164bff80486e9ae6a095a97667b365c46ceabd86
[ "Apache-2.0" ]
12
2021-10-30T11:33:28.000Z
2022-03-31T14:22:58.000Z
up/tasks/sparse/models/heads/cls_head.py
ModelTC/EOD
164bff80486e9ae6a095a97667b365c46ceabd86
[ "Apache-2.0" ]
23
2021-11-01T07:26:17.000Z
2022-03-27T05:55:37.000Z
from up.utils.general.registry_factory import MODULE_ZOO_REGISTRY from up.tasks.cls.models.heads import BaseClsHead, ConvNeXtHead __all__ = ['SparseBaseClsHead', 'SparseConvNeXtHead'] @MODULE_ZOO_REGISTRY.register('sparse_base_cls_head') class SparseBaseClsHead(BaseClsHead): def __init__(self, num_classes, in_plane, input_feature_idx=-1, use_pool=True, dropout=None): super(SparseBaseClsHead, self).__init__(num_classes, in_plane, input_feature_idx=-1, use_pool=True, dropout=None) def forward_net(self, x): x = x['features'][self.input_feature_idx] x = self.get_pool_output(x) x = self.get_dropout(x) logits = self.get_logits(x) return {'logits': logits} @MODULE_ZOO_REGISTRY.register('sparse_convnext_head') class SparseConvNeXtHead(ConvNeXtHead): def __init__(self, num_classes, in_plane, input_feature_idx=-1, head_init_scale=1., use_pool=True, dropout=None): super(SparseConvNeXtHead, self).__init__(num_classes, in_plane, input_feature_idx, use_pool, dropout) def forward_net(self, x): x = x['features'][self.input_feature_idx] x = self.get_pool_output(x) x = self.layer_norm(x) x = self.get_dropout(x) logits = self.get_logits(x) return {'logits': logits}
36.974359
109
0.647018
177
1,442
4.881356
0.293785
0.016204
0.104167
0.078704
0.641204
0.569444
0.569444
0.53125
0.53125
0.475694
0
0.003704
0.25104
1,442
38
110
37.947368
0.796296
0
0
0.387097
0
0
0.071429
0
0
0
0
0
0
1
0.129032
false
0
0.064516
0
0.322581
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
0
0
0
1
0
8b8159fcb82d3a08050148abdcf3102b1846cbb7
4,753
py
Python
app/xl/long_runner.py
evgeniyabrosin/anfisa
ac4aef1a816de05ee2a45aa5b220e2baf93574de
[ "Apache-2.0" ]
8
2019-03-26T16:07:46.000Z
2021-12-30T13:38:06.000Z
app/xl/long_runner.py
evgeniyabrosin/anfisa
ac4aef1a816de05ee2a45aa5b220e2baf93574de
[ "Apache-2.0" ]
13
2018-11-07T19:37:20.000Z
2022-02-21T17:11:45.000Z
app/xl/long_runner.py
evgeniyabrosin/anfisa
ac4aef1a816de05ee2a45aa5b220e2baf93574de
[ "Apache-2.0" ]
15
2018-10-16T08:15:11.000Z
2022-02-21T14:07:29.000Z
# Copyright (c) 2019. Partners HealthCare and other members of # Forome Association # # Developed by Sergey Trifonov based on contributions by Joel Krier, # Michael Bouzinier, Shamil Sunyaev and other members of Division of # Genetics, Brigham and Women's Hospital # # 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 threading import Condition from datetime import datetime from forome_tools.job_pool import ExecutionTask from forome_tools.log_err import logException from app.config.a_config import AnfisaConfig #=============================================== class XL_LongRunner_DTreeCounts(ExecutionTask): def __init__(self, ds_h, rq_id, dtree_h, point_idxs = None): ExecutionTask.__init__(self, "dtree-counts") self.mDS = ds_h self.mRqID = rq_id self.mDTreeH = dtree_h self.mCondition = Condition() self.mCounts = [None] * len(dtree_h) self.mFailureCount = 0 self.mNextPointIdxs = [] self.mTimeAccess = datetime.now() for idx in (range(len(dtree_h)) if point_idxs is None else point_idxs): if dtree_h.pointNotActive(idx): self.mCounts[idx] = self.mDS.getEvalSpace().makeEmptyCounts() else: self.mNextPointIdxs.append(idx) def getTaskType(self): return "dtree-counts" def outOfDate(self, cur_datetime): with self.mDS: return (self.mCondition is None and cur_datetime - self.mTimeAccess > AnfisaConfig.cconfigOption("long.run.passtime")) def execIt(self): while True: with self.mDS: if len(self.mNextPointIdxs) == 0: break idx = self.mNextPointIdxs[0] try: with self.mCondition: self.mCondition.notify_all() counts = self.mDS.getEvalSpace().evalTotalCounts( self.mDTreeH.getActualCondition(idx)) except Exception as err: logException("Long run exception in DS=%s" % self.mDS.getName()) self.mFailureCount += 1 if self.mFailureCount > AnfisaConfig.configOption( "long.run.failures"): raise err else: continue with self.mDS: self.mTimeAccess = datetime.now() self.mCounts[idx] = counts if counts[0] == 0 and self.mDTreeH.checkZeroAfter(idx): for idx1 in range(idx, len(self.mCounts)): self.mCounts[idx1] = counts[:] for j, pcounts in enumerate(self.mCounts): if pcounts is not None and j in self.mNextPointIdxs: self.mNextPointIdxs.remove(j) with self.mDS: with self.mCondition: self.mCondition.notify_all() self.mCondition = None return False def getEvaluatedCounts(self, next_points = None, time_end = None): condition = None with self.mDS: if next_points is not None: next_points_idxs = [] for idx in next_points: if (0 <= idx < len(self.mCounts) and self.mCounts[idx] is None): next_points_idxs.append(idx) for idx in self.mNextPointIdxs: if (idx not in next_points_idxs and self.mCounts[idx] is None): next_points_idxs.append(idx) self.mNextPointIdxs = next_points_idxs while time_end is not None: time_now = datetime.now() if time_now >= time_end: break with self.mDS: condition = self.mCondition if condition is None: break timeout = (time_end - time_now).total_seconds() with condition: condition.wait(timeout) with self.mDS: self.mTimeAccess = datetime.now() return self.mCounts[:] #===============================================
39.608333
77
0.564696
519
4,753
5.071291
0.33526
0.029255
0.029255
0.029635
0.094225
0.094225
0.094225
0.034954
0.034954
0.034954
0
0.005438
0.34231
4,753
119
78
39.941176
0.836532
0.185777
0
0.252747
0
0
0.022095
0
0
0
0
0
0
1
0.054945
false
0.010989
0.054945
0.010989
0.164835
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
0
0
0
1
0
8b8201f75514c47ff34e925027bea925196f4d34
23,209
py
Python
cosmos_virtual_assistant_uf.py
Nishit014/COSMOS
3042377715f6f4b0eb0a75b6b360415a965754df
[ "MIT" ]
1
2021-06-27T11:53:43.000Z
2021-06-27T11:53:43.000Z
cosmos_virtual_assistant_uf.py
Aayush9027/COSMOS_VIRTUAL_ASSISTANT
d02aa04a66b2acdfeaf9270607059182f54e78a5
[ "MIT" ]
null
null
null
cosmos_virtual_assistant_uf.py
Aayush9027/COSMOS_VIRTUAL_ASSISTANT
d02aa04a66b2acdfeaf9270607059182f54e78a5
[ "MIT" ]
1
2021-06-25T12:04:24.000Z
2021-06-25T12:04:24.000Z
import pyttsx3 import speech_recognition as sr import os import subprocess #from requests import request , session #from pprint import pprint as pp import json import requests import datetime from datetime import date import time import calendar import warnings import random import wikipedia import webbrowser from pywhatkit import sendwhatmsg_instantly import smtplib import sys import pyjokes import pyautogui import PyPDF2 from tkinter.filedialog import * import psutil import speedtest import wolframalpha warnings.filterwarnings("ignore") #ignoring all the warnings if sys.platform == "win32": engine=pyttsx3.init('sapi5') voices=engine.getProperty('voices') engine.setProperty('voice',voices[1].id) else: engine=pyttsx3.init('nsss') #sapi5 - SAPI5 on Windows #nsss - NSSpeechSynthesizer on Mac OS X #espeak - eSpeak on every other platform voices=engine.getProperty('voices') #for i in range(48): #print(voices[i].id) engine.setProperty('voice',voices[10].id)#10b 17 26 28 37 39 def speak(audio): #fn for talking txt to spch,audio is string engine.say(audio)#say fn for speaking print(audio) engine.runAndWait() def take_command(): r=sr.Recognizer() with sr.Microphone() as source: print('Go ahead,I am listening....') #r.pause_threshold=1 r.adjust_for_ambient_noise(source) audio=r.listen(source) try: print('Hold on a momment,Recognizing...') query=r.recognize_google(audio,language='en-in') print(f'User said:{query}\n') except: speak("There was some problem please try again") return "None" return query def wish(): hour = int(datetime.datetime.now().hour) if hour>=0 and hour<12: speak("Good Morning!") elif hour>=12 and hour<18: speak("Good Afternoon!") else: speak("Good Evening!") speak("I am COSMOS. How may I help you") def open_file(filename,filename1): if sys.platform == "win32": os.startfile(filename) else: try: opener = f'/Applications/{filename}.app/Contents/MacOS/{filename1}' subprocess.call([opener]) except: opener = f'/System/Applications/{filename}.app/Contents/MacOS/{filename1}' subprocess.call([opener]) def sendEmail(to,content): server=smtplib.SMTP("smtp.gmail.com",587) server.ehlo() server.starttls() server.login("email","password") server.sendmail("email id",to,content) server.close() def news(): #https://newsapi.org/ ##get apikey from here api_key='Your api key here!!!' main_url = f'http://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey={api_key}' main_page = requests.get(main_url).json() # print(main_page) articles = main_page["articles"] # print(articles) head = [] numbers=["first","second","third","fourth","fifth"] for ar in articles: head.append(ar["title"]) for i in range (len(numbers)): speak(f"today's {numbers[i]} news is: {head[i]}") def crypto(slug): #https://coinmarketcap.com/ ##get apikey from here apiurl='https://pro-api.coinmarketcap.com' headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': 'Your api key here!!!', } session=requests.session() session.headers.update(headers) def coins_price(apiurl,slug): url=apiurl+'/v1/cryptocurrency/quotes/latest' parameters={'slug':slug} r=session.get(url,params=parameters) data=r.json()['data'] all=str(data) x=all.find('price') all=all[x:x+20] for p in all.split(): try: float(p) price=p except: pass speak(f'{slug} price is {price}') return price #pp(coins_price(apiurl,slug)) coins_price(apiurl,slug) def weather(): def loc(): try: ipadd=requests.get("https://api.ipify.org").text url="https://get.geojs.io/v1/ip/geo/"+ipadd+".json" geo_requests= requests.get(url) geo_data=geo_requests.json() city=geo_data['city'] except: city='delhi' return city #https://home.openweathermap.org/ ##get apikey from here api_key = 'Your api key here!!!' base_url = 'https://api.openweathermap.org/data/2.5/weather?' city_name = loc() url = base_url + "&q=" + city_name + "&appid=" + api_key session=requests.session() r = session.get(url) data = r.json() #data if data["cod"] != "404": y = data["main"] current_temperature = y["temp"] current_humidiy = y["humidity"] z = data["weather"] weather_description = z[0]["description"] #print(" Temperature is " +str(int(current_temperature-273.15)) +" degree celcius\n humidity is " + str(current_humidiy) +"%\n description " + str(weather_description)) speak(" Temperature is " +str(int(current_temperature-273.15)) +" degree celcius\n humidity is " + str(current_humidiy) +"%\n with " + str(weather_description)+'in '+city_name) def pdf_reader(): book=askopenfilename() try: pdfreader=PyPDF2.PdfFileReader(book) pages=pdfreader.numPages speak(f"Total numbers of pages in this pdf are {pages}") speak("sir please enter the page number you want me to read") pg=int(input("please enter the page number:")) for num in range(pg,pages): page=pdfreader.getPage(pg) text=page.extractText() speak(text) except : speak("Operation Cancelled !") def adv_search(): query=input('Question: ') #https://products.wolframalpha.com/api/ ##get apikey from here app_id='Your api key here!!!' client=wolframalpha.Client(app_id) if 'no thanks' in query or 'thanks' in query or 'close advance search mode' in query: speak('closing advance search mode') else: res=client.query(query) ans=next(res.results).text speak(ans) speak('want to search anything else?') adv_search() def TaskExecution(): # function for coin toss task def htLine1(): speak("It's " + res) def htLine2(): speak("You got " + res) def htLine3(): speak("It landed on " + res) wish() bye=True while bye: query=take_command().lower() #query=input() ##comment above and remove this for typing instead of speaking for testing # Tasks if "what is your name" in query: speak('I am COSMOS your virtual assistant.') continue if "tell me about yourself" in query: speak('I am COSMOS your virtual assistant. What can I do for you?') continue elif 'why cosmos' in query or 'Why is your name cosmos' in query: speak("Just like cosmos is filled with endless possibilities this program also have endless possibilites and thats why cosmos") continue elif 'price of' in query or 'tell me the price of' in query: query=query.replace('tell me the price of ','') query=query.replace('price of ','') crypto(query) speak('need something else?') elif 'weather' in query: #query=query.replace('how is the weather in',' ')## can be made to take location ##not implemented #query=query.replace('weather in',' ') #query=query.replace('weather',' ') weather() speak('need something else?') elif "open notepad" in query: npath="C:\\WINDOWS\\system32\\notepad.exe" os.startfile(npath) elif "open command prompt" in query: os.system("start cmd") bye=False elif 'the time' in query: strTime=datetime.datetime.now().strftime('%H:%M') #print(f'its {strTime}') speak(f'its {strTime}') speak('you want me to do anything else?') elif "todays date" in query or "the date"in query: today = date.today() d2 = today.strftime("%B %d, %Y") speak(f"Today is {d2}") speak('you want me to do anything else?') elif "ip address" in query: ip=requests.get('https://api.ipify.org').text#.text returns ip in unicode speak(f"Your IP Address is {ip}") speak('you want me to do anything else?') elif 'wikipedia' in query: speak('Searching in wikipedia') query=query.replace('wikipedia',' ') results=wikipedia.summary(query,sentences=2) speak('According to wikipedia') #print(results) speak(results) speak('you want me to do anything else') elif 'open google' in query: webbrowser.open("https://google.com") bye=False elif 'open youtube' in query: webbrowser.open('https://youtube.com') bye=False elif 'what is' in query: #query=query.replace('what is',' ') result=wikipedia.summary(query,sentences=2) #print(result) speak(result) speak('anything else?') elif 'search in youtube' in query or 'open in youtube' in query: #search in youtube query=query.replace('search in youtube',' ') query=query.replace('open in youtube',' ') webbrowser.open(f'https://www.youtube.com/results?search_query={query}') speak(f'searchin in youtube {query}') bye=False #walframalpha elif 'advance search mode' in query or 'advanced search mode' in query: ##not gonna work by speaking input speak('Advance search mode activated') try: adv_search() except Exception as e: speak("Sorry,I am currently unable to find the answers.Please try again later") speak('do you want me to do anything else?') continue elif 'search' in query or 'search in google' in query or 'open in google' in query: #search in google tab query=query.replace('search',' ') query=query.replace('search in google',' ') query=query.replace('open in google',' ') webbrowser.open(f"https://google.com/search?q={query}") speak(f'searching in google {query}') bye=False elif ("open gfg" in query or "open geeksforgeeks" in query): webbrowser.open("https://www.geeksforgeeks.org") bye=False elif "send message on whatsapp" in query or 'send message' in query: speak("To whom should I send a message") speak(" Please type the number ") no=input("Enter the number:") speak(" what should I send ?") speak('You will have to scan for whatsapp web.') subquery=take_command().lower() sendwhatmsg_instantly(f"+91{no}",f"{subquery}") bye=False elif "email" in query: try: speak("To whom do you want to send mail?") to=input("Enter the mail id to whom you want to send:") speak("what should i say?") subquery=take_command().lower() sendEmail(to,subquery) speak("Email has been sent.") speak('want to do anything else?') except Exception as e: speak("Sorry,I am currently unable to send the email.Please try again later") speak('do you want me to do anything else?') elif 'visual studio code' in query or 'open code' in query or 'code' in query or 'visual code' in query: open_file('Visual Studio Code','Electron') speak('visual studio code is open now') bye=False elif 'safari' in query: open_file('Safari','Safari') speak('Safari is open now') bye=False elif 'calculator' in query: open_file('Calculator','Calculator') speak('Calculator is open now') bye=False elif 'chrome' in query: open_file('Google Chrome','Google Chrome') speak('Chrome is open now') bye=False elif "close notepad" in query: speak("okay sir, closing notepad") os.system("taskkill/f /im notepad.exe") speak('you want me to do anything else?') elif ("close cmd"in query or "close command prompt" in query): speak("okay sir, closing cmd") os.system("taskkill /f /im cmd.exe") speak('you want me to do anything else?') elif 'joke' in query or 'jokes' in query: joke = pyjokes.get_joke('en','all') #print(joke) speak(joke) speak('anything else?') elif 'jobs' in query or 'job' in query or 'job recommandation' in query or 'work' in query: platforms = [ 'linkedin', 'indeed', 'glassdoor', 'hackerrank', 'naukri', 'intern shala' ] speak("Select a platform that you prefer:") print('\n'.join(platforms)) statement1 = take_command().lower() #statement1 = input() if (statement1 == 0): continue if 'linkedin' in statement1 or 'LinkedIn' in statement1 or 'Linkedin' in statement1: webbrowser.open_new_tab("https://www.linkedin.com/jobs") speak("LinkedIn is open now") break elif 'indeed' in statement1: webbrowser.open_new_tab("https://www.indeed.com/jobs") speak("Indeed is open now") break elif 'glassdoor' in statement1: webbrowser.open_new_tab("https://www.glassdoor.com/jobs") speak("Glassdoor is open now") break elif 'hackerrank' in statement1: webbrowser.open_new_tab( "https://www.hackerrank.com/jobs/search") speak("HackerRank is open now") break elif 'naukri' in statement1: webbrowser.open_new_tab("https://www.naukri.com/jobs") speak("Naukri is open now") break elif 'intern shala' in statement1: webbrowser.open_new_tab('internshala.com') speak('Intern Shala is open now') break else: speak("Sorry we couldn't find your search!!!") speak('you want me to do anything else?') #time.sleep(3) elif "shut down the system" in query: os.system("shutdown /s /t 5") elif 'movie ticket booking' in query or 'movie booking' in query or 'movie ticket' in query: speak('opening bookmyshow') webbrowser.open_new_tab("https://in.bookmyshow.com/") speak(" Book my show website is open now") bye=False elif "restart the system" in query: os.system("shutdown /r /t 5") elif 'online courses' in query or 'course' in query: platforms = [ 'coursera', 'udemy', 'edx', 'skillshare', 'datacamp', 'udacity' ] speak("Select a platform that you prefer : ") print("\n".join(platforms)) statement1 = take_command().lower() if statement1 == 0: continue if 'coursera' in statement1: webbrowser.open_new_tab("https://www.coursera.org") speak("Coursera is open now") bye=False elif 'udemy' in statement1: webbrowser.open_new_tab("https://www.udemy.com") speak("udemy is open now") bye=False elif 'edx' in statement1: webbrowser.open_new_tab("https://www.edx.org/") speak("edx is open now") bye=False elif 'skillshare' in statement1: webbrowser.open_new_tab("https://www.skillshare.com") speak("skill share is open now") bye=False elif 'datacamp' in statement1: webbrowser.open_new_tab("https://www.datacamp.com") speak("datacamp is open now") bye=False elif 'udacity' in statement1: webbrowser.open_new_tab("https://www.udacity.com") speak("udacity is open now") bye=False else: speak("Sorry we couldn't find your search!!!") speak('you want me to do anything else?') elif 'train ticket booking' in query or 'train booking' in query or 'train ticket' in query or 'train ticket' in query: speak('opening website for train ticket booking') webbrowser.open_new_tab("https://www.railyatri.in/train-ticket/") speak(" IRCTC website is open now, have a good journey !") bye=False elif 'bus ticket booking' in query or 'bus booking' in query or 'bus ticket' in query: speak('opening website for bus ticket booking') webbrowser.open_new_tab("https://www.redbus.in") speak(" Red bus website is open now, have a good journey !") bye=False elif 'airplane ticket booking' in query or 'airplane booking' in query or 'airplane ticket' in query: speak('opening website for airplane ticket booking') webbrowser.open_new_tab("https://www.goindigo.in") speak(" Indigo website is open now, have a good journey !") bye=False elif "hotel" in query or "hotel booking" in query: speak('Opening go ibibo .com') webbrowser.open_new_tab('https://goibibo.com/hotels') bye=False elif "sleep the system" in query: os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0") elif 'switch the window' in query: if sys.platform == "win32": pyautogui.keyDown("alt") pyautogui.press("tab") time.sleep(1) pyautogui.keyUp("alt") bye=False else: pyautogui.keyDown("command") pyautogui.press("tab") time.sleep(1) pyautogui.keyUp("command") bye=False elif ("tell me news" in query or "news" in query): speak("Please wait, Fetching the latest news") news() speak('need something else?') elif ("tell me my location" in query or "location" in query): speak("Hold on,Locating our current location") try: ipadd=requests.get("https://api.ipify.org").text url="https://get.geojs.io/v1/ip/geo/"+ipadd+".json" geo_requests= requests.get(url) geo_data=geo_requests.json() city=geo_data['city'] country=geo_data['country'] speak(f"We are in {city},{country}") speak('need something else?') except Exception as e: speak("Sorry,I am unable to locate our current location due to poor connectivity. Please try after sometime.") bye=False elif "take a screenshot" in query or "take screenshot" in query: name=datetime.datetime.now() speak("taking screenshot...") time.sleep(3) img=pyautogui.screenshot() img.save(f"{name}.png") speak("Screenshot taken") speak('need anything else?') elif "read pdf" in query or " read book " in query : pdf_reader() bye=False elif "how much battery is left" in query or "how much power is left" in query or "battery" in query: battery=psutil.sensors_battery() percentage=battery.percent speak(f"We have {percentage} percent battery. ") if percentage>=50: speak("We have enough power to go on.") elif percentage>=20 and percentage<50: speak("You shall connect the system to a charging point") elif percentage<20: speak("Battery about to die,connect to a charging point as soon as possible") speak('you want me to do anything else') elif "internet speed" in query: speak("Checking internet speed") st=speedtest.Speedtest() dl=round(float(st.download())/8000000,2) up=round(float(st.upload())/8000000,2) speak(f"Current downloading speed is {dl}mb/s while uploading speed is {up}") speak('you want me to do anything else?') elif "volume up" in query: pyautogui.press("volumeup") speak('you want me to do anything else?') elif "volume down" in query: pyautogui.press("volumedown") speak('you want me to do anything else?') elif "volume mute" in query or "mute" in query: pyautogui.press("volumemute") speak('you want me to do anything else?') elif 'flip the coin' in query or 'toss the coin' in query or 'toss a coin' in query or 'flip a coin' in query: chances = ['Heads', 'Tails'] res = random.choice(chances) picLine = random.randint(1, 3) lines = [htLine1, htLine2, htLine3] lines[picLine - 1]() speak('you want me to do anything else?') elif 'dice' in query: num = random.randint(1, 6) speak("Your rolled " + str(num)) speak('you want me to do anything else?') elif 'bye' in query or 'no' in query or ' no thanks' in query: speak('Untill next time') bye=False else: speak("Sorry,I don't know how to do that right now but i am still learning how to be more helpful") speak('anything else?') #time.sleep(2) if __name__=="__main__": TaskExecution()
38.553156
186
0.550605
2,753
23,209
4.602252
0.207047
0.051934
0.029834
0.015627
0.334333
0.255406
0.220521
0.197948
0.146725
0.10513
0
0.009358
0.341592
23,209
602
187
38.553156
0.819776
0.05653
0
0.251521
0
0.002028
0.316213
0.010969
0
0
0
0
0
1
0.032454
false
0.004057
0.048682
0
0.089249
0.01217
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b849ac15aeae749f8a20c70f9517f14b9a20eb1
3,402
py
Python
features/haralick.py
annaformaniuk/smoke-detection
217014e9a2a5b9861f4cda3d4c1abce4aca34773
[ "MIT" ]
7
2019-05-29T07:43:40.000Z
2022-02-10T07:44:11.000Z
features/haralick.py
annaformaniuk/smoke-detection
217014e9a2a5b9861f4cda3d4c1abce4aca34773
[ "MIT" ]
1
2020-06-07T10:50:50.000Z
2020-06-07T10:50:50.000Z
features/haralick.py
annaformaniuk/smoke-detection
217014e9a2a5b9861f4cda3d4c1abce4aca34773
[ "MIT" ]
4
2019-11-26T15:05:03.000Z
2021-05-10T13:41:15.000Z
# from https://gogul09.github.io/software/texture-recognition import cv2 import numpy as np import os import glob import mahotas as mt from sklearn.svm import LinearSVC from typing import List import matplotlib.pyplot as plt import pickle # load the training dataset train_path = "../inputs/for_texture_model/train" train_names = os.listdir(train_path) # empty list to hold feature vectors and train labels train_features = [] train_labels = [] def extract_features(image): # calculate haralick texture features for 4 types of adjacency textures = mt.features.haralick(image) # take the mean of it and return it ht_mean = textures.mean(axis=0) return ht_mean def train_feature_model(): # loop over the training dataset print("[STATUS] Started extracting haralick textures..") for train_name in train_names: current_path = train_path + "/" + train_name current_label = train_name index = 1 for file in glob.glob(current_path + "/*.jpg"): print("Processing Image - {} in {}".format( index, current_label)) # read the training image image = cv2.imread(file) # convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # extract haralick texture from the image features = extract_features(gray) # append the feature vector and label train_features.append(features) train_labels.append(current_label) # show loop update index += 1 # have a look at the size of our feature vector and labels print("Training features: {}".format(np.array(train_features).shape)) print("Training labels: {}".format(np.array(train_labels).shape)) # create the classifier print("[STATUS] Creating the classifier..") clf_svm = LinearSVC(random_state=9) # fit the training data and labels print("[STATUS] Fitting data/label to model..") clf_svm.fit(train_features, train_labels) # save the model to disk filename = 'outputs/finalized_model.sav' pickle.dump(clf_svm, open(filename, 'wb')) # loop over the test images test_path = "../inputs/for_texture_model/test" fig = plt.figure(figsize=(5, 5)) for i, file in enumerate(glob.glob(test_path + "/*.jpg")): # read the input image image = cv2.imread(file) # convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # extract haralick texture from the image features = extract_features(gray) # evaluate the model and predict label prediction = clf_svm.predict(features.reshape(1, -1))[0] # show the label ax = fig.add_subplot(1, 4, i + 1) ax.imshow(image, interpolation="nearest", cmap=plt.cm.gray) ax.set_title(prediction, fontsize=10) ax.set_xticks([]) ax.set_yticks([]) # display the output image fig.tight_layout() plt.show()
35.072165
77
0.581717
395
3,402
4.891139
0.374684
0.028468
0.029503
0.020704
0.168737
0.142857
0.111801
0.111801
0.111801
0.111801
0
0.011479
0.334215
3,402
96
78
35.4375
0.841501
0.214874
0
0.111111
0
0
0.113293
0.034743
0
0
0
0
0
1
0.037037
false
0
0.166667
0
0.222222
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b87afec28b6e06554c41af8512eee6c2652795a
4,441
py
Python
asciidoxy/templates/helpers.py
lurch/asciidoxy
9781ba696637fadbf62f1b7c5da843b0d292007d
[ "Apache-2.0" ]
null
null
null
asciidoxy/templates/helpers.py
lurch/asciidoxy
9781ba696637fadbf62f1b7c5da843b0d292007d
[ "Apache-2.0" ]
null
null
null
asciidoxy/templates/helpers.py
lurch/asciidoxy
9781ba696637fadbf62f1b7c5da843b0d292007d
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2019-2020, TomTom (http://tomtom.com). # # 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. """Helper functions for API reference templates.""" from asciidoxy.generator import Context def _arg_name(param): if param.name: return f" {param.name}" else: return "" def link_from_ref(ref, context: Context, nested_start="&lt;", nested_end="&gt;", args_start="(", args_end=")", skip_args=False): if ref is None: return "" if ref.nested is not None: if len(ref.nested) > 0: nested = (f"{nested_start}" f"{', '.join(link_from_ref(r, context) for r in ref.nested)}" f"{nested_end}") else: nested = f"{nested_start}{nested_end}" else: nested = "" if not skip_args and ref.args is not None: if len(ref.args) > 0: arg_parts = [f"{link_from_ref(a.type, context)}{_arg_name(a)}" for a in ref.args] args = f"{args_start}{', '.join(arg_parts)}{args_end}" else: args = f"{args_start}{args_end}" else: args = "" if ref.id: return (f"{ref.prefix or ''}{context.link_to_element(ref.id, ref.name)}{nested}{args}" f"{ref.suffix or ''}").strip() else: return f"{ref.prefix or ''}{ref.name}{nested}{args}{ref.suffix or ''}".strip() def print_ref(ref, nested_start="&lt;", nested_end="&gt;", args_start="(", args_end=")"): if ref is None: return "" if ref.nested is not None: if len(ref.nested) > 0: nested = f"{nested_start}{', '.join(print_ref(r) for r in ref.nested)}{nested_end}" else: nested = f"{nested_start}{nested_end}" else: nested = "" if ref.args is not None: if len(ref.args) > 0: arg_parts = [f"{print_ref(a.type)}{_arg_name(a)}" for a in ref.args] args = f"{args_start}{', '.join(arg_parts)}{args_end}" else: args = f"{args_start}{args_end}" else: args = "" return f"{ref.prefix or ''}{ref.name}{nested}{args}{ref.suffix or ''}".strip() def argument_list(params, context: Context): return f"({', '.join(type_and_name(p, context) for p in params)})" def type_list(params): return f"({', '.join(print_ref(p.type) for p in params)})" def has(elements): return len(list(elements)) > 0 def chain(first_collection, second_collection): yield from first_collection yield from second_collection def type_and_name(param, context: Context): return f"{link_from_ref(param.type, context)} {param.name}".strip() def method_signature(element, context: Context, max_width: int = 80): static = "static" if element.static else "" return_type = link_from_ref(element.returns.type, context) if element.returns else "" method_name = element.name method_without_params = " ".join(part for part in (static, return_type, method_name) if part) if not element.params: return (f"{method_without_params}()") return_type_no_ref = print_ref(element.returns.type, context) if element.returns else "" method_without_params_length = len(" ".join(part for part in (static, return_type_no_ref, method_name) if part)) param_sizes = [len(f"{print_ref(p.type)} {p.name}".strip()) for p in element.params] indent_size = method_without_params_length + 1 first_indent = "" if any(indent_size + size + 1 > max_width for size in param_sizes): indent_size = 4 first_indent = "\n " param_separator = f",\n{' ' * indent_size}" formatted_params = f"{param_separator.join(type_and_name(p, context) for p in element.params)}" return (f"{method_without_params}({first_indent}{formatted_params})")
33.390977
99
0.611124
618
4,441
4.221683
0.218447
0.024147
0.021081
0.02453
0.415102
0.380222
0.380222
0.350326
0.325029
0.302798
0
0.006657
0.255798
4,441
132
100
33.643939
0.782753
0.139383
0
0.383721
0
0.011628
0.272345
0.159043
0
0
0
0
0
1
0.104651
false
0
0.011628
0.046512
0.267442
0.069767
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b88d9d29f78c551c398e16471317d51e96b8e76
2,511
py
Python
fin_model_course/pltemplates/graphics/model_structure.py
whoopnip/fin-model-course
e6c5ae313bba601c4aca0f334818b61cc0393118
[ "MIT" ]
5
2020-08-29T15:28:39.000Z
2021-12-01T16:53:25.000Z
fin_model_course/pltemplates/graphics/model_structure.py
whoopnip/fin-model-course
e6c5ae313bba601c4aca0f334818b61cc0393118
[ "MIT" ]
16
2020-02-26T16:03:47.000Z
2021-06-15T15:17:37.000Z
fin_model_course/pltemplates/graphics/model_structure.py
whoopnip/fin-model-course
e6c5ae313bba601c4aca0f334818b61cc0393118
[ "MIT" ]
3
2021-01-22T19:38:36.000Z
2021-09-28T08:14:00.000Z
import pyexlatex as pl import pyexlatex.table as lt import pyexlatex.presentation as lp import pyexlatex.graphics as lg import pyexlatex.layouts as ll def get_model_structure_graphic() -> lg.TikZPicture: inputs_block_options = [ 'fill=orange!30' ] model_block_options = [ 'fill=blue!50' ] sub_model_block_options = [ 'fill=blue!90' ] step_block_options = [ 'fill=cyan!20' ] outputs_block_options = [ 'fill=green!20' ] text_options = [ 'text=white' ] step_text_options = [ 'text=black' ] inputs_text_options = outputs_text_options = step_text_options arrow_options = [ 'line width=0.75mm', ] inputs_rectangle = lg.Rectangle(2, 8, offset=(-3.35, 4), contents=pl.Bold('Inputs'), shape_options=inputs_block_options, text_options=inputs_text_options) model_rectangle = lg.Rectangle(5, 8, offset=(1.25, 4), contents=pl.Bold('Model'), content_position='bottom', content_offset=0.2, shape_options=model_block_options, text_options=text_options) outputs_rectangle = lg.Rectangle(2, 8, offset=(5.85, 4), contents=pl.Bold('Outputs'), shape_options=outputs_block_options, text_options=outputs_text_options) sub_model_rectangles = [] step_rectangles = [] for i in range(3): y_offset = 1.75 + i * 2.5 sub_model_rectangles.append( lg.Rectangle(4, 1.75, offset=(1.25, y_offset), contents='Sub-Model', shape_options=sub_model_block_options, text_options=text_options, content_position='bottom'), ) for j in range(3): x_offset = j * 1.25 step_rectangles.append( lg.Rectangle(1.1, 1, offset=(x_offset, y_offset + 0.2), contents='Step', shape_options=step_block_options, text_options=step_text_options, ) ) arrows = [ lg.Arrow((-2.3, 4), (-1.3, 4), options=arrow_options), lg.Arrow((3.8, 4), (4.8, 4), options=arrow_options), ] return lg.TikZPicture([ inputs_rectangle, model_rectangle, *sub_model_rectangles, *step_rectangles, outputs_rectangle, *arrows, ])
29.541176
112
0.560335
286
2,511
4.646853
0.244755
0.124154
0.094808
0.086531
0.261099
0.100828
0.058691
0
0
0
0
0.040144
0.335325
2,511
84
113
29.892857
0.756141
0
0
0
0
0
0.056949
0
0
0
0
0
0
1
0.014706
false
0
0.073529
0
0.102941
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
0
0
0
1
0
8b89b607196b90b61199e59cb3a2c777f0b348f7
1,748
py
Python
calc.py
V-Perotto/Contador_NomeSobrenome_Decimal
1e625306254c3f48e4c722e6ad04601f65af4c3c
[ "CC0-1.0" ]
null
null
null
calc.py
V-Perotto/Contador_NomeSobrenome_Decimal
1e625306254c3f48e4c722e6ad04601f65af4c3c
[ "CC0-1.0" ]
null
null
null
calc.py
V-Perotto/Contador_NomeSobrenome_Decimal
1e625306254c3f48e4c722e6ad04601f65af4c3c
[ "CC0-1.0" ]
null
null
null
from alfabeto import * from main import nameSur # Listas letras = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] def start(nameSur): letra = nameSur.split() junto = ''.join(letra) return junto def calc_alfabeto(letters, spaces): for word in nameSur: switcher = { 'a' or 'A': letraA, 'b' or 'B': letraB, 'c' or 'B': letraC, 'd' or 'B': letraD, 'e' or 'B': letraE, 'f' or 'B': letraF, 'g' or 'B': letraG, 'h' or 'B': letraH, 'i' or 'B': letraI, 'j' or 'B': letraJ, 'k' or 'B': letraK, 'l' or 'B': letraL, 'm' or 'B': letraM, 'n' or 'B': letraN, 'o' or 'B': letraO, 'p' or 'B': letraP, 'q' or 'B': letraQ, 'r' or 'B': letraR, 's' or 'B': letraS, 't' or 'B': letraT, 'u' or 'B': letraU, 'v' or 'B': letraV, 'w' or 'B': letraW, 'x' or 'B': letraX, 'y' or 'B': letraY, 'z' or 'B': letraZ, ' ': nonLetra # default: print("ERROR: Incorrect Character") } for word in nameSur: for letter in letras: if word == letter: letters += 1 return letters if word == " ": spaces += 1 return spaces print("\nTem", letters, "letras.") print("Tem", spaces, "espacos.")
31.214286
119
0.371854
221
1,748
2.936652
0.384615
0.115562
0.009245
0.012327
0.080123
0.080123
0.080123
0.080123
0.080123
0.080123
0
0.001942
0.410755
1,748
56
120
31.214286
0.628155
0.029176
0
0.04
0
0
0.076151
0
0
0
0
0
0
1
0.04
false
0
0.04
0
0.14
0.04
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b914a0a6371ff8952db67b7eee682b5c44c059b
569
py
Python
nengo_ssp/hrr_algebra.py
nsdumont/nengo_ssp
9530a4618e213fb695b52887772c1309d0f07a0b
[ "MIT" ]
null
null
null
nengo_ssp/hrr_algebra.py
nsdumont/nengo_ssp
9530a4618e213fb695b52887772c1309d0f07a0b
[ "MIT" ]
null
null
null
nengo_ssp/hrr_algebra.py
nsdumont/nengo_ssp
9530a4618e213fb695b52887772c1309d0f07a0b
[ "MIT" ]
null
null
null
import numpy as np from nengo_spa.algebras.hrr_algebra import HrrAlgebra from nengo.utils.numpy import is_number class HrrAlgebra(HrrAlgebra): def fractional_bind(self, A, b): """Fractional circular convolution.""" if not is_number(b): raise ValueError("b must be a scalar.") return np.fft.ifft(np.fft.fft(A, axis=0)**b, axis=0) def bind(self, a, b): n = len(a) if len(b) != n: raise ValueError("Inputs must have same length.") return np.fft.ifft(np.fft.fft(a) * np.fft.fft(b), n=n)
35.5625
62
0.620387
89
569
3.910112
0.460674
0.071839
0.068966
0.057471
0.137931
0.137931
0.137931
0.137931
0
0
0
0.004684
0.249561
569
16
62
35.5625
0.810304
0.056239
0
0
0
0
0.090226
0
0
0
0
0
0
1
0.153846
false
0
0.230769
0
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
0
0
0
0
0
1
0
8b9247a613a137d9a893fcd8004929a037e3fffd
2,234
py
Python
server.py
Xinzhe-Qi/15112-Term-Project
07a4b78d23629478039667ed4c29287e5e781bf3
[ "MIT" ]
null
null
null
server.py
Xinzhe-Qi/15112-Term-Project
07a4b78d23629478039667ed4c29287e5e781bf3
[ "MIT" ]
null
null
null
server.py
Xinzhe-Qi/15112-Term-Project
07a4b78d23629478039667ed4c29287e5e781bf3
[ "MIT" ]
null
null
null
import socket from _thread import * import pickle from board import Board import time hostname = socket.gethostname() ipAddr = socket.gethostbyname(hostname) print(ipAddr) server = ipAddr port = 5556 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind((server, port)) except socket.error as e: print(str(e)) s.listen(2) print("Waiting for a connection, Server Started") bo = Board() currentId = "b" connections = 0 def threaded_client(conn): global currentId, bo, connections variable = bo bo.start_user = currentId if connections > 2: bo.start_user = "s" data1 = pickle.dumps(variable) if currentId == "w": bo.ready = True bo.startTime = time.time() conn.send(data1) currentId = bo.start_user = "w" connections += 1 while True: try: data2 = conn.recv(4096*4).decode("utf-8") if not data2: break else: if data2.count("move") > 0: info = data2.split(" ") x = int(info[1]) y = int(info[2]) pos = (x, y) color = info[3] bo.addMove(pos, color) elif data2 == "reset": bo.__init__() elif data2 == "winner b": bo.winner = "b" elif data2 == "winner w": bo.winner = "w" print("Reveived", data2) if bo.ready: if bo.turn == "w": bo.time1 = 900 - (time.time() - bo.startTime) - bo.storedTime1 else: bo.time2 = 900 - (time.time() - bo.startTime) - bo.storedTime2 sendData = pickle.dumps(bo) print("Sending ", bo) conn.sendall(sendData) except Exception as e: print(e) break connections -= 1 if connections < 2: bo = Board() currentId = "w" print("Disconnected") conn.close() while True: conn, addr = s.accept() print("Connected to:", addr) start_new_thread(threaded_client, (conn,))
21.27619
86
0.499552
245
2,234
4.497959
0.408163
0.019056
0.029946
0.029038
0.043557
0.043557
0
0
0
0
0
0.029261
0.388093
2,234
104
87
21.480769
0.776884
0
0
0.135135
0
0
0.053812
0
0
0
0
0
0
1
0.013514
false
0
0.067568
0
0.081081
0.108108
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8b98b8d35fd76526fa88fe1c8a30101c9a8baac3
9,713
py
Python
bot/ts/ThreadSafeTSConnection.py
Asnanon/ts-gw2-verifyBot
4da70450bc53631e61a42d18df36f5aef710cdbe
[ "MIT" ]
null
null
null
bot/ts/ThreadSafeTSConnection.py
Asnanon/ts-gw2-verifyBot
4da70450bc53631e61a42d18df36f5aef710cdbe
[ "MIT" ]
null
null
null
bot/ts/ThreadSafeTSConnection.py
Asnanon/ts-gw2-verifyBot
4da70450bc53631e61a42d18df36f5aef710cdbe
[ "MIT" ]
null
null
null
import logging from threading import RLock from typing import Callable, Tuple, TypeVar import schedule import ts3 from ts3.query import TS3ServerConnection from bot.config import Config LOG = logging.getLogger(__name__) R = TypeVar('R') def default_exception_handler(ex): """ prints the trace and returns the exception for further inspection """ LOG.debug("Exception caught in default_exception_handler: ", exc_info=ex) return ex def signal_exception_handler(ex): """ returns the exception without printing it, useful for expected exceptions, signaling that an exception occurred """ return ex def ignore_exception_handler(ex): """ acts as if no exception was raised, equivalent to except: pass""" return None class ThreadSafeTSConnection: RETRIES = 3 @property def uri(self): return "telnet://%s:%s@%s:%s" % (self._user, self._password, self._host, str(self._port)) def __init__(self, user, password, host, port, keepalive_interval=None, server_id=None, bot_nickname=None): """ Creates a new threadsafe TS3 connection. user: user to connect as password: password to connect to user with host: host of TS3 server port: port for server queries keepalive_interval: interval in which the keepalive is sent to the ts3 server server_id: the server id of the TS3 server we want to address, in case we have multiple. Note that the server id HAS to be selected at some point, using the "use" command. It has just been wrapped in here to allow for more convenient copying of the TS3 connection where the appropriate server is selected automatically. bot_nickname: nickname for the bot. Could be suffixed, see gentleRename. If None is passed, no naming will take place. """ self._user = user self._password = password self._host = host self._port = port self._keepalive_interval = int(keepalive_interval) self._server_id = server_id self._bot_nickname = bot_nickname + '-' + str(id(self)) self.lock = RLock() self.ts_connection = None # done in init() self._keepalive_job = None self.init() def init(self): if self.ts_connection is not None: try: self.ts_connection.close() except Exception: pass # may already be closed, doesn't matter. self.ts_connection = ts3.query.TS3ServerConnection(self.uri) # This hack allows using the "quit" command, so the bot does not appear as "timed out" in the Ts3 Client & Server log self.ts_connection.COMMAND_SET = set(self.ts_connection.COMMAND_SET) # creat copy of frozenset self.ts_connection.COMMAND_SET.add('quit') # add command if self._keepalive_interval is not None: if self._keepalive_job is not None: schedule.cancel_job(self._keepalive_job) # to avoid accumulating keepalive calls during re-inits self._keepalive_job = schedule.every(self._keepalive_interval).seconds.do(self.keepalive) if self._server_id is not None: self.ts3exec(lambda tc: tc.exec_("use", sid=self._server_id)) if self._bot_nickname is not None: self.forceRename(self._bot_nickname) def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): self.close() return None def keepalive(self): LOG.info(f"Keepalive Ts Connection {self._bot_nickname}") self.ts3exec(lambda tc: tc.send_keepalive()) def ts3exec(self, handler: Callable[[TS3ServerConnection], R], exception_handler=lambda ex: default_exception_handler(ex)) -> Tuple[R, Exception]: # eh = lambda ex: print(ex)): """ Excecutes a query() or exec_() on the internal TS3 connection. handler: a function ts3.query.TS3ServerConnection -> any exception_handler: a function Exception -> any. None will be interpreted as not having encountered an exception. The default handler prints the stacktrace for the exception and returns the exception itself. This changes the workflow of executing erroring code: instead of try-catching we need to decompose the tuple returned from this function and check if the exception result is anything but None. E.g.: try: res = ts3con.query(...) except Exception as ex: # error handling becomes res,ex = threadsafe_ts3con.ts3exec(lambda tc: tc.query(...)) if ex: # error handling Note that the exception handler is only executed iff an exception is actually being handled! returns a tuple with the results of the two handlers (result first, exception result second). """ reinit = False with self.lock: failed = True fails = 0 res = None exres = None while failed and fails < ThreadSafeTSConnection.RETRIES: failed = False try: res = handler(self.ts_connection) except ts3.query.TS3TransportError: failed = True fails += 1 LOG.error("Critical error on transport level! Attempt %s to restart the connection and send the command again.", str(fails), ) reinit = True except Exception as ex: exres = exception_handler(ex) if reinit: self.init() return res, exres def close(self): if self._keepalive_job is not None: schedule.cancel_job(self._keepalive_job) # This hack allows using the "quit" command, so the bot does not appear as "timed out" in the Ts3 Client & Server log if self.ts_connection is not None: self.ts_connection.exec_("quit") # send quit self.ts_connection.close() # immediately quit del self.ts_connection def gentleRename(self, nickname): """ Renames self to nickname, but attaches a running counter to the name if the nickname is already taken. """ i = 1 new_nick = "%s(%d)" % (nickname, i) while not self.ts3exec(lambda tc: tc.query("clientfind", pattern=new_nick).first(), signal_exception_handler)[1]: i += 1 new_nick = "%s(%d)" % (nickname, i) new_nick = "%s(%d)" % (nickname, i) self.ts3exec(lambda tc: tc.exec_("clientupdate", client_nickname=new_nick)) self._bot_nickname = new_nick return self._bot_nickname def forceRename(self, target_nickname): """ Attempts to forcefully rename self. If the chosen nickname is already taken, the bot will attempt to kick that user. If that fails the bot will fall back to gentle renaming itself. """ whoami_response, _ = self.ts3exec(lambda tc: tc.query("whoami").first()) imposter, error = self.ts3exec(lambda tc: tc.query("clientfind", pattern=target_nickname).first(), signal_exception_handler) # check if nickname is already in use if whoami_response['client_nickname'] != target_nickname: if error: if error.resp.error.get('id') == '512': # no result self.ts3exec(lambda tc: tc.exec_("clientupdate", client_nickname=target_nickname)) LOG.info("Forcefully renamed self to '%s'.", target_nickname) else: LOG.error("Error on rename when searching for users", exc_info=error) else: if whoami_response['client_id'] != imposter['clid']: _, ex = self.ts3exec(lambda tc: tc.exec_("clientkick", reasonid=5, reasonmsg="Reserved Nickname", clid=imposter.get("clid")), signal_exception_handler) if ex: LOG.warning( "Renaming self to '%s' after kicking existing user with reserved name failed." " Warning: this usually only happens for serverquery logins, meaning you are running multiple bots or you" " are having stale logins from crashed bot instances on your server. Only restarts can solve the latter.", target_nickname) else: LOG.info("Kicked user who was using the reserved registration bot name '%s'.", target_nickname) target_nickname = self.gentleRename(target_nickname) LOG.info("Renamed self to '%s'.", target_nickname) else: self.ts3exec(lambda tc: tc.exec_("clientupdate", client_nickname=target_nickname)) else: LOG.info("No rename necessary") self._bot_nickname = target_nickname return self._bot_nickname def create_connection(config: Config, nickname: str) -> ThreadSafeTSConnection: return ThreadSafeTSConnection(config.user, config.passwd, config.host, config.port, config.keepalive_interval, config.server_id, nickname)
45.176744
171
0.601153
1,146
9,713
4.961606
0.268761
0.027436
0.033767
0.029898
0.179036
0.142983
0.126451
0.105698
0.083539
0.074569
0
0.006237
0.323175
9,713
214
172
45.38785
0.858686
0.29826
0
0.225564
0
0
0.128452
0.004034
0
0
0
0
0
1
0.105263
false
0.037594
0.052632
0.022556
0.24812
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
0
0
0
1
0
8ba24d39fccf745cf193a9313e6f0347c33e72ba
1,122
py
Python
workalendar/europe/georgia.py
macharmi/workalendar
4f8644484d6ba56c66e4bb82c377aa19eccfc0dc
[ "MIT" ]
null
null
null
workalendar/europe/georgia.py
macharmi/workalendar
4f8644484d6ba56c66e4bb82c377aa19eccfc0dc
[ "MIT" ]
null
null
null
workalendar/europe/georgia.py
macharmi/workalendar
4f8644484d6ba56c66e4bb82c377aa19eccfc0dc
[ "MIT" ]
null
null
null
from ..core import OrthodoxCalendar from ..registry_tools import iso_register @iso_register('GE') class Georgia(OrthodoxCalendar): 'Country of Georgia' "Sources: " "https://en.wikipedia.org/wiki/Public_holidays_in_Georgia_(country)" "https://www.officeholidays.com/countries/georgia/2021" include_christmas = False include_christmas_eve = False include_new_years_day = True include_orthodox_christmas = True include_epiphany = False include_good_friday = True include_easter_saturday = True include_easter_sunday = True include_easter_monday = True FIXED_HOLIDAYS = OrthodoxCalendar.FIXED_HOLIDAYS + ( (1, 2, "Day After New Year"), (1, 19, "Orthodox Epiphany"), (3, 3, "Mother's Day"), (3, 8, "International Women's Day"), (4, 9, "Day Of National Unity"), (5, 9, "Day Of Victory Over Fascism"), (5, 12, "Saint Andrew The First-Called Day"), (5, 26, "Independence Day"), (8, 28, "Saint Mary's Day"), (10, 14, "Day Of Svetitskovloba"), (11, 23, "Saint George's Day"), )
30.324324
72
0.646168
140
1,122
4.992857
0.564286
0.078684
0.072961
0
0
0
0
0
0
0
0
0.039581
0.234403
1,122
36
73
31.166667
0.774156
0.016043
0
0
0
0
0.331551
0
0
0
0
0
0
1
0
false
0
0.066667
0
0.433333
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
0
0
0
1
0
8ba46c9ce685361335be0d77dfae9a2dd018991f
2,502
py
Python
sorts.py
zhangxl97/leetcode
aa94228eba86d761ce5c9b6bfb8b2015c1629074
[ "MIT" ]
1
2020-09-12T10:35:22.000Z
2020-09-12T10:35:22.000Z
sorts.py
zhangxl97/leetcode
aa94228eba86d761ce5c9b6bfb8b2015c1629074
[ "MIT" ]
null
null
null
sorts.py
zhangxl97/leetcode
aa94228eba86d761ce5c9b6bfb8b2015c1629074
[ "MIT" ]
null
null
null
from typing import List class sort: def quick(self, nums:List[int]) -> List[int]: if len(nums) >= 2: base = nums[-1] # 选取基准值,可以为任何值 left, right = [], [] nums = nums[:-1] for num in nums: if num >= base: # 大于等于基准值的数存于right right.append(num) else: # 小于基准值的数存于left left.append(num) # print(left, '\t', base, '\t', right) return self.quick(left) + [base] + self.quick(right) else: return nums def quick_sort(self, nums: list, left: int, right: int) -> None: if left < right: i = left j = right # 取第一个元素为枢轴量 pivot = nums[left] while i != j: # 交替扫描和交换 # 从右往左找到第一个比枢轴量小的元素,交换位置 while j > i and nums[j] > pivot: j -= 1 if j > i: # 如果找到了,进行元素交换 # nums[i], nums[j] = nums[j], nums[i] # break nums[i] = nums[j] i += 1 # 从左往右找到第一个比枢轴量大的元素,交换位置 while i < j and nums[i] < pivot: i += 1 if i < j: nums[j] = nums[i] j -= 1 # 至此完成一趟快速排序,枢轴量的位置已经确定好了,就在i位置上(i和j)值相等 nums[i] = pivot print(nums) # 以i为枢轴进行子序列元素交换 self.quick_sort(nums, left, j-1) self.quick_sort(nums, j+1, right) def merge(self, a, b): c = [] h = j = 0 while j < len(a) and h < len(b): if a[j] < b[h]: c.append(a[j]) j += 1 else: c.append(b[h]) h += 1 if j == len(a): for i in b[h:]: c.append(i) else: for i in a[j:]: c.append(i) return c def merge_sort(self, lists): if len(lists) <= 1: return lists middle = len(lists)//2 left = self.merge_sort(lists[:middle]) right = self.merge_sort(lists[middle:]) return self.merge(left, right) def main(): s = sort() array = [2,3,5,1,1,4,6,15] # array = [4,1,2,3,5] print(array) # print(s.merge_sort(array)) s.quick_sort(array, 0, len(array)-1) print(array) if __name__ == "__main__": main()
26.617021
68
0.406475
293
2,502
3.416382
0.228669
0.02997
0.026973
0.01998
0.06993
0
0
0
0
0
0
0.022642
0.470424
2,502
93
69
26.903226
0.73283
0.120703
0
0.179104
0
0
0.003665
0
0
0
0
0
0
1
0.074627
false
0
0.014925
0
0.179104
0.044776
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8ba6b11d7fb6854358fc0d437c22f1ff827b55c0
6,622
py
Python
energy_consumption_lstm/data/model.py
DiarmuidKelly/predictors
9087302ab3cc54463807b0777f341b575a8fcc90
[ "MIT" ]
null
null
null
energy_consumption_lstm/data/model.py
DiarmuidKelly/predictors
9087302ab3cc54463807b0777f341b575a8fcc90
[ "MIT" ]
null
null
null
energy_consumption_lstm/data/model.py
DiarmuidKelly/predictors
9087302ab3cc54463807b0777f341b575a8fcc90
[ "MIT" ]
null
null
null
import datetime as dt import numpy as np def calculate_ranges(dataset): arr = np.array(dataset) mean = np.mean(arr, axis=0) min = np.min(arr, axis=0) max = np.max(arr, axis=0) ranges = np.array((min, mean, max)).T return ranges class Record: def __init__(self): self.time_date = 0 self.global_active_Ah_min = 0 self.global_reactive_Ah_min = 0 self.voltage = 0 self.current = 0 self.sub_meters = [] self.residual_active_energy = 0 self.error_active = 0 self.power = 0 self.raw_power = 0 def process_entry(self, arr): ret = [self.__date_time_timestamp(arr[0], arr[1])] if arr[2] == '?': return False # global active power in kilowatts to Amps to Ah ret.append(self.__convert_watts_to_amps(float(arr[2]) * (1000 / 60), float(arr[4]))) # global reactive power in kilowatts to Amps to Ah ret.append(self.__convert_watts_to_amps(float(arr[3]) * (1000 / 60), float(arr[4]))) # volts ret.append(float(arr[4])) # amps ret.append(float(arr[5])) # Sub meters from watt hours to Amp hours ret.append(self.__convert_Wh_to_Ah(float(arr[6]), float(arr[4]))) ret.append(self.__convert_Wh_to_Ah(float(arr[7]), float(arr[4]))) ret.append(self.__convert_Wh_to_Ah(float(arr[8]), float(arr[4]))) # Active power in Ah not measured by the sub meters ret.append((ret[1]) - (ret[5] + ret[6] + ret[7])) # Power in Ah difference between volts * current and global active power # (volts * amps) - global active kilowatts * 1000 # / volts ret.append(self.__convert_watts_to_amps((float(arr[4]) * float(arr[5])) - (float(arr[2]) * 1000), float(arr[4]))) ret.append(float(arr[4]) * float(arr[5])) return ret def __calc_phase_from_real(self): self.__convert_amps_to_watts(self.global_active_Ah_min, self.voltage) def process_record(self, rec, ranges): # self.time_date = self.__date_time_vector(rec[0], ranges[0]) self.time_date = rec[0] self.global_active_Ah_min = self.__global_active_Ah_vector(rec[1], ranges[1]) self.global_reactive_Ah_min = self.__global_reactive_Ah_vector(rec[2], ranges[2]) self.voltage = self.__voltage_vector(rec[3], ranges[3]) self.current = self.__current_vector(rec[4], ranges[4]) self.sub_meters = self.__sub_meter_vector([rec[5], rec[6], rec[7]], [ranges[5], ranges[6], ranges[7]]) self.residual_active_energy = self.__residual_active_energy_vector(rec[8], ranges[8]) self.error_active = self.__error_active_vector(rec[9], ranges[9]) self.power = self.__power_vector(rec[10], ranges[10]) self.raw_power = rec[10] def __date_time_timestamp(self, date, time): date = date.split("/") date = dt.date(int(date[2]), int(date[1]), int(date[0])).isoformat() date = dt.datetime.fromisoformat("{}T{}".format(date, time)) return date.timestamp() # 100,000 records processed in 0.4 seconds def __date_time_vector(self, val, time_date_range): if time_date_range[0] > val or val > time_date_range[2]: raise Exception("Value out of range") val = (val - time_date_range[0]) / (time_date_range[2] - time_date_range[0]) return abs(val) def __global_active_Ah_vector(self, val, global_active_Ah_min_range): if global_active_Ah_min_range[0] > val or val > global_active_Ah_min_range[2]: raise Exception("Value out of range") val = (val - global_active_Ah_min_range[0]) / (global_active_Ah_min_range[2] - global_active_Ah_min_range[0]) return abs(val) def __global_reactive_Ah_vector(self, val, global_reactive_Ah_min_range): if global_reactive_Ah_min_range[0] > val or val > global_reactive_Ah_min_range[2]: raise Exception("Value out of range") val = (val - global_reactive_Ah_min_range[0]) / (global_reactive_Ah_min_range[2] - global_reactive_Ah_min_range[0]) return abs(val) def __voltage_vector(self, val, voltage_range): if voltage_range[0] > val or val > voltage_range[2]: raise Exception("Value out of range") val = (val - voltage_range[0]) / (voltage_range[2] - voltage_range[0]) return abs(val) def __current_vector(self, val, current_range): if current_range[0] > val or val > current_range[2]: raise Exception("Value out of range") val = (val - current_range[0]) / (current_range[2] - current_range[0]) return abs(val) def __sub_meter_vector(self, vals, sub_meters_range): if sub_meters_range[0][0] > vals[0] or vals[0] > sub_meters_range[0][2]: raise Exception("Value out of range") vals[0] = (vals[0] - sub_meters_range[0][0]) / (sub_meters_range[0][2] - sub_meters_range[0][0]) if sub_meters_range[1][0] > vals[1] or vals[1] > sub_meters_range[1][2]: raise Exception("Value out of range") vals[1] = (vals[1] - sub_meters_range[1][0]) / (sub_meters_range[1][2] - sub_meters_range[1][0]) if sub_meters_range[2][0] > vals[2] or vals[2] > sub_meters_range[2][2]: raise Exception("Value out of range") vals[2] = (vals[2] - sub_meters_range[2][0]) / (sub_meters_range[2][2] - sub_meters_range[2][0]) return vals def __residual_active_energy_vector(self, val, residual_active_energy_range): if residual_active_energy_range[0] > val or val > residual_active_energy_range[2]: raise Exception("Value out of range") val = (val - residual_active_energy_range[0]) / (residual_active_energy_range[2] - residual_active_energy_range[0]) return abs(val) def __error_active_vector(self, val, error_active_range): if error_active_range[0] > val or val > error_active_range[2]: raise Exception("Value out of range") val = (val - error_active_range[0]) / (error_active_range[2] - error_active_range[0]) return abs(val) def __power_vector(self, val, power_range): if power_range[0] > val or val > power_range[2]: raise Exception("Value out of range") val = (val - power_range[0]) / (power_range[2] - power_range[0]) return abs(val) def __convert_watts_to_amps(self, watts, volts): return watts / volts def __convert_amps_to_watts(self, amps, volts): return amps * volts def __convert_Wh_to_Ah(self, wh, volts): return wh / volts
43.854305
123
0.643914
999
6,622
3.957958
0.103103
0.044006
0.056651
0.05564
0.495448
0.363935
0.221548
0.213202
0.161609
0.143146
0
0.034631
0.228179
6,622
150
124
44.146667
0.738994
0.064029
0
0.171171
0
0
0.03315
0
0
0
0
0
0
1
0.162162
false
0
0.018018
0.027027
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8ba816e0011648c0f031c8c0072d0e07ef644345
3,639
py
Python
python ex12.py
IMDCGP105-1819/portfolio-s184286
e5485f640f341090823bbcaabe287376a048b2c4
[ "MIT" ]
null
null
null
python ex12.py
IMDCGP105-1819/portfolio-s184286
e5485f640f341090823bbcaabe287376a048b2c4
[ "MIT" ]
null
null
null
python ex12.py
IMDCGP105-1819/portfolio-s184286
e5485f640f341090823bbcaabe287376a048b2c4
[ "MIT" ]
null
null
null
""" Task 3 Write an application that allows you to calculate the cost of a trip. Implement a function called hotel_cost that takes one argument, nights, as input. The hotel costs £70 per night – so return a suitable value. Implement a function called plane_ticket_cost that accepts a string, city, and a float, class, as inputs. The function should handle the following locations, returning their associated round trip costs that are multiplied by the class amount. “New York”: £2,000 “Auckland”: £790 “Venice”: £154 “Glasgow”: £65 The class multiplier starts at 1 for economy and goes up in .3 steps: 1.3 = premium economy, 1.6 = business class and 1.9 = first class. Then implement the rental_car_cost function with an argument called days. The function should calculate the cost of hiring a car with the following considerations: •Every day of car hire costs £30 •If you rent the car for more than 7 days, you get £50 off your total •If you rent the car for more than 3 days, you get £30 off your total oThese two discounts cannot be applied at the same time. Define a function total_cost which accepts two arguments; city and days. It should call the other functions and return the sum of the cost of the trip. Save the file as the next numeric ex value and commit to GitHub. """ nights = int(input("how many number of nights stay?")) def hotel_cost(nights): nights*70 print("number of nights",nights) hotel_cost(nights) city=str(input("select your destination: New york, Auckland, Venice, Glasgow: ")) def plane_ticket_cost(city, _class): # the function should handle the following locations, returning thier associated round trip costs that are multiplied by the class amount. if city=='New york': plane_ticket_cost = 2000.00 elif city=='Auckland': plane_ticket_cost = 790.00 elif city=='Venice': plane_ticket_cost = 154.00 elif city=='Glasgow': plane_ticket_cost = 65.00 # the class multiplier starts at 1 for economy and goes up in 3 steps: 1.3 premium economy 1.6 = business class and 1.9 = first class. _class=float(input("Select your Travel Class: 1=Economy, 1.3=Premium Economy, 1.6=Business Class, 1.9=First Class: ")) if _class=='1': print("Economy Travel Class selected") elif _class=='1.3': print("Premium Economy Travel Class selected") elif _class=='1.6': print("Business Class Travel Class selected") elif _class=='1.9': print("First Class Travel Class selected") plane_ticket_cost(city, _class) days=float(input("enter how many number of days car hire required: ")) def rental_car_cost(days): # Every day of car hire costs £30 if days > 0: print(days * 30) elif days > 3: print(days * 30 -30.00) # If you rent the car for more than 3 days, you get £30 off your total elif days > 7: print (days * 30 -50.00) # If you rent the car for more than 7 days, you get £50 off your total # These two discounts cannot be applied at the same time. rental_car_cost(days) def total_cost(city,days): # accepts two arguments, city and days. # it should call the other functions and return the sum of the cost of the trip. print("the Hotel Cost is:", hotel_cost(nights)) print("the Plane Ticket Cost: ", plane_ticket_cost(city, _class)) print(" Rental Car Cost:", rental_car_cost(days) ) print("Choice of city:", city) print("for ",days, "no of Days") print("Travelling in", _class, ) total_cost(city,days)
34.657143
183
0.687826
593
3,639
4.178752
0.252951
0.039952
0.054479
0.01937
0.464891
0.435835
0.424132
0.395077
0.319613
0.284907
0
0.035727
0.230833
3,639
104
184
34.990385
0.84423
0.52377
0
0
0
0.02381
0.327329
0
0
0
0
0
0
1
0.095238
false
0
0
0
0.095238
0.333333
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8ba86635b84461a1f0a395b2d0b3f48cfc499bf5
7,050
py
Python
segment_chars.py
indranildchandra/Automatic-Licence-Plate-Recognizer
12abcf40459f8e2d5d7491aedaed2ee3ea1eb1a7
[ "Apache-2.0" ]
1
2020-10-12T12:49:05.000Z
2020-10-12T12:49:05.000Z
segment_chars.py
indranildchandra/Automatic-Licence-Plate-Recognizer
12abcf40459f8e2d5d7491aedaed2ee3ea1eb1a7
[ "Apache-2.0" ]
null
null
null
segment_chars.py
indranildchandra/Automatic-Licence-Plate-Recognizer
12abcf40459f8e2d5d7491aedaed2ee3ea1eb1a7
[ "Apache-2.0" ]
null
null
null
import pandas as pd import numpy as np import cv2 import os import math import pickle from matplotlib import pyplot as plt from PIL import Image from matplotlib.pyplot import imshow # %matplotlib inline def rotate_image(img): # gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) gray = img edges = cv2.Canny(gray,50,150,apertureSize = 3) lines = cv2.HoughLines(edges,1,np.pi/180,200) angle = 0 if lines is not None: for rho,theta in lines[0]: angle = math.degrees(theta)-90 a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + 1000*(-b)) y1 = int(y0 + 1000*(a)) x2 = int(x0 - 1000*(-b)) y2 = int(y0 - 1000*(a)) # print(angle) # Do skew correction only if the angle of rotation is greather than 3 degrees if abs(angle%90) > 3: if angle < 0: angle = -1* angle if angle > 45: angle = 90-angle (h, w) = img.shape[:2] center = (w // 2, h // 2) M = cv2.getRotationMatrix2D(center, angle, 1.0) rotated = cv2.warpAffine(img, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) # cv2.putText(rotated, "Angle: {:.2f} degrees".format(angle), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # print("Image rotated by angle: {:.3f}".format(angle)) return rotated else: return img def square(img): """ This function resize non square image to square one (height == width) :param img: input image as numpy array :return: numpy array """ # image after making height equal to width squared_image = img # Get image height and width h = img.shape[0] w = img.shape[1] # In case height superior than width if h > w: diff = h-w if diff % 2 == 0: x1 = np.zeros(shape=(h, diff//2)) x2 = x1 else: x1 = np.zeros(shape=(h, diff//2)) x2 = np.zeros(shape=(h, (diff//2)+1)) squared_image = np.concatenate((x1, img, x2), axis=1) # In case height inferior than width if h < w: diff = w-h if diff % 2 == 0: x1 = np.zeros(shape=(diff//2, w)) x2 = x1 else: x1 = np.zeros(shape=(diff//2, w)) x2 = np.zeros(shape=((diff//2)+1, w)) squared_image = np.concatenate((x1, img, x2), axis=0) return squared_image def get_segmented_chars(img_file_path, annotation): img = cv2.imread(img_file_path) # imshow(img) img = img[round(img.shape[0]*0.1):round(img.shape[0]*0.9), round(img.shape[1]*0.1):round(img.shape[1]*0.9)] # imshow(img) imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # imshow(imgray) imgray = rotate_image(imgray) # imshow(imgray) kernel = np.ones((8,8), np.uint8) eroded_img = cv2.erode(imgray, kernel, iterations=1) # imshow(eroded_img) imgray = eroded_img height = img.shape[0] width = img.shape[1] area = height * width scale1 = 0.001 # static value scale2 = 0.1 # static value area_condition1 = area * scale1 area_condition2 = area * scale2 # # Global Thresholding # ret1,th1 = cv2.threshold(imgray,127,255,cv2.THRESH_BINARY) # # Otsu's Thresholding # ret2,th2 = cv2.threshold(imgray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # # Adaptive Mean Thresholding # th4 = cv2.adaptiveThreshold(imgray,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2) # # Adaptive Gaussian Thresholding # th5 = cv2.adaptiveThreshold(imgray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) # Otsu's thresholding after Gaussian filtering blur = cv2.GaussianBlur(imgray,(5,5),0) ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # titles = ['Original Grayscale Image', 'Global Thresholding', 'Otsu thresholding', 'Otsu thresholding after Gaussian filtering', # 'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding'] # images = [imgray, th1, th2, th3, th4, th5] # for i in range(6): # plt.subplot(3,2,i+1),plt.imshow(images[i],'gray') # plt.title(titles[i]) # plt.xticks([]),plt.yticks([]) # plt.show() # get contours contours, hierarchy = cv2.findContours(th3, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # sort contours contours = sorted(contours, key=cv2.contourArea, reverse=True) # filter contours final_contours = [] aspect_ratio_filtered_contours = [] aspect_ratio_filtered_contours_area = [] area_filtered_contours = [] area_filtered_contours_centroids = [] for cnt in contours: (x,y,w,h) = cv2.boundingRect(cnt) if (w * h > area_condition1 and w * h < area_condition2 and (w/h > 0.3 or h/w > 0.3)): aspect_ratio_filtered_contours.append(cnt) aspect_ratio_filtered_contours_area.append(w * h) if aspect_ratio_filtered_contours_area: max_cnt_area = max(aspect_ratio_filtered_contours_area) counter = 1 for cnt, cnt_area in zip(aspect_ratio_filtered_contours, aspect_ratio_filtered_contours_area): if cnt_area >= 0.3 * max_cnt_area: area_filtered_contours.append(cnt) cnt_moment = cv2.moments(cnt) area_filtered_contours_centroids.append((counter, int(cnt_moment['m10']/cnt_moment['m00']), int(cnt_moment['m01']/cnt_moment['m00']))) counter += 1 if len(area_filtered_contours) > len(annotation): area_filtered_contours_centroids.sort(key = lambda x: x[2], reverse=True) # print(area_filtered_contours_centroids) centroid_means = [sum(ele) / len(area_filtered_contours_centroids) for ele in zip(*area_filtered_contours_centroids)] # print(centroid_means) centroid_mean_distance = list() for ele in area_filtered_contours_centroids: centroid_mean_distance.append((ele[0], ele[1], ele[2], abs(math.sqrt((ele[1] - centroid_means[1])**2 + (ele[2] - centroid_means[2])**2)))) centroid_mean_distance.sort(key = lambda x: x[3], reverse=False) # print(centroid_mean_distance) counter = 1 for cnt, cnt_centroid_mean_dist in zip(area_filtered_contours, centroid_mean_distance): if counter <= 7: final_contours.append(cnt) counter += 1 else: break else: final_contours = area_filtered_contours # final_contours = area_filtered_contours cropped_chars = [] bounding_boxes = [] for cnt in final_contours: (x,y,w,h) = cv2.boundingRect(cnt) cv2.drawContours(img, [cnt], 0, (0, 255, 0), 3) cv2.rectangle(img, (x,y), (x+w,y+h), (255, 0, 0), 2) c = th3[y:y+h,x:x+w] c = np.array(c) c = cv2.bitwise_not(c) c = square(c) c = cv2.resize(c,(28,28), interpolation = cv2.INTER_AREA) cropped_chars.append(c) bounding_boxes.append((x,y,w,h)) # sort shortlisted contours from left to right if cropped_chars: a = list(map(tuple, zip(cropped_chars, final_contours, bounding_boxes))) sorted_cropped_chars, sorted_final_contours, sorted_bounding_boxes = zip(*sorted(a, key = lambda x: x[2][0], reverse=False)) else: sorted_cropped_chars = [] sorted_final_contours = [] sorted_bounding_boxes = [] # fig, axes = plt.subplots(3, 3, sharex=True, sharey=True) # for cropped_char, ax in zip(sorted_cropped_chars, axes.flat): # ax.imshow(cropped_char) # ax.axis('off') for index, cnt in enumerate(sorted_final_contours): (x,y,w,h) = cv2.boundingRect(cnt) img = cv2.putText(img, str(annotation[index]).upper(), (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (50,50,50), 2) # green - (36,255,12) return sorted_cropped_chars, img
31.61435
141
0.699433
1,110
7,050
4.290991
0.237838
0.070544
0.054587
0.04535
0.279866
0.17258
0.141088
0.119253
0.062566
0
0
0.050253
0.158865
7,050
222
142
31.756757
0.752951
0.274326
0
0.152174
0
0
0.002374
0
0
0
0
0
0
1
0.021739
false
0
0.065217
0
0.115942
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
0
0
0
1
0
8bab05cccc2b06bc0e17af38af464fd773e79545
5,358
py
Python
beastx/__main__.py
Mrunal1911/Beast-X
b7b13b3b5db754894a830569909c4b77aa1ff19d
[ "MIT" ]
null
null
null
beastx/__main__.py
Mrunal1911/Beast-X
b7b13b3b5db754894a830569909c4b77aa1ff19d
[ "MIT" ]
null
null
null
beastx/__main__.py
Mrunal1911/Beast-X
b7b13b3b5db754894a830569909c4b77aa1ff19d
[ "MIT" ]
null
null
null
import logging from pathlib import Path from sys import argv import var import telethon.utils from telethon import TelegramClient from telethon import events,Button import os from var import Var from . import beast from telethon.tl import functions from beastx.Configs import Config from telethon.tl.functions.messages import AddChatUserRequest from telethon.tl.functions.users import GetFullUserRequest from telethon.tl.functions.channels import LeaveChannelRequest from telethon.tl.functions.account import UpdateProfileRequest from telethon.tl.types import InputMessagesFilterDocument from resources.startup.sanskar import autobot,autopilot,customize from beastx.utils import load_module, start_assistant import asyncio from telethon.tl.functions.channels import InviteToChannelRequest from . import bot bot = beast sed = logging.getLogger("beastx") #rom . import semxx,semxxx ##################################### plugin_channel = "@BeastX_Plugins" ##################################### if Var.TG_BOT_TOKEN_BF_HER is None: try: print("BOT_TOKEN not Found") bot.loop.run_until_complete(autobot()) except BaseException as er: print(er) else: pass sur = Config.PRIVATE_GROUP_ID UL = Config.TG_BOT_USER_NAME_BF_HER VR = "Beast 0.1" chat_id = sur sed = logging.getLogger("beastx") async def add_bot(bot_token): await bot.start(bot_token) bot.me = await bot.get_me() bot.uid = telethon.utils.get_peer_id(bot.me) #om = await beast.get_me() #mm = await sedmrunal.get_me() #try: #MSG = f""" #✨𝔹𝕖𝕒𝕤𝕥 ℍ𝕒𝕤 𝔹𝕖𝕖𝕟 𝔻𝕖𝕡𝕝𝕠𝕪𝕖𝕕! #--------------------- #┏━━━━━━━━━━━━━━━━━ #┣•Assistant➠ @{mm.username} #┣•User➠ @{om.username} #┣•Version➠ {VR} #┗━━━━━━━━━━━━━━━━━ #Do `.ping `or` /alive` for check userbot working #""" ''' await sedmrunal.send_message(sur, MSG, buttons=[ [Button.url("⭐Updates", url="https://t.me/BeastX_Userbot")], [ Button.url("⚡Support",url="https://t.me/BeastX_Support")] ]) except Exception as e: sed.info(str(e)) sed.info("---------------------------------------") sed.info("Bruh you forgot add assistant in log group") sed.info("---------------------------------------") ''' try: bot.tgbot = None if Var.TG_BOT_USER_NAME_BF_HER is not None: bot.tgbot = TelegramClient( "TG_BOT_TOKEN", api_id=Var.APP_ID, api_hash=Var.API_HASH ).start(bot_token=Var.TG_BOT_TOKEN_BF_HER) bot.loop.run_until_complete(add_bot(Var.TG_BOT_USER_NAME_BF_HER)) else: bot.start() except BaseException as er: sed.info(er) async def a(): sed.info("Connecting...") ; o = "" la = 0 try: await bot.start() ; sed.info("beastx connected") ; o = "client" except: sed.info("Telegram String Session Wrong or Expired Please Add new one ") ; quit(1) import glob async def a(): documentss = await bot.get_messages(plugin_channel, None , filter=InputMessagesFilterDocument) total = int(documentss.total) total_doxx = range(0, total) for ixo in total_doxx: mxo = documentss[ixo].id downloaded_file_name = await bot.download_media(await bot.get_messages(plugin_channel, ids=mxo), "beastx/modules/") if "(" not in downloaded_file_name: path1 = Path(downloaded_file_name) shortname = path1.stem load_module(shortname.replace(".py", "")) sed.info("Installed Plugin `{}` successfully.".format(os.path.basename(downloaded_file_name))) else: sed.info("Plugin `{}` has been pre-installed and cannot be installed.".format(os.path.basename(downloaded_file_name))) logger_group = Var.PRIVATE_GROUP_ID if not str(logger_group).startswith("-100"): try: bot.loop.run_until_complete(autopilot()) except BaseException as er: print(er) else: pass bot.loop.run_until_complete(a()) path = "beastx/modules/*.py" files = glob.glob(path) for name in files: with open(name) as f: path1 = Path(f.name) shortname = path1.stem load_module(shortname.replace(".py", "")) if Config.ENABLE_ASSISTANTBOT == "ENABLE": path = "beastx/modules/assistant/*.py" files = glob.glob(path) for name in files: with open(name) as f: path1 = Path(f.name) shortname = path1.stem start_assistant(shortname.replace(".py", "")) sed.info("beastx And Assistant Bot Have Been Installed Successfully !") sed.info("---------------------------------------") sed.info("------------@BeastX_Userbot------------") sed.info("---------------------------------------") else: sed.info("beastx Has Been Installed Sucessfully !") sed.info("Hope you will enjoy") #await bot.send_message(chat_id,MSG) #else: # sed.info("your Get_Msg disable") bot.run_until_disconnected()
28.652406
140
0.58044
635
5,358
4.833071
0.313386
0.038775
0.031932
0.037471
0.254806
0.203324
0.140762
0.102313
0.07755
0.052134
0
0.003537
0.261292
5,358
186
141
28.806452
0.759727
0.067749
0
0.324074
0
0
0.138139
0.035198
0
0
0
0
0
1
0
false
0.018519
0.212963
0
0.212963
0.027778
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bac89c0e7fe595c62cbe29b2411dd910e49d2c2
859
py
Python
tests/day02/test_day02.py
SebastiaanZ/aoc-2019
e1fe4630b0f375be0b79398e07e23b9c0196efbb
[ "MIT" ]
3
2019-12-02T19:38:14.000Z
2020-01-28T00:06:09.000Z
tests/day02/test_day02.py
SebastiaanZ/aoc-2019
e1fe4630b0f375be0b79398e07e23b9c0196efbb
[ "MIT" ]
6
2020-03-24T17:58:40.000Z
2022-03-12T00:18:45.000Z
tests/day02/test_day02.py
SebastiaanZ/aoc-2019
e1fe4630b0f375be0b79398e07e23b9c0196efbb
[ "MIT" ]
null
null
null
import unittest from solutions.day02.solution import ship_computer from tests.helpers import Puzzle class DayTwoTests(unittest.TestCase): """Tests for my solutions to Day 1 of the Advent of Code 2019.""" def test_ship_computer_with_example_data(self): """Test the ship computer used for day 2 using the example data provided in the puzzle.""" test_cases = ( Puzzle(data=[1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50], answer=3500), ) for puzzle in test_cases: with self.subTest(data=puzzle.data, answer=puzzle.answer): # We don't have a noun or verb, so fake it by supplying the values already in place noun = puzzle.data[1] verb = puzzle.data[2] self.assertEqual(ship_computer(puzzle.data, noun=noun, verb=verb), puzzle.answer)
37.347826
99
0.641444
125
859
4.336
0.52
0.092251
0.04059
0
0
0
0
0
0
0
0
0.050794
0.266589
859
22
100
39.045455
0.809524
0.264261
0
0
0
0
0
0
0
0
0
0
0.076923
1
0.076923
false
0
0.230769
0
0.384615
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
0
0
0
1
0
8bacb9d61c16b4122f25721e214182358d00a686
24,678
py
Python
ActiveSuspensions/2DOF Fuzzy Suspension.py
MarcoFerrari128/Portfolio
82cd81a4235dbd804cd13100b2304a04ca6771b5
[ "MIT" ]
null
null
null
ActiveSuspensions/2DOF Fuzzy Suspension.py
MarcoFerrari128/Portfolio
82cd81a4235dbd804cd13100b2304a04ca6771b5
[ "MIT" ]
null
null
null
ActiveSuspensions/2DOF Fuzzy Suspension.py
MarcoFerrari128/Portfolio
82cd81a4235dbd804cd13100b2304a04ca6771b5
[ "MIT" ]
null
null
null
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import ode import FLC import pyprind from numpy.linalg import eig import pandas as pd def impulse(lenght): i = 0 Impulse = [] while i < lenght: if i == 99: Impulse.append(1) else: Impulse.append(0) i += 1 return 0.1 * np.array(Impulse) def bump(): i = 0 Bump = [] while i < 1: if i <= 0.5625 and i >= 0.5: Bump.append(0.05 * (1 - np.cos(32 * np.pi * i))) else: Bump.append(0) i += 0.001 return np.array(Bump) def step(lenght): i = 0 Step = [] while i < lenght: if i <= 500: Step.append(0) else: Step.append(1) i += 1 return 0.1 * np.array(Step) def rough2(lenght): """Random road condition. Every 10 time sample a new random value is given. This simulates a car moving on a road at 36 km/h with roughness wide 1 cm. """ i = 0 Rough = [] while i < lenght/10: j = 0 sample = np.random.randn() # setting correct max height while j < 10: # add the same value for 10 time steps Rough.append(sample) j += 1 i += 1 return 0.1 * np.array(Rough) / np.max(Rough) / 2 def rough3(lenght): """Road condition defined by the ISO 8608 standard""" k = 3 # ISO road condition N = lenght + 1 # data points L = 10 # lenght of road profile B = L / N # sampling interval n0 = 0.1 dn = 1 / L # Frequency band n = np.arange(dn, N*dn, dn) # frequency band phi = 2 * np.pi * (np.random.rand(len(n))) Amp1 = np.sqrt(dn) * (2**k) * (1e-3) * n0/n x = np.arange(0, L-B, B) hx = np.zeros(len(x)) for i in np.arange(len(x)): hx[i] = np.sum(Amp1 * np.cos(2 * np.pi * n * x[i] + phi)) return 0.1 * hx / np.max(hx) def rough(): """Reading values from file Rough.txt""" f = open('Rough.txt','r') RoughList = [] for line in f: RoughList.append(float(line)) return np.array(RoughList) def RMS(array): """Calculates the root-mean-squared value of an array. """ return np.sqrt(array @ array / array.size) def derivate(array, step=100): """Calculates the first order derivative of an array. It differs from np.diff because this returns an array of the same lenght as the input one. It becomes useful for plotting. """ deriv = np.zeros_like(array) deriv[0] = array[1] - array[0] deriv[1:] = np.diff(array) return deriv * step # ============================================================================= # Importing values of PID # ============================================================================= StepPID = pd.read_excel('Scalino.xlsx') StepPID = np.asarray(StepPID) ImpulsePID = pd.read_excel('impulso.xlsx') ImpulsePID = np.asarray(ImpulsePID) BumpPID = pd.read_excel('BumpPID.xlsx') BumpPID = np.asarray(BumpPID) RoughPID = pd.read_excel('Rough.xlsx') RoughPID = np.asarray(RoughPID) # ============================================================================= # STATE SPACE REPRESENTATION # x1 = x_body # x2 = x_wheel # x3 = x_body' # x4 = x_wheel' # ============================================================================= # Main spring stiffness k_s = 15000 # N/m # Sprung mass m_b = 250 # kg # Viscous damper c_s = 1000 # N/(m/s) # Unsprung mass (wheel) m_w = 30 # kg # Tyre stiffness k_t = 150000 # N/m # Skyhook damping c_sky = 1000 # N/(m/s) # Different road simulations Impulse = impulse(1000) Step = step(1000) Bump = bump() Rough = rough() def fuzzySuspensionModel(timeScale, state, road): x1, x2, x3, x4 = state fuzzyForce = FLC.FLC(x1 - x2, x3) xdot1 = x3 xdot2 = x4 xdot3 = (-k_s / m_b * x1 + k_s / m_b * x2 - c_s / m_b * x3 + c_s / m_b * x4 + 1 / m_b * fuzzyForce) xdot4 = (k_s / m_w * x1 - (k_t + k_s) / m_w * x2 + c_s / m_w * x3 - c_s / m_w * x4 + k_t / m_w * road - 1 / m_w * fuzzyForce) return np.array([xdot1, xdot2, xdot3, xdot4]) def passiveSuspensionModel(timeScale, state, road): x1, x2, x3, x4 = state xdot1 = x3 xdot2 = x4 xdot3 = -k_s / m_b * x1 + k_s / m_b * x2 - c_s / m_b * x3 + c_s / m_b * x4 xdot4 = (k_s / m_w * x1 - (k_t + k_s) / m_w * x2 + c_s / m_w * x3 - c_s / m_w * x4 + k_t / m_w * road) return np.array([xdot1, xdot2, xdot3, xdot4]) def skyhookSuspensionModel(timeScale, state, road): x1, x2, x3, x4 = state xdot1 = x3 xdot2 = x4 xdot3 = (-k_s / m_b * x1 + k_s / m_b * x2 - c_s / m_b * x3 + c_s / m_b * x4 - c_sky / m_b * x3) xdot4 = (k_s / m_w * x1 - (k_t + k_s) / m_w * x2 + c_s / m_w * x3 - c_s / m_w * x4 + k_t / m_w * road) return np.array([xdot1, xdot2, xdot3, xdot4]) # ============================================================================= # ## ODE solution - fuzzy # ============================================================================= # Step solStep = ode(fuzzySuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solStep.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time = [] StepState = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Step') while solStep.successful() and solStep.t < tFin: solStep.set_f_params(Step[counter]) solStep.integrate(solStep.t + dt) StepState.append(solStep.y) Time.append(solStep.t) counter += 1 progress.update() Time = np.asarray(Time) StepState = np.asarray(StepState) # Impulse solImpulse = ode(fuzzySuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solImpulse.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time = [] ImpulseState = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Impulse') while solImpulse.successful() and solImpulse.t < tFin: solImpulse.set_f_params(Impulse[counter]) solImpulse.integrate(solImpulse.t + dt) ImpulseState.append(solImpulse.y) Time.append(solImpulse.t) counter += 1 progress.update() Time = np.asarray(Time) ImpulseState = np.asarray(ImpulseState) # Bump solBump = ode(fuzzySuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solBump.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time = [] BumpState = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Bump') while solBump.successful() and solBump.t < tFin: solBump.set_f_params(Bump[counter]) solBump.integrate(solBump.t + dt) BumpState.append(solBump.y) Time.append(solBump.t) counter += 1 progress.update() Time = np.asarray(Time) BumpState = np.asarray(BumpState) # Rough road solRough = ode(fuzzySuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solRough.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time = [] RoughState = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Rough') while solRough.successful() and solRough.t < tFin: solRough.set_f_params(Rough[counter]) solRough.integrate(solRough.t + dt) RoughState.append(solRough.y) Time.append(solRough.t) counter += 1 progress.update() Time = np.asarray(Time) RoughState = np.asarray(RoughState) # ============================================================================= # ## ODE solution - passive # ============================================================================= # Step solStep2 = ode(passiveSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solStep2.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time2 = [] StepState2 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Step') while solStep2.successful() and solStep2.t < tFin: solStep2.set_f_params(Step[counter]) solStep2.integrate(solStep2.t + dt) StepState2.append(solStep2.y) Time2.append(solStep2.t) counter += 1 progress.update() Time2 = np.asarray(Time2) StepState2 = np.asarray(StepState2) # Impulse solImpulse2 = ode(passiveSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solImpulse2.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time2 = [] ImpulseState2 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Impulse') while solImpulse2.successful() and solImpulse2.t < tFin: solImpulse2.set_f_params(Impulse[counter]) solImpulse2.integrate(solImpulse2.t + dt) ImpulseState2.append(solImpulse2.y) Time2.append(solImpulse2.t) counter += 1 progress.update() Time2 = np.asarray(Time2) ImpulseState2 = np.asarray(ImpulseState2) # Bump solBump2 = ode(passiveSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solBump2.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time2 = [] BumpState2 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Bump') while solBump2.successful() and solBump2.t < tFin: solBump2.set_f_params(Bump[counter]) solBump2.integrate(solBump2.t + dt) BumpState2.append(solBump2.y) Time2.append(solBump2.t) counter += 1 progress.update() Time2 = np.asarray(Time2) BumpState2 = np.asarray(BumpState2) # Rough road solRough2 = ode(passiveSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solRough2.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time2 = [] RoughState2 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Rough') while solRough2.successful() and solRough2.t < tFin: solRough2.set_f_params(Rough[counter]) solRough2.integrate(solRough2.t + dt) RoughState2.append(solRough2.y) Time2.append(solRough2.t) counter += 1 progress.update() Time2 = np.asarray(Time2) RoughState2 = np.asarray(RoughState2) # ============================================================================= # ## ODE solution - skyhook # ============================================================================= # Step solStep3 = ode(skyhookSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solStep3.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time3 = [] StepState3 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Step') while solStep3.successful() and solStep3.t < tFin: solStep3.set_f_params(Step[counter]) solStep3.integrate(solStep3.t + dt) StepState3.append(solStep3.y) Time3.append(solStep3.t) counter += 1 progress.update() Time3 = np.asarray(Time3) StepState3 = np.asarray(StepState3) # Impulse solImpulse3 = ode(skyhookSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solImpulse3.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time3 = [] ImpulseState3 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Impulse') while solImpulse3.successful() and solImpulse3.t < tFin: solImpulse3.set_f_params(Impulse[counter]) solImpulse3.integrate(solImpulse3.t + dt) ImpulseState3.append(solImpulse3.y) Time3.append(solImpulse3.t) counter += 1 progress.update() Time3 = np.asarray(Time3) ImpulseState3 = np.asarray(ImpulseState3) # Bump solBump3 = ode(skyhookSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solBump3.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time3 = [] BumpState3 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Bump') while solBump3.successful() and solBump3.t < tFin: solBump3.set_f_params(Bump[counter]) solBump3.integrate(solBump3.t + dt) BumpState3.append(solBump3.y) Time3.append(solBump3.t) counter += 1 progress.update() Time3 = np.asarray(Time3) BumpState3 = np.asarray(BumpState3) # Rough road solRough3 = ode(skyhookSuspensionModel).set_integrator('dopri5', atol=1e-6) state0 = [0, 0, 0, 0] solRough3.set_initial_value(state0) tFin = 10 - 0.01 dt = 0.01 Time3 = [] RoughState3 = [] counter = 0 progress = pyprind.ProgBar(1000, title='Processing: Rough') while solRough3.successful() and solRough3.t < tFin: solRough3.set_f_params(Rough[counter]) solRough3.integrate(solRough3.t + dt) RoughState3.append(solRough3.y) Time3.append(solRough3.t) counter += 1 progress.update() Time3 = np.asarray(Time3) RoughState3 = np.asarray(RoughState3) # ============================================================================= # ACCELERATION EVALUATION (AND FUZZY FORCE) # ============================================================================= # Step StepAcc = derivate(StepState[:, 2]) StepAcc2 = derivate(StepState2[:, 2]) StepAcc3 = derivate(StepState3[:, 2]) StepForce = (-k_s * StepState[:, 0] + k_s * StepState[:, 1] - c_s * StepState[:, 2] + c_s * StepState[:, 3] - StepAcc[:] * m_b) # Impulse ImpulseAcc = derivate(ImpulseState[:, 2]) ImpulseAcc2 = derivate(ImpulseState2[:, 2]) ImpulseAcc3 = derivate(ImpulseState3[:, 2]) ImpulseForce = (-k_s * ImpulseState[:, 0] + k_s * ImpulseState[:, 1] - c_s * ImpulseState[:, 2] + c_s * ImpulseState[:, 3] - ImpulseAcc[:] * m_b) # Bump BumpAcc = derivate(BumpState[:, 2]) BumpAcc2 = derivate(BumpState2[:, 2]) BumpAcc3 = derivate(BumpState3[:, 2]) BumpForce = (-k_s * BumpState[:, 0] + k_s * BumpState[:, 1] - c_s * BumpState[:, 2] + c_s * BumpState[:, 3] - BumpAcc[:] * m_b) # Rough RoughAcc = derivate(RoughState[:, 2]) RoughAcc2 = derivate(RoughState2[:, 2]) RoughAcc3 = derivate(RoughState3[:, 2]) RoughForce = (-k_s * RoughState[:, 0] + k_s * RoughState[:, 1] - c_s * RoughState[:, 2] + c_s * RoughState[:, 3] - RoughAcc[:] * m_b) # ============================================================================= # # PLOTTING # ============================================================================= # Step plt.figure(1) plt.plot(Time, 1e3 * StepState[:, 0], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * StepState2[:, 0], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * StepState3[:, 0], 'C3', label='Skyhook', linewidth=1) plt.plot(StepPID[:, 0], 1e3 * StepPID[:, 1], 'C4', label='PID', linewidth=1) plt.plot(Time, 1e3 * Step, 'C0', label='Road', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel('Body displacement [mm]') plt.legend() plt.figure(2) plt.plot(Time, 1e3 * StepState[:, 1], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * StepState2[:, 1], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * StepState3[:, 1], 'C3', label='Skyhook', linewidth=1) plt.plot(StepPID[:, 0], 1e3 * StepPID[:, 2], 'C4', label='PID', linewidth=1) plt.xlabel('Time [s]') plt.ylabel('Unsprung mass displacement [mm]') plt.legend() plt.figure(3) plt.plot(Time, StepAcc, 'C1', label='Fuzzy') plt.plot(Time2, StepAcc2, 'C2', label='Passive', linewidth=1) plt.plot(Time3, StepAcc3, 'C3', label='Skyhook', linewidth=1) plt.plot(StepPID[:, 0], StepPID[:, 3], 'C4', label='PID', linewidth=1) # plt.plot(Time, StepForce/m_b, 'C0', label='Force', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel(r'Body acceleration [m/${s^2}$]') plt.legend() # Impulse plt.figure(4) plt.plot(Time, 1e3 * ImpulseState[:, 0], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * ImpulseState2[:, 0], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * ImpulseState3[:, 0], 'C3', label='Skyhook', linewidth=1) plt.plot(ImpulsePID[:, 0], 1e3 * ImpulsePID[:, 1], 'C4', label='PID', linewidth=1) plt.plot(Time, 1e3 * Impulse, 'C0', label='Road', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel('Body displacement [mm]') plt.legend() plt.figure(5) plt.plot(Time, 1e3 * ImpulseState[:, 1], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * ImpulseState2[:, 1], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * ImpulseState3[:, 1], 'C3', label='Skyhook', linewidth=1) plt.plot(ImpulsePID[:, 0], 1e3 * ImpulsePID[:, 2], 'C4', label='PID', linewidth=1) plt.xlabel('Time [s]') plt.ylabel('Unsprung mass displacement [mm]') plt.legend() plt.figure(6) plt.plot(Time, ImpulseAcc, 'C1', label='Fuzzy') plt.plot(Time2, ImpulseAcc2, 'C2', label='Passive', linewidth=1) plt.plot(Time3, ImpulseAcc3, 'C3', label='Skyhook', linewidth=1) plt.plot(ImpulsePID[:, 0], ImpulsePID[:, 3], 'C4', label='PID', linewidth=1) # plt.plot(Time, ImpulseForce/m_b, 'C0', label='Force', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel(r'Body acceleration [m/${s^2}$]') plt.legend() # Bump plt.figure(7) plt.plot(Time, 1e3 * BumpState[:, 0], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * BumpState2[:, 0], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * BumpState3[:, 0], 'C3', label='Skyhook', linewidth=1) plt.plot(BumpPID[:, 0], 1e3 * BumpPID[:, 1], 'C4', label='PID', linewidth=1) plt.plot(Time, 1e3 * Bump, 'C0', label='Road', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel('Body displacement [mm]') plt.legend() plt.figure(8) plt.plot(Time, 1e3 * BumpState[:, 1], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * BumpState2[:, 1], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * BumpState3[:, 1], 'C3', label='Skyhook', linewidth=1) plt.plot(BumpPID[:, 0], 1e3 * BumpPID[:, 2], 'C4', label='PID', linewidth=1) plt.xlabel('Time [s]') plt.ylabel('Unsprung mass displacement [mm]') plt.legend() plt.figure(9) plt.plot(Time, BumpAcc, 'C1', label='Fuzzy') plt.plot(Time2, BumpAcc2, 'C2', label='Passive', linewidth=1) plt.plot(Time3, BumpAcc3, 'C3', label='Skyhook', linewidth=1) plt.plot(BumpPID[:, 0], BumpPID[:, 3], 'C4', label='PID', linewidth=1) # plt.plot(Time, BumpForce/m_b, 'C0', label='Force', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel(r'Body acceleration [m/${s^2}$]') plt.legend() # Rough plt.figure(10) plt.plot(Time, 1e3 * RoughState[:, 0], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * RoughState2[:, 0], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * RoughState3[:, 0], 'C3', label='Skyhook', linewidth=1) plt.plot(RoughPID[:, 0], 1e3 * RoughPID[:, 1], 'C4', label='PID', linewidth=1) plt.plot(Time, 1e3 * Rough, 'C0', label='Road', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel('Body displacement [mm]') plt.legend() plt.figure(11) plt.plot(Time, 1e3 * RoughState[:, 1], 'C1', label='Fuzzy') plt.plot(Time2, 1e3 * RoughState2[:, 1], 'C2', label='Passive', linewidth=1) plt.plot(Time3, 1e3 * RoughState3[:, 1], 'C3', label='Skyhook', linewidth=1) plt.plot(RoughPID[:, 0], 1e3 * RoughPID[:, 2], 'C4', label='PID', linewidth=1) plt.xlabel('Time [s]') plt.ylabel('Unsprung mass displacement [mm]') plt.legend() plt.figure(12) plt.plot(Time, RoughAcc, 'C1', label='Fuzzy') plt.plot(Time2, RoughAcc2, 'C2', label='Passive', linewidth=1) plt.plot(Time3, RoughAcc3, 'C3', label='Skyhook', linewidth=1) plt.plot(RoughPID[:, 0], RoughPID[:, 3], 'C4', label='PID', linewidth=1) # plt.plot(Time, RoughForce/m_b, 'C0', label='Force', linewidth=0.8) plt.xlabel('Time [s]') plt.ylabel(r'Body acceleration [m/${s^2}$]') plt.legend() # ============================================================================= # RESULTS # ============================================================================= # Calculation of RMS for: # (1) Body displacement # (2) Body accelaration # (3) Wheel hop (unsprung mass displacement) #StepFuzzyRMS = np.array([ # RMS(StepState[:, 0]), # RMS(StepAcc), # RMS(StepState[:, 1]) # ]) # #StepPassiveRMS = np.array([ # RMS(StepState2[:, 0]), # RMS(StepAcc2), # RMS(StepState2[:, 1]) # ]) # #StepSkyhookRMS = np.array([ # RMS(StepState3[:, 0]), # RMS(StepAcc3), # RMS(StepState3[:, 1]) # ]) # #StepResult = np.array([ # (StepFuzzyRMS - StepPassiveRMS) / StepPassiveRMS, # (StepSkyhookRMS - StepPassiveRMS) / StepPassiveRMS, # ]) * 100 # #ImpulseFuzzyRMS = np.array([ # RMS(ImpulseState[:, 0]), # RMS(ImpulseAcc), # RMS(ImpulseState[:, 1]) # ]) # #ImpulsePassiveRMS = np.array([ # RMS(ImpulseState2[:, 0]), # RMS(ImpulseAcc2), # RMS(ImpulseState2[:, 1]) # ]) # #ImpulseSkyhookRMS = np.array([ # RMS(ImpulseState3[:, 0]), # RMS(ImpulseAcc3), # RMS(ImpulseState3[:, 1]) # ]) # #ImpulseResult = np.array([ # (ImpulseFuzzyRMS - ImpulsePassiveRMS) / ImpulsePassiveRMS, # (ImpulseSkyhookRMS - ImpulsePassiveRMS) / ImpulsePassiveRMS # ]) * 100 # #BumpFuzzyRMS = np.array([ # RMS(BumpState[:, 0]), # RMS(BumpAcc), # RMS(BumpState[:, 1]) # ]) # #BumpPassiveRMS = np.array([ # RMS(BumpState2[:, 0]), # RMS(BumpAcc2), # RMS(BumpState2[:, 1]) # ]) # #BumpSkyhookRMS = np.array([ # RMS(BumpState3[:, 0]), # RMS(BumpAcc3), # RMS(BumpState3[:, 1]) # ]) # #BumpResult = np.array([ # (BumpFuzzyRMS - BumpPassiveRMS) / BumpPassiveRMS, # (BumpSkyhookRMS - BumpPassiveRMS) / BumpPassiveRMS # ]) * 100 RoughFuzzyRMS = np.array([ RMS(RoughState[:, 0] - Rough), RMS(RoughAcc), RMS(RoughState[:, 1] - Rough) ]) RoughPassiveRMS = np.array([ RMS(RoughState2[:, 0] - Rough), RMS(RoughAcc2), RMS(RoughState2[:, 1] - Rough) ]) RoughSkyhookRMS = np.array([ RMS(RoughState3[:, 0] - Rough), RMS(RoughAcc3), RMS(RoughState3[:, 1] - Rough) ]) RoughPIDRMS = np.array([ RMS(RoughPID[:, 1] - Rough[:-1]), RMS(RoughPID[:, 3]), RMS(RoughPID[:, 2] - Rough[:-1]) ]) RoughResult = np.array([ (RoughFuzzyRMS - RoughPassiveRMS) / RoughPassiveRMS, (RoughSkyhookRMS - RoughPassiveRMS) / RoughPassiveRMS, (RoughPIDRMS - RoughPassiveRMS) / RoughPassiveRMS ]) * 100 #RoughResult = np.array([ # (RoughFuzzyRMS - RMS(Rough)) / RMS(Rough), # (RoughSkyhookRMS - RMS(Rough)) / RMS(Rough), # (RoughPIDRMS - RMS(Rough)) / RMS(Rough) # ]) * 100 # ============================================================================= # FFT ANALYSIS # ============================================================================= label = ['Fuzzy', 'Passive', 'Skyhook', 'PID'] colors = ['C1', 'C2', 'C3', 'C4'] i = 0 for acc in [StepAcc, StepAcc2, StepAcc3, StepPID[:, 3]]: fft = np.fft.fft(acc) freq = np.fft.fftfreq(len(acc), 0.01) plt.figure(13) plt.loglog(np.abs(freq), np.abs(fft), colors[i], label=label[i], linewidth=1) i += 1 plt.legend() plt.xlabel('Frequency [Hz]') plt.ylabel('Acceleration') plt.title('Step') i = 0 for acc in [ImpulseAcc, ImpulseAcc2, ImpulseAcc3, ImpulsePID[:, 3]]: fft = np.fft.fft(acc) freq = np.fft.fftfreq(len(acc), 0.01) plt.figure(14) plt.loglog(np.abs(freq), np.abs(fft), colors[i], label=label[i], linewidth=1) i += 1 plt.legend() plt.xlabel('Frequency [Hz]') plt.ylabel('Acceleration') plt.title('Impulse') i = 0 for acc in [BumpAcc, BumpAcc2, BumpAcc3]: fft = np.fft.fft(acc) freq = np.fft.fftfreq(len(acc), 0.01) plt.figure(15) plt.loglog(np.abs(freq), np.abs(fft), colors[i], label=label[i], linewidth=1) i += 1 plt.legend() plt.xlabel('Frequency [Hz]') plt.ylabel('Acceleration') plt.title('Bump') i = 0 for acc in [RoughAcc, RoughAcc2, RoughAcc3]: fft = np.fft.fft(acc) freq = np.fft.fftfreq(len(acc), 0.01) plt.figure(16) plt.loglog(np.abs(freq), np.abs(fft),colors[i], label=label[i], linewidth=1) i += 1 plt.legend() plt.xlabel('Frequency [Hz]') plt.ylabel('Acceleration') plt.title('Rough')
29.73253
82
0.56678
3,041
24,678
4.54686
0.106544
0.02835
0.033847
0.039343
0.496565
0.458451
0.451508
0.450278
0.409055
0.352354
0
0.055422
0.22279
24,678
829
83
29.768396
0.665485
0.214077
0
0.400372
0
0
0.067452
0
0
0
0
0
0
1
0.020484
false
0.040968
0.013035
0
0.054004
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
0
0
0
1
0
8bae7f55a261a7c3c248850c794f2efd73be536a
950
py
Python
pywatts/modules/wrappers/dl_wrapper.py
KIT-IAI/pyWATTS
68993bb51ff272c1a98add31e2b537b63e9d0848
[ "MIT" ]
30
2020-10-04T17:32:58.000Z
2022-03-18T15:06:39.000Z
pywatts/modules/wrappers/dl_wrapper.py
KIT-IAI/pyWATTS
68993bb51ff272c1a98add31e2b537b63e9d0848
[ "MIT" ]
123
2020-10-26T14:42:12.000Z
2022-03-31T09:15:55.000Z
pywatts/modules/wrappers/dl_wrapper.py
KIT-IAI/pyWATTS
68993bb51ff272c1a98add31e2b537b63e9d0848
[ "MIT" ]
7
2020-10-21T15:13:43.000Z
2022-03-07T15:47:49.000Z
# pylint: disable=W0223 # Pylint cannot handle abstract subclasses of abstract base classes from abc import ABC import xarray as xr from pywatts.modules.wrappers.base_wrapper import BaseWrapper class DlWrapper(BaseWrapper, ABC): """ Super class for deep learning framework wrappers :param model: The deep learning model :param name: The name of the wrappers :type name: str :param fit_kwargs: The fit keyword arguments necessary for fitting the model :type fit_kwargs: dict """ def __init__(self, model, name, fit_kwargs=None): super().__init__(name) self.model = model if fit_kwargs is None: fit_kwargs = {} self.fit_kwargs = fit_kwargs self.compiled = False @staticmethod def _to_dl_input(data: xr.Dataset): result = {} for dv in data.data_vars: da = data[dv] result[dv] = da.values return result
26.388889
80
0.656842
124
950
4.870968
0.5
0.104305
0.043046
0
0
0
0
0
0
0
0
0.005789
0.272632
950
36
81
26.388889
0.868307
0.347368
0
0
0
0
0
0
0
0
0
0
0
1
0.111111
false
0
0.166667
0
0.388889
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bb2c815f8cb9c7313bf196f810ccfc535e6256b
435
py
Python
第4章/program/Chapter_4_compare.py
kingname/SourceCodeOfBook
ab7275108994dca564905818b678bbd2f771c18e
[ "MIT" ]
274
2018-10-01T11:07:25.000Z
2022-03-17T13:48:45.000Z
第4章/program/Chapter_4_compare.py
kingname/SourceCodeOfBook
ab7275108994dca564905818b678bbd2f771c18e
[ "MIT" ]
6
2019-02-28T14:18:21.000Z
2022-03-02T14:57:39.000Z
第4章/program/Chapter_4_compare.py
kingname/SourceCodeOfBook
ab7275108994dca564905818b678bbd2f771c18e
[ "MIT" ]
110
2018-10-16T06:08:37.000Z
2022-03-16T08:19:29.000Z
import requests import time from multiprocessing.dummy import Pool def query(url): requests.get(url) start = time.time() for i in range(100): query('https://baidu.com') end = time.time() print(f'单线程循环访问100次百度,耗时:{end - start}') start = time.time() url_list = [] for i in range(100): url_list.append('https://baidu.com') pool = Pool(5) pool.map(query, url_list) end = time.time() print(f'5线程访问100次百度,耗时:{end - start}')
18.125
40
0.682759
69
435
4.26087
0.434783
0.108844
0.088435
0.07483
0.210884
0
0
0
0
0
0
0.037736
0.147126
435
23
41
18.913043
0.754717
0
0
0.333333
0
0
0.211982
0.048387
0
0
0
0
0
1
0.055556
false
0
0.166667
0
0.222222
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bb4b5b36380f83dc59bb259a75e2877488cbe5c
750
py
Python
array/max_subarray.py
elenaborisova/LeetCode-Solutions
98376aab7fd150a724e316357ae5ea46988d9eac
[ "MIT" ]
null
null
null
array/max_subarray.py
elenaborisova/LeetCode-Solutions
98376aab7fd150a724e316357ae5ea46988d9eac
[ "MIT" ]
null
null
null
array/max_subarray.py
elenaborisova/LeetCode-Solutions
98376aab7fd150a724e316357ae5ea46988d9eac
[ "MIT" ]
null
null
null
# DP; Time: O(n); Space: O(1) def max_subarray(nums): for i in range(1, len(nums)): if nums[i - 1] > 0: nums[i] += nums[i - 1] return max(nums) # Time: O(n); Space: O(1) def max_subarray2(nums): max_sum = nums[0] curr_sum = nums[0] for i in range(len(nums)): if curr_sum + nums[i] > nums[i]: curr_sum += nums[i] else: curr_sum = nums[i] if curr_sum > max_sum: max_sum = curr_sum # curr_sum = max(nums[i], curr_sum + nums[i]) # max_sum = max(max_sum, curr_sum) return max_sum # Test cases: print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) == 6) print(max_subarray([1]) == 1) print(max_subarray([5, 4, -1, 7, 8]) == 23)
22.058824
57
0.52
128
750
2.890625
0.257813
0.121622
0.148649
0.12973
0.194595
0.194595
0.102703
0.102703
0
0
0
0.053846
0.306667
750
33
58
22.727273
0.657692
0.186667
0
0
0
0
0
0
0
0
0
0
0
1
0.105263
false
0
0
0
0.210526
0.157895
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bb4f4ea88058eb0410caa3dc14fb32b876055fc
4,696
py
Python
python/trezorlib/cosi.py
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
null
null
null
python/trezorlib/cosi.py
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
1
2019-02-08T00:22:42.000Z
2019-02-13T09:41:54.000Z
python/trezorlib/cosi.py
Kayuii/trezor-crypto
6556616681a4e2d7e18817e8692d4f6e041dee01
[ "MIT" ]
2
2019-02-07T23:57:09.000Z
2020-10-21T07:07:27.000Z
# This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. from functools import reduce from typing import Iterable, List, Tuple from . import _ed25519, messages from .tools import expect # XXX, these could be NewType's, but that would infect users of the cosi module with these types as well. # Unsure if we want that. Ed25519PrivateKey = bytes Ed25519PublicPoint = bytes Ed25519Signature = bytes def combine_keys(pks: Iterable[Ed25519PublicPoint]) -> Ed25519PublicPoint: """Combine a list of Ed25519 points into a "global" CoSi key.""" P = [_ed25519.decodepoint(pk) for pk in pks] combine = reduce(_ed25519.edwards_add, P) return Ed25519PublicPoint(_ed25519.encodepoint(combine)) def combine_sig( global_R: Ed25519PublicPoint, sigs: Iterable[Ed25519Signature] ) -> Ed25519Signature: """Combine a list of signatures into a single CoSi signature.""" S = [_ed25519.decodeint(si) for si in sigs] s = sum(S) % _ed25519.l sig = global_R + _ed25519.encodeint(s) return Ed25519Signature(sig) def get_nonce( sk: Ed25519PrivateKey, data: bytes, ctr: int = 0 ) -> Tuple[int, Ed25519PublicPoint]: """Calculate CoSi nonces for given data. These differ from Ed25519 deterministic nonces in that there is a counter appended at end. Returns both the private point `r` and the partial signature `R`. `r` is returned for performance reasons: :func:`sign_with_privkey` takes it as its `nonce` argument so that it doesn't repeat the `get_nonce` call. `R` should be combined with other partial signatures through :func:`combine_keys` to obtain a "global commitment". """ # r = hash(hash(sk)[b .. 2b] + M + ctr) # R = rB h = _ed25519.H(sk) bytesize = _ed25519.b // 8 assert len(h) == bytesize * 2 r = _ed25519.Hint(h[bytesize:] + data + ctr.to_bytes(4, "big")) R = _ed25519.scalarmult(_ed25519.B, r) return r, Ed25519PublicPoint(_ed25519.encodepoint(R)) def verify( signature: Ed25519Signature, digest: bytes, pub_key: Ed25519PublicPoint ) -> None: """Verify Ed25519 signature. Raise exception if the signature is invalid.""" # XXX this *might* change to bool function _ed25519.checkvalid(signature, digest, pub_key) def verify_m_of_n( signature: Ed25519Signature, digest: bytes, m: int, n: int, mask: int, keys: List[Ed25519PublicPoint], ) -> None: if m < 1: raise ValueError("At least 1 signer must be specified") selected_keys = [keys[i] for i in range(n) if mask & (1 << i)] if len(selected_keys) < m: raise ValueError( "Not enough signers ({} required, {} found)".format(m, len(selected_keys)) ) global_pk = combine_keys(selected_keys) return verify(signature, digest, global_pk) def pubkey_from_privkey(privkey: Ed25519PrivateKey) -> Ed25519PublicPoint: """Interpret 32 bytes of data as an Ed25519 private key. Calculate and return the corresponding public key. """ return Ed25519PublicPoint(_ed25519.publickey_unsafe(privkey)) def sign_with_privkey( digest: bytes, privkey: Ed25519PrivateKey, global_pubkey: Ed25519PublicPoint, nonce: int, global_commit: Ed25519PublicPoint, ) -> Ed25519Signature: """Create a CoSi signature of `digest` with the supplied private key. This function needs to know the global public key and global commitment. """ h = _ed25519.H(privkey) a = _ed25519.decodecoord(h) S = (nonce + _ed25519.Hint(global_commit + global_pubkey + digest) * a) % _ed25519.l return Ed25519Signature(_ed25519.encodeint(S)) # ====== Client functions ====== # @expect(messages.CosiCommitment) def commit(client, n, data): return client.call(messages.CosiCommit(address_n=n, data=data)) @expect(messages.CosiSignature) def sign(client, n, data, global_commitment, global_pubkey): return client.call( messages.CosiSign( address_n=n, data=data, global_commitment=global_commitment, global_pubkey=global_pubkey, ) )
33.784173
105
0.70379
624
4,696
5.200321
0.376603
0.024653
0.020339
0.01171
0.0302
0.019723
0
0
0
0
0
0.070952
0.201661
4,696
138
106
34.028986
0.794612
0.380963
0
0.081081
0
0
0.028521
0
0
0
0
0
0.013514
1
0.121622
false
0
0.054054
0.027027
0.283784
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
0
0
0
1
0
8bb52f491af72661c47a685434d4940a457e1a8b
2,881
py
Python
workflow/scripts/modifyFastQC.py
StephenRicher/RNA-Flow
57890772cb95beb390990618eb02f5d6e138312b
[ "MIT" ]
null
null
null
workflow/scripts/modifyFastQC.py
StephenRicher/RNA-Flow
57890772cb95beb390990618eb02f5d6e138312b
[ "MIT" ]
null
null
null
workflow/scripts/modifyFastQC.py
StephenRicher/RNA-Flow
57890772cb95beb390990618eb02f5d6e138312b
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Create new FastQC zip directory with a new sample name for multiQC.""" import os import sys import logging import zipfile import tempfile import argparse __version__ = '1.0.0' def main(zipIn, zipOut, sample, **kwargs): with tempfile.TemporaryDirectory() as tmpDir: # Create temporary file path for storing updated 'fastqc_data.txt' updatedData = os.path.join(tmpDir, 'fastqc_data-updated.txt') # Copy Zip archive to new location but extract 'fastqc_data.txt' with zipfile.ZipFile(zipIn, 'r') as zipInfd, zipfile.ZipFile(zipOut, 'w') as zipOutfd: zipOutfd.comment = zipInfd.comment for item in zipInfd.infolist(): if item.filename.endswith('fastqc_data.txt'): # Retrieve archive name for adding back in later. arcname = item.filename # Extract data to temporary directory. originalData = zipInfd.extract(item.filename, tmpDir) else: zipOutfd.writestr(item, zipInfd.read(item.filename)) with open(originalData) as originalf, open(updatedData, 'w') as updatef: for line in originalf: if line.startswith('Filename'): header, filename = line.split() filename = sample updatef.write(f'{header}\t{filename}\n') else: updatef.write(line) # Add updated data back to the original zip path with zipfile.ZipFile(zipOut, mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.write(updatedData, arcname) def parse_arguments(): custom = argparse.ArgumentParser(add_help=False) custom.set_defaults(function=main) custom.add_argument( 'zipIn', help='FastQC output zip directory.') custom.add_argument( 'zipOut', help='Path to updated FastQC zip directory.') custom.add_argument( 'sample', help='New sample name for multiQC parsing.') epilog='Stephen Richer, University of Bath, Bath, UK (sr467@bath.ac.uk)' base = argparse.ArgumentParser(add_help=False) base.add_argument( '--version', action='version', version=f'%(prog)s {__version__}') base.add_argument( '--verbose', action='store_const', const=logging.DEBUG, default=logging.INFO, help='verbose logging for debugging') parser = argparse.ArgumentParser( epilog=epilog, description=__doc__, parents=[base, custom]) args = parser.parse_args() log_format='%(asctime)s - %(levelname)s - %(funcName)s - %(message)s' logging.basicConfig(level=args.verbose, format=log_format) return args if __name__ == '__main__': args = parse_arguments() return_code = args.function(**vars(args)) logging.shutdown() sys.exit(return_code)
34.710843
94
0.637279
336
2,881
5.342262
0.404762
0.030641
0.021727
0.017827
0.095822
0
0
0
0
0
0
0.003259
0.254426
2,881
82
95
35.134146
0.832402
0.121138
0
0.127273
0
0
0.162302
0.017857
0
0
0
0
0
1
0.036364
false
0
0.109091
0
0.163636
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
0
0
0
1
0
8bb84845a4e4ca234bb0e7dc0448fc8b70e6253a
843
py
Python
chill/examples/chill/testcases/lu.py
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
5
2019-05-20T03:35:41.000Z
2021-09-16T22:22:13.000Z
chill/examples/chill/testcases/lu.py
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
null
null
null
chill/examples/chill/testcases/lu.py
CompOpt4Apps/Artifact-DataDepSimplify
4fa1bf2bda2902fec50a54ee79ae405a554fc9f4
[ "MIT" ]
null
null
null
# LAPACK optimization strategy for LU factorization. from chill import * source('lu.c') procedure('lu') loop(0) TJ = 64 original() tile(1, 3, TJ, 1) split(1, 2, 'L1-L2>=2') #t2-t4>=2 permute(3, 2, [2,4,3]) # mini-LU permute(1, 2, [3,4,2]) # other than mini-LU split(1, 2, 'L2>=L1-1') # seperate MM by t4 >= t2-1 # now optimize for TRSM TK1 = 256 TI1 = 256 TJ1 = 8 UI1 = 1 UJ1 = 1 tile(4, 2, TI1, 2) split(4, 3, 'L5<=L2-1') #split t10 <= t4-1 tile(4, 5, TK1, 3) tile(4, 5, TJ1, 4) datacopy([[4,1]], 4, false, 1) datacopy([[4,2]], 5) unroll(4, 5, UI1) unroll(4, 6, UJ1) datacopy([[5,1]], 3, false, 1) # now optimize for MM TK2 = 256 TI2 = 256 TJ2 = 8 UI2 = 1 UJ2 = 1 tile(1, 4, TK2, 2) tile(1, 3, TI2, 3) tile(1, 5, TJ2, 4) datacopy([[1,1]], 4, false, 1) datacopy([[1,2]], 5) unroll(1, 5, UI2) unroll(1, 6, UJ2) print_code()
17.204082
52
0.578885
175
843
2.782857
0.331429
0.041068
0.024641
0.061602
0.065708
0
0
0
0
0
0
0.182222
0.199288
843
48
53
17.5625
0.539259
0.201661
0
0
0
0
0.045732
0
0
0
0
0
0
1
0
false
0
0.026316
0
0.026316
0.026316
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bb96428aea103e57829628f8aba75da646487e4
6,803
py
Python
scripts/DailyJob/api_data_fetcher.py
SamFangshan/CZ2006CarPark
663b0370e7d2e0cbe4d0a7391656a731fc7dac52
[ "MIT" ]
2
2020-02-26T03:28:02.000Z
2020-04-25T07:03:36.000Z
scripts/DailyJob/api_data_fetcher.py
SamFangshan/CZ2006CarPark
663b0370e7d2e0cbe4d0a7391656a731fc7dac52
[ "MIT" ]
null
null
null
scripts/DailyJob/api_data_fetcher.py
SamFangshan/CZ2006CarPark
663b0370e7d2e0cbe4d0a7391656a731fc7dac52
[ "MIT" ]
null
null
null
import json import pandas as pd import numpy as np from urllib.request import Request, urlopen from onemap_converter import OneMapConverter def load_HDB_carpark(): converter = OneMapConverter('FJIANG003@e.ntu.edu.sg', 'XS4teTdcYz') # Load HDB Carpark Information url_HDB_carpark = 'https://data.gov.sg/api/action/datastore_search?resource_id=139a3035-e624-4f56-b63f-89ae28d4ae4c&limit={}' req_HDB_carpark = Request(url_HDB_carpark.format(1), headers={'User-Agent': 'Mozilla/5.0'}) webpage_HDB_carpark = urlopen(req_HDB_carpark).read() data_HDB_carpark = json.loads(webpage_HDB_carpark.decode()) no_rec = data_HDB_carpark['result']['total'] # number of HDB Carpark Records url_HDB_carpark = 'https://data.gov.sg/api/action/datastore_search?resource_id=139a3035-e624-4f56-b63f-89ae28d4ae4c&limit={}' req_HDB_carpark = Request(url_HDB_carpark.format(no_rec), headers={'User-Agent': 'Mozilla/5.0'}) webpage_HDB_carpark = urlopen(req_HDB_carpark).read() data_HDB_carpark = json.loads(webpage_HDB_carpark.decode()) # Load HDB Carpark Lots Information url_HDB_lots_info = 'https://api.data.gov.sg/v1/transport/carpark-availability' req_HDB_lots_info = Request(url_HDB_lots_info, headers={'User-Agent': 'Mozilla/5.0'}) webpage_HDB_lots_info = urlopen(req_HDB_lots_info).read() data_HDB_lots_info = json.loads(webpage_HDB_lots_info.decode()) # Load HDB Carpark Information into Pandas Data Frame short_term_parking = [data_HDB_carpark['result']['records'][i]['short_term_parking'] for i in range(no_rec)] car_park_type = [data_HDB_carpark['result']['records'][i]['car_park_type'] for i in range(no_rec)] x_coord = [data_HDB_carpark['result']['records'][i]['x_coord'] for i in range(no_rec)] y_coord = [data_HDB_carpark['result']['records'][i]['y_coord'] for i in range(no_rec)] coord = [(x_coord[i], y_coord[i]) for i in range(no_rec)] coord = [converter.convert(float(coord[i][0]), float(coord[i][1])) for i in range(no_rec)] x_coord = [coord[i][0] for i in range(no_rec)] y_coord = [coord[i][1] for i in range(no_rec)] free_parking = [data_HDB_carpark['result']['records'][i]['free_parking'] for i in range(no_rec)] gantry_height = [data_HDB_carpark['result']['records'][i]['gantry_height'] for i in range(no_rec)] car_park_basement = [data_HDB_carpark['result']['records'][i]['car_park_basement'] for i in range(no_rec)] night_parking = [data_HDB_carpark['result']['records'][i]['night_parking'] for i in range(no_rec)] address = [data_HDB_carpark['result']['records'][i]['address'] for i in range(no_rec)] car_park_decks = [data_HDB_carpark['result']['records'][i]['car_park_decks'] for i in range(no_rec)] car_park_no = [data_HDB_carpark['result']['records'][i]['car_park_no'] for i in range(no_rec)] type_of_parking_system = [data_HDB_carpark['result']['records'][i]['type_of_parking_system'] for i in range(no_rec)] HDB_carpark = { 'carParkNo': car_park_no, 'address': address, 'xCoord': x_coord, 'yCoord': y_coord, 'carParkType': car_park_type, 'typeOfParkingSystem': type_of_parking_system, 'shortTermParking': short_term_parking, 'freeParking': free_parking, 'nightParking': night_parking, 'carParkDecks': car_park_decks, 'gantryHeight': gantry_height, 'carParkBasement': car_park_basement, } HDB_carpark = pd.DataFrame.from_dict(HDB_carpark) # Load HDB Carpark Lots Information into Pandas Data Frame HDB_lots_info = {} for record in data_HDB_lots_info['items'][0]['carpark_data']: carpark_info = record['carpark_info'] car_lot_num = 0 motor_lot_num = 0 heavy_lot_num = 0 for i in range(len(carpark_info)): if carpark_info[i]['lot_type'] == 'C': car_lot_num = carpark_info[i]['total_lots'] elif carpark_info[i]['lot_type'] == 'Y': motor_lot_num = carpark_info[i]['total_lots'] elif carpark_info[i]['lot_type'] == 'L': heavy_lot_num = carpark_info[i]['total_lots'] try: if HDB_lots_info[record['carpark_number']][1] == 0: HDB_lots_info[record['carpark_number']][1] = car_lot_num if HDB_lots_info[record['carpark_number']][2] == 0: HDB_lots_info[record['carpark_number']][2] = motor_lot_num if HDB_lots_info[record['carpark_number']][3] == 0: HDB_lots_info[record['carpark_number']][3] = heavy_lot_num except: HDB_lots_info[record['carpark_number']] = [record['carpark_number'], car_lot_num, motor_lot_num, heavy_lot_num] HDB_lots_info = dict(zip(range(len(HDB_lots_info)), HDB_lots_info.values())) columns = ['carParkNo', 'carLotNum', 'motorLotNum', 'heavyLotNum'] HDB_lots_info = pd.DataFrame.from_dict(HDB_lots_info, orient='index', columns=columns) # Merge two Pandas Data Frames HDB_carpark = pd.merge(HDB_carpark, HDB_lots_info, on='carParkNo', how='inner') # Provide rates information # Information Source: # https://www.hdb.gov.sg/cs/infoweb/car-parks/short-term-parking/short-term-parking-charges central = ['HLM', 'KAB', 'KAM', 'KAS', 'PRM', 'SLS', 'SR1', 'SR2', 'TPM', 'UCS'] loading = ['GSML', 'BRBL', 'JCML', 'T55', 'GEML', 'KAML', 'J57L', 'J6OL', 'TPL', 'EPL', 'BL8L'] car_rates = '$0.60 per half-hour' motor_rates = '$0.20 per half-hour' heavy_rates = '$1.20 per half-hour' central_rates = """$1.20 per half-hour (7:00am to 5:00pm, Monday to Saturday) $0.60 per half hour (Other hours) """ loading_rates = """Free - First 15 minutes $2 - first half hour $4 - subsequent half hour """ HDB_carpark['carRates'] = np.where(pd.to_numeric(HDB_carpark['carLotNum']) != 0, car_rates, None) HDB_carpark['carRates'] = np.where(np.isin(HDB_carpark['carParkNo'], central), central_rates, HDB_carpark['carRates']) HDB_carpark['motorRates'] = np.where(pd.to_numeric(HDB_carpark['motorLotNum']) != 0, motor_rates, None) HDB_carpark['heavyRates'] = np.where(pd.to_numeric(HDB_carpark['heavyLotNum']) != 0, heavy_rates, None) HDB_carpark['carRates'] = np.where(np.isin(HDB_carpark['carParkNo'], loading), loading_rates, HDB_carpark['carRates']) HDB_carpark['motorRates'] = np.where(np.isin(HDB_carpark['carParkNo'], loading), loading_rates, HDB_carpark['motorRates']) HDB_carpark['heavyRates'] = np.where(np.isin(HDB_carpark['carParkNo'], loading), loading_rates, HDB_carpark['heavyRates']) return HDB_carpark
58.646552
129
0.66456
955
6,803
4.442932
0.198953
0.134339
0.057035
0.044073
0.559981
0.496583
0.449446
0.331369
0.251473
0.204337
0
0.019367
0.187858
6,803
115
130
59.156522
0.748597
0.0538
0
0.080808
0
0.020202
0.245838
0.006846
0
0
0
0
0
1
0.010101
false
0
0.050505
0
0.070707
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
0
0
0
1
0
8bbca367e9908a584ebeb0ff48984d79eb8c67ba
859
py
Python
api_updater.py
jpes707/quiz-api
18af31b9cdba8927e4e7a38e0bd3623e938cf7dc
[ "MIT" ]
null
null
null
api_updater.py
jpes707/quiz-api
18af31b9cdba8927e4e7a38e0bd3623e938cf7dc
[ "MIT" ]
null
null
null
api_updater.py
jpes707/quiz-api
18af31b9cdba8927e4e7a38e0bd3623e938cf7dc
[ "MIT" ]
null
null
null
import os from mongo_config import questions_collection, client def get_relative_path(*args): return os.path.join(os.path.dirname(os.path.abspath(__file__)), *args) questions_collection.delete_many({}) # clears all questions in MongoDB question_objects = [] lines = [line[:-1] for line in open(get_relative_path('trivia.txt'), 'r').readlines()] + [''] for idx in range(0, len(lines), 6): question = lines[idx] correct_answer = lines[idx + 1] wrong_answers = lines[idx + 2 : idx + 5] choices = [correct_answer] + wrong_answers # not shuffled yet question_object = {'question': question, 'correct_answer': correct_answer, 'choices': choices} question_objects.append(question_object) questions_collection.insert_many(question_objects) # puts all questions from txt file into MongoDB client.close() print('Questions updated!')
37.347826
99
0.733411
116
859
5.215517
0.5
0.08595
0.049587
0
0
0
0
0
0
0
0
0.008141
0.142026
859
22
100
39.045455
0.812754
0.10943
0
0
0
0
0.076216
0
0
0
0
0
0
1
0.058824
false
0
0.117647
0.058824
0.235294
0.058824
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bbcec0ab14f44786258536c11d18bbc453834f6
2,429
py
Python
util.py
AndreasWieg/PC-BIGAN
0738f9bf56bd30b43eb2db9765ce9bae25ca81f6
[ "MIT" ]
null
null
null
util.py
AndreasWieg/PC-BIGAN
0738f9bf56bd30b43eb2db9765ce9bae25ca81f6
[ "MIT" ]
null
null
null
util.py
AndreasWieg/PC-BIGAN
0738f9bf56bd30b43eb2db9765ce9bae25ca81f6
[ "MIT" ]
null
null
null
import numpy as np import random from plyfile import PlyData, PlyElement import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from pyntcloud import PyntCloud import os import sys import re def shuffle_data(training_data): np.random.shuffle(training_data) return training_data def save_pointcloud(leaf,counter,leaf_name,number_points): leaf = np.asarray(leaf) leaf = np.reshape(leaf,(number_points,3)) leaf_final = [] x = 0 for e in enumerate(leaf): leaf_final.append(tuple(leaf[x])) x = x +1 vertex = np.array(leaf_final,dtype=[('x', 'f4'), ('y', 'f4'),('z', 'f4')]) el = PlyElement.describe(vertex, 'vertex') PlyData([el]).write('%s_%d.ply' % (leaf_name,counter)) def load_data(number_points,reduction_step): training_data = [] #counter = 1 for file in os.listdir("C:/Users/Andreas/Desktop/PG-PGGAN/table_new_%d" % (reduction_step)): if file.endswith(".ply"): cloud = PyntCloud.from_file("C:/Users/Andreas/Desktop/PG-PGGAN/table_new_%d/%s" % (reduction_step,file)) cloud_array = np.asarray(cloud.points) training_data.append(cloud_array) return training_data def load_data_table(number_points,reduction_step): training_data = [] counter = 1 if not os.path.exists("C:/Users/Andreas/Desktop/PG-PGGAN/table_new_%d" % reduction_step): os.mkdir("C:/Users/Andreas/Desktop/PG-PGGAN/table_new_%d" % reduction_step) table_uri = ("C:/Users/Andreas/Desktop/PG-PGGAN/table_new_%d" % reduction_step) print(table_uri) for file in os.listdir("C:/Users/Andreas/Desktop/PG-PGGAN/table"): if file.endswith(".ply"): cloud = PyntCloud.from_file("C:/Users/Andreas/Desktop/PG-PGGAN/table/%s" % file) cloud = cloud.get_sample(name="points_random",n = number_points) cloud = PyntCloud(cloud) cloud_array = np.asarray(cloud.points) cloud.to_file(table_uri + "/out_file_%d.ply" % (counter)) counter = counter + 1 training_data.append(cloud_array) else: training_data = load_data(number_points,reduction_step) print(len(training_data)) print("data loaded") training_data = np.asarray(training_data) print("getting Trainingdata into the right format") #training_data = training_data.reshape(8509,3072) print(training_data.shape) print(" trainingdata formated") return training_data
37.369231
107
0.691231
340
2,429
4.741176
0.285294
0.119107
0.056452
0.086849
0.407568
0.372829
0.310174
0.310174
0.254342
0.251861
0
0.009519
0.178263
2,429
64
108
37.953125
0.798096
0.02429
0
0.196429
0
0
0.190034
0.132601
0
0
0
0
0
1
0.071429
false
0
0.160714
0
0.285714
0.107143
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bbd00b53513bf84f5c58a5ce90fbc7b1806da00
7,474
py
Python
seq_to_seq.py
jlibovicky/char-nmt-two-step-decoder
3fa90c38556f23568f6b88eb98e4bc2193f3b744
[ "BSD-3-Clause" ]
null
null
null
seq_to_seq.py
jlibovicky/char-nmt-two-step-decoder
3fa90c38556f23568f6b88eb98e4bc2193f3b744
[ "BSD-3-Clause" ]
null
null
null
seq_to_seq.py
jlibovicky/char-nmt-two-step-decoder
3fa90c38556f23568f6b88eb98e4bc2193f3b744
[ "BSD-3-Clause" ]
null
null
null
"""Encoder-decoder model.""" from typing import List, Tuple, Union import torch import torch.nn as nn from encoder import Encoder, VanillaEncoder from decoder import Decoder, VanillaDecoder T = torch.Tensor def compute_attention_entropy( att_matrix: T, query_mask: T) -> float: # att matrix is: batch x heads x q_len x k_len # first entropy of each distribution, non-existing key positions # must be asked out prenorm_entropies = -(torch.log(att_matrix) * att_matrix) prenorm_entropies[prenorm_entropies.isnan()] = 0.0 distr_entropies = prenorm_entropies.sum(3) # shape: batch x head x q_len # now average over relevant query positions batch_head_entropies = ( distr_entropies * query_mask.unsqueeze(1)).sum(2) / query_mask.sum() return batch_head_entropies.mean(0).mean(0).cpu().numpy() class Seq2SeqModel(nn.Module): def __init__( self, vocab_size: Union[int, Tuple[int, int]], conv_filters: List[int], nar_output: bool = False, char_embedding_dim: int = 128, dim: int = 512, shrink_factor: int = 5, charformer_block_size: int = 5, highway_layers: int = 2, char_ff_layers: int = 2, ff_dim: int = None, layers: int = 6, attention_heads: int = 8, dropout: float = 0.1, char_process_type: str = "conv", vanilla_encoder: bool = False, vanilla_decoder: bool = False, share_char_repr: bool = False) -> None: super().__init__() self.layers = layers if isinstance(vocab_size, tuple): src_vocab_size, tgt_vocab_size = vocab_size else: src_vocab_size, tgt_vocab_size = vocab_size, vocab_size if vanilla_encoder: self.encoder: Union[Encoder, VanillaEncoder] = VanillaEncoder( char_vocabulary_size=src_vocab_size, dim=dim, layers=layers, ff_dim=ff_dim, attention_heads=attention_heads, dropout=dropout) else: self.encoder = Encoder( vocab_size=src_vocab_size, char_embedding_dim=char_embedding_dim, conv_filters=conv_filters, dim=dim, shrink_factor=shrink_factor, charformer_block_size=charformer_block_size, highway_layers=highway_layers, char_ff_layers=char_ff_layers, ff_dim=ff_dim, layers=layers, attention_heads=attention_heads, dropout=dropout, decoder_style_padding=share_char_repr, char_process_type=char_process_type) if vanilla_decoder: self.decoder: Union[Decoder, VanillaDecoder] = VanillaDecoder( char_vocabulary_size=tgt_vocab_size, dim=dim, layers=layers, ff_dim=ff_dim, attention_heads=attention_heads, dropout=dropout, encoder=self.encoder if ( # type: ignore share_char_repr and vanilla_encoder) else None) else: self.decoder = Decoder( char_vocabulary_size=tgt_vocab_size, char_embedding_dim=char_embedding_dim, conv_filters=conv_filters, nar_output=nar_output, dim=dim, shrink_factor=shrink_factor, highway_layers=highway_layers, char_ff_layers=char_ff_layers, layers=layers, ff_dim=ff_dim, attention_heads=attention_heads, char_process_type=char_process_type, dropout=dropout, encoder=self.encoder if # type: ignore share_char_repr else None) def forward( self, src_batch: T, src_mask: T, tgt_batch: T, tgt_mask: T, loss_function: nn.Module, log_details: bool = False) -> Tuple[T, T]: encoded, enc_mask, enc_attention = self.encoder(src_batch, src_mask) loss, details = self.decoder( encoded, enc_mask, tgt_batch, tgt_mask, loss_function, log_details=log_details) if log_details: details["enc_attentions"] = enc_attention details["enc_attention_entropies"] = [ compute_attention_entropy(att, enc_mask) for att in enc_attention] shrinked_mask = details["decoder_mask"] details["dec_attention_entropies"] = [ compute_attention_entropy(att, shrinked_mask) for att in details["decoder_self_attention"]] details["encdec_attention_entropies"] = [ compute_attention_entropy(att, shrinked_mask) for att in details["decoder_self_attention"]] return loss, details @torch.no_grad() def greedy_decode( self, src_batch: T, input_mask: T, eos_token_id: int, max_len: int = 400) -> Tuple[T, T]: encoder_states, encoded_mask, _ = self.encoder(src_batch, input_mask) decoded, mask = self.decoder.greedy_decode( encoder_states, encoded_mask, eos_token_id, max_len=max_len) return decoded, mask @torch.no_grad() def sample( self, src_batch: T, input_mask: T, n_samples: int, eos_token_id: int, max_len: int = 400) -> List[Tuple[T, T]]: encoder_states, encoded_mask, _ = self.encoder(src_batch, input_mask) return [ self.decoder.greedy_decode( encoder_states, encoded_mask, eos_token_id, max_len=max_len, sample=True) for _ in range(n_samples)] @torch.no_grad() def beam_search( self, src_batch: T, input_mask: T, eos_token_id: int, beam_size: int = 5, len_norm: float = 0.5, max_len: int = 400) -> Tuple[T, T]: encoder_states, encoded_mask, _ = self.encoder(src_batch, input_mask) decoded, mask = self.decoder.beam_search( encoder_states, encoded_mask, eos_token_id, beam_size=beam_size, len_norm=len_norm, max_len=max_len) return decoded, mask @property def char_level_param_count(self) -> int: """Number of parameters in character processing layers.""" relevant_parts = [] if hasattr(self.encoder, "embeddings"): relevant_parts = [self.encoder.embeddings] if isinstance(self.encoder, Encoder): relevant_parts.append(self.encoder.char_encoder) if isinstance(self.decoder, VanillaDecoder): relevant_parts.append(self.decoder.transformer.embeddings) else: relevant_parts.extend([ self.decoder.nar_proj, self.decoder.output_proj]) if not self.decoder.nar_output: relevant_parts.append(self.decoder.char_decoder_rnn) if not self.decoder.char_embeddings not in relevant_parts: relevant_parts.extend([ self.decoder.char_embeddings, self.decoder.char_encoder]) char_parameters = { p for part in relevant_parts for p in part.parameters()} return sum(p.numel() for p in char_parameters)
37.18408
77
0.596602
864
7,474
4.844907
0.190972
0.039417
0.014333
0.0344
0.41376
0.382704
0.323459
0.298853
0.277114
0.277114
0
0.006729
0.323923
7,474
200
78
37.37
0.82169
0.039872
0
0.320988
0
0
0.021791
0.016203
0
0
0
0
0
1
0.04321
false
0
0.030864
0
0.117284
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
0
0
0
1
0
8bbe4fd060a6878adde13a88356535b7bfb0e331
29,288
py
Python
tests/utils.py
Ouranosinc/cowbird
108195ca6abbd58fd75b180f6fa7d40eab0f8ea5
[ "MIT" ]
1
2021-02-04T18:56:36.000Z
2021-02-04T18:56:36.000Z
tests/utils.py
Ouranosinc/cowbird
108195ca6abbd58fd75b180f6fa7d40eab0f8ea5
[ "MIT" ]
12
2021-02-05T22:01:10.000Z
2022-03-09T14:23:10.000Z
tests/utils.py
Ouranosinc/cowbird
108195ca6abbd58fd75b180f6fa7d40eab0f8ea5
[ "MIT" ]
null
null
null
import functools import json as json_pkg # avoid conflict name with json argument employed for some function import os from distutils.version import LooseVersion from typing import TYPE_CHECKING from urllib.parse import urlparse import mock import requests import requests.exceptions from pyramid.httpexceptions import HTTPException from pyramid.testing import DummyRequest from pyramid.testing import setUp as PyramidSetUp from webtest.app import AppError, TestApp # noqa from webtest.response import TestResponse from cowbird.app import get_app from cowbird.constants import COWBIRD_ROOT, get_constant from cowbird.services.service import Service from cowbird.utils import ( CONTENT_TYPE_JSON, USE_TEST_CELERY_APP_CFG, SingletonMeta, get_header, get_settings_from_config_ini, is_null, null ) # employ example INI config for tests where needed to ensure that configurations are valid TEST_INI_FILE = os.path.join(COWBIRD_ROOT, "config/cowbird.example.ini") TEST_CFG_FILE = os.path.join(COWBIRD_ROOT, "config/config.example.yml") class TestAppContainer(object): test_app = None # type: Optional[TestApp] app = None # type: Optional[TestApp] url = None # type: Optional[str] if TYPE_CHECKING: # pylint: disable=W0611,unused-import from typing import Any, Callable, Collection, Dict, Iterable, List, Optional, Type, Union from pyramid.request import Request from cowbird.typedefs import ( JSON, AnyCookiesType, AnyHeadersType, AnyResponseType, CookiesType, HeadersType, SettingsType ) from cowbird.utils import NullType # pylint: disable=C0103,invalid-name TestAppOrUrlType = Union[str, TestApp] AnyTestItemType = Union[TestAppOrUrlType, TestAppContainer] class TestVersion(LooseVersion): """ Special version supporting ``latest`` keyword to ignore safeguard check of :func:`warn_version` during development. .. seealso:: Environment variable ``COWBIRD_TEST_VERSION`` should be set with the desired version or ``latest`` to evaluate even new features above the last tagged version. """ __test__ = False # avoid invalid collect depending on specified input path/items to pytest def __init__(self, vstring): if isinstance(vstring, (TestVersion, LooseVersion)): self.version = vstring.version return if vstring == "latest": self.version = vstring # noqa return super(TestVersion, self).__init__(vstring) def _cmp(self, other): if not isinstance(other, TestVersion): other = TestVersion(other) if self.version == "latest" and other.version == "latest": return 0 if self.version == "latest": return 1 if other.version == "latest": return -1 return super(TestVersion, self)._cmp(other) class MockMagpieService(Service): required_params = [] def __init__(self, settings, name, **kwargs): super(MockMagpieService, self).__init__(settings, name, **kwargs) self.event_users = [] self.event_perms = [] self.outbound_perms = [] def json(self): return {"name": self.name, "event_users": self.event_users, "event_perms": self.event_perms, "outbound_perms": self.outbound_perms} def get_resource_id(self, resource_full_name): pass def user_created(self, user_name): self.event_users.append(user_name) def user_deleted(self, user_name): self.event_users.remove(user_name) def permission_created(self, permission): self.event_perms.append(permission.resource_full_name) def permission_deleted(self, permission): self.event_perms.remove(permission.resource_full_name) def create_permission(self, permission): self.outbound_perms.append(permission) def delete_permission(self, permission): for perm in self.outbound_perms: if perm == permission: self.outbound_perms.remove(perm) return class MockAnyServiceBase(Service): ResourceId = 1000 def get_resource_id(self, resource_full_name): # type (str) -> str return MockAnyService.ResourceId def user_created(self, user_name): pass def user_deleted(self, user_name): pass def permission_created(self, permission): pass def permission_deleted(self, permission): pass class MockAnyService(MockAnyServiceBase): required_params = [] def clear_services_instances(): # Remove the service instances initialized with test specific config SingletonMeta._instances.clear() # pylint: disable=W0212 def config_setup_from_ini(config_ini_file_path): settings = get_settings_from_config_ini(config_ini_file_path) config = PyramidSetUp(settings=settings) return config def get_test_app(settings=None): # type: (Optional[SettingsType]) -> TestApp """ Instantiate a local test application. """ config = config_setup_from_ini(TEST_INI_FILE) config.registry.settings["cowbird.url"] = "http://localhost:80" config.registry.settings["cowbird.ini_file_path"] = TEST_INI_FILE config.registry.settings["cowbird.config_path"] = TEST_CFG_FILE config.registry.settings["mongo_uri"] = "mongodb://{host}:{port}/{db_name}".format( host=os.getenv("COWBIRD_TEST_DB_HOST", "127.0.0.1"), port=os.getenv("COWBIRD_TEST_DB_PORT", "27017"), db_name=os.getenv("COWBIRD_TEST_DB_NAME", "cowbird-test") ) # For test, we want to use the real Celery app which is properly mocked # By setting the internal setting USE_TEST_CELERY_APP_CFG to true, the pyramid celery app will not be used config.registry.settings[USE_TEST_CELERY_APP_CFG] = True if settings: config.registry.settings.update(settings) test_app = TestApp(get_app({}, **config.registry.settings)) return test_app def get_app_or_url(test_item): # type: (AnyTestItemType) -> TestAppOrUrlType """ Obtains the referenced test application, local application or remote URL from `Test Case` implementation. """ if isinstance(test_item, (TestApp, str)): return test_item test_app = getattr(test_item, "test_app", None) if test_app and isinstance(test_app, TestApp): return test_app app_or_url = getattr(test_item, "app", None) or getattr(test_item, "url", None) if not app_or_url: raise ValueError("Invalid test class, application or URL could not be found.") return app_or_url def get_hostname(test_item): # type: (AnyTestItemType) -> str """ Obtains stored hostname in the class implementation. """ app_or_url = get_app_or_url(test_item) if isinstance(app_or_url, TestApp): app_or_url = get_constant("COWBIRD_URL", app_or_url.app.registry) return urlparse(app_or_url).hostname def get_headers(app_or_url, header_dict): # type: (TestAppOrUrlType, AnyHeadersType) -> HeadersType """ Obtains stored headers in the class implementation. """ if isinstance(app_or_url, TestApp): return dict(header_dict.items()) # noqa return header_dict def get_response_content_types_list(response): # type: (AnyResponseType) -> List[str] """ Obtains the specified response Content-Type header(s) without additional formatting parameters. """ content_types = [] known_types = ["application", "audio", "font", "example", "image", "message", "model", "multipart", "text", "video"] for part in response.headers["Content-Type"].split(";"): for sub_type in part.strip().split(","): if "=" not in sub_type and sub_type.split("/")[0] in known_types: content_types.append(sub_type) return content_types def get_json_body(response): # type: (AnyResponseType) -> JSON """ Obtains the JSON payload of the response regardless of its class implementation. """ if isinstance(response, TestResponse): return response.json return response.json() def json_msg(json_body, msg=null): # type: (JSON, Optional[str]) -> str """ Generates a message string with formatted JSON body for display with easier readability. """ json_str = json_pkg.dumps(json_body, indent=4, ensure_ascii=False) if msg is not null: return "{}\n{}".format(msg, json_str) return json_str def mock_get_settings(test): """ Decorator to mock :func:`cowbird.utils.get_settings` to allow retrieval of settings from :class:`DummyRequest`. .. warning:: Only apply on test methods (not on class TestCase) to ensure that :mod:`pytest` can collect them correctly. """ from cowbird.utils import get_settings as real_get_settings def mocked(container): if isinstance(container, DummyRequest): return container.registry.settings return real_get_settings(container) @functools.wraps(test) def wrapped(*_, **__): # mock.patch("cowbird.services.get_settings", side_effect=mocked) with mock.patch("cowbird.utils.get_settings", side_effect=mocked): return test(*_, **__) return wrapped def mock_request(request_path_query="", # type: str method="GET", # type: str params=None, # type: Optional[Dict[str, str]] body="", # type: Union[str, JSON] content_type=None, # type: Optional[str] headers=None, # type: Optional[AnyHeadersType] cookies=None, # type: Optional[AnyCookiesType] settings=None, # type: SettingsType ): # type: (...) -> Request """ Generates a fake request with provided arguments. Can be employed by functions that expect a request object as input to retrieve details such as body content, the request path, or internal settings, but that no actual request needs to be accomplished. """ parts = request_path_query.split("?") path = parts[0] query = dict() if len(parts) > 1 and parts[1]: for part in parts[1].split("&"): kv = part.split("=") # handle trailing keyword query arguments without values if kv[0]: # handle invalid keyword missing query[kv[0]] = kv[1] if len(kv) > 1 else None elif params: query = params request = DummyRequest(path=path, params=query) request.path_qs = request_path_query request.method = method request.content_type = content_type request.headers = headers or {} request.cookies = cookies or {} request.matched_route = None # cornice method if content_type: request.headers["Content-Type"] = content_type request.body = body try: if body: # set missing DummyRequest.json attribute request.json = json_pkg.loads(body) # type: ignore except (TypeError, ValueError): pass request.registry.settings = settings or {} return request # noqa # fake type of what is normally expected just to avoid many 'noqa' def test_request(test_item, # type: AnyTestItemType method, # type: str path, # type: str data=None, # type: Optional[Union[JSON, str]] json=None, # type: Optional[Union[JSON, str]] body=None, # type: Optional[Union[JSON, str]] params=None, # type: Optional[Dict[str, str]] timeout=10, # type: int retries=3, # type: int allow_redirects=True, # type: bool content_type=None, # type: Optional[str] headers=None, # type: Optional[HeadersType] cookies=None, # type: Optional[CookiesType] **kwargs # type: Any ): # type: (...) -> AnyResponseType """ Calls the request using either a :class:`webtest.TestApp` instance or :class:`requests.Request` from a string URL. Keyword arguments :paramref:`json`, :paramref:`data` and :paramref:`body` are all looked for to obtain the data. Header ``Content-Type`` is set with respect to explicit :paramref:`json` or via provided :paramref:`headers` when available. Explicit :paramref:`content_type` can also be provided to override all of these. Request cookies are set according to :paramref:`cookies`, or can be interpreted from ``Set-Cookie`` header. .. warning:: When using :class:`TestApp`, some internal cookies can be stored from previous requests to retain the active user. Make sure to provide new set of cookies (or logout user explicitly) if different session must be used, otherwise they will be picked up automatically. For 'empty' cookies, provide an empty dictionary. :param test_item: one of `BaseTestCase`, `webtest.TestApp` or remote server URL to call with `requests` :param method: request method (GET, POST, PATCH, PUT, DELETE) :param path: test path starting at base path that will be appended to the application's endpoint. :param params: query parameters added to the request path. :param json: explicit JSON body content to use as request body. :param data: body content string to use as request body, can be JSON if matching ``Content-Type`` is identified. :param body: alias to :paramref:`data`. :param content_type: Enforce specific content-type of provided data body. Otherwise, attempt to retrieve it from request headers. Inferred JSON content-type when :paramref:`json` is employed, unless overridden explicitly. :param headers: Set of headers to send the request. Header ``Content-Type`` is looked for if not overridden. :param cookies: Cookies to provide to the request. :param timeout: passed down to :mod:`requests` when using URL, otherwise ignored (unsupported). :param retries: number of retry attempts in case the requested failed due to timeout (only when using URL). :param allow_redirects: Passed down to :mod:`requests` when using URL, handled manually for same behaviour when using :class:`TestApp`. :param kwargs: any additional keywords that will be forwarded to the request call. :return: response of the request """ method = method.upper() status = kwargs.pop("status", None) # obtain json body from any json/data/body kw and empty {} if not specified # reapply with the expected webtest/requests method kw afterward _body = json or data or body or {} app_or_url = get_app_or_url(test_item) if isinstance(app_or_url, TestApp): # set 'cookies' handled by the 'TestApp' instance if not present or different if cookies is not None: cookies = dict(cookies) # convert tuple-list as needed if not app_or_url.cookies or app_or_url.cookies != cookies: app_or_url.cookies.update(cookies) # obtain Content-Type header if specified to ensure it is properly applied kwargs["content_type"] = content_type if content_type else get_header("Content-Type", headers) # update path with query parameters since TestApp does not have an explicit argument when not using GET if params: path += "?" + "&".join("{!s}={!s}".format(k, v) for k, v in params.items() if v is not None) kwargs.update({ "params": _body, # TestApp uses 'params' for the body during POST (these are not the query parameters) "headers": dict(headers or {}), # adjust if none provided or specified as tuple list }) # convert JSON body as required if _body is not None and (json is not None or kwargs["content_type"] == CONTENT_TYPE_JSON): kwargs["params"] = json_pkg.dumps(_body, cls=json_pkg.JSONEncoder) kwargs["content_type"] = CONTENT_TYPE_JSON # enforce if only 'json' keyword provided kwargs["headers"]["Content-Length"] = str(len(kwargs["params"])) # need to fix with override JSON payload if status and status >= 300: kwargs["expect_errors"] = True err_code = None err_msg = None try: resp = app_or_url._gen_request(method, path, **kwargs) # pylint: disable=W0212 # noqa: W0212 except AppError as exc: err_code = exc err_msg = str(exc) except HTTPException as exc: err_code = exc.status_code err_msg = str(exc) + str(getattr(exc, "exception", "")) except Exception as exc: err_code = 500 err_msg = "Unknown: {!s}".format(exc) finally: if err_code: info = json_msg({"path": path, "method": method, "body": _body, "headers": kwargs["headers"]}) result = "Request raised unexpected error: {!s}\nError: {}\nRequest:\n{}" raise AssertionError(result.format(err_code, err_msg, info)) # automatically follow the redirect if any and evaluate its response max_redirect = kwargs.get("max_redirects", 5) while 300 <= resp.status_code < 400 and max_redirect > 0: # noqa resp = resp.follow() max_redirect -= 1 assert max_redirect >= 0, "Maximum follow redirects reached." # test status accordingly if specified assert resp.status_code == status or status is None, "Response not matching the expected status code." return resp kwargs.pop("expect_errors", None) # remove keyword specific to TestApp content_type = get_header("Content-Type", headers) if json or content_type == CONTENT_TYPE_JSON: kwargs["json"] = _body elif data or body: kwargs["data"] = _body url = "{url}{path}".format(url=app_or_url, path=path) while True: try: return requests.request(method, url, params=params, headers=headers, cookies=cookies, timeout=timeout, allow_redirects=allow_redirects, **kwargs) except requests.exceptions.ReadTimeout: if retries <= 0: raise retries -= 1 def visual_repr(item): # type: (Any) -> str try: if isinstance(item, (dict, list)): return json_pkg.dumps(item, indent=4, ensure_ascii=False) except Exception: # noqa pass return "'{}'".format(repr(item)) def format_test_val_ref(val, ref, pre="Fail", msg=None): if is_null(msg): _msg = "({}) Failed condition between test and reference values.".format(pre) else: _msg = "({}) Test value: {}, Reference value: {}".format(pre, visual_repr(val), visual_repr(ref)) if isinstance(msg, str): _msg = "{}\n{}".format(msg, _msg) return _msg def all_equal(iter_val, iter_ref, any_order=False): if not (hasattr(iter_val, "__iter__") and hasattr(iter_ref, "__iter__")): return False if len(iter_val) != len(iter_ref): return False if any_order: return all(it in iter_ref for it in iter_val) return all(it == ir for it, ir in zip(iter_val, iter_ref)) def check_all_equal(iter_val, iter_ref, msg=None, any_order=False): # type: (Collection[Any], Union[Collection[Any], NullType], Optional[str], bool) -> None """ :param iter_val: tested values. :param iter_ref: reference values. :param msg: override message to display if failing test. :param any_order: allow equal values to be provided in any order, otherwise order must match as well as values. :raises AssertionError: If all values in :paramref:`iter_val` are not equal to values within :paramref:`iter_ref`. If :paramref:`any_order` is ``False``, also raises if equal items are not in the same order. """ r_val = repr(iter_val) r_ref = repr(iter_ref) assert all_equal(iter_val, iter_ref, any_order), format_test_val_ref(r_val, r_ref, pre="All Equal Fail", msg=msg) def check_val_equal(val, ref, msg=None): # type: (Any, Union[Any, NullType], Optional[str]) -> None """:raises AssertionError: if :paramref:`val` is not equal to :paramref:`ref`.""" assert is_null(ref) or val == ref, format_test_val_ref(val, ref, pre="Equal Fail", msg=msg) def check_val_not_equal(val, ref, msg=None): # type: (Any, Union[Any, NullType], Optional[str]) -> None """:raises AssertionError: if :paramref:`val` is equal to :paramref:`ref`.""" assert is_null(ref) or val != ref, format_test_val_ref(val, ref, pre="Not Equal Fail", msg=msg) def check_val_is_in(val, ref, msg=None): # type: (Any, Union[Any, NullType], Optional[str]) -> None """:raises AssertionError: if :paramref:`val` is not in to :paramref:`ref`.""" assert is_null(ref) or val in ref, format_test_val_ref(val, ref, pre="Is In Fail", msg=msg) def check_val_not_in(val, ref, msg=None): # type: (Any, Union[Any, NullType], Optional[str]) -> None """:raises AssertionError: if :paramref:`val` is in to :paramref:`ref`.""" assert is_null(ref) or val not in ref, format_test_val_ref(val, ref, pre="Not In Fail", msg=msg) def check_val_type(val, ref, msg=None): # type: (Any, Union[Type[Any], NullType, Iterable[Type[Any]]], Optional[str]) -> None """:raises AssertionError: if :paramref:`val` is not an instanced of :paramref:`ref`.""" assert isinstance(val, ref), format_test_val_ref(val, repr(ref), pre="Type Fail", msg=msg) def check_raises(func, exception_type, msg=None): # type: (Callable[[], Any], Type[Exception], Optional[str]) -> Exception """ Calls the callable and verifies that the specific exception was raised. :raise AssertionError: on failing exception check or missing raised exception. :returns: raised exception of expected type if it was raised. """ msg = ": {}".format(msg) if msg else "." try: func() except Exception as exc: # pylint: disable=W0703 msg = "Wrong exception [{!s}] raised instead of [{!s}]{}" \ .format(type(exc).__name__, exception_type.__name__, msg) assert isinstance(exc, exception_type), msg return exc raise AssertionError("Exception [{!s}] was not raised{}".format(exception_type.__name__, msg)) def check_no_raise(func, msg=None): # type: (Callable[[], Any], Optional[str]) -> Any """ Calls the callable and verifies that no exception was raised. :raise AssertionError: on any raised exception. """ try: return func() except Exception as exc: # pylint: disable=W0703 msg = ": {}".format(msg) if msg else "." raise AssertionError("Exception [{!r}] was raised when none is expected{}".format(type(exc).__name__, msg)) def check_response_basic_info(response, # type: AnyResponseType expected_code=200, # type: int expected_type=CONTENT_TYPE_JSON, # type: str expected_method="GET", # type: str extra_message=None, # type: Optional[str] ): # type: (...) -> Union[JSON, str] """ Validates basic `Cowbird` API response metadata. For UI pages, employ :func:`check_ui_response_basic_info` instead. If the expected content-type is JSON, further validations are accomplished with specific metadata fields that are always expected in the response body. Otherwise, minimal validation of basic fields that can be validated regardless of content-type is done. :param response: response to validate. :param expected_code: status code to validate from the response. :param expected_type: Content-Type to validate from the response. :param expected_method: method 'GET', 'POST', etc. to validate from the response if an error. :param extra_message: additional message to append to every specific test message if provided. :return: json body of the response for convenience. """ def _(_msg): return _msg + " " + extra_message if extra_message else _msg check_val_is_in("Content-Type", dict(response.headers), msg=_("Response doesn't define 'Content-Type' header.")) content_types = get_response_content_types_list(response) check_val_is_in(expected_type, content_types, msg=_("Response doesn't match expected HTTP Content-Type header.")) code_message = "Response doesn't match expected HTTP status code." if expected_type == CONTENT_TYPE_JSON: # provide more details about mismatching code since to help debug cause of error code_message += "\nReason:\n{}".format(json_msg(get_json_body(response))) check_val_equal(response.status_code, expected_code, msg=_(code_message)) if expected_type == CONTENT_TYPE_JSON: body = get_json_body(response) check_val_is_in("code", body, msg=_("Parameter 'code' should be in response JSON body.")) check_val_is_in("type", body, msg=_("Parameter 'type' should be in response JSON body.")) check_val_is_in("detail", body, msg=_("Parameter 'detail' should be in response JSON body.")) check_val_equal(body["code"], expected_code, msg=_("Parameter 'code' should match HTTP status code.")) check_val_equal(body["type"], expected_type, msg=_("Parameter 'type' should match HTTP Content-Type header.")) check_val_not_equal(body["detail"], "", msg=_("Parameter 'detail' should not be empty.")) else: body = response.text if response.status_code >= 400: # error details available for any content-type, just in different format check_val_is_in("url", body, msg=_("Request URL missing from contents,")) check_val_is_in("path", body, msg=_("Request path missing from contents.")) check_val_is_in("method", body, msg=_("Request method missing from contents.")) if expected_type == CONTENT_TYPE_JSON: # explicitly check by dict-key if JSON check_val_equal(body["method"], expected_method, msg=_("Request method not matching expected value.")) return body def check_error_param_structure(body, # type: JSON param_value=null, # type: Optional[Any] param_name=null, # type: Optional[str] param_compare=null, # type: Optional[Any] is_param_value_literal_unicode=False, # type: bool param_name_exists=False, # type: bool param_compare_exists=False, # type: bool ): # type: (...) -> None """ Validates error response ``param`` information based on different Cowbird version formats. :param body: JSON body of the response to validate. :param param_value: Expected 'value' of param the parameter. Contained field value not verified if ``null``, only presence of the field. :param param_name: Expected 'name' of param. Ignored for older Cowbird version that did not provide this information. Contained field value not verified if ``null`` and ``param_name_exists`` is ``True`` (only its presence). If provided, automatically implies ``param_name_exists=True``. Skipped otherwise. :param param_compare: Expected 'compare'/'param_compare' value (filed name according to version) Contained field value not verified if ``null`` and ``param_compare_exists`` is ``True`` (only its presence). If provided, automatically implies ``param_compare_exists=True``. Skipped otherwise. :param is_param_value_literal_unicode: param value is represented as `u'{paramValue}'` for older Cowbird version. :param param_name_exists: verify that 'name' is in the body, not validating its value. :param param_compare_exists: verify that 'compare'/'param_compare' is in the body, not validating its value. :raises AssertionError: on any failing condition """ check_val_type(body, dict) check_val_is_in("param", body) check_val_type(body["param"], dict) check_val_is_in("value", body["param"]) if param_name_exists or param_name is not null: check_val_is_in("name", body["param"]) if param_name is not null: check_val_equal(body["param"]["name"], param_name) if param_value is not null: check_val_equal(body["param"]["value"], param_value) if param_compare_exists or param_compare is not null: check_val_is_in("compare", body["param"]) if param_compare is not null: check_val_equal(body["param"]["compare"], param_compare)
44.042105
120
0.651974
3,725
29,288
4.962148
0.147919
0.024995
0.008656
0.00844
0.237611
0.172041
0.126866
0.094135
0.069087
0.055886
0
0.003908
0.248703
29,288
664
121
44.108434
0.836121
0.354275
0
0.148241
0
0
0.108272
0.007167
0.002513
0
0
0
0.030151
1
0.110553
false
0.017588
0.057789
0.007538
0.298995
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
0
0
0
1
0
8bc1dc764cc3286fa9cb0c9dbac2a3360dc97788
764
py
Python
sqds/jobs/update_guilds.py
abey79/sqds
acab1d9c6d4a010fff9d8e89a5fdd9d94def7c89
[ "MIT" ]
null
null
null
sqds/jobs/update_guilds.py
abey79/sqds
acab1d9c6d4a010fff9d8e89a5fdd9d94def7c89
[ "MIT" ]
null
null
null
sqds/jobs/update_guilds.py
abey79/sqds
acab1d9c6d4a010fff9d8e89a5fdd9d94def7c89
[ "MIT" ]
null
null
null
from django.utils import timezone from django_extensions.management.jobs import BaseJob from ..models import Player, Guild def update_guild(ally_code): should_execute = False try: player = Player.objects.get(ally_code=ally_code) guild = player.guild; since_last_update = timezone.now() - guild.last_updated if since_last_update.total_seconds() >= 4 * 3600: should_execute = True except Player.DoesNotExist: should_execute = True if should_execute: Guild.objects.update_or_create_from_swgoh(ally_code=ally_code) class Job(BaseJob): help = "Update PREPARE and PREPAIRED data from swgoh.help" def execute(self): update_guild(116235559) update_guild(343174317)
27.285714
70
0.704188
97
764
5.309278
0.484536
0.07767
0.046602
0.062136
0
0
0
0
0
0
0
0.038655
0.221204
764
27
71
28.296296
0.826891
0
0
0.1
0
0
0.064136
0
0
0
0
0
0
1
0.1
false
0
0.15
0
0.35
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
0
0
0
1
0
8bc3ea498abafb408b2345871e2adf30ac6a71a4
1,907
py
Python
src/saleor_app/install.py
przlada/saleor-app-framework-python
3a561c93bf586b4210e7b3c4d2db3408046a9599
[ "BSD-3-Clause" ]
20
2021-05-18T18:05:25.000Z
2022-03-02T00:39:15.000Z
src/saleor_app/install.py
przlada/saleor-app-framework-python
3a561c93bf586b4210e7b3c4d2db3408046a9599
[ "BSD-3-Clause" ]
13
2021-10-19T19:05:24.000Z
2022-03-22T13:17:55.000Z
src/saleor_app/install.py
przlada/saleor-app-framework-python
3a561c93bf586b4210e7b3c4d2db3408046a9599
[ "BSD-3-Clause" ]
11
2021-06-09T21:24:56.000Z
2022-03-12T17:33:30.000Z
import logging import secrets import string from typing import Awaitable, Callable, List from saleor_app.conf import get_settings from saleor_app.errors import InstallAppError from saleor_app.graphql import GraphQLError, get_executor, get_saleor_api_url from saleor_app.mutations import CREATE_WEBHOOK from saleor_app.schemas.core import AppToken, DomainName, Url, WebhookData logger = logging.getLogger(__name__) async def install_app( domain: DomainName, token: AppToken, events: List[str], target_url: Url, save_app_data: Callable[[DomainName, WebhookData], Awaitable], ): alphabet = string.ascii_letters + string.digits secret_key = "".join(secrets.choice(alphabet) for _ in range(20)) api_url = get_saleor_api_url(domain) executor = get_executor(host=api_url, auth_token=token) settings = get_settings() response, errors = await executor( CREATE_WEBHOOK, variables={ "input": { "targetUrl": target_url, "events": [event.upper() for event in events], "name": settings.app_name, "secretKey": secret_key, } }, ) if errors: logger.warning("Webhook create mutation raised an error") raise GraphQLError("Webhook create mutation raised an error") webhook_error = response["data"]["webhookCreate"].get("errors") if webhook_error: logger.warning( "Unable to finish installation of app for %s. Received error: %s", domain, webhook_error, ) raise InstallAppError("Failed to create webhook for %s.", domain) saleor_webhook_id = response["data"]["webhookCreate"]["webhook"]["id"] install_app_data = WebhookData( token=token, webhook_id=saleor_webhook_id, webhook_secret_key=secret_key ) await save_app_data(domain, install_app_data)
31.783333
80
0.678553
224
1,907
5.549107
0.361607
0.040225
0.052293
0.024135
0.054706
0.054706
0
0
0
0
0
0.001363
0.230729
1,907
59
81
32.322034
0.845944
0
0
0
0
0
0.133718
0
0
0
0
0
0
1
0
false
0
0.183673
0
0.183673
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
0
0
0
1
0
8bc5033e6745dd8bddb7a355569fc61f7cd99932
1,410
py
Python
tools/other/syn.py
fengjixuchui/geospy
12ff83372a7e128babd8f16c357672d1495022c8
[ "MIT" ]
1
2019-11-12T05:53:25.000Z
2019-11-12T05:53:25.000Z
tools/other/syn.py
fengjixuchui/geospy
12ff83372a7e128babd8f16c357672d1495022c8
[ "MIT" ]
null
null
null
tools/other/syn.py
fengjixuchui/geospy
12ff83372a7e128babd8f16c357672d1495022c8
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import random import time from scapy.all import IP, TCP, send from threading import Thread # Import modules for SYN flood import tools.randomData as randomData def SYN_ATTACK(threads, attack_time, target): # Finish global FINISH FINISH = False target_ip = target.split(":")[0] target_port = int(target.split(":")[1]) print("\033[1;34m"+"[*]"+"\033[0m"+" Starting SYN attack...") threads_list = [] # SYN flood def syn_flood(): global FINISH while True: if FINISH: break IP_Packet = IP() IP_Packet.src = randomData.random_IP() IP_Packet.dst = target_ip TCP_Packet = TCP() TCP_Packet.sport = random.randint(1000, 10000) TCP_Packet.dport = target_port TCP_Packet.flags = "S" TCP_Packet.seq = random.randint(1000, 10000) TCP_Packet.window = random.randint(1000, 10000) try: send(IP_Packet / TCP_Packet, verbose = False) except Exception as e: print(e) else: print("\033[1;32m"+"[+]"+"\033[0m"+" SYN packet was sent!") # Start threads for thread in range(0, threads): print("\033[1;34m"+"[*]"+"\033[0m"+" Staring thread " + str(thread) + "...") t = Thread(target = syn_flood) t.start() threads_list.append(t) # Sleep selected secounds time.sleep(attack_time) # Terminate threads for thread in threads_list: FINISH = True thread.join() print("\033[1;77m"+"[i]"+"\033[0m"+" Attack completed.")
23.114754
78
0.668085
203
1,410
4.522167
0.394089
0.068627
0.039216
0.071895
0.104575
0.104575
0
0
0
0
0
0.061366
0.179433
1,410
60
79
23.5
0.732066
0.087234
0
0.047619
0
0
0.128125
0
0
0
0
0
0
1
0.047619
false
0
0.119048
0
0.166667
0.119048
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bc5c14508eaa101207214cbf9fa6cdfc7a9bf62
19,405
py
Python
NIQ_uncompiled/source_code/check_valid.py
wxhawkins/NestIQ
3a004d330e2c68b0c7eb0b0676bc4d044e52cbe4
[ "Apache-2.0" ]
null
null
null
NIQ_uncompiled/source_code/check_valid.py
wxhawkins/NestIQ
3a004d330e2c68b0c7eb0b0676bc4d044e52cbe4
[ "Apache-2.0" ]
null
null
null
NIQ_uncompiled/source_code/check_valid.py
wxhawkins/NestIQ
3a004d330e2c68b0c7eb0b0676bc4d044e52cbe4
[ "Apache-2.0" ]
null
null
null
import time import datetime as dt from pathlib import Path from tkinter import messagebox import re import niq_misc import math import traceback from niq_misc import replace_entry def check_valid_vertex_file(gui): """ Checks user-provided vertex selection file (HTML) for issues that could cause errors with downstream processes. Returns: True if file passes all tests, else displays error message and returns False """ niq_misc.remove_curly(gui.vertex_file_E) vertex_path = Path(gui.vertex_file_E.get()) # Check if path is empty if vertex_path.name == "": messagebox.showerror("Vertex File Error", "Please provide a vertex file.") return False # Check if path has invalid path if vertex_path.suffix not in (".html", ""): messagebox.showerror("Vertex Selection Error", r'Vertex selection file must have ".html" extension.') return False # Check if path exists if not vertex_path.exists(): messagebox.showerror("Vertex Selection Error", "Provided vertex selection file not found.") return False with open(vertex_path, "r") as original_file: original_lines = original_file.readlines() # Remove extra table data lines if present cleaned_content = str() found = False for line in original_lines: if "<div class" in line: found = True if found: cleaned_content += line # Get datapoints tokens = re.finditer(r">([\d\.-]+)</span>", cleaned_content) token_num = 0 try: # Every other value in tokens will be temperature and so is ignored for counter, match in enumerate(tokens): token_num = counter if not (counter % 2) == 0: round(float(match.group(1))) except: messagebox.showerror(("Vertex File Error"), "Vertex file is unreadable. Please try another.") return False if token_num < 2: messagebox.showerror( "Vertex File Error", "No vertices detected in vertex file.\n\n" + 'When saving plots, ensure the file type option is set to \"Webpage, Complete\" not \"Webpage, HTML only\".' ) return False return True def check_valid_main(gui, first_in=True, check_output=True): """ Checks for valid configuration of all parameters housed on the Main tab. This includes extensive review of the input file provided. Args: first_in (bool): False if current file is second or later in a queue of multiple input files check_output (bool): if False, output file names are not examined """ def check_input_file(gui): """ Checks several aspects of the input file to ensure it is compatable with all downstream processing. Also displays warnings for less severe format violations. """ def check_datetime_intervals(): """ Sets time interval between temperature readings and checks for gaps in date/time column. """ delta_secs = (datetimes[-1] - datetimes[0]).total_seconds() interval = dt.timedelta(seconds=round(delta_secs / len(master_list))) if not gui.show_warns_BV.get(): return True # If interval is greater than or equal to one minute if interval.seconds >= 60: i = 1 while i < len(datetimes): if datetimes[i - 1] + interval != datetimes[i]: messagebox.showwarning( "Date/time Warning", f"{file_name_appendage}Discontinuous date/time found for data point {master_list[i][0]}." + "The run will continue, but this could cause inaccurate statistical output.", ) i += 1 return True # If interval is less than one minute # Identify first change in date/time i = 0 while datetimes[i] == datetimes[0]: i += 1 # Find least common denominator with one minute LCD = abs(interval.seconds*60) // math.gcd(interval.seconds, 60) dp_leap = int(LCD / interval.seconds) # There should be a whole number minute change after this many data points min_leap = dt.timedelta(minutes=int(LCD / 60)) # That whole number of minutes is this i += dp_leap while i < len(datetimes): if datetimes[i - dp_leap] + min_leap != datetimes[i]: messagebox.showwarning( "Date/time Warning", f"{file_name_appendage}Discontinuous date/time found for data point {master_list[i][0]}." + "The run will continue, but this could cause inaccurate statistical output.", ) i += dp_leap return True in_file_path = gui.active_input_path file_name_appendage = f"For file: {in_file_path.name} \n\n" datetimes = [] if in_file_path.name == "": messagebox.showerror("Input error (Main tab)", "No input file provided.") return False if not in_file_path.exists(): messagebox.showerror("Input File Error", "".join((file_name_appendage, "File with provided path could not be found."))) return False if in_file_path.suffix not in (".csv", ".html"): messagebox.showerror("Input File Error", f'{file_name_appendage} Input file must have "csv" or "html" extension.') return False try: # In the case of an HTML input, simply check for the presence of input file data if in_file_path.suffix == ".html": with open(in_file_path, "r") as f: content = f.read() if "NestIQ input data" in content: return True else: messagebox.showerror("Input File Error", f'{file_name_appendage} HTML file does not contain the necessary information for processing.') return False with open(in_file_path, "r") as f: lines = f.readlines() master_list = [line.strip().rstrip(",").split(",") for line in lines] pop_indices = [] # Remove lines not conforming to expected format (such as headers) for i in range(len(master_list[:-1])): # Cells in data point column must contain only numbers if not str(master_list[i][0]).isnumeric(): pop_indices.append(i) for pop_count, index in enumerate(pop_indices): master_list.pop(index - pop_count) master_list.pop(len(master_list) - 1) prev_line = master_list[0] if len(prev_line) < 3: gui.air_valid = False for line in master_list[1:]: line = line[:4] if gui.air_valid else line[:3] # Check if data points are continuous and sequential try: if not int(line[0]) == (int(prev_line[0]) + 1): raise ValueError except: messagebox.showerror( "Data Point Error", f"{file_name_appendage}Error after data point " + f"{prev_line[0]}. Data point number is not sequential with regard to previous data point.", ) return False # Test conversion of date/time string to datetime object try: datetimes.append(niq_misc.convert_to_datetime(line[1])) except ValueError: messagebox.showerror( "Date/Time Error", f"{file_name_appendage}Invalid date/time found for data point {line[0]}. Date/Time should be in MM/DD/YYYY HH:MM (:SS) format." ) return False # Check egg temperatures column try: float(line[2]) except: messagebox.showerror("Temperature Error", f"{file_name_appendage}Invalid temperature given for data point {line[0]}.") return False # Check air temperatures column if appropriate if gui.air_valid: try: float(line[3]) except (IndexError, ValueError): gui.air_valid = False if gui.show_warns_BV.get(): messagebox.showwarning( "Air Temperature Warning", f"{file_name_appendage}Invalid air temperature detected for data point " + f"{line[0]}. Air temperatures will not be plotted or included in statistical output.", ) prev_line = line # Lastly, check if date/times are continuous return check_datetime_intervals() except Exception as e: print(e) traceback.print_exc() messagebox.showerror( "Unknown Error", f"{file_name_appendage}There was an unidentifiable error with the provided input file. " + "This is sometimes the result of 'extra' cells in the input file.\n\n" + "Please reference the NestIQ manual for details regarding proper input file format." + " This can be accessed by clicking 'Help' in the top right.", ) return False def check_out_file(gui, entry, title): """ Checks if the name provided for a given output file is valid. This includes asking the user if they want to override if a file with the same name already exists. Args: entry (tk.Entry): entry box being examined title (string): how to reference the current entry box if error messeage is triggered """ if entry.get() == "": messagebox.showerror(f"{title} Error", "File name is empty.") return False entry_path = Path(entry.get()) if entry_path.is_dir(): messagebox.showerror(f"{title} Error", "Directory provided but no file name.") return False # Add extension if not present if entry == gui.plot_file_E: ext = ".html" elif entry == gui.stats_file_E or entry == gui.multi_in_stats_file_E: ext = ".csv" entry_path = Path(entry.get()).with_suffix(ext) # Default to "output_files" directory if only filename (no dir) provided if str(entry_path.parent) == ".": entry_path = gui.master_dir_path / "output_files" / entry_path replace_entry(entry, str(entry_path)) # Check if plot file already exists and if so, ask to override if entry_path.exists(): if gui.show_warns_BV.get(): if not messagebox.askyesno("Override?", f"The file '{entry.get()}' already exists. Do you want to override?"): return False try: entry_path.unlink() except PermissionError: messagebox.showerror(f"{title} Error", "File could not be overridden. Please ensure files are closed before overriding.") return False return True # Check time entry boxes for time_str in (gui.day_start_E.get(), gui.night_start_E.get()): try: time.strptime(time_str, "%H:%M") except ValueError: messagebox.showerror("Daytime Start/End Error", f"Provided value of {time_str} is invalid. Please provide times in 24 hr HH:MM (:SS) format.") return False # Check data smoothing box try: if not float(gui.smoothing_radius_E.get()).is_integer(): raise ValueError if int(gui.smoothing_radius_E.get()) < 0: messagebox.showerror("Data Smoothing Radius Error", "Data smoothing radius must be greater than or equal to zero.") return False except ValueError: messagebox.showerror("Data Smoothing Radius Error", "Data smoothing radius must be an integer.") return False # Check duration threshold box try: if int(float(gui.dur_thresh_E.get())) < 0: messagebox.showerror("Duration Threshold Error", "Duration threshold cannot be less than zero.") return False except ValueError: messagebox.showerror("Duration Threshold Error", "Invalid duration threshold (could not convert to integer).") return False if not check_input_file(gui): return False if check_output: if gui.make_plot_BV.get(): if not check_out_file(gui, gui.plot_file_E, "Plot File"): return False if gui.get_stats_BV.get(): if not check_out_file(gui, gui.stats_file_E, "Stats Output File"): return False if gui.multi_in_stats_BV.get() and first_in: if not check_out_file(gui, gui.multi_in_stats_file_E, "Compile Summary"): return False return True def check_valid_adv(gui): """ Checks for valid configuration of all parameters housed on the Advanced tab. """ def try_autofill(): """ Checks if all Markov model parameter boxes are empty and runs unsupervised learning if so. """ for entry in ( gui.init_off_E, gui.init_on_E, gui.off_off_trans_E, gui.off_on_trans_E, gui.on_on_trans_E, gui.on_off_trans_E, gui.off_mean_E, gui.on_mean_E, gui.off_stdev_E, gui.on_stdev_E, ): if entry.get() != "": return False gui.unsupervised_learning(auto_run=True) return True try: entries = (gui.init_off_E, gui.init_on_E, gui.off_off_trans_E, gui.off_on_trans_E, gui.on_on_trans_E, gui.on_off_trans_E) for entry in entries: if float(entry.get()) < 0: raise ValueError("Probability less than 0 provided.") except ValueError: if try_autofill(): return True messagebox.showerror("Parameter Error (Advanced tab)", "Probabilities must be real numbers greater than 0.") return False try: (float(mean) for mean in (gui.off_mean_E.get(), gui.on_mean_E.get())) except TypeError: messagebox.showerror("Parameter Error (Advanced tab)", "Means must be real numbers.") return False try: for stdev in (gui.off_stdev_E.get(), gui.on_stdev_E.get()): if float(stdev) <= 0: raise ValueError("Standard deviation less than 0 provided.") except: messagebox.showerror("Parameter Error (Advanced tab)", "Standard deviations must be real numbers greater than 0.") return False return True def check_valid_plot_ops(gui): """ Checks for valid configuration of all parameters housed on the Plot Options tab. """ # Check plot dimensions if gui.manual_plot_dims.get(): valid = True try: if int(gui.plot_dim_x_E.get()) < 1 or int(gui.plot_dim_y_E.get()) < 1: valid = False except: valid = False if not valid: messagebox.showwarning( "Plot Dimensions Warning", ("Provided plot dimensions are not valid; please provide positive integers. Automatic resolution detection will be used."), ) gui.manual_plot_dims.set(0) try: if float(gui.title_font_size_E.get()) < 0: raise ValueError("Provided plot title font size is less than 0") except ValueError: messagebox.showerror("Plot title Font Size Error (Plot Options tab)", "Invalid plot title font size was provided.") return False try: if float(gui.axis_title_font_size_E.get()) < 0: raise ValueError("Provided axis title font size is less than 0") except ValueError: messagebox.showerror("Axis Title Font Size Error (Plot Options tab)", "Invalid axis title font size was provided.") return False try: if float(gui.axis_label_font_size_E.get()) < 0: raise ValueError("Provided axis label font size is less than 0") except ValueError: messagebox.showerror("Axis Label Font Size Error (Plot Options tab)", "Invalid axis label font size was provided.") return False try: if int(gui.axis_tick_size_E.get()) < 0: raise ValueError("Provided axis tick size is less than 0") except ValueError: messagebox.showerror("Axis Tick Size Error (Plot Options tab)", "Invalid axis tick size was provided.") return False try: if float(gui.legend_font_size_E.get()) < 0: raise ValueError("Provided legend font size is less than 0") except ValueError: messagebox.showerror("Legend Font Size Error (Plot Options tab)", "Invalid legend font size was provided.") return False # Check plot element sizes/widths try: if float(gui.on_point_size_E.get()) < 0: raise ValueError("Provided on-bout point size is less than 0") except ValueError: messagebox.showerror("Point Size Error (Plot Options tab)", "Invalid on-bout point size was provided.") return False try: if float(gui.bout_line_width_E.get()) < 0: raise ValueError("Provided bout line width is less than 0") except ValueError: messagebox.showerror("Line Width Error (Plot Options tab)", "Invalid bout line width was provided.") return False try: if float(gui.air_line_width_E.get()) < 0: raise ValueError("Provided air line width is less than 0") except ValueError: messagebox.showerror("Line Width Error (Plot Options tab)", "Invalid air temperature line width was provided.") return False if gui.show_day_markers_BV.get(): try: if float(gui.day_marker_width_E.get()) < 0: raise ValueError("Provided day marker size is less than 0") except ValueError: messagebox.showerror("Day Marker Size Error (Plot Options tab)", "Invalid day marker size was provided.") return False return True def check_valid_stat_ops(gui): """ Checks for valid configuration of all parameters housed on the Stat Options tab. """ try: float(gui.time_above_temper_E.get()) except: messagebox.showerror("Custom Temperature Error (Stat Options tab)", 'Invalid "Time above" temperature.') return False try: float(gui.time_below_temper_E.get()) except: messagebox.showerror("Custom Temperature Error (Stat Options tab)", 'Invalid "Time below" temperature.') return False return True
38.198819
171
0.588199
2,393
19,405
4.646051
0.174676
0.040565
0.030401
0.040925
0.385231
0.314535
0.270462
0.227469
0.19329
0.14454
0
0.005537
0.329915
19,405
507
172
38.274162
0.849496
0.13311
0
0.37069
0
0.008621
0.269212
0.014956
0
0
0
0
0
1
0.025862
false
0
0.025862
0
0.206897
0.005747
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bcfdd9c7b143588acd04d3d0910371718e911e3
2,977
py
Python
amodem/sampling.py
Matthew-MK/amodem
a75dda9ab0f7445589a036357e604703ccb34726
[ "MIT" ]
766
2015-01-14T15:48:07.000Z
2022-03-30T01:19:48.000Z
amodem/sampling.py
Matthew-MK/amodem
a75dda9ab0f7445589a036357e604703ccb34726
[ "MIT" ]
42
2015-01-02T18:50:11.000Z
2022-03-11T19:10:35.000Z
amodem/sampling.py
Matthew-MK/amodem
a75dda9ab0f7445589a036357e604703ccb34726
[ "MIT" ]
116
2015-01-14T20:43:52.000Z
2022-03-24T13:10:30.000Z
import itertools import numpy as np from . import common class Interpolator: def __init__(self, resolution=1024, width=128): self.width = width self.resolution = resolution N = resolution * width u = np.arange(-N, N, dtype=float) window = np.cos(0.5 * np.pi * u / N) ** 2.0 # raised cosine h = np.sinc(u / resolution) * window self.filt = [] for index in range(resolution): # split into multiphase filters filt = h[index::resolution] filt = filt[::-1] # flip (due to convolution) self.filt.append(filt) lengths = [len(f) for f in self.filt] self.coeff_len = 2 * width assert set(lengths) == set([self.coeff_len]) # verify same lengths assert len(self.filt) == resolution defaultInterpolator = Interpolator() class Sampler: def __init__(self, src, interp=None, freq=1.0): self.freq = freq self.equalizer = lambda x: x # LTI equalization filter if interp is not None: self.interp = interp self.resolution = self.interp.resolution self.filt = self.interp.filt self.width = self.interp.width # polyphase filters are centered at (width + 1) index padding = [0.0] * self.interp.width # pad with zeroes to "simulate" regular sampling self.src = itertools.chain(padding, src) self.offset = self.interp.width + 1 # samples' buffer to be used by interpolation self.buff = np.zeros(self.interp.coeff_len) self.index = 0 self.take = self._take else: # skip interpolation (for testing) src = iter(src) self.take = lambda size: common.take(src, size) def _take(self, size): frame = np.zeros(size) count = 0 for frame_index in range(size): offset = self.offset # offset = k + (j / self.resolution) k = int(offset) # integer part j = int((offset - k) * self.resolution) # fractional part coeffs = self.filt[j] # choose correct filter phase end = k + self.width # process input until all buffer is full with samples try: while self.index < end: self.buff[:-1] = self.buff[1:] self.buff[-1] = next(self.src) # throws StopIteration self.index += 1 except StopIteration: break self.offset += self.freq # apply interpolation filter frame[frame_index] = np.dot(coeffs, self.buff) count = frame_index + 1 return self.equalizer(frame[:count]) def resample(src, dst, df=0.0): x = common.load(src) sampler = Sampler(x, Interpolator()) sampler.freq += df y = sampler.take(len(x)) dst.write(common.dumps(y))
32.010753
75
0.555929
360
2,977
4.552778
0.363889
0.042709
0.027456
0.015863
0.016473
0.016473
0
0
0
0
0
0.014308
0.342627
2,977
92
76
32.358696
0.823199
0.161572
0
0
0
0
0
0
0
0
0
0
0.030769
1
0.061538
false
0
0.046154
0
0.153846
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
0
0
0
1
0
8bd1ed48c83c831815502fd8f24e3c648f5c81ee
3,741
py
Python
libs/dungeon.py
IdeaBot/explorer
2cd02cacb2a37f3da3308e79e88f8c26f4401b8e
[ "MIT" ]
null
null
null
libs/dungeon.py
IdeaBot/explorer
2cd02cacb2a37f3da3308e79e88f8c26f4401b8e
[ "MIT" ]
null
null
null
libs/dungeon.py
IdeaBot/explorer
2cd02cacb2a37f3da3308e79e88f8c26f4401b8e
[ "MIT" ]
null
null
null
''' Dungeon object class created 2019-03-19 by NGnius ''' # import math import random DEFAULT_SIZE = 16 WIDTH = 42 ANIMATION_CHAR = '*' BLANK_CHAR = '.' PORTAL_CHAR = '0' class Dungeon(): def __init__(self, size=DEFAULT_SIZE, level=1): self.WIDTH = WIDTH self.size = size self.level = level # make board self._board = self._make_board() # list of list; size^2 self._animated_board = self._make_board() # 2 randomly placed portals self.portals = (self.find_random_location(), self.find_random_location()) def animate(self, fr, to, _char=ANIMATION_CHAR): vector = (to[0]-fr[0], to[1]-fr[1]) n = (vector[0]**2 + vector[1]**2)**(0.5) uvector = (vector[0]/n, vector[1]/n) # print(uvector, 'is your vector, Victor') for i in range(1, max(abs(vector[0]), abs(vector[1]))): self._animated_board[fr[0]+round(i*uvector[0])][fr[1]+round(i*uvector[1])] = _char self._animated_board[to[0]][to[1]] = _char # just in case it's missed by vector drawing def move_place(self, obj, coords): if self._verify_coords(coords): self._board[coords[0]][coords[1]] = obj def move_swap(self, coords1, coords2): if self._verify_coords(coords1) and self._verify_coords(coords2): self._board[coords1[0]][coords1[1]], self._board[coords2[0]][coords2[1]] = self._board[coords2[0]][coords2[1]], self._board[coords1[0]][coords1[1]] def _make_board(self, fill=None): board = list() for x in range(WIDTH): board.append(list()) for y in range(self.size): board[x].append(fill) return board def draw_board(self, blank=BLANK_CHAR): board_str = '' for y in range(self.size): row_str = '' for x in range(WIDTH): if self._animated_board[x][y] is not None: row_str += self._animated_board[x][y] self._animated_board[x][y] = None # reset animations as we go elif (x,y) in self.portals: row_str += PORTAL_CHAR elif self._board[x][y] is not None: row_str += self._board[x][y].char else: row_str += blank board_str = '\n' + row_str + board_str return board_str def do_turn(self): done_turn = list() # do move or attack for people on board for x in range(WIDTH): for y in range(self.size): person = self._board[x][y] if person is not None and person.name not in done_turn: # print('Move/Attacking', person.name) person.move_or_attack() done_turn.append(person.name) def get_person(self, coords): if coords[0] >= WIDTH or coords[1] >= self.size: return return self._board[coords[0]][coords[1]] def find_person(self, name): for x in range(WIDTH): for y in range(self.size): person = self._board[x][y] if person is not None: if person.name == name: return (x,y) def find_random_location(self): person_at = not None # legit while person_at is not None: coords = (random.randrange(0, self.size), random.randrange(0, self.size)) person_at = self.get_person(coords) return coords def _verify_coords(self, coords): if coords[0] >= WIDTH or coords[0] < 0: return False if coords[1] >= self.size or coords[1] < 0: return False return True
35.971154
159
0.555199
509
3,741
3.917485
0.208251
0.049649
0.024574
0.022066
0.282849
0.219659
0.157472
0.157472
0.125376
0.069208
0
0.027975
0.321572
3,741
103
160
36.320388
0.757683
0.083667
0
0.148148
0
0
0.001465
0
0
0
0
0
0
1
0.135802
false
0
0.012346
0
0.259259
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
0
0
0
1
0
8bd2af77c54189a911eb6a57a33e86e0c8005dbd
10,917
py
Python
scrapyproject/showingspiders/toho_v2.py
gas1121/JapanCinemaStatusSpider
67c7b963914565589f64dd1bcf18839a4160ea34
[ "MIT" ]
2
2018-06-07T13:28:03.000Z
2018-12-10T14:04:53.000Z
scrapyproject/showingspiders/toho_v2.py
gas1121/JapanCinemaStatusSpider
67c7b963914565589f64dd1bcf18839a4160ea34
[ "MIT" ]
null
null
null
scrapyproject/showingspiders/toho_v2.py
gas1121/JapanCinemaStatusSpider
67c7b963914565589f64dd1bcf18839a4160ea34
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import unicodedata import json import arrow import scrapy from scrapyproject.showingspiders.showing_spider import ShowingSpider from scrapyproject.items import (ShowingLoader, init_show_booking_loader) from scrapyproject.utils import TohoUtil class TohoV2Spider(ShowingSpider): """ Toho site spider version 2. Improve crawling speed as we grab data from json api instead of site page. useful json api: theater list: https://hlo.tohotheater.jp/responsive/json/theater_list.json?_dc=1488106193 movies showing now: https://hlo.tohotheater.jp/data_net/json/movie/TNPI3090.JSON movies coming soon: https://hlo.tohotheater.jp/data_net/json/movie/TNPI3080.JSON time schedule table: https://hlo.tohotheater.jp/net/schedule/TNPI3070J02.do? __type__=json&movie_cd=014174&vg_cd=028&term=99&seq_disp_term=7 &site_cd=&enter_kbn=&_dc=1488106557 detail schedule table for movie: https://hlo.tohotheater.jp/net/schedule/TNPI3070J01.do? __type__=json&movie_cd=014174&vg_cd=028&show_day=20170226 &term=99&isMember=&site_cd=028&enter_kbn=&_dc=1488106558 cinema schedult table: https://hlo.tohotheater.jp/net/schedule/TNPI3050J02.do? __type__=html&__useResultInfo__=no&vg_cd=076&show_day=20170226 &term=99&isMember=&enter_kbn=&_dc=1488120297 Visit page example: https://www.tohotheater.jp/theater/find.html https://hlo.tohotheater.jp/net/movie/TNPI3090J01.do https://hlo.tohotheater.jp/net/movie/TNPI3060J01.do?sakuhin_cd=014174 https://hlo.tohotheater.jp/net/ticket/034/TNPI2040J03.do We will first crawl cinema list, then crawl each cinema's schedule data, and generate booking page urls to crawl exact booking number """ name = "toho_v2" allowed_domains = ["hlo.tohotheater.jp", "www.tohotheater.jp"] start_urls = [ 'https://hlo.tohotheater.jp/responsive/json/theater_list.json' ] def parse(self, response): """ crawl theater list data first """ try: theater_list = json.loads(response.text) except json.JSONDecodeError: return if (not theater_list): return for curr_cinema in theater_list: cinema_name_list = self.get_cinema_name_list(curr_cinema) if not self.is_cinema_crawl(cinema_name_list): continue site_cd = curr_cinema['VIT_GROUP_CD'] show_day = self.date curr_cinema_url = self.generate_cinema_schedule_url( site_cd, show_day) request = scrapy.Request(curr_cinema_url, callback=self.parse_cinema) yield request def get_cinema_name_list(self, curr_cinema): # replace full width text before compare vit_group_nm = unicodedata.normalize('NFKC', curr_cinema['VIT_GROUP_NM']) theater_name = unicodedata.normalize('NFKC', curr_cinema['THEATER_NAME']) theater_name_english = unicodedata.normalize( 'NFKC', curr_cinema['THEATER_NAME_ENGLISH']) site_name = unicodedata.normalize('NFKC', curr_cinema['SITE_NM']) return [vit_group_nm, theater_name, theater_name_english, site_name] def generate_cinema_schedule_url(self, site_cd, show_day): """ json data url for single cinema, all movies of curr cinema """ url = 'https://hlo.tohotheater.jp/net/schedule/TNPI3050J02.do?'\ '__type__=html&__useResultInfo__=no'\ '&vg_cd={site_cd}&show_day={show_day}&term=99'.format( site_cd=site_cd, show_day=show_day) return url def parse_cinema(self, response): # some cinemas may not open and will return empty response try: schedule_data = json.loads(response.text) except json.JSONDecodeError: return if (not schedule_data): return result_list = [] for curr_cinema in schedule_data: showing_url_parameter = {} date_str = curr_cinema['showDay']['date'] showing_url_parameter['show_day'] = arrow.get( date_str, 'YYYYMMDD').replace(tzinfo='UTC+9') for sub_cinema in curr_cinema['list']: self.parse_sub_cinema( response, sub_cinema, showing_url_parameter, result_list) for result in result_list: if result: yield result def parse_sub_cinema(self, response, sub_cinema, showing_url_parameter, result_list): site_cd = sub_cinema['code'] showing_url_parameter['site_cd'] = site_cd data_proto = ShowingLoader(response=response) data_proto.add_cinema_name(sub_cinema['name']) cinema_site = TohoUtil.generate_cinema_homepage_url(site_cd) data_proto.add_cinema_site(cinema_site, sub_cinema['name']) data_proto.add_value('source', self.name) for curr_movie in sub_cinema['list']: self.parse_movie(response, curr_movie, showing_url_parameter, data_proto, result_list) def parse_movie(self, response, curr_movie, showing_url_parameter, data_proto, result_list): """ parse movie showing data movie may have different versions """ movie_data_proto = ShowingLoader(response=response) movie_data_proto.add_value(None, data_proto.load_item()) movie_data_proto.add_title( title=curr_movie['name'], title_en=curr_movie['ename']) title_list = movie_data_proto.get_title_list() if not self.is_movie_crawl(title_list): return showing_url_parameter['movie_cd'] = curr_movie['code'] for curr_screen in curr_movie['list']: self.parse_screen(response, curr_screen, showing_url_parameter, movie_data_proto, result_list) def parse_screen(self, response, curr_screen, showing_url_parameter, data_proto, result_list): showing_url_parameter['theater_cd'] = curr_screen['theaterCd'] showing_url_parameter['screen_cd'] = curr_screen['code'] screen_data_proto = ShowingLoader(response=response) screen_data_proto.add_value(None, data_proto.load_item()) screen_data_proto.add_screen_name(curr_screen['ename']) for curr_showing in curr_screen['list']: # filter empty showing if not curr_showing['unsoldSeatInfo']: continue self.parse_showing(response, curr_showing, showing_url_parameter, screen_data_proto, result_list) def parse_showing(self, response, curr_showing, showing_url_parameter, data_proto, result_list): def parse_time(time_str): """ ex. "24:40" """ time = time_str.split(":") return (int(time[0]), int(time[1])) showing_url_parameter['showing_cd'] = curr_showing['code'] showing_data_proto = ShowingLoader(response=response) showing_data_proto.add_value(None, data_proto.load_item()) # time like 24:40 can not be directly parsed, # so we need to shift time properly start_hour, start_minute = parse_time(curr_showing['showingStart']) showing_data_proto.add_value('start_time', self.get_time_from_text( start_hour, start_minute)) end_hour, end_minute = parse_time(curr_showing['showingEnd']) showing_data_proto.add_value('end_time', self.get_time_from_text( end_hour, end_minute)) showing_data_proto.add_value('seat_type', 'NormalSeat') # query screen number from database showing_data_proto.add_total_seat_count() # check whether need to continue crawl booking data or stop now if not self.crawl_booking_data: result_list.append(showing_data_proto.load_item()) return booking_data_proto = init_show_booking_loader(response=response) booking_data_proto.add_value('showing', showing_data_proto.load_item()) book_status = curr_showing['unsoldSeatInfo']['unsoldSeatStatus'] booking_data_proto.add_book_status(book_status, util=TohoUtil) book_status = booking_data_proto.get_output_value('book_status') if book_status in ['SoldOut', 'NotSold']: # sold out or not sold total_seat_count = showing_data_proto.get_output_value( 'total_seat_count') book_seat_count = ( total_seat_count if book_status == 'SoldOut' else 0) booking_data_proto.add_value('book_seat_count', book_seat_count) booking_data_proto.add_time_data() result_list.append(booking_data_proto.load_item()) return else: # normal, need to crawl book number on order page url = self.generate_showing_url(**showing_url_parameter) request = scrapy.Request(url, callback=self.parse_normal_showing) request.meta["data_proto"] = booking_data_proto.load_item() result_list.append(request) def generate_showing_url(self, site_cd, show_day, theater_cd, screen_cd, movie_cd, showing_cd): """ generate showing url from given data :param show_day: arrow object """ # example: javascript:ScheduleUtils.purchaseTicket( # "20170212", "076", "013132", "0761", "11", "2") # example: https://hlo.tohotheater.jp/net/ticket/076/TNPI2040J03.do # ?site_cd=076&jyoei_date=20170209&gekijyo_cd=0761&screen_cd=10 # &sakuhin_cd=014183&pf_no=5&fnc=1&pageid=2000J01&enter_kbn= day_str = show_day.format('YYYYMMDD') return "https://hlo.tohotheater.jp/net/ticket/{site_cd}/"\ "TNPI2040J03.do?site_cd={site_cd}&jyoei_date={jyoei_date}"\ "&gekijyo_cd={gekijyo_cd}&screen_cd={screen_cd}"\ "&sakuhin_cd={sakuhin_cd}&pf_no={pf_no}&fnc={fnc}"\ "&pageid={pageid}&enter_kbn={enter_kbn}".format( site_cd=site_cd, jyoei_date=day_str, gekijyo_cd=theater_cd, screen_cd=screen_cd, sakuhin_cd=movie_cd, pf_no=showing_cd, fnc="1", pageid="2000J01", enter_kbn="") def parse_normal_showing(self, response): booked_seat_count = len(response.css('[alt~="購入済(選択不可)"]')) result = init_show_booking_loader( response=response, item=response.meta["data_proto"]) result.add_value('book_seat_count', booked_seat_count) result.add_time_data() yield result.load_item()
45.298755
79
0.646973
1,348
10,917
4.909496
0.191395
0.053037
0.045935
0.041251
0.381233
0.275914
0.170444
0.130251
0.105168
0.055606
0
0.02972
0.257214
10,917
240
80
45.4875
0.78641
0.203169
0
0.1
0
0
0.111494
0.031584
0
0
0
0
0
1
0.06875
false
0
0.04375
0
0.20625
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
0
0
0
1
0
8bd49f53da7caa09d61a988bf0e05ae48ef80b17
947
py
Python
tasks.py
ggrbill/fortran-examples
a790462fa3956a65505d4f529556f81cd5b0de95
[ "MIT" ]
null
null
null
tasks.py
ggrbill/fortran-examples
a790462fa3956a65505d4f529556f81cd5b0de95
[ "MIT" ]
null
null
null
tasks.py
ggrbill/fortran-examples
a790462fa3956a65505d4f529556f81cd5b0de95
[ "MIT" ]
null
null
null
from invoke import task @task() def clean(ctx): """ Delete 'build' folder. """ print("Cleaning!") ctx.run("rm -Rf build") @task( help = { 'cclean': "Call Clean task (Delete 'build' folder) before build again." } ) def build(ctx, cclean=False): """ Build Fortran95 code. """ if cclean: clean(ctx) print("Building!") commands = [ 'mkdir build', 'cd build', 'f95 -c ../src/vector_math.f95 ../src/hello.f95', 'f95 hello.o vector_math.o -o hello', ] ctx.run(' && '.join(commands)) @task( help = { 'cclean': "Call Clean task (Delete 'build' folder) before build again." } ) def build_fc(ctx, cclean=False): """ Build C code that calls a Fortran95 module. """ if cclean: clean(ctx) print("Building!") commands = [ 'mkdir build', 'cd build', 'gcc -c ../src/callfortran.c', 'f95 callfortran.o ../src/modulefort.f95', ] ctx.run(' && '.join(commands))
18.211538
74
0.583949
122
947
4.508197
0.360656
0.043636
0.092727
0.065455
0.443636
0.443636
0.443636
0.443636
0.443636
0.443636
0
0.022008
0.232313
947
52
75
18.211538
0.734525
0.092925
0
0.540541
0
0
0.462228
0.055058
0
0
0
0
0
1
0.081081
false
0
0.027027
0
0.108108
0.081081
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bd769344a472b553f48b5163b0040a5e6c76aa3
4,313
py
Python
src/advent/year2019/intcode.py
davidism/advent
761756f179c3547f44ec035880f29f58d80903f8
[ "BSD-3-Clause" ]
5
2019-12-09T06:02:22.000Z
2021-12-03T18:02:49.000Z
src/advent/year2019/intcode.py
davidism/advent
761756f179c3547f44ec035880f29f58d80903f8
[ "BSD-3-Clause" ]
null
null
null
src/advent/year2019/intcode.py
davidism/advent
761756f179c3547f44ec035880f29f58d80903f8
[ "BSD-3-Clause" ]
2
2019-09-19T04:44:33.000Z
2021-05-09T14:39:58.000Z
from collections import defaultdict from collections import deque from typing import Deque from typing import Dict from typing import Iterable from typing import List from advent.load import read_input def op(code: int, size: int, write=False): def wrapper(f): f.op = code f.size = size f.write = size - 1 if write else -1 return f return wrapper def find_ops(cls): for key, value in vars(cls).items(): if key.startswith("op_"): cls._op_to_name[value.op] = key return cls @find_ops class Interpreter: _op_to_name: Dict[int, str] = {} def __init__(self, data: List[int], input=None, output=None): self.data = defaultdict(int, enumerate(data)) self.pos = 0 self.ops = {k: getattr(self, v) for k, v in self._op_to_name.items()} self.input = prepare_io(input) self.output = prepare_io(output, output=True) self.halted = False self.rel = 0 def __getitem__(self, item: int) -> int: return self.data[item] def __setitem__(self, item: int, value: int): self.data[item] = value def run(self): if self.halted: return False while True: modes, op = divmod(self.data[self.pos], 100) self.pos += 1 op = self.ops[op] args = [self.data[self.pos + i] for i in range(op.size)] self.pos += op.size for i, arg in enumerate(args): modes, mode = divmod(modes, 10) if mode == 0: if i != op.write: args[i] = self.data[arg] if mode == 2: if i == op.write: args[i] = self.rel + arg else: args[i] = self.data[self.rel + arg] try: op(*args) except HaltExecution: self.halted = True break except WaitInput: self.pos -= 1 + op.size break return True @op(99, 0) def op_halt(self): raise HaltExecution @op(1, 3, True) def op_add(self, a, b, dest): self.data[dest] = a + b @op(2, 3, True) def op_mul(self, a, b, dest): self.data[dest] = a * b @op(3, 1, True) def op_read(self, dest): try: value = self.input.popleft() except IndexError: raise WaitInput from None self.data[dest] = value @op(4, 1) def op_write(self, value): self.output.append(value) @op(5, 2) def op_jnz(self, test, goto): if test: self.pos = goto @op(6, 2) def op_jz(self, test, goto): if not test: self.pos = goto @op(7, 3, True) def op_lt(self, a, b, dest): self.data[dest] = int(a < b) @op(8, 3, True) def op_eq(self, a, b, dest): self.data[dest] = int(a == b) @op(9, 1) def op_rel(self, delta): self.rel += delta class InterpreterGroup: def __init__(self): self.group: List[Interpreter] = [] @property def output(self) -> deque: return self.group[-1].output def attach(self, interpreter: Interpreter): if not self.group: self.group.append(interpreter) else: self.output.extendleft(reversed(interpreter.input)) interpreter.input = self.output self.group.append(interpreter) def feedback(self): self.output.extend(self.group[0].input) self.group[0].input = self.output def run(self): while True: for interpreter in self.group: interpreter.run() if any(interpreter.halted for interpreter in self.group): break def prepare_io(value: Iterable[int] = None, output=False) -> Deque[int]: if value is None: return deque() if not ( hasattr(value, "append" if output else "popleft") or isinstance(value, deque) ): return deque(value) return value class HaltExecution(Exception): pass class WaitInput(Exception): pass def read_intcode(name=None) -> List[int]: return [int(x) for x in read_input(name, 2).split(",")]
23.828729
85
0.537909
566
4,313
4.021201
0.213781
0.045694
0.019772
0.017575
0.137961
0.065026
0.065026
0.04833
0.04833
0.04833
0
0.013518
0.348249
4,313
180
86
23.961111
0.796158
0
0
0.126866
0
0
0.003942
0
0
0
0
0
0
1
0.179104
false
0.014925
0.052239
0.022388
0.350746
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
0
0
0
1
0
8bdc456df221aa9aaf1072900c707aafc646d202
3,123
py
Python
scripts/find_best_fit.py
NERC-CEH/nanofase-calibration
e45da5f0566e345504214018eb4b9c013bab4c57
[ "BSD-3-Clause" ]
null
null
null
scripts/find_best_fit.py
NERC-CEH/nanofase-calibration
e45da5f0566e345504214018eb4b9c013bab4c57
[ "BSD-3-Clause" ]
null
null
null
scripts/find_best_fit.py
NERC-CEH/nanofase-calibration
e45da5f0566e345504214018eb4b9c013bab4c57
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python3 import os import sys import argparse import re import shutil import numpy as np from netCDF4 import Dataset """This script is useful for finding the best find from the `optimize.log` file, the getting the parameters for this fit from logged results""" # Parse the input arguments parser = argparse.ArgumentParser(description='Find the best parameters so find') parser.add_argument('--caldir', '-c', help='path to the calibration directory', default='./') parser.add_argument('--yearrange', '-yr', nargs=2, type=int, help='year range to run calibration for (inclusive)') parser.set_defaults(yearrange=[2009,2012]) args = parser.parse_args() cal_dir = args.caldir year_range = range(args.yearrange[0], args.yearrange[1]+1) # Open the optimize.log file and find the best fit by plucking the cost and run ID # from each line that begins with 'C' (Cost for...) with open(os.path.join(cal_dir, 'optimize.log')) as f: costs = [] ids = [] for line in f: if line[0] == 'C': split = re.split('Cost for |\: ', line) ids.append(split[1]) costs.append(float(split[2])) # Print the minimum cost and the corresponding run ID costs = np.array(costs) run_id = ids[costs.argmin()] print(f'Minimum cost: {costs.min()}') print(f'For run ID: {run_id}') # Now get the parameters that produced that cost params_f = np.load(os.path.join(cal_dir, 'results', f'{run_id}.npz')) params = params_f['params'] # Finally, we can recreate the NetCDF files used for this run param_names = ['resuspension_alpha', 'resuspension_beta', 'sediment_transport_a', 'sediment_transport_c', 'deposition_alpha', 'deposition_beta', 'bank_erosion_alpha', 'bank_erosion_beta'] # Get the template for the 2D array nc_subcatchment = Dataset(os.path.join(cal_dir, 'data', f'{args.yearrange[0]}_no-emissions.nc'), 'r') var = nc_subcatchment['flow_dir'][:,:] catchment_mask = var.mask catchment_shape = var.shape n_cells = var.count() # Make a copy of the template NetCDFs to add this iteration's params to for year in year_range: dst_path = os.path.join(cal_dir, f'data_cache/{year}_no-emissions_{run_id}.nc') shutil.copy(os.path.join(cal_dir, f'data/{year}_no-emissions.nc'), dst_path) # Pull out the 1D arrays for each parameter from the params variable, then # reshape to the correct grid shape and mask and add to NetCDF file for i, param in enumerate(param_names): param_1d = params[n_cells*i:n_cells*i+n_cells] param_2d = np.ma.masked_array(np.empty(catchment_shape), mask=catchment_mask) # Reshape into 2D arrays, taking into account the mask j = 0 for i, _ in np.ndenumerate(param_2d): if ~catchment_mask[i]: param_2d[i] = param_1d[j] j = j + 1 # Now add this variable to the NetCDF file, placing a copy in the cache for year in year_range: # Then create the new variables nc = Dataset(os.path.join(cal_dir, f'data_cache/{year}_no-emissions_{run_id}.nc'), 'r+') var = nc.createVariable(param, datatype=float, dimensions=('y','x')) var[:] = param_2d nc.close()
42.780822
114
0.700288
499
3,123
4.252505
0.346693
0.01885
0.028275
0.036758
0.110745
0.069274
0.055137
0.04524
0.04524
0.04524
0
0.011249
0.174512
3,123
72
115
43.375
0.81187
0.23471
0
0.039216
0
0
0.240931
0.065383
0
0
0
0
0
1
0
false
0
0.137255
0
0.137255
0.039216
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bde4876eb8d22e2a2bf6ea4f21056c49d4893b8
347
py
Python
examples/simple1.py
jimcortez/spotipy_twisted
49ff2a4a5a5a9b3184b22adbe068eb91a38f3102
[ "MIT" ]
null
null
null
examples/simple1.py
jimcortez/spotipy_twisted
49ff2a4a5a5a9b3184b22adbe068eb91a38f3102
[ "MIT" ]
null
null
null
examples/simple1.py
jimcortez/spotipy_twisted
49ff2a4a5a5a9b3184b22adbe068eb91a38f3102
[ "MIT" ]
null
null
null
import spotipy_twisted birdy_uri = 'spotify:artist:2WX2uTcsvV5OnS0inACecP' spotify = spotipy_twisted.Spotify() results = spotify.artist_albums(birdy_uri, album_type='album') albums = results['items'] while results['next']: results = spotify.next(results) albums.extend(results['items']) for album in albums: print(album['name'])
20.411765
62
0.743516
42
347
6
0.47619
0.111111
0
0
0
0
0
0
0
0
0
0.013201
0.126801
347
16
63
21.6875
0.818482
0
0
0
0
0
0.17341
0.106936
0
0
0
0
0
1
0
false
0
0.1
0
0.1
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bdf0a8fc72d26035fdc4522645b4d01820727b6
4,905
py
Python
arrows/pytorch/seg_utils.py
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
arrows/pytorch/seg_utils.py
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
arrows/pytorch/seg_utils.py
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
# ckwg +28 # Copyright 2018 by Kitware, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither name of Kitware, Inc. nor the names of any contributors may be used # to endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import division from __future__ import print_function from __future__ import absolute_import import six import warnings import numpy as np import torch try: import cv2 except ImportError: cv2 = None def bitget(byteval, idx): return ((byteval & (1 << idx)) != 0) def label_colormap(N=256): cmap = np.zeros((N, 3)) for i in six.moves.range(0, N): id = i r, g, b = 0, 0, 0 for j in six.moves.range(0, 8): r = np.bitwise_or(r, (bitget(id, 0) << 7 - j)) g = np.bitwise_or(g, (bitget(id, 1) << 7 - j)) b = np.bitwise_or(b, (bitget(id, 2) << 7 - j)) id = (id >> 3) cmap[i, 0] = r cmap[i, 1] = g cmap[i, 2] = b cmap = cmap.astype(np.float32) / 255 cmap = (cmap * 255).astype(np.uint8) return cmap def label2rgb(lbl, img=None, label_names=None, n_labels=None, alpha=0.3, thresh_suppress=0): import skimage.color if label_names is None: if n_labels is None: n_labels = lbl.max() + 1 # +1 for bg_label 0 else: if n_labels is None: n_labels = len(label_names) else: assert n_labels == len(label_names) cmap = label_colormap(n_labels) lbl_viz = cmap[lbl] lbl_viz[lbl == -1] = (0, 0, 0) # unlabeled if img is not None: img_gray = skimage.color.rgb2gray(img) img_gray = skimage.color.gray2rgb(img_gray) img_gray *= 255 lbl_viz = alpha * lbl_viz + (1 - alpha) * img_gray lbl_viz = lbl_viz.astype(np.uint8) if label_names is None: return lbl_viz # cv2 is required only if label_names is not None import cv2 if cv2 is None: warnings.warn('label2rgb with label_names requires OpenCV (cv2), ' 'so ignoring label_names values.') return lbl_viz np.random.seed(1234) for label in np.unique(lbl): if label == -1: continue # unlabeled mask = lbl.squeeze() == label if 1. * mask.sum() / mask.size < thresh_suppress: continue mask = (mask * 255).astype(np.uint8) import scipy.ndimage y, x = scipy.ndimage.center_of_mass(mask) y, x = map(int, [y, x]) if lbl.squeeze()[y, x] != label: Y, X = np.where(mask) point_index = np.random.randint(0, len(Y)) y, x = Y[point_index], X[point_index] text = label_names[label] font_face = cv2.FONT_HERSHEY_SIMPLEX font_scale = 0.7 thickness = 2 text_size, baseline = cv2.getTextSize( text, font_face, font_scale, thickness) def get_text_color(color): if color[0] * 0.299 + color[1] * 0.587 + color[2] * 0.114 > 170: return (0, 0, 0) return (255, 255, 255) color = get_text_color(lbl_viz[0, 0, y, x]) cv2.putText(lbl_viz[0, 0, :, :], text, (x - text_size[0] // 2, y), font_face, font_scale, color, thickness) return lbl_viz def transform(img): mean_bgr = np.array([104.00698793, 116.66876762, 122.67891434]) img = img[:, :, ::-1] # RGB -> BGR img = img.astype(np.float64) img -= mean_bgr img = img.transpose(2, 0, 1) img = torch.from_numpy(img).float() return img
33.367347
80
0.626504
711
4,905
4.21519
0.345992
0.022022
0.016016
0.014014
0.109776
0.06006
0.06006
0.045379
0.045379
0.045379
0
0.043307
0.275025
4,905
146
81
33.59589
0.799494
0.321916
0
0.138298
0
0
0.024605
0
0
0
0
0
0.010638
1
0.053191
false
0
0.12766
0.010638
0.265957
0.010638
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8bdf61ec1b8d8328f9ce10467e5dc4c43240c500
6,421
py
Python
fdtd/2d/src/fdtd/solver.py
Elena-Torres-Lozano/MCFNL2021
b60ecda2dc35fe08ce6cf131c45acc0349dce29c
[ "BSD-3-Clause" ]
null
null
null
fdtd/2d/src/fdtd/solver.py
Elena-Torres-Lozano/MCFNL2021
b60ecda2dc35fe08ce6cf131c45acc0349dce29c
[ "BSD-3-Clause" ]
null
null
null
fdtd/2d/src/fdtd/solver.py
Elena-Torres-Lozano/MCFNL2021
b60ecda2dc35fe08ce6cf131c45acc0349dce29c
[ "BSD-3-Clause" ]
null
null
null
import math import numpy as np import scipy.constants as sp import copy import time X = 0 # Cartesian indices Y = 1 L = 0 # Lower U = 1 # Upper def gaussian(x, delay, spread): return np.exp( - ((x-delay)**2 / (2*spread**2)) ) def subsId(id): if id is None: return -1 else: return id-1 class Solver: class Fields: def __init__(self, ex, ey, hz): self.ex = ex self.ey = ey self.hz = hz def get(self): return (self.ex, self.ey, self.hz) __timeStepPrint = 5000 def __init__(self, mesh, options, probes, sources): self.options = options self._mesh = copy.deepcopy(mesh) self._probes = copy.deepcopy(probes) for p in self._probes: box = self._mesh.elemIdToBox(p["elemId"]) box = self._mesh.snap(box) ids = self._mesh.toIdx(box) Nxy = abs(ids[Y] - ids[X]) p["mesh"] = {"origin": box[L], "steps": abs(box[U]-box[L]) / Nxy} p["indices"] = ids p["time"] = [0.0] p["values"] = [np.zeros((Nxy[X], Nxy[Y]))] # for initial in self._initialCond: # if initial["type"] == "gaussian": # position=self._mesh.pos # values=Solver.movingGaussian(position, 0, \ # sp.speed_of_light,initial["peakPosition"],\ # initial["gaussianAmplitude"], \ # initial["gaussianSpread"] ) # p["values"]= [values[ids[0]:ids[1]]] # else: # raise ValueError(\ # "Invalid initial condition type: " + initial["type"] ) self._sources = copy.deepcopy(sources) for source in self._sources: box = self._mesh.elemIdToBox(source["elemId"]) ids = mesh.toIdx(box) source["index"] = ids self.old = self.Fields( ex = np.zeros( (mesh.pos[X].size-1, mesh.pos[Y].size ) ), ey = np.zeros( (mesh.pos[X].size, mesh.pos[Y].size-1) ), hz = np.zeros( (mesh.pos[X].size-1, mesh.pos[Y].size-1) ) ) def _dt(self): return self.options["cfl"] * min(self._mesh.steps()) / math.sqrt(2.0) def timeStep(self): return self._dt() / sp.speed_of_light def getProbes(self): res = self._probes return res # ======================= UPDATE E ============================= def _updateE(self, t, dt, overFields = None): eNew = (np.zeros( self.old.ex.shape ), np.zeros( self.old.ey.shape ) ) (ex, ey, h) = self.old.get() e = (ex, ey) (dX, dY) = self._mesh.steps() A = dX * dY eNew[X][:,1:-1] = e[X][:,1:-1] + dt/A*dX * (h[:,1:] - h[:,:-1]) eNew[Y][1:-1,:] = e[Y][1:-1,:] - dt/A*dY * (h[1:,:] - h[:-1,:]) # Boundary conditions for bound in self._mesh.bounds: xy = bound.orientation() (lx, ux) = (bound.arrayIdx(L,X), \ bound.arrayIdx(U,X)) (ly, uy) = (bound.arrayIdx(L,Y), \ bound.arrayIdx(U,Y)) if isinstance(bound, self._mesh.BoundPEC): eNew[xy][lx:ux,ly:uy] = 0.0 else: raise ValueError("Unrecognized boundary type") # Subgridding and updating e[X][:] = eNew[X][:] e[Y][:] = eNew[Y][:] # ======================= UPDATE H ============================= def _updateH(self, t, dt): hNew = np.zeros( self.old.hz.shape ) (ex, ey, h) = self.old.get() (dX, dY) = self._mesh.steps() A = dX * dY hNew[:,:] = h[:,:] \ - dt/A * dY * ey[1:, :] \ + dt/A * dX * ex[ :, 1:] \ + dt/A * dY * ey[:-1, :] \ - dt/A * dX * ex[ :, :-1] # Source terms for source in self._sources: if source["type"] == "dipole": magnitude = source["magnitude"] if magnitude["type"] == "gaussian": c0 = sp.speed_of_light delay = c0 * magnitude["gaussianDelay"] spread = c0 * magnitude["gaussianSpread"] id = source["index"] hNew[id[L][X]:id[U][X], id[L][Y]:id[U][Y]] += \ gaussian(t, delay, spread)*dt else: raise ValueError(\ "Invalid source magnitude type: " + magnitude["type"]) else: raise ValueError("Invalid source type: " + source["type"]) h[:] = hNew[:] def _updateProbes(self, t): for p in self._probes: dimensionalTime = t/sp.speed_of_light writeStep = "samplingPeriod" in p \ and (dimensionalTime/p["samplingPeriod"] >= len(p["time"])) writeStep = writeStep or "samplingPeriod" not in p if writeStep: p["time"].append(dimensionalTime) idx = p["indices"] values = np.zeros(tuple(idx[U]-idx[L])) values[:,:] = \ self.old.hz[ idx[L][X]:idx[U][X], idx[L][Y]:idx[U][Y] ] p["values"].append(values) def solve(self, dimensionalFinalTime): tic = time.time() t = 0.0 dt = self._dt() numberOfTimeSteps = \ int(dimensionalFinalTime * sp.speed_of_light / dt) for n in range(numberOfTimeSteps): self._updateE(t, dt, self.old) t += dt/2.0 self._updateH(t, dt) t += dt/2.0 self._updateProbes(t) if n % self.__timeStepPrint == 0 or n+1 == numberOfTimeSteps: remaining = (time.time() - tic) * \ (numberOfTimeSteps-n) / (n+1) min = math.floor(remaining / 60.0) sec = remaining % 60.0 print(" Step: %6d of %6d. Remaining: %2.0f:%02.0f"% (n, \ numberOfTimeSteps-1, min, sec)) print(" CPU Time: %f [s]" % (time.time() - tic)) @staticmethod def movingGaussian(x,y,t,c,center,A,spread): return A*np.exp(-(((x-center)-c*t)**2 /(2*spread**2)))
33.973545
79
0.454914
741
6,421
3.874494
0.213225
0.033438
0.015674
0.024382
0.129223
0.069314
0.062696
0.048764
0.033438
0.033438
0
0.017719
0.375954
6,421
189
80
33.973545
0.698777
0.102165
0
0.116788
0
0
0.057257
0
0
0
0
0
0
1
0.094891
false
0
0.036496
0.036496
0.211679
0.014599
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be140e08c2dfb6a0ad53e343aaf11199164a255
487
py
Python
secret.py
yoyu777/Poll-Bot
db239b42c5c5e1af38a7c0a12b977c38949f0724
[ "MIT" ]
null
null
null
secret.py
yoyu777/Poll-Bot
db239b42c5c5e1af38a7c0a12b977c38949f0724
[ "MIT" ]
null
null
null
secret.py
yoyu777/Poll-Bot
db239b42c5c5e1af38a7c0a12b977c38949f0724
[ "MIT" ]
null
null
null
# Import the Secret Manager client library. from google.cloud import secretmanager # Create the Secret Manager client. secretmanager_client = secretmanager.SecretManagerServiceClient() def get_discord_token(project_id,secret_id): latest_secret_version=secretmanager_client.access_secret_version( name=f'projects/{project_id}/secrets/{secret_id}/versions/latest' ) discord_bot_token = latest_secret_version.payload.data.decode("UTF-8") return discord_bot_token
34.785714
74
0.804928
61
487
6.131148
0.540984
0.104278
0.085562
0.117647
0
0
0
0
0
0
0
0.002326
0.117043
487
14
75
34.785714
0.867442
0.154004
0
0
0
0
0.15122
0.139024
0
0
0
0
0
1
0.125
false
0
0.125
0
0.375
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be594b734f337508a46bc13ebf1d32d3f8e6f53
1,663
py
Python
Bot/extensions/moderation/ban.py
ChrissisCodeXD/Hikari-TestProject
236c8fc9081172d9edff6d629e5d11c5abe64205
[ "MIT" ]
null
null
null
Bot/extensions/moderation/ban.py
ChrissisCodeXD/Hikari-TestProject
236c8fc9081172d9edff6d629e5d11c5abe64205
[ "MIT" ]
null
null
null
Bot/extensions/moderation/ban.py
ChrissisCodeXD/Hikari-TestProject
236c8fc9081172d9edff6d629e5d11c5abe64205
[ "MIT" ]
null
null
null
from imports import * ban_plugin = lightbulb.Plugin("moderation.ban") ban_plugin.add_checks( lightbulb.checks.guild_only, lightbulb.checks.bot_has_guild_permissions(hikari.Permissions.BAN_MEMBERS), lightbulb.checks.has_guild_permissions(hikari.Permissions.BAN_MEMBERS), ) @ban_plugin.command() @lightbulb.check_exempt(utils.mod_check) @lightbulb.option("reason", "The Reason for kicking the Member", str, required=False) @lightbulb.option("member", "Kicks the given Member", hikari.Member, required=True) @lightbulb.command("ban", "Kicks the given Member") @lightbulb.implements(lightbulb.UserCommand, lightbulb.SlashCommand, lightbulb.PrefixCommand, lightbulb.MessageCommand) async def ban(ctx: lightbulb.Context) -> None: if type(ctx) == lightbulb.context.UserContext: user = ctx.options.target elif type(ctx) == lightbulb.context.MessageContext: user = ctx.options.target.author else: user = ctx.options.member flags = [] if ctx.interaction: flags.append(hikari.MessageFlag.EPHEMERAL) res = ctx.options.reason or f"'No Reason Provided.' By {ctx.author}" await ban_member(user, ctx.get_guild(), res) if not flags: await ctx.respond(f"Banning **{user}**") if not flags: await ctx.edit_last_response(f"Succesfully banned `{user}` for `{res}`!") else: await ctx.respond(f"Succesfully banned `{user}` for `{res}`!", flags=flags[0]) async def ban_member(user, guild, res): await ban_plugin.bot.rest.ban_member(user=user, guild=guild, reason=res) def load(bot): bot.add_plugin(ban_plugin) def unload(bot): bot.remove_plugin(ban_plugin)
33.938776
119
0.719784
219
1,663
5.351598
0.360731
0.046075
0.048635
0.042662
0.156997
0.12628
0.078498
0
0
0
0
0.000708
0.150932
1,663
48
120
34.645833
0.82932
0
0
0.108108
0
0
0.144919
0
0
0
0
0
0
1
0.054054
false
0
0.027027
0
0.081081
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
0
0
0
1
0
8be760a4114acf5a4db49d05c1ef322eef5d00e1
1,779
py
Python
leetcode/easy/compare-version-numbers.py
rainzhop/cumulus-tank
09ebc7858ea53630e30606945adfea856a80faa3
[ "MIT" ]
null
null
null
leetcode/easy/compare-version-numbers.py
rainzhop/cumulus-tank
09ebc7858ea53630e30606945adfea856a80faa3
[ "MIT" ]
null
null
null
leetcode/easy/compare-version-numbers.py
rainzhop/cumulus-tank
09ebc7858ea53630e30606945adfea856a80faa3
[ "MIT" ]
null
null
null
# https://leetcode.com/problems/compare-version-numbers/ # # Compare two version numbers version1 and version2. # If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0. # # You may assume that the version strings are non-empty and contain only digits and the . character. # The . character does not represent a decimal point and is used to separate number sequences. # For instance, 2.5 is not "two and a half" or "half way to version three", # it is the fifth second-level revision of the second first-level revision. # # Here is an example of version numbers ordering: # 0.1 < 1.1 < 1.2 < 13.37 # # Credits: # Special thanks to @ts for adding this problem and creating all test cases. class Solution(object): def compareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ for d in version1.spilt('.'): d = d.lstrip('0') if d == "": d = "0" v1.append(eval(d)) for d in version2.spilt('.'): d = d.lstrip('0') if d == "": d = "0" v2.append(eval(d)) v1Len = len(v1) v2Len = len(v2) for i in xrange(min(v1Len, v2Len)): d1 = v1[i] d2 = v2[i] if d1 < d2: return -1 elif d1 > d2: return 1 if v1Len < v2Len: for d in v2[v1Len:]: if d != 0: break else: return 0 return -1 elif v1Len > v2Len: for d in v1[v2Len:]: if d != 0: break else: return 0 return 1 else: return 0
30.152542
100
0.518269
234
1,779
3.940171
0.435897
0.045553
0.02603
0.052061
0.18872
0.099783
0.099783
0.099783
0.099783
0
0
0.058394
0.383924
1,779
58
101
30.672414
0.782847
0.416526
0
0.514286
0
0
0.006098
0
0
0
0
0
0
1
0.028571
false
0
0
0
0.257143
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
0
0
0
1
0
8be7873229c136c3351120aeb123d5e799820294
710
py
Python
utils.py
florenthemmi/ips-by-country
2f63ec2108ceaae97221de52654753c545733d84
[ "MIT" ]
1
2021-05-24T06:16:49.000Z
2021-05-24T06:16:49.000Z
utils.py
florenthemmi/ips-by-country
2f63ec2108ceaae97221de52654753c545733d84
[ "MIT" ]
null
null
null
utils.py
florenthemmi/ips-by-country
2f63ec2108ceaae97221de52654753c545733d84
[ "MIT" ]
null
null
null
from datetime import datetime from config import CIDR_MAX_SUBNETS class IPRange(object): def __init__(self, data): self.range_start = data[0] self.range_end = data[1] self.total_ips = int(data[2]) self.assign_date = datetime.strptime(data[3], '%d/%m/%y') self.owner = data[4] self.cidr = IPRange.get_cidr(self.range_start, self.total_ips) @staticmethod def get_cidr(range_start, total_ips): mask = CIDR_MAX_SUBNETS.get(total_ips, None) if not mask: return None return '{}/{}'.format(range_start, CIDR_MAX_SUBNETS[total_ips]) def __str__(self): return '{}'.format(self.cidr or self.range_start)
26.296296
71
0.640845
99
710
4.313131
0.424242
0.117096
0.098361
0
0
0
0
0
0
0
0
0.009276
0.240845
710
26
72
27.307692
0.782931
0
0
0
0
0
0.021127
0
0
0
0
0
0
1
0.166667
false
0
0.111111
0.055556
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be7899428e46960e100ad08d01429e3242a6f7d
4,897
py
Python
keats_crawler/crawl.py
mannmann2/keats-crawler
9fc108b75e63bf3dfac0c18ed2f0bec84d003c14
[ "MIT" ]
8
2021-01-21T19:34:59.000Z
2022-02-14T23:09:48.000Z
keats_crawler/crawl.py
mannmann2/keats-crawler
9fc108b75e63bf3dfac0c18ed2f0bec84d003c14
[ "MIT" ]
null
null
null
keats_crawler/crawl.py
mannmann2/keats-crawler
9fc108b75e63bf3dfac0c18ed2f0bec84d003c14
[ "MIT" ]
1
2021-12-27T11:09:44.000Z
2021-12-27T11:09:44.000Z
"""Main module.""" from config import * import os import re from threading import Thread import requests from urllib.parse import unquote from bs4 import BeautifulSoup from m3u8downloader.main import M3u8Downloader from selenium import webdriver from selenium.webdriver.chrome.options import Options VIDEO_DICT = {} PATH = f'{PATH}{MODULE}/' if not os.path.exists(PATH): print('Creating directory at', PATH) os.makedirs(PATH) options = Options() if HEADLESS: options.add_argument("--headless") driver = webdriver.Chrome(PATH_TO_CHROMEDRIVER, options=options) def is_duplicate(href, anchor): code = href.split('=')[-1] file = f'{code} - {MODULE}/{anchor}\n' with open('duplicates.txt', 'r') as f: files = f.readlines() if file in files: return True return False def remember(url, anchor): code = url.split('=')[-1] file = f'{code} - {MODULE}/{anchor}' with open('duplicates.txt', 'a') as f: f.write(file + '\n') def res_download(url, anchor): if REMEMBER_DOWNLOADS: remember(url, anchor) try: res = requests.get(url + '&redirect=1', timeout=10, cookies=COOKIE_DICT) except requests.exceptions.Timeout: print('timeout...') return name = unquote(res.url.split('/')[-1]) name = re.sub(r'[\\/:*?"<>|]', '.', name) if anchor.endswith('URL') and not name.endswith('.pdf'): print(f'--- {name} ... skipping') return with open(f'{PATH}{name}', 'wb') as f: f.write(res.content) print(f'--- {name} ... Done') def parse_frame(iframe): driver.switch_to.frame(iframe) video_frame = driver.find_element_by_xpath("//iframe[@name='kplayer_ifp']") driver.switch_to.frame(video_frame) src = driver.page_source.replace('\n', ' ') soup = BeautifulSoup(src, 'html.parser') name = soup.find('title').text match = re.search('\<video.*?\</video>', src) soup2 = BeautifulSoup(match.group(0), 'html.parser') m3u8 = soup2.find('video')['src'].split('?')[0] driver.switch_to.default_content() return name, m3u8 def vid_download(name, m3u8): name_ = re.sub(r'[\\/:*?"<>|]', '.', name) path = f'{PATH}{name_}.mp4' M3u8Downloader(m3u8, path).start() print(f'--- {name} ... Done') def run(): print('Starting...') driver.get('https://keats.kcl.ac.uk/my') for k, v in COOKIE_DICT.items(): driver.add_cookie({'name': k, 'value': v}) driver.get(URLS[MODULE]) soup = BeautifulSoup(driver.page_source.replace('\n', ' '), 'html.parser') links = soup.find_all('a', class_='aalink') if SKIP_DUPLICATES: vid_links = [(link.text, link['href']) for link in links if '/kalvid' in link.get('href', '') and not is_duplicate(link['href'], link.text)] res_links = [(link.text, link['href']) for link in links if '/resource' in link.get('href', '') and not is_duplicate(link['href'], link.text)] url_links = [(link.text, link['href']) for link in links if '/mod/url' in link.get('href', '') and not is_duplicate(link['href'], link.text)] else: vid_links = [(link.text, link['href']) for link in links if '/kalvid' in link.get('href', '')] res_links = [(link.text, link['href']) for link in links if '/resource' in link.get('href', '')] url_links = [(link.text, link['href']) for link in links if '/mod/url' in link.get('href', '')] if DOWNLOAD_RESOURCES: print('Downloading...', len(res_links), 'resources') threads = [] for i, (anchor, url) in enumerate(res_links + url_links): th = Thread(target=res_download, args=(url, anchor)) th.start() threads.append(th) for th in threads: th.join() print('Done') if DOWNLOAD_VIDEOS: if VIDEO_LIMIT: vid_links = vid_links[:VIDEO_LIMIT] print('Found', len(vid_links), 'videos') print('Extracting video links...') ch = 'y' for i, (anchor, url) in enumerate(vid_links): if VIDEO_PROMPT: ch = input(f'Download {anchor}? (y/n) ') if ch in ['y', 'Y']: driver.get(url) iframe = driver.find_element_by_xpath("//iframe[@class='mwEmbedKalturaIframe'] | //iframe[@id='contentframe']") name, m3u8 = parse_frame(iframe) VIDEO_DICT[name] = (m3u8, url, anchor) # threads = [] for name, (m3u8, url, anchor) in VIDEO_DICT.items(): vid_download(name, m3u8) if REMEMBER_DOWNLOADS: remember(url, anchor) # th = Thread(target=vid_download, args=(name, m3u8)) # th.start() # threads.append(th) # for th in threads: # th.join() print('Done') driver.quit() if __name__ == '__main__': run()
27.357542
150
0.588115
630
4,897
4.463492
0.253968
0.025605
0.027738
0.036273
0.321124
0.282006
0.217994
0.198791
0.198791
0.198791
0
0.009693
0.241576
4,897
178
151
27.511236
0.747442
0.031244
0
0.088496
0
0
0.151278
0.020283
0
0
0
0
0
1
0.053097
false
0
0.088496
0
0.185841
0.097345
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be7ac2245946060119cdd1d1ac823a02f85034d
892
py
Python
bot.py
fangyi-zhou/renamer
ec1215f7afea1c942116a37bdd2a5fcbabee6e94
[ "Unlicense" ]
null
null
null
bot.py
fangyi-zhou/renamer
ec1215f7afea1c942116a37bdd2a5fcbabee6e94
[ "Unlicense" ]
null
null
null
bot.py
fangyi-zhou/renamer
ec1215f7afea1c942116a37bdd2a5fcbabee6e94
[ "Unlicense" ]
null
null
null
import os import re import discord from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv("DISCORD_TOKEN") RENAME_REGEX = re.compile(r"^[Ii]'m (\w+)$") if TOKEN is None: raise RuntimeError("Bot TOKEN not set") client = discord.Client() @client.event async def on_ready(): print("We have logged in as {0.user}".format(client)) @client.event async def on_message(message): if message.author == client.user: return match = re.match(RENAME_REGEX, message.content) if match: name = match[1] try: await client.http.change_nickname(message.guild.id, message.author.id, name) await message.channel.send(f"Hello {name}!") except discord.errors.Forbidden: await message.channel.send( f"Hello {name}! I do not have permission to change your name" ) client.run(TOKEN)
21.756098
88
0.649103
123
892
4.642276
0.536585
0.035026
0.059545
0.077058
0.210158
0.210158
0.115587
0
0
0
0
0.002937
0.236547
892
40
89
22.3
0.835536
0
0
0.071429
0
0
0.161435
0
0
0
0
0
0
1
0
false
0
0.142857
0
0.178571
0.035714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be86bfbc616af693be4c8b1bf95b938750cfb4b
8,035
py
Python
market/views.py
morphosis-nitmz/Stock-Bridge-2018
5f7d55a5dfeed52e2fa46fd1e2abd6bba80c954a
[ "MIT" ]
12
2019-09-10T02:51:01.000Z
2022-03-23T07:19:34.000Z
market/views.py
morphosis-nitmz/Stock-Bridge-2018
5f7d55a5dfeed52e2fa46fd1e2abd6bba80c954a
[ "MIT" ]
null
null
null
market/views.py
morphosis-nitmz/Stock-Bridge-2018
5f7d55a5dfeed52e2fa46fd1e2abd6bba80c954a
[ "MIT" ]
8
2019-06-26T14:16:23.000Z
2022-01-07T08:48:08.000Z
from datetime import datetime from decimal import Decimal from django.conf import settings from django.contrib.auth import get_user_model from django.shortcuts import render, redirect from django.http import HttpResponseRedirect, HttpResponse from django.views.generic import View, ListView from django.urls import reverse from django.contrib import messages from django.contrib.auth.decorators import login_required from django.utils import timezone from django.utils.timezone import localtime from rest_framework.views import APIView from rest_framework.response import Response from .models import Company, CompanyCMPRecord, InvestmentRecord, Transaction from .forms import StockTransactionForm, CompanyChangeForm from stock_bridge.mixins import LoginRequiredMixin, CountNewsMixin, AdminRequiredMixin User = get_user_model() START_TIME = timezone.make_aware(getattr(settings, 'START_TIME')) STOP_TIME = timezone.make_aware(getattr(settings, 'STOP_TIME')) @login_required def deduct_tax(request): """ Deduct income tax """ if request.user.is_superuser: for user in User.objects.all(): tax = user.cash * Decimal(0.4) user.cash -= tax user.save() return HttpResponse('success') return redirect('/') @login_required def update_market(request): """ Update company's cmp after applying formula """ if request.user.is_superuser: # update company cmp data company_qs = Company.objects.all() for company in company_qs: company.update_cmp() obj = CompanyCMPRecord.objects.create(company=company, cmp=company.cmp) return HttpResponse('cmp updated') return redirect('/') class CompanyAdminCompanyUpdateView(AdminRequiredMixin, View): """ View for admin to change company's CMP """ def get(self, request, *args, **kwargs): company = Company.objects.get(code=kwargs.get('code')) return render(request, 'market/admin_company_change.html', { 'object': company, 'company_list': Company.objects.all(), 'form': CompanyChangeForm() }) def post(self, request, *args, **kwargs): company = Company.objects.get(code=kwargs.get('code')) price = request.POST.get('price') old_price = company.cmp company.cmp = Decimal(int(price)) company.save() company.calculate_change(old_price) print('price', int(price)) url = reverse('market:admin', kwargs={'code': company.code}) return HttpResponseRedirect(url) class CompanyCMPCreateView(View): def get(self, request, *args, **kwargs): for company in Company.objects.all(): obj = CompanyCMPRecord.objects.create(company=company, cmp=company.cmp) return HttpResponse('success') class CompanySelectionView(LoginRequiredMixin, CountNewsMixin, View): def get(self, request, *args, **kwargs): return render(request, 'market/select_company.html', { 'object_list': Company.objects.all() }) class CompanyCMPChartData(APIView): # used django rest framework authentication_classes = [] permission_classes = [] def get(self, request, format=None, *args, **kwargs): qs = CompanyCMPRecord.objects.filter(company__code=kwargs.get('code')) if qs.count() > 15: qs = qs[:15] qs = reversed(qs) # reverse timestamp sorting i.e. latest data should be in front labels = [] cmp_data = [] for cmp_record in qs: labels.append(localtime(cmp_record.timestamp).strftime('%H:%M')) cmp_data.append(cmp_record.cmp) current_cmp = Company.objects.get(code=kwargs.get('code')).cmp if cmp_data[-1] != current_cmp: labels.append(timezone.make_aware(datetime.now()).strftime('%H:%M')) cmp_data.append(current_cmp) data = { "labels": labels, "cmp_data": cmp_data, } return Response(data) class CompanyTransactionView(LoginRequiredMixin, CountNewsMixin, View): def get(self, request, *args, **kwargs): company = Company.objects.get(code=kwargs.get('code')) obj, created = InvestmentRecord.objects.get_or_create(user=request.user, company=company) stocks_owned = obj.stocks return render(request, 'market/transaction_market.html', { 'object': company, 'company_list': Company.objects.all(), 'stocks_owned': stocks_owned, 'form': StockTransactionForm() }) def post(self, request, *args, **kwargs): company = Company.objects.get(code=kwargs.get('code')) current_time = timezone.make_aware(datetime.now()) if current_time >= START_TIME and current_time <= STOP_TIME: user = request.user mode = request.POST.get('mode') quantity = int(request.POST.get('quantity')) price = company.cmp investment_obj, obj_created = InvestmentRecord.objects.get_or_create(user=user, company=company) if quantity > 0: if mode == 'buy': purchase_amount = Decimal(quantity) * price if user.cash >= purchase_amount: if company.stocks_remaining >= quantity: # user.buy_stocks(quantity, price) # company.user_buy_stocks(quantity) # investment_obj.add_stocks(quantity) obj = Transaction.objects.create( user=user, company=company, num_stocks=quantity, price=price, mode=mode, user_net_worth=InvestmentRecord.objects.calculate_net_worth(user) ) messages.success(request, 'Transaction Complete!') else: messages.error(request, 'The company does not have that many stocks left!') else: messages.error(request, 'Insufficient Balance for this transaction!') elif mode == 'sell': if quantity <= investment_obj.stocks and quantity <= company.stocks_offered: # user.sell_stocks(quantity, price) # company.user_sell_stocks(quantity) # investment_obj.reduce_stocks(quantity) obj = Transaction.objects.create( user=user, company=company, num_stocks=quantity, price=price, mode=mode, user_net_worth=InvestmentRecord.objects.calculate_net_worth(user) ) messages.success(request, 'Transaction Complete!') else: messages.error(request, 'Please enter a valid quantity!') else: messages.error(request, 'Please enter a valid mode!') else: messages.error(request, 'The quantity cannot be negative!') else: # msg = 'The market will be live from {start} to {stop}'.format( # start=START_TIME.strftime('%H:%M'), # stop=STOP_TIME.strftime('%H:%M') # ) msg = 'The market is closed!' messages.info(request, msg) url = reverse('market:transaction', kwargs={'code': company.code}) return HttpResponseRedirect(url) class UserTransactionHistoryView(LoginRequiredMixin, CountNewsMixin, ListView): template_name = 'market/user_transaction_history.html' def get_queryset(self, *args, **kwargs): return Transaction.objects.get_by_user(user=self.request.user)
40.994898
108
0.601369
824
8,035
5.745146
0.226942
0.035488
0.019011
0.026616
0.362062
0.317279
0.292353
0.278623
0.203845
0.182932
0
0.00142
0.299067
8,035
195
109
41.205128
0.839134
0.07094
0
0.335526
0
0
0.079769
0.01668
0
0
0
0
0
1
0.065789
false
0
0.111842
0.013158
0.315789
0.006579
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be87a2381ba6a63956f68b01f8d66e526e6f9d0
21,478
py
Python
library.py
Kladmen228/kurs_work-c-
6648ca3d4f454aaa429993db80cd2fc6a3ab2bb4
[ "Apache-2.0" ]
2
2020-07-11T21:12:42.000Z
2020-07-11T21:49:22.000Z
library.py
Kladmen228/kurs_work-PP
6648ca3d4f454aaa429993db80cd2fc6a3ab2bb4
[ "Apache-2.0" ]
null
null
null
library.py
Kladmen228/kurs_work-PP
6648ca3d4f454aaa429993db80cd2fc6a3ab2bb4
[ "Apache-2.0" ]
null
null
null
# coding=utf8 import os from tkinter import messagebox from tkinter import ttk from tkinter import * import tkinter as tk import database from tkinter import filedialog databaseName = 'dataBase.db' who = 0 currentUserID = 0 currentTable = 0 root = tk.Tk() root.title("Библиотека") root.geometry("1750x500") root.resizable(False, False) var1 = IntVar() var2 = IntVar() var3 = IntVar() # region tables frame = ttk.Treeview(root) frame.place(relx=0.15, rely=0.05, relwidth=0.33, relheight=0.89) frame2 = ttk.Treeview(root) frame2.place(relx=0.65, rely=0.05, relwidth=0.33, relheight=0.89) frame["columns"] = ("ID", "Название", "Автор", "Год издания", "Кол-во") frame.column("#0", width=0, stretch=tk.NO) frame.column("ID", width=40, stretch=tk.NO) frame.column("Название", width=200, stretch=tk.NO) frame.column("Автор", width=200, stretch=tk.NO) frame.column("Год издания", width=80, stretch=tk.NO) frame.column("Кол-во", width=50, stretch=tk.NO) frame.heading("ID", text="ID", anchor=tk.W) frame.heading("Название", text="Название", anchor=tk.W) frame.heading("Автор", text="Автор", anchor=tk.W) frame.heading("Год издания", text="Год издания", anchor=tk.W) frame.heading("Кол-во", text="Кол-во", anchor=tk.W) frame2["columns"] = ("ID", "Название", "Автор", "Год издания", "Идентификатор") frame2.column("#0", width=0, stretch=tk.NO) frame2.column("ID", width=40, stretch=tk.NO) frame2.column("Название", width=200, stretch=tk.NO) frame2.column("Автор", width=150, stretch=tk.NO) frame2.column("Год издания", width=80, stretch=tk.NO) frame2.column("Идентификатор", width=100, stretch=tk.NO) frame2.heading("ID", text="ID", anchor=tk.W) frame2.heading("Название", text="Название", anchor=tk.W) frame2.heading("Автор", text="Автор", anchor=tk.W) frame2.heading("Год издания", text="Год издания", anchor=tk.W) frame2.heading("Идентификатор", text="Идентификатор", anchor=tk.W) # endregion def connect_to_database(): try: global databaseName tmp = filedialog.askopenfilename(filetypes=(("DB", "*.db"), ("All files", "*.*"))) if tmp: databaseName = tmp database.databaseName = databaseName fill_LibTable() Exit() except Exception as e: print(e) def fill_LibTable(): try: if not os.path.isfile(databaseName): answer = messagebox.askokcancel(title="INFO", message="База данных не обнаружена!\nВыберете файл базы данных") if answer: connect_to_database() else: exit(0) frame.delete(*frame.get_children()) books = database.fill_libTable() for i in books: frame.insert('', 'end', values=i) except Exception as e: print(e) def fill_on_hand_table(): global currentTable try: if currentUserID != -999: currentTable = 0 button_take.configure(state='normal') button_give.configure(state='normal') frame2.heading("Идентификатор", text="Идентификатор", anchor=tk.W) button_sortCount2.configure(text='Идентификатору') frame2.delete(*frame2.get_children()) books = database.fill_onHandTableLib(currentUserID, who) for i in books: frame2.insert('', 'end', values=i) except Exception as e: print(e) def fill_middle_time(): global currentTable try: currentTable = 1 button_take.configure(state='disabled') button_give.configure(state='disabled') frame2.heading("Идентификатор", text="Среднее время", anchor=tk.W) button_sortCount2.configure(text='Времени') frame2.delete(*frame2.get_children()) books = database.fill_middle() for i in books: frame2.insert('', 'end', values=i) except Exception as e: print(e) def fill_frequency(): global currentTable try: currentTable = 2 button_take.configure(state='disabled') button_give.configure(state='disabled') frame2.heading("Идентификатор", text="Частота выдачи", anchor=tk.W) button_sortCount2.configure(text='Частоте') frame2.delete(*frame2.get_children()) books = database.fill_frequency() for i in books: frame2.insert('', 'end', values=i) except Exception as e: print(e) def sort_frame(byWhat): try: frame.delete(*frame.get_children()) books = database.sort1(byWhat) for i in books: frame.insert('', 'end', values=i) except Exception as e: print(e) def sort_frame2(byWhat): try: frame2.delete(*frame2.get_children()) books = database.sort2(byWhat, who, currentUserID, currentTable) for i in books: frame2.insert('', 'end', values=i) except Exception as e: print(e) def add_book(): try: if len(entry_id.get()) != 0 and len(entry_title.get()) != 0 and len(entry_author.get()) != 0 and \ len(entry_year.get()) != 0 and len(entry_count.get()) != 0: data = [entry_id.get(), entry_title.get(), entry_author.get(), entry_year.get(), entry_count.get()] if data[0].isdigit(): if not database.check_id(int(entry_id.get())): messagebox.showerror("TypeError", "Введенный Id уже существует") return else: messagebox.showerror("TypeError", "Id должен быть указан числом") return if not data[3].isdigit(): messagebox.showerror("TypeError", "Год издания должен быть указан числом") return if not data[4].isdigit(): messagebox.showerror("TypeError", "Кол-во экземпляров должно быть указано числом") return frame.insert('', 'end', values=data) database.add_to_database(data) else: messagebox.showerror("InputError", "Все поля должны быть заполнены") except Exception as e: print(e) def del_book(): try: i = frame.selection()[0] book = frame.item(i).values() frame.delete(i) book = str(book).split() ID = book[2][1:-1] database.del_from_database(ID) except IndexError: messagebox.showerror('error', 'Вы не выбрали книгу') def replace_book(table): try: if table == "Library": button_take.configure(state='normal') button_give.configure(state='normal') i = frame.selection()[0] book = frame.item(i).values() book = str(book).split() ID = book[2][1:-1] if database.give_book(int(ID), currentUserID) > 1: frame.item(i, values=database.get_book(ID)) frame2.insert('', 'end', values=database.get_book_onHand(ID)) else: frame2.insert('', 'end', values=database.get_book_onHand(ID)) frame.delete(i) elif table == "NotInLibrary": i = frame2.selection()[0] book = frame2.item(i).values() book = str(book).split() ID = book[2][1:-1] takeID = book[len(book) - 3][:-2] database.take_book(ID, takeID) database.get_middleTime(ID) database.get_frequency(ID) frame2.delete(i) fill_LibTable() else: print('Где-то закралась ошибочка') except IndexError: messagebox.showerror('error', 'Вы не выбрали книгу') def add_count(count): try: i = frame.selection()[0] book = frame.item(i).values() book = str(book).split() ID = book[2][1:-1] database.add_countBooks(ID, count) fill_LibTable() except IndexError: messagebox.showerror('error', 'Вы не выбрали книгу') def all_disabled(): button_middle.configure(state='disabled') button_add.configure(state='disabled') button_del.configure(state='disabled') button_take.configure(state='disabled') button_give.configure(state='disabled') button_plusOne.configure(state='disabled') button_plusTwo.configure(state='disabled') button_plusFive.configure(state='disabled') button_plusTen.configure(state='disabled') button_plusFT.configure(state='disabled') button_plusTwenty.configure(state='disabled') button_sortID.configure(state='disabled') button_sortID2.configure(state='disabled') button_sortName.configure(state='disabled') button_sortName2.configure(state='disabled') button_sortAuthor.configure(state='disabled') button_sortAuthor2.configure(state='disabled') button_sortYear.configure(state='disabled') button_sortYear2.configure(state='disabled') button_sortCount.configure(state='disabled') button_sortCount2.configure(state='disabled') button_frequency.configure(state='disabled') def login(): global who global currentUserID all_disabled() if len(entry_userId.get()) != 0 and len(entry_pass.get()) != 0: userID = database.check_user(entry_userId.get(), entry_pass.get()) if userID: if userID == "0": who = 0 button_take.configure(state='normal') button_give.configure(state='normal') elif userID == "1": who = 1 button_middle.configure(state='normal') button_add.configure(state='normal') button_del.configure(state='normal') button_take.configure(state='normal') button_give.configure(state='normal') button_frequency.configure(state='normal') button_onHand.configure(state='normal') elif userID == "2": who = 2 button_middle.configure(state='normal') button_add.configure(state='normal') button_del.configure(state='normal') button_take.configure(state='normal') button_give.configure(state='normal') button_plusOne.configure(state='normal') button_plusTwo.configure(state='normal') button_plusFive.configure(state='normal') button_plusTen.configure(state='normal') button_plusFT.configure(state='normal') button_plusTwenty.configure(state='normal') button_frequency.configure(state='normal') button_onHand.configure(state='normal') elif userID == "5": messagebox.showerror('error', 'Неверный пароль') return else: messagebox.showerror('error', 'Пользователь не найден') else: messagebox.showerror('error', 'Заполните необходимые поля') return var1.set(0) var2.set(0) var3.set(0) if len(entry_userId.get()) != 0: currentUserID = entry_userId.get() fill_on_hand_table() entry_userId.delete(0, 'end') entry_pass.delete(0, 'end') button_sortID.configure(state='normal') button_sortID2.configure(state='normal') button_sortName.configure(state='normal') button_sortName2.configure(state='normal') button_sortAuthor.configure(state='normal') button_sortAuthor2.configure(state='normal') button_sortYear.configure(state='normal') button_sortYear2.configure(state='normal') button_sortCount.configure(state='normal') button_sortCount2.configure(state='normal') button_exit.configure(state='normal') button_enter.configure(state='disabled') button_reg.configure(state='disabled') def reg(): if len(entry_userId.get()) != 0 and len(entry_pass.get()) != 0: if var1.get() == 1 and var2.get() == 0 and var3.get() == 0: if database.reg_user(entry_userId.get(), entry_pass.get(), "0"): messagebox.showinfo('Успех', 'Регистрация прошла успешно') login() else: messagebox.showerror('error', 'Введенный логин уже существует') elif var1.get() == 0 and var2.get() == 1 and var3.get() == 0: if database.reg_user(entry_userId.get(), entry_pass.get(), "1"): messagebox.showinfo('Успех', 'Регистрация прошла успешно') login() else: messagebox.showerror('error', 'Введенный логин уже существует') elif var1.get() == 0 and var2.get() == 0 and var3.get() == 1: if database.reg_user(entry_userId.get(), entry_pass.get(), "2"): messagebox.showinfo('Успех', 'Регистрация прошла успешно') login() else: messagebox.showerror('error', 'Введенный логин уже существует') else: messagebox.showerror('error', 'Необходимо выбрать один из типов пользователей') else: messagebox.showerror('error', 'Необходимо указать логин и пароль для регистрации') def Exit(): global who global currentUserID who = 0 currentUserID = -999 all_disabled() button_enter.configure(state='normal') button_reg.configure(state='normal') frame2.delete(*frame2.get_children()) # region UI создание графического интерфейса l_frame = LabelFrame(root, relief=FLAT) l_frame.place(relx=0.025, rely=0.85, relwidth=0.12, relheight=0.14) button_add = tk.Button(root, text="Добавить", bg='#BDBDBD', command=lambda: add_book(), state='disabled') button_add.place(relx=0.045, rely=0.40, relwidth=0.1, relheight=0.05) button_del = tk.Button(root, text="Удалить", bg='#BDBDBD', command=lambda: del_book(), state='disabled') button_del.place(relx=0.045, rely=0.46, relwidth=0.1, relheight=0.05) button_give = tk.Button(root, text="->Взять книгу->", bg='#BDBDBD', command=lambda: replace_book("Library"), state='disabled') button_give.place(relx=0.52, rely=0.05, relwidth=0.1, relheight=0.05) button_take = tk.Button(root, text="<-Вернуть книгу<-", bg='#BDBDBD', command=lambda: replace_book("NotInLibrary"), state='disabled') button_take.place(relx=0.52, rely=0.11, relwidth=0.1, relheight=0.05) button_middle = tk.Button(root, text="Среднее время на руках", bg='#BDBDBD', command=lambda: fill_middle_time(), state='disabled') button_middle.place(relx=0.52, rely=0.32, relwidth=0.1, relheight=0.05) button_frequency = tk.Button(root, text="Частота выдачи", bg='#BDBDBD', command=lambda: fill_frequency(), state='disabled') button_frequency.place(relx=0.52, rely=0.38, relwidth=0.1, relheight=0.05) button_onHand = tk.Button(root, text="Список книг на руках", bg='#BDBDBD', command=lambda: fill_on_hand_table(), state='disabled') button_onHand.place(relx=0.52, rely=0.44, relwidth=0.1, relheight=0.05) button_sortID = tk.Button(root, text="ID", bg='#BDBDBD', command=lambda: sort_frame("ID"), state='disabled') button_sortID.place(relx=0.22, rely=0.945, relwidth=0.03, relheight=0.05) button_sortName = tk.Button(root, text="Названию", bg='#BDBDBD', command=lambda: sort_frame("Name"), state='disabled') button_sortName.place(relx=0.255, rely=0.945, relwidth=0.05, relheight=0.05) button_sortAuthor = tk.Button(root, text="Автору", bg='#BDBDBD', command=lambda: sort_frame("Author"), state='disabled') button_sortAuthor.place(relx=0.31, rely=0.945, relwidth=0.05, relheight=0.05) button_sortYear = tk.Button(root, text="Году", bg='#BDBDBD', command=lambda: sort_frame("Year"), state='disabled') button_sortYear.place(relx=0.365, rely=0.945, relwidth=0.05, relheight=0.05) button_sortCount = tk.Button(root, text="Количеству", bg='#BDBDBD', command=lambda: sort_frame("Count"), state='disabled') button_sortCount.place(relx=0.42, rely=0.945, relwidth=0.05, relheight=0.05) button_sortID2 = tk.Button(root, text="ID", bg='#BDBDBD', command=lambda: sort_frame2("ID"), state='disabled') button_sortID2.place(relx=0.72, rely=0.945, relwidth=0.03, relheight=0.05) button_sortName2 = tk.Button(root, text="Названию", bg='#BDBDBD', command=lambda: sort_frame2("Name"), state='disabled') button_sortName2.place(relx=0.755, rely=0.945, relwidth=0.05, relheight=0.05) button_sortAuthor2 = tk.Button(root, text="Автору", bg='#BDBDBD', command=lambda: sort_frame2("Author"), state='disabled') button_sortAuthor2.place(relx=0.81, rely=0.945, relwidth=0.05, relheight=0.05) button_sortYear2 = tk.Button(root, text="Году", bg='#BDBDBD', command=lambda: sort_frame2("Year"), state='disabled') button_sortYear2.place(relx=0.865, rely=0.945, relwidth=0.05, relheight=0.05) button_sortCount2 = tk.Button(root, text="Идентификатору", bg='#BDBDBD', command=lambda: sort_frame2("takeID"), state='disabled') button_sortCount2.place(relx=0.92, rely=0.945, relwidth=0.06, relheight=0.05) button_plusOne = tk.Button(root, text="+1", bg='#BDBDBD', command=lambda: add_count(1), state='disabled') button_plusOne.place(relx=0.52, rely=0.6, relwidth=0.03, relheight=0.05) button_plusTwo = tk.Button(root, text="+2", bg='#BDBDBD', command=lambda: add_count(2), state='disabled') button_plusTwo.place(relx=0.555, rely=0.6, relwidth=0.03, relheight=0.05) button_plusFive = tk.Button(root, text="+5", bg='#BDBDBD', command=lambda: add_count(5), state='disabled') button_plusFive.place(relx=0.59, rely=0.6, relwidth=0.03, relheight=0.05) button_plusTen = tk.Button(root, text="+10", bg='#BDBDBD', command=lambda: add_count(10), state='disabled') button_plusTen.place(relx=0.52, rely=0.665, relwidth=0.03, relheight=0.05) button_plusFT = tk.Button(root, text="+15", bg='#BDBDBD', command=lambda: add_count(15), state='disabled') button_plusFT.place(relx=0.555, rely=0.665, relwidth=0.03, relheight=0.05) button_plusTwenty = tk.Button(root, text="+20", bg='#BDBDBD', command=lambda: add_count(20), state='disabled') button_plusTwenty.place(relx=0.59, rely=0.665, relwidth=0.03, relheight=0.05) button_refresh = tk.Button(root, text="Обновить БД", bg='#BDBDBD', command=lambda: (Exit(), fill_LibTable(), fill_on_hand_table()), state='normal') button_refresh.place(relx=0.52, rely=0.8, relwidth=0.1, relheight=0.05) button_connect = tk.Button(root, text="Подключить БД", bg='#BDBDBD', command=lambda: connect_to_database(), state='normal') button_connect.place(relx=0.52, rely=0.86, relwidth=0.1, relheight=0.05) button_enter = tk.Button(l_frame, text="Вход", bg='#BDBDBD', command=lambda: login()) button_enter.place(relx=0, rely=-0.1, relwidth=0.48, relheight=0.5) button_reg = tk.Button(l_frame, text="Регистрация", bg='#BDBDBD', command=lambda: reg()) button_reg.place(relx=0, rely=0.46, relwidth=1, relheight=0.4) button_exit = tk.Button(l_frame, text="Выход", bg='#BDBDBD', command=lambda: Exit(), state='disabled') button_exit.place(relx=0.52, rely=-0.1, relwidth=0.48, relheight=0.5) entry_id = tk.Entry(root, font=12) entry_id.place(relx=0.045, rely=0.05, relwidth=0.1, relheight=0.05) entry_userId = tk.Entry(root, font=12) entry_userId.place(relx=0.025, rely=0.6, relwidth=0.1, relheight=0.05) entry_pass = tk.Entry(root, font=12) entry_pass.place(relx=0.025, rely=0.66, relwidth=0.1, relheight=0.05) entry_title = tk.Entry(root, font=12) entry_title.place(relx=0.045, rely=0.12, relwidth=0.1, relheight=0.05) entry_author = tk.Entry(root, font=12) entry_author.place(relx=0.045, rely=0.19, relwidth=0.1, relheight=0.05) entry_year = tk.Entry(root, font=12) entry_year.place(relx=0.045, rely=0.26, relwidth=0.1, relheight=0.05) entry_count = tk.Entry(root, font=12) entry_count.place(relx=0.045, rely=0.33, relwidth=0.1, relheight=0.05) label_id = tk.Label(root, font=12, text="Id:", fg='black') label_id.place(relx=0.023, rely=0.05) label_title = tk.Label(root, font=12, text="Назв:", fg='black') label_title.place(relx=0.01, rely=0.12) label_author = tk.Label(root, font=12, text="Автор:", fg='black') label_author.place(relx=0.005, rely=0.19) label_year = tk.Label(root, font=12, text="Год:", fg='black') label_year.place(relx=0.015, rely=0.26) label_count = tk.Label(root, font=12, text="Кол-во:", fg='black') label_count.place(relx=0.005, rely=0.33) label_sort = tk.Label(root, font=12, text="Сортировка по:", fg='black') label_sort.place(relx=0.148, rely=0.945) label_sort2 = tk.Label(root, font=12, text="Сортировка по:", fg='black') label_sort2.place(relx=0.647, rely=0.945) label_fill = tk.Label(root, font=12, text="Пополнение", fg='black') label_fill.place(relx=0.52, rely=0.55, relwidth=0.1, relheight=0.05) label_func = tk.Label(root, font=12, text="Формирование отчетов", fg='black') label_func.place(relx=0.52, rely=0.27, relwidth=0.1, relheight=0.05) label_func = tk.Label(root, font=12, text="Тип пользователя", fg='black') label_func.place(relx=0.036, rely=0.55) user = Checkbutton(root, font=12, text="Пользователь", fg='black', variable=var1) user.place(relx=0.011, rely=0.72, relwidth=0.1, relheight=0.05) lib_worker = Checkbutton(root, font=12, text="Библиотекарь", fg='black', variable=var2) lib_worker.place(relx=0.01, rely=0.76, relwidth=0.1, relheight=0.05) admin = Checkbutton(root, font=12, text="Админ", fg='black', variable=var3) admin.place(relx=0.0195, rely=0.8, relwidth=0.05, relheight=0.05) fill_LibTable() # endregion if __name__ == "__main__": root.mainloop()
44.193416
122
0.648524
2,887
21,478
4.723935
0.117769
0.068778
0.037396
0.062912
0.532483
0.485775
0.399325
0.30591
0.27548
0.250403
0
0.047536
0.196853
21,478
485
123
44.284536
0.743072
0.004097
0
0.355505
0
0
0.122054
0.000982
0
0
0
0
0
1
0.034404
false
0.020642
0.016055
0
0.06422
0.020642
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be8ad1bff74a971fe98e6113f758f85c95026e6
621
py
Python
utilities.py
tsilifis/BayesEmbed-mfGP
61ee75284bac34084ee4d171257023cc4d60c910
[ "MIT" ]
null
null
null
utilities.py
tsilifis/BayesEmbed-mfGP
61ee75284bac34084ee4d171257023cc4d60c910
[ "MIT" ]
null
null
null
utilities.py
tsilifis/BayesEmbed-mfGP
61ee75284bac34084ee4d171257023cc4d60c910
[ "MIT" ]
null
null
null
from datetime import datetime import numpy as np def add_basis_element(W): """ Given a D x d orthonormal matrix W (with d << D), it computes a new vector v that is orthogonal to all d columns of W and add it as an additional column. Return : D x (d+1) orthonormal matrix [W v] """ dim = W.shape[1] d = W.shape[0] v = np.random.randn(d) v = v / np.linalg.norm(v) u = np.zeros(v.shape) for i in range(dim): u = u - np.sum(W[:, i] * v) * W[:, i] v = (v - u).reshape(-1, 1) v = v / np.linalg.norm(v) return np.hstack([W, v]) def compact_timestamp(): return '{:%Y%m%d_%H%M%S}'.format(datetime.now())
23
83
0.621578
123
621
3.105691
0.487805
0.02356
0.015707
0.052356
0.078534
0.078534
0
0
0
0
0
0.010204
0.21095
621
26
84
23.884615
0.769388
0.318841
0
0.133333
0
0
0.039024
0
0
0
0
0
0
1
0.133333
false
0
0.133333
0.066667
0.4
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
8be92b2b82e61183cec9beb6bacf4eefc2f03ab0
4,049
py
Python
data/LoadingScripts/adapt_tcga.py
Bertinus/causal_cell_embedding
417b55749130fc7b7832fd3ee4c49feff4a04593
[ "MIT" ]
null
null
null
data/LoadingScripts/adapt_tcga.py
Bertinus/causal_cell_embedding
417b55749130fc7b7832fd3ee4c49feff4a04593
[ "MIT" ]
null
null
null
data/LoadingScripts/adapt_tcga.py
Bertinus/causal_cell_embedding
417b55749130fc7b7832fd3ee4c49feff4a04593
[ "MIT" ]
null
null
null
import numpy as np import pandas as pd ######################################################################################################################## # Load data ######################################################################################################################## print("Adapt TCGA: Loading data. Might take some time...") # TCGA gene expression matrix data = pd.read_csv('Data/Downstream_Tasks/TcgaTargetGtex_rsem_gene_tpm', sep='\t') # Load Ensembl Id conversion table conversion_table = pd.read_csv('Data/Downstream_Tasks/ensembl_names.txt', sep='\t') # Get list of landmark genes gene_info = pd.read_csv("Data/L1000_PhaseI/GSE92742_Broad_LINCS/GSE92742_Broad_LINCS_gene_info.txt", sep="\t") ######################################################################################################################## # Build conversion map ######################################################################################################################## print("Adapt TCGA: build conversion map") # Build name to ensembl dictionary name_to_ensembl_dict = {} for l in conversion_table.iterrows(): name_to_ensembl_dict[l[1]['Approved symbol']] = l[1]['Ensembl gene ID'] # Manually add landmark genes that are not in the ensembl ID table not_matched_dict = {"EPRS": "ENSG00000136628", "AARS": "ENSG00000090861", "TOMM70A": "ENSG00000154174", "KIAA0196": "ENSG00000164961", "KIAA0907": "ENSG00000132680", "PAPD7": "ENSG00000112941", "IKBKAP": "ENSG00000070061", "HIST2H2BE": "ENSG00000184678", "WRB": "ENSG00000182093", "KIAA0355": "ENSG00000166398", "TMEM5": "ENSG00000118600", "HDGFRP3": "ENSG00000166503", "PRUNE": "ENSG00000143363", "HIST1H2BK": "ENSG00000197903", "HN1L": "ENSG00000206053", "H2AFV": "ENSG00000105968", "KIF1BP": "ENSG00000198954", "KIAA1033": "ENSG00000136051", "FAM69A": "ENSG00000154511", "TMEM110": "ENSG00000213533", "ATP5S": "ENSG00000125375", "SQRDL": "ENSG00000137767", "TMEM2": "ENSG00000135048", "ADCK3": "ENSG00000163050", "NARFL": "ENSG00000103245", "FAM57A": "ENSG00000167695", "LRRC16A": "ENSG00000079691", "FAM63A": "ENSG00000143409", "TSTA3": "ENSG00000104522"} name_to_ensembl_dict = {**name_to_ensembl_dict, **not_matched_dict} landmark_ensembl_dict = {name: name_to_ensembl_dict[name] for name in gene_info[gene_info['pr_is_lm'] == 1]['pr_gene_symbol']} landmark_ensembl_to_name_dict = {landmark_ensembl_dict[name]: name for name in landmark_ensembl_dict.keys()} ######################################################################################################################## # Retrieve part of TCGA matrix that corresponds to landmark genes ######################################################################################################################## print("Adapt TCGA: modify TCGA matrix") # Remove version of the ensembl ID in TCGA data data['ensembl'] = data['sample'].apply(lambda s: s.split('.')[0]) # Restrict to landmark genes data_lamdmark_genes = data[data['ensembl'].apply(lambda s: s in landmark_ensembl_dict.values())] data_lamdmark_genes = data_lamdmark_genes.drop(['sample'], axis=1) # Add gene names to the matrix data_lamdmark_genes['name'] = data_lamdmark_genes['ensembl'].apply(lambda s: landmark_ensembl_to_name_dict[s]) data_lamdmark_genes = data_lamdmark_genes.set_index('name') data_lamdmark_genes = data_lamdmark_genes.drop(['ensembl'], axis=1) # Save data_lamdmark_genes.to_csv("Data/Downstream_Tasks/tcga_landmark_genes.csv")
46.011364
120
0.514942
358
4,049
5.586592
0.410615
0.06
0.085
0.0425
0.156
0.114
0.038
0
0
0
0
0.119562
0.210916
4,049
88
121
46.011364
0.506416
0.095826
0
0
0
0
0.35268
0.070673
0
0
0
0
0
1
0
false
0
0.039216
0
0.039216
0.058824
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
4738887a5abd7d5e02db7c0d3385f50ba3f81899
8,290
py
Python
cli/cli.py
MustafaTheCoder/create-a-cli-tool
9f7c327927e22b390a58c8c8b599a59cad246f2e
[ "MIT" ]
3
2021-09-27T10:35:24.000Z
2021-10-02T08:16:46.000Z
cli/cli.py
MustafaTheCoder/create-a-cli-tool
9f7c327927e22b390a58c8c8b599a59cad246f2e
[ "MIT" ]
1
2021-09-22T15:44:30.000Z
2021-09-22T15:44:30.000Z
cli/cli.py
MustafaTheCoder/create-a-cli-tool
9f7c327927e22b390a58c8c8b599a59cad246f2e
[ "MIT" ]
3
2021-09-21T05:19:42.000Z
2021-10-02T08:16:48.000Z
import asyncio import sys from typing import Any, Callable, List, Optional, Union from .commands import Command from .commands import CommandGroup as Group from .errors import * class CLI: """ The CLI class it self, this will represent your cli. Parameters ----------- name: :class:`str` The name of your CLI no_welcome_message: :class:`bool` Choose if you want to display a welcome message or not. command_not_found_message: :class:`str` Pick whatever error message you want to print out when a command is not found. """ def __init__( self, name: str, no_welcome_message: bool = False, command_not_found_message: str = "Command not found.", ) -> None: self.name: str = str(name) self.commands: List[Command] = [ Command( name="help", func=self.show_help, description="Shows this message.", ) ] self.no_welcome_message: bool = no_welcome_message self.command_not_found_message: str = command_not_found_message def command( self, name: Optional[str] = None, description: Optional[str] = None, aliases: List[Optional[Command]] = [], ) -> Callable[..., Any,]: """ Make a command for your cli. Parameters ----------- name: :class:`str` The name of the command, Default to the name of your function. description: :class:`str` The description of the command, Defaults to the function's doc. aliases: :class:`List[str]` A list of strings that contains the name of the aliases you want. """ def decorator( func: Callable[ ..., Any, ] ) -> Command: if asyncio.iscoroutinefunction(func): raise NoCorountines("Functions must not be coroutines.") if not name: cmd: Command = Command.from_function(func) else: cmd: Command = Command(name=name, func=func, description=description) # type: ignore if cmd.name.count(" ") > 0: raise NameHasSpaces("Command cannot have spaces.") if cmd in self.commands: raise CommandAlreadyExists(f"The command named {cmd.name} already exists.") self.commands.append(cmd) if aliases: for alias in aliases: self.commands.append( Command( name=alias, func=func, description=description, ) ) return cmd return decorator def group( self, name: Optional[str] = None, description: Optional[str] = None, aliases: List[Optional[Group]] = [], ) -> Callable[..., Any,]: """ Make a command group for your cli. Parameters ----------- name: :class:`str` The name of the group, Default to the name of your function. description: :class:`str` The description of the group, Defaults to the function's doc. aliases: :class:`List[str]` A list of strings that contains the name of the aliases you want. """ def decorator( func: Callable[ ..., Any, ] ) -> Group: if asyncio.iscoroutinefunction(func): raise RuntimeError("Functions must not be coroutines.") if not name: cmd: Group = Group.from_function(func) else: cmd: Group = Group(name=name, func=func, description=description) # type: ignore if cmd.name.count(" ") > 0: raise NameHasSpaces("Command cannot have spaces.") if cmd in self.commands: raise CommandAlreadyExists(f"The group named {cmd.name} already exists.") self.commands.append(cmd) if aliases: for alias in aliases: self.commands.append( Group( name=alias, func=func, description=description, ) ) return cmd return decorator def run( self, interactive: bool = True, ) -> None: """ Run your cli. Parameters ----------- interactive: :class:`bool` Pick if the cli should be interactive or not, if set to false you will do like ``python3 main.py command_name``. """ if interactive: if not self.no_welcome_message: print("Welcome to " + self.name) args: List[str] = input(">>> ").split() while args and args[0] not in ( "exit", "quit", ): cmd = self.get_command(args[0]) if not cmd: print(self.command_not_found_message) args = input(">>> ").split() elif type(cmd) == Command: print(type(cmd)) try: cmd._func(*args[1:]) except TypeError as e: cmd._func() args: List[str] = input(">>> ").split() # type: ignore elif type(cmd) == Group: for subcmd in cmd.children: # type: ignore if subcmd.name == args[0]: try: subcmd._func(*args[2:]) except TypeError as e: print(e) args: List[str] = input(">>> ").split() # type: ignore else: try: cmd._func(*args[1:]) except TypeError: cmd._func() args: List[str] = input(">>> ").split() # type: ignore else: cmd = self.get_command(sys.argv[1]) # type: ignore if not cmd: print(self.command_not_found_message) return if type(cmd) == Command: try: cmd._func(*sys.argv[2:]) except TypeError: cmd._func() else: for subcmd in cmd: # type: ignore if subcmd.name == sys.argv[2]: try: subcmd._func(*sys.argv[2:]) except TypeError: subcmd._func() break else: try: cmd._func(*sys.argv[1:]) except TypeError: cmd._func() def get_command(self, name: str) -> Union[Group, Command]: # type: ignore for command in self.commands: if command.name == name: return command # type: ignore def remove_command( self, name: str, ) -> None: """ Remove a command. Parameters ----------- name: :class:`str` The name of the command that you want to remove. """ for cmd in self.commands: if cmd.name == name: self.commands.remove(cmd) break def show_help( self, ) -> None: for cmd in self.commands: print(f"{cmd.name} - {cmd.description}") def add_shard( self, shard, ): """ Add a shard to the cli. Parameters ----------- shard: :class:`cli.cli.ext.shard.Shard` The shard you want to add """ shard = shard _shard_cmds = shard._inject() for cmd in _shard_cmds: self.commands.append(cmd)
30.932836
124
0.458987
801
8,290
4.677903
0.166042
0.038431
0.019215
0.035228
0.559381
0.473712
0.459301
0.443288
0.411529
0.326128
0
0.003042
0.444873
8,290
267
125
31.048689
0.811169
0.186731
0
0.545455
0
0
0.05011
0
0
0
0
0
0
1
0.056818
false
0
0.034091
0
0.130682
0.034091
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
473f1e1eeb6b340b2ca16fc3da17da150f626195
661
py
Python
setup.py
libre-man/DJFeet
7517e7930bdc23d22765c64d7351d4011515dcaa
[ "MIT" ]
2
2018-09-29T22:41:28.000Z
2018-10-02T16:07:11.000Z
setup.py
libre-man/DJFeet
7517e7930bdc23d22765c64d7351d4011515dcaa
[ "MIT" ]
null
null
null
setup.py
libre-man/DJFeet
7517e7930bdc23d22765c64d7351d4011515dcaa
[ "MIT" ]
null
null
null
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'A program does that is a DJ by using feedback provided by the dancers.', 'author': 'Thomas Schaper', 'url': 'https://gitlab.com/SilentDiscoAsAService/DJFeet', 'download_url': 'https://gitlab.com/SilentDiscoAsAService/DJFeet', 'author_email': 'thomas@libremail.nl', 'version': '0.0', 'install_requires': ['nose'], 'packages': ['dj_feet'], 'scripts': [], 'entry_points': { 'console_scripts': [ 'server = dj_feet.cli:main' ] }, 'name': 'dj_feet' } setup(**config)
26.44
92
0.621785
73
661
5.520548
0.69863
0.044665
0.069479
0.084367
0.218362
0.218362
0
0
0
0
0
0.003876
0.219365
661
24
93
27.541667
0.777132
0
0
0
0
0
0.538578
0
0
0
0
0
0
1
0
false
0
0.136364
0
0.136364
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
0
0
0
1
0
473fc3dd716cb4c46c867f24ed27e15522aed178
1,802
py
Python
tests/post/test_metrics_server.py
ssalaues/metalk8s
cca4a4c64fe9cd4d7b87717aa3fda1642144da4b
[ "Apache-2.0" ]
null
null
null
tests/post/test_metrics_server.py
ssalaues/metalk8s
cca4a4c64fe9cd4d7b87717aa3fda1642144da4b
[ "Apache-2.0" ]
null
null
null
tests/post/test_metrics_server.py
ssalaues/metalk8s
cca4a4c64fe9cd4d7b87717aa3fda1642144da4b
[ "Apache-2.0" ]
null
null
null
import json import kubernetes.config import pytest_bdd import pytest_bdd.parsers import utils.helper pytest_bdd.scenarios('features/metrics_server.feature') @pytest_bdd.when('I wait for metrics-server to be initialized') def wait_until_initialized(kubeconfig): client = kubernetes.config.new_client_from_config(config_file=kubeconfig) # It can take up to a minute before metrics-server scraped some stats, see # https://github.com/kubernetes-incubator/metrics-server/issues/134 and # https://github.com/kubernetes-incubator/metrics-server/issues/136 for _ in utils.helper.retry(90, wait=1): try: (_, response_code, _) = client.call_api( '/api/v1/namespaces/kube-system/services' '/https:metrics-server:443/proxy/healthz', 'GET', _preload_content=False) except kubernetes.client.rest.ApiException as exc: response_code = exc.status if response_code == 200: break @pytest_bdd.when(pytest_bdd.parsers.parse('I GET a {kind} from {path}')) def raw_request(request, kubeconfig, kind, path): client = kubernetes.config.new_client_from_config(config_file=kubeconfig) (response, response_code, response_headers) = client.call_api( path, 'GET', _preload_content=False) assert response_code == 200 assert response_headers['content-type'] == 'application/json' request.raw_response = json.loads(response.data.decode('utf-8')) assert request.raw_response['kind'] == kind @pytest_bdd.then(pytest_bdd.parsers.parse( 'I should count as many nodes as {group_name} hosts')) def node_count_match(request, inventory_obj, group_name): assert len(request.raw_response['items']) == \ len(inventory_obj.get_groups_dict()[group_name])
34
78
0.712542
237
1,802
5.21519
0.451477
0.058252
0.038835
0.040453
0.218447
0.182848
0.182848
0.182848
0.098706
0.098706
0
0.013468
0.175916
1,802
52
79
34.653846
0.818855
0.115427
0
0.060606
0
0
0.173585
0.068553
0
0
0
0
0.121212
1
0.090909
false
0
0.151515
0
0.242424
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
0
0
0
1
0
474625e55d420bbe1645d7c53baf9bb6b0997f55
2,615
py
Python
works/test/dssm/model.py
didazxc/autoflow
6682102efae90b0af00ba920cd4fa2020694d5f2
[ "MIT" ]
null
null
null
works/test/dssm/model.py
didazxc/autoflow
6682102efae90b0af00ba920cd4fa2020694d5f2
[ "MIT" ]
null
null
null
works/test/dssm/model.py
didazxc/autoflow
6682102efae90b0af00ba920cd4fa2020694d5f2
[ "MIT" ]
null
null
null
import torch from torch import nn class UserModel(nn.Module): def __init__(self, filter_sizes, userprofile_size, applist_size, output_size=32, char_embed_size=32, chars_size=6000, out_channel_size=3): super().__init__() # embedding of lines and apps self.embed = nn.Embedding(chars_size, char_embed_size) # charCNN self.convs = nn.ModuleList([ nn.Sequential(nn.Conv1d(char_embed_size, out_channel_size, filter_size)) for filter_size in filter_sizes ]) self.conv_out_size = out_channel_size * len(filter_sizes) self.lines_output_layer = nn.Sequential( nn.Dropout(0.5), nn.Linear(self.conv_out_size, output_size), nn.ReLU() ) # combine self.output_layer = nn.Sequential( nn.Linear(output_size+applist_size+userprofile_size, output_size), nn.ReLU(), nn.Linear(output_size, output_size), nn.ReLU() ) def forward(self, lines, applist, userprofile): # lines lines_embed_out = self.embed(lines).permute(0, 2, 1) conv_outs = [conv(lines_embed_out) for conv in self.convs] pool_outs = [nn.functional.max_pool1d(out, out.shape[-1]) for out in conv_outs] convs_out = torch.cat(pool_outs, dim=1).view(-1, self.conv_out_size) lines_output = self.lines_output_layer(convs_out) # combine output = torch.cat([lines_output, applist, userprofile], dim=-1) output = self.output_layer(output) return output class DS(nn.Module): def __init__(self, userprofile_size=1384, applist_size=1000, embed_size=32, vid_table_size=22261, aid_table_size=13727): super().__init__() self.user_embed = UserModel([3, 5, 10], userprofile_size, applist_size, output_size=embed_size) self.vid_embed = nn.Embedding(vid_table_size, embed_size) self.aid_embed = nn.Embedding(aid_table_size, embed_size) self.video_output_layer = nn.Sequential( nn.Linear(2*embed_size, embed_size), nn.ReLU(), nn.Linear(embed_size, embed_size), nn.ReLU() ) def forward(self, vid, aid, lines, applist, userprofile): user = self.user_embed(lines, applist, userprofile) video = self.video_output_layer(torch.cat([self.vid_embed(vid), self.aid_embed(aid)], dim=-1)) cosine = torch.cosine_similarity(user, video, dim=-1) return cosine @staticmethod def get_cate(x): return 1 if x >= 0.5 else 0
38.455882
104
0.636711
349
2,615
4.475645
0.226361
0.06338
0.044814
0.028809
0.251601
0.140845
0
0
0
0
0
0.026248
0.256979
2,615
67
105
39.029851
0.777663
0.021797
0
0.132075
0
0
0
0
0
0
0
0
0
1
0.09434
false
0
0.037736
0.018868
0.226415
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
0
0
0
1
0
474a6941a53b9666a0f1df165d06680657ea0def
3,066
py
Python
ukol.py
tenhobi/NI-MPI
5c6c4f5fd28487e807315ce6da33b81f0db4908d
[ "MIT" ]
null
null
null
ukol.py
tenhobi/NI-MPI
5c6c4f5fd28487e807315ce6da33b81f0db4908d
[ "MIT" ]
null
null
null
ukol.py
tenhobi/NI-MPI
5c6c4f5fd28487e807315ce6da33b81f0db4908d
[ "MIT" ]
null
null
null
import numpy as np class Solver: def __init__(self, matrix, vector, initialVector, precision, gamma): self.initialVector = initialVector self.precision = precision self.matrix = matrix self.bVector = vector self.gamma = gamma # lower triangular part self.l = np.tril(matrix, -1) # upper triangular part self.u = np.triu(matrix, 1) # diagonal component self.d = np.diag(np.diag(matrix)) # init Q - must be set by subclases self.q = None self.qinv = None def solve(self): """Starts to compute iterations and then returns count of iterations and result.""" iterationCount = 0 x = None if self.canConverge(): x = self.initialVector while self.isNotPreciseEnough(x): iterationCount = iterationCount + 1 x = self.doIteration(x) return iterationCount, x def canConverge(self): """Can converge if the value of spectral radius is less than 1.""" e = np.identity(self.matrix.shape[0], dtype = np.float64) return self.getSpectralRadius(e - self.qinv @ self.matrix) < 1 def isNotPreciseEnough(self, iteration): """Chech whether precision is not already sufficient.""" return (np.linalg.norm(self.matrix @ iteration - self.bVector) / np.linalg.norm(self.bVector)) > self.precision def doIteration(self, lastIteration): """Does next iteration.""" return self.qinv @ (self.q - self.matrix) @ lastIteration + self.qinv @ self.bVector def getSpectralRadius(self, matrix): """Returns max absolute eigenvalue of matrix, aka spectral radius.""" return max(abs(np.linalg.eigvals(matrix))) class JacobiSolver(Solver): def __init__(self, matrix, vector, initialVector, precision, gamma): super().__init__(matrix, vector, initialVector, precision, gamma) self.q = self.d self.qinv = np.linalg.inv(self.q) class GaussSeidelSolver(Solver): def __init__(self, matrix, vector, initialVector, precision, gamma, omega = 1): super().__init__(matrix, vector, initialVector, precision, gamma) self.omega = omega self.q = (1 / omega) * self.d + self.l self.qinv = np.linalg.inv(self.q) ### ----- config # parameters gamma = 3 omega = 1 precision = 10**-6 # matrix matrix = np.zeros((20, 20), dtype = np.float64) np.fill_diagonal(matrix, gamma) np.fill_diagonal(matrix[:, 1:], -1) # upper part np.fill_diagonal(matrix[1:, :], -1) # lower part # vector b bVector = np.full((20, 1), gamma - 2, dtype = np.float64) bVector[0] = bVector[0] + 1 bVector[-1] = bVector[-1] + 1 # initial vector initialVector = np.zeros(bVector.shape, dtype = np.float64) ### ----- solver # use one of these: #solver = JacobiSolver(matrix, bVector, initialVector, precision, gamma) solver = GaussSeidelSolver(matrix, bVector, initialVector, precision, gamma, omega) solver.solve()
31.285714
119
0.628506
368
3,066
5.173913
0.293478
0.047269
0.099265
0.089286
0.235294
0.193277
0.168067
0.142857
0.088235
0
0
0.017444
0.25212
3,066
97
120
31.608247
0.812909
0.179713
0
0.109091
0
0
0
0
0
0
0
0
0
1
0.145455
false
0
0.018182
0
0.309091
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
0
0
0
1
0
474bb5e6e62ca2caee71dee1fac0a250c57c5dda
12,491
py
Python
src/python/dxpy/utils/__init__.py
psung/dx-toolkit
f3a430c5e24184215eb4a9883a179edf07bfa08b
[ "Apache-2.0" ]
null
null
null
src/python/dxpy/utils/__init__.py
psung/dx-toolkit
f3a430c5e24184215eb4a9883a179edf07bfa08b
[ "Apache-2.0" ]
null
null
null
src/python/dxpy/utils/__init__.py
psung/dx-toolkit
f3a430c5e24184215eb4a9883a179edf07bfa08b
[ "Apache-2.0" ]
null
null
null
# Copyright (C) 2013-2014 DNAnexus, Inc. # # This file is part of dx-toolkit (DNAnexus platform client libraries). # # 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. """ Utilities shared by dxpy modules. """ from __future__ import (print_function, unicode_literals) import os, json, collections, concurrent.futures, traceback, sys, time, gc import dateutil.parser from .thread_pool import PrioritizingThreadPool from .. import logger from ..compat import basestring def _force_quit(signum, frame): # traceback.print_stack(frame) os._exit(os.EX_IOERR) # os.abort() def get_futures_threadpool(max_workers): #import signal #if force_quit_on_sigint: # signal.signal(signal.SIGINT, _force_quit) #return concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) return PrioritizingThreadPool(max_workers=max_workers) def wait_for_a_future(futures, print_traceback=False): """ Return the next future that completes. If a KeyboardInterrupt is received, then the entire process is exited immediately. See wait_for_all_futures for more notes. """ while True: try: future = next(concurrent.futures.as_completed(futures, timeout=10000000000)) break except concurrent.futures.TimeoutError: pass except KeyboardInterrupt: if print_traceback: traceback.print_stack() else: print('') os._exit(os.EX_IOERR) return future def wait_for_all_futures(futures, print_traceback=False): """ Wait indefinitely for all futures in the input iterable to complete. Use a timeout to enable interrupt handling. Call os._exit() in case of KeyboardInterrupt. Otherwise, the atexit registered handler in concurrent.futures.thread will run, and issue blocking join() on all worker threads, requiring us to listen to events in worker threads in order to enable timely exit in response to Ctrl-C. Note: This still doesn't handle situations where Ctrl-C is pressed elsewhere in the code and there are worker threads with long-running tasks. Note: os._exit() doesn't work well with interactive mode (e.g. ipython). This may help: import __main__ as main; if hasattr(main, '__file__'): os._exit() else: os.exit() """ try: while True: waited_futures = concurrent.futures.wait(futures, timeout=60) if len(waited_futures.not_done) == 0: break except KeyboardInterrupt: if print_traceback: traceback.print_stack() else: print('') os._exit(os.EX_IOERR) def response_iterator(request_iterator, thread_pool, max_active_tasks=4, num_retries=0, retry_after=90, queue_id=''): """ :param request_iterator: This is expected to be an iterator producing inputs for consumption by the worker pool. :type request_iterator: iterator of callable_, args, kwargs :param thread_pool: thread pool to submit the requests to :type thread_pool: PrioritizingThreadPool :param max_active_tasks: The maximum number of tasks that may be either running or waiting for consumption of their result. :type max_active_tasks: int :param num_retries: The number of times to retry the request. :type num_retries: int :param retry_after: The number of seconds to wait before retrying the request. :type retry_after: number :param queue_id: hashable object to divide incoming requests into independent queues :type queue_id: object Rate-limited asynchronous multithreaded task runner. Consumes tasks from *request_iterator*. Yields their results in order, while allowing up to *max_active_tasks* to run simultaneously. Unlike concurrent.futures.Executor.map, prevents new tasks from starting while there are *max_active_tasks* or more unconsumed results. **Retry behavior**: If *num_retries* is positive, the task runner uses a simple heuristic to retry slow requests. If there are 4 or more tasks in the queue, and all but the first one are done, the first task will be discarded after *retry_after* seconds and resubmitted with the same parameters. This will be done up to *num_retries* times. If retries are used, tasks should be idempotent. """ # Debug fallback #for _callable, args, kwargs in request_iterator: # yield _callable(*args, **kwargs) #return num_results_yielded = 0 next_request_index = 0 def make_priority_fn(request_index): # The more pending requests are between the data that has been # returned to the caller and this data, the less likely this # data is to be needed soon. This results in a higher number # here (and therefore a lower priority). return lambda: request_index - num_results_yielded def submit(callable_, args, kwargs, retries=num_retries): """ Submit the task. Return (future, (callable_, args, kwargs), retries) """ future = thread_pool.submit_to_queue(queue_id, make_priority_fn(next_request_index), callable_, *args, **kwargs) return (future, (callable_, args, kwargs), retries) def resubmit(callable_, args, kwargs, retries): """ Submit the task. Return (future, (callable_, args, kwargs), retries) """ logger.warn("{}: Retrying {} after timeout".format(__name__, callable_)) # TODO: resubmitted tasks should be prioritized higher return submit(callable_, args, kwargs, retries=retries-1) # Each item is (future, (callable_, args, kwargs), retries): # # future: Future for the task being performed # callable_, args, kwargs: callable and args that were supplied # retries: number of additional times they request may be retried tasks_in_progress = collections.deque() for _i in range(max_active_tasks): try: callable_, args, kwargs = next(request_iterator) # print "Submitting (initial batch):", callable_, args, kwargs tasks_in_progress.append(submit(callable_, args, kwargs)) next_request_index += 1 except StopIteration: break while len(tasks_in_progress) > 0: future, callable_and_args, retries = tasks_in_progress.popleft() try: result = future.result(timeout=retry_after) except concurrent.futures.TimeoutError: # print "Timeout while waiting for", f, "which has", f.retries, "retries left" if retries > 0 and len(tasks_in_progress) > 2 and all(f.done() for (f, _callable, _retries) in tasks_in_progress): # The stale future will continue to run and will reduce the effective size of the pool by 1. If too many # futures are retried, the pool will block until one of the stale futures quits. # f.cancel() doesn't work because there's no way to interrupt a thread. prev_callable, prev_args, prev_kwargs = callable_and_args future, callable_and_args, retries = resubmit(prev_callable, prev_args, prev_kwargs, retries) next_request_index += 1 tasks_in_progress.appendleft((future, callable_and_args, retries)) continue except KeyboardInterrupt: print('') os._exit(os.EX_IOERR) del future # Free the future we just consumed now, instead of next # time around the loop gc.collect() try: callable_, args, kwargs = next(request_iterator) except StopIteration: pass else: tasks_in_progress.append(submit(callable_, args, kwargs)) next_request_index += 1 yield result del result num_results_yielded += 1 def string_buffer_length(buf): orig_pos = buf.tell() buf.seek(0, os.SEEK_END) buf_len = buf.tell() buf.seek(orig_pos) return buf_len def normalize_time_input(t, future=False): """ Converts inputs such as: "2012-05-01" "-5d" 1352863174 to milliseconds since epoch. See http://labix.org/python-dateutil and :meth:`normalize_timedelta`. """ error_msg = 'Error: Could not parse {t} as a timestamp or timedelta. Expected a date format or an integer with a single-letter suffix: s=seconds, m=minutes, h=hours, d=days, w=weeks, M=months, y=years, e.g. "-10d" indicates 10 days ago' if isinstance(t, basestring): try: t = normalize_timedelta(t) except ValueError: try: t = int(time.mktime(dateutil.parser.parse(t).timetuple())*1000) except ValueError: raise ValueError(error_msg.format(t=t)) now = int(time.time()*1000) if t < 0 or (future and t < now): t += now return t def normalize_timedelta(timedelta): """ Given a string like "1w" or "-5d", convert it to an integer in milliseconds. Integers without a suffix are interpreted as seconds. Note: not related to the datetime timedelta class. """ try: return int(timedelta) * 1000 except ValueError as e: t, suffix = timedelta[:-1], timedelta[-1:] suffix_multipliers = {'s': 1000, 'm': 1000*60, 'h': 1000*60*60, 'd': 1000*60*60*24, 'w': 1000*60*60*24*7, 'M': 1000*60*60*24*30, 'y': 1000*60*60*24*365} if suffix not in suffix_multipliers: raise ValueError() return int(t) * suffix_multipliers[suffix] # See http://stackoverflow.com/questions/4126348 class OrderedDefaultdict(collections.OrderedDict): def __init__(self, *args, **kwargs): newdefault = None newargs = () if args: newdefault = args[0] if not (newdefault is None or callable(newdefault)): raise TypeError('first argument must be callable or None') newargs = args[1:] self.default_factory = newdefault super(self.__class__, self).__init__(*newargs, **kwargs) def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value def __reduce__(self): args = self.default_factory if self.default_factory else tuple() return type(self), args, None, None, self.items() def group_array_by_field(array, field='group'): groups = OrderedDefaultdict(list) for item in array: if field not in item and None not in groups: groups[None] = [] groups[item.get(field)].append(item) return groups def merge(d, u): """ Recursively updates a dictionary. Example: merge({"a": {"b": 1, "c": 2}}, {"a": {"b": 3}}) = {"a": {"b": 3, "c": 2}} """ for k, v in u.items(): if isinstance(v, collections.Mapping): r = merge(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d def _dict_raise_on_duplicates(ordered_pairs): """ Reject duplicate keys. """ d = {} for k, v in ordered_pairs: if k in d: raise ValueError("duplicate key: %r" % (k,)) else: d[k] = v return d def json_load_raise_on_duplicates(*args, **kwargs): """ Like json.load(), but raises an error on duplicate keys. """ kwargs['object_pairs_hook'] = _dict_raise_on_duplicates return json.load(*args, **kwargs) def json_loads_raise_on_duplicates(*args, **kwargs): """ Like json.loads(), but raises an error on duplicate keys. """ kwargs['object_pairs_hook'] = _dict_raise_on_duplicates return json.loads(*args, **kwargs) def warn(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) # Moved to the bottom due to circular imports from .exec_utils import run, convert_handlers_to_dxlinks, parse_args_as_job_input, entry_point, DXJSONEncoder
39.15674
241
0.660716
1,654
12,491
4.833736
0.296252
0.028768
0.038274
0.021889
0.129956
0.109819
0.089806
0.071044
0.071044
0.071044
0
0.017179
0.2497
12,491
318
242
39.279874
0.835894
0.407173
0
0.314815
0
0.006173
0.050478
0
0
0
0
0.003145
0
1
0.123457
false
0.012346
0.04321
0.012346
0.271605
0.067901
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
474cbd8308c2b1410045a858c934a70c927f171d
2,946
py
Python
mkserialisable.py
cedadev/ipython_project
fd9c85c20d3689435684cf4b681dfaab1c0a825b
[ "BSD-3-Clause-Clear" ]
null
null
null
mkserialisable.py
cedadev/ipython_project
fd9c85c20d3689435684cf4b681dfaab1c0a825b
[ "BSD-3-Clause-Clear" ]
null
null
null
mkserialisable.py
cedadev/ipython_project
fd9c85c20d3689435684cf4b681dfaab1c0a825b
[ "BSD-3-Clause-Clear" ]
null
null
null
"""Routines to make objects serialisable. Each of the functions in this module makes a specific type of object serialisable. In most cases, this module needs to be imported and the function run in both the serialising and the unserialising environments. Here's a summary (see function documentation for details): mk_ellipsis: Ellipsis. mk_slots: classes with __slots__ but not __dict__. mk_netcdf: netCDF4. mk_cf: cf. """ import copy_reg _done = [] # ellipsis def mk_ellipsis (): """Make the Ellipsis builtin serialisable.""" if 'ellipsis' in _done: return copy_reg.pickle(type(Ellipsis), lambda e: 'Ellipsis') # slots def _construct_slots (cls, attrs): o = object.__new__(cls) for k, v in attrs.iteritems(): setattr(o, k, v) return o def _reduce_slots (o): attrs = dict((k, getattr(o, k)) for k in o.__slots__ if hasattr(o, k)) return _construct_slots, (type(o), attrs) def mk_slots (*objs): """Make the classes that have __slots__ but not __dict__ serialisable. Takes a number of types (new-style classes) to make serialisable. """ for cls in objs: copy_reg.pickle(cls, _reduce_slots) # netcdf def mk_netcdf (): """Make objects in the netCDF4 module serialisable. Depends on ncserialisable; see that module's documentation for details. This replaces the netCDF4 module with ncserialisable directly through sys.modules; to access netCDF4 directly, use ncserialisable.netCDF4. Call this before importing any module that uses netCDF4. """ if 'netcdf' in _done: return import sys from nc_ipython import ncserialisable sys.modules['netCDF4'] = ncserialisable # cf def _construct_cf_units (attrs): u = object.__new__(cf.Units) for k, v in attrs.iteritems(): setattr(u, k, v) if hasattr(u, 'units'): u.units = u.units return u def _reduce_cf_units (u): attrs = dict((k, getattr(u, k)) for k in u.__slots__ if hasattr(u, k)) return _construct_cf_units, (attrs,) def mk_cf (): """Make objects in the cf module serialisable. Calls mk_netcdf, and so depends on ncserialisable. Call this before importing cf. """ if 'cf' in _done: return mk_netcdf() global cf import cf mk_slots( cf.data.ElementProperties, cf.Data, cf.data.SliceData, #cf.Units, cf.pp.Variable, cf.pp.VariableCalc, cf.pp.VariableCalcBounds, cf.pp.VariableBounds, #cf.org_field.SliceVariable, #cf.org_field.SliceCoordinate, #cf.org_field.SliceField, #cf.org_field.SliceVariableList, #cf.org_field.SliceFieldList, #cf.org_field.Flags, cf.field.SliceField, cf.field.SliceFieldList, cf.Flags, cf.coordinate.SliceCoordinate, cf.variable.SliceVariable, cf.variable.SliceVariableList ) copy_reg.pickle(cf.Units, _reduce_cf_units)
23.95122
79
0.67685
401
2,946
4.778055
0.291771
0.025574
0.031315
0.015658
0.029228
0.029228
0.029228
0
0
0
0
0.003089
0.230821
2,946
123
80
23.95122
0.842454
0.418873
0
0.090909
0
0
0.02157
0
0
0
0
0
0
1
0.145455
false
0
0.072727
0
0.345455
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
0
0
0
1
0
474d5c6d6e9e1b1ea76c41c137dcb55b272f1e24
1,769
py
Python
api_teacher.py
sabertooth9/KUET-Teachers-Web-Scrapper-
0b1cea4f3e60f440b882bef971a942e42d0ab048
[ "Apache-2.0" ]
1
2019-12-21T13:35:46.000Z
2019-12-21T13:35:46.000Z
api_teacher.py
sabertooth9/KUET-Teachers-Web-Scrapper-
0b1cea4f3e60f440b882bef971a942e42d0ab048
[ "Apache-2.0" ]
null
null
null
api_teacher.py
sabertooth9/KUET-Teachers-Web-Scrapper-
0b1cea4f3e60f440b882bef971a942e42d0ab048
[ "Apache-2.0" ]
null
null
null
from flask import Flask from flask_restful import Api, Resource, reqparse from kuet_teacher_data import get_data app = Flask(__name__) api = Api(app) data = get_data() class Teacher_data(Resource): def get(self,id="CSE"): if(id=='ALL' or id=='all'): return data, 200 for datac in data: if(datac==id): return data.get(datac),200 return "Not Found",404 def contains(j,id): if(id in j.get("name").lower()): return True if(id in j.get("weblink").lower()): return True if(id in j.get("designation").lower()): return True if(id in j.get("image").lower()): return True if(id in j.get("phone").lower()): return True if(id in j.get("mail").lower()): return True return False; class search_dept_teacher(Resource): def get(self,dept,id): ans = [] id = id.lower() for datac in data: if(datac == dept or dept.lower()=='all'): for j in data.get(datac): if(contains(j,id)): ans.append(j) if(len(ans) > 0): return ans, 200 return "Not Found", 404 class search_teacher(Resource): def get(self, id): ans = [] id = id.lower() for datac in data: for j in data.get(datac): if(contains(j, id)): ans.append(j) if(len(ans) > 0): return ans, 200 return "Not Found", 404 api.add_resource(Teacher_data,"/data","/data/","/data/<string:id>") api.add_resource(search_dept_teacher,"/find/<string:dept>/<string:id>") api.add_resource(search_teacher,"/find/<string:id>") if __name__ == "__main__": app.run()
26.402985
71
0.544375
244
1,769
3.831967
0.204918
0.029947
0.038503
0.04492
0.559358
0.452406
0.362567
0.362567
0.228877
0.168984
0
0.018806
0.308649
1,769
66
72
26.80303
0.745707
0
0
0.464286
0
0
0.089932
0.017534
0
0
0
0
0
1
0.071429
false
0
0.053571
0
0.428571
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
474f1702de3c8a82c6ec6ce0f179522a071b3434
19,771
py
Python
simulators/iam_module.py
jason-neal/companion_simulations
b5773e5539011d492b7128d0dd2778041ce50d52
[ "MIT" ]
1
2018-09-04T19:06:44.000Z
2018-09-04T19:06:44.000Z
simulators/iam_module.py
jason-neal/companion_simulations
b5773e5539011d492b7128d0dd2778041ce50d52
[ "MIT" ]
85
2017-03-25T22:37:02.000Z
2022-03-01T16:49:14.000Z
simulators/iam_module.py
jason-neal/companion_simulations
b5773e5539011d492b7128d0dd2778041ce50d52
[ "MIT" ]
1
2017-08-18T10:56:39.000Z
2017-08-18T10:56:39.000Z
import datetime import logging import os import warnings import matplotlib.pyplot as plt import numpy as np import pandas as pd from logutils import BraceMessage as __ from tqdm import tqdm import simulators from mingle.models.broadcasted_models import inherent_alpha_model from mingle.utilities.chisqr import chi_squared from mingle.utilities.norm import chi2_model_norms, continuum, arbitrary_rescale, arbitrary_minimums from mingle.utilities.phoenix_utils import load_starfish_spectrum from mingle.utilities.simulation_utilities import check_inputs, spec_max_delta from simulators.common_setup import setup_dirs, sim_helper_function from numpy import float64, ndarray from spectrum_overload.spectrum import Spectrum from typing import Dict, List, Optional, Tuple, Union def iam_helper_function(star: str, obsnum: Union[int, str], chip: int, skip_params: bool = False) -> Tuple[ str, Dict[str, Union[str, float, List[Union[str, float]]]], str]: """Specifies parameter files and output directories given observation parameters.""" return sim_helper_function(star, obsnum, chip, skip_params=skip_params, mode="iam") def setup_iam_dirs(star: str) -> None: basedir = setup_dirs(star, mode="iam") os.makedirs(os.path.join(basedir, "grid_plots"), exist_ok=True) os.makedirs(os.path.join(basedir, "fudgeplots"), exist_ok=True) return None def iam_analysis(obs_spec, model1_pars, model2_pars, rvs=None, gammas=None, verbose=False, norm=False, save_only=True, chip=None, prefix=None, errors=None, area_scale=False, wav_scale=True, norm_method="scalar", fudge=None): """Run two component model over all model combinations.""" rvs = check_inputs(rvs) gammas = check_inputs(gammas) if isinstance(model1_pars, list): logging.debug(__("Number of close model_pars returned {0}", len(model1_pars))) if isinstance(model2_pars, list): logging.debug(__("Number of close model_pars returned {0}", len(model2_pars))) # Solution Grids to return iam_grid_chisqr_vals = np.empty((len(model1_pars), len(model2_pars))) args = [model2_pars, rvs, gammas, obs_spec] kwargs = {"norm": norm, "save_only": save_only, "chip": chip, "prefix": prefix, "verbose": verbose, "errors": errors, "area_scale": area_scale, "wav_scale": wav_scale, "norm_method": norm_method, "fudge": fudge, } for ii, params1 in enumerate(tqdm(model1_pars)): iam_grid_chisqr_vals[ii] = iam_wrapper(ii, params1, *args, **kwargs) if save_only: return None else: return iam_grid_chisqr_vals # Just output the best value for each model pair def continuum_alpha(model1: Spectrum, model2: Spectrum, chip: Optional[int] = None) -> float64: """Inherent flux ratio between the continuum of the two models. Assumes already scaled by area. Takes mean alpha of chip or full """ assert not np.any(np.isnan(model1.xaxis)) assert not np.any(np.isnan(model1.flux)) assert not np.any(np.isnan(model2.xaxis)) assert not np.any(np.isnan(model2.flux)) # Fit models with continuum cont1 = continuum(model1.xaxis, model1.flux, method="exponential") cont2 = continuum(model2.xaxis, model2.flux, method="exponential") # Masking for individual chips if chip is None: chip = -1 # Full Crires range all_limits = {-1: [2111, 2169], 1: [2111, 2124], 2: [2125, 2139], 3: [2140, 2152], 4: [2153, 2169]} chip_limits = all_limits[chip] mask1 = (model1.xaxis > chip_limits[0]) * (model1.xaxis < chip_limits[1]) mask2 = (model2.xaxis > chip_limits[0]) * (model2.xaxis < chip_limits[1]) continuum_ratio = cont2[mask2] / cont1[mask1] alpha_ratio = np.nanmean(continuum_ratio) return alpha_ratio def iam_wrapper(num, params1, model2_pars, rvs, gammas, obs_spec, norm=False, verbose=False, save_only=True, chip=None, prefix=None, errors=None, area_scale=True, wav_scale=True, grid_slices=False, norm_method="scalar", fudge=None): """Wrapper for iteration loop of iam. params1 fixed, model2_pars are many. fudge is multiplicative on companion spectrum. """ if prefix is None: sf = os.path.join( simulators.paths["output_dir"], obs_spec.header["OBJECT"].upper(), "iam_{0}_{1}-{2}_part{6}_host_pars_[{3}_{4}_{5}].csv".format( obs_spec.header["OBJECT"].upper(), int(obs_spec.header["MJD-OBS"]), chip, params1[0], params1[1], params1[2], num)) prefix = os.path.join( simulators.paths["output_dir"], obs_spec.header["OBJECT"].upper()) # for fudge else: sf = "{0}_part{4}_host_pars_[{1}_{2}_{3}].csv".format( prefix, params1[0], params1[1], params1[2], num) save_filename = sf if os.path.exists(save_filename) and save_only: print("'{0}' exists, so not repeating calculation.".format(save_filename)) return None else: if not save_only: iam_grid_chisqr_vals = np.empty(len(model2_pars)) for jj, params2 in enumerate(model2_pars): if verbose: print(("Starting iteration with parameters: " "{0}={1},{2}={3}").format(num, params1, jj, params2)) # Main Part rv_limits = observation_rv_limits(obs_spec, rvs, gammas) obs_spec = obs_spec.remove_nans() assert ~np.any(np.isnan(obs_spec.flux)), "Observation has nan" # Load phoenix models and scale by area and wavelength limit mod1_spec, mod2_spec = \ prepare_iam_model_spectra(params1, params2, limits=rv_limits, area_scale=area_scale, wav_scale=wav_scale) # Estimated flux ratio from models inherent_alpha = continuum_alpha(mod1_spec, mod2_spec, chip) # Combine model spectra with iam model mod1_spec.plot(label=params1) mod2_spec.plot(label=params2) plt.close() if fudge or (fudge is not None): fudge_factor = float(fudge) mod2_spec.flux *= fudge_factor # fudge factor multiplication mod2_spec.plot(label="fudged {0}".format(params2)) plt.title("fudges models") plt.legend() fudge_prefix = os.path.basename(os.path.normpath(prefix)) fname = os.path.join(simulators.paths["output_dir"], obs_spec.header["OBJECT"].upper(), "iam", "fudgeplots", "{1}_fudged_model_spectra_factor={0}_num={2}_iter_{3}.png".format(fudge_factor, fudge_prefix, num, jj)) plt.savefig(fname) plt.close() warnings.warn("Using a fudge factor = {0}".format(fudge_factor)) iam_grid_func = inherent_alpha_model(mod1_spec.xaxis, mod1_spec.flux, mod2_spec.flux, rvs=rvs, gammas=gammas) iam_grid_models = iam_grid_func(obs_spec.xaxis) # Continuum normalize all iam_gird_models def axis_continuum(flux): """Continuum to apply along axis with predefined variables parameters.""" return continuum(obs_spec.xaxis, flux, splits=20, method="exponential", top=20) iam_grid_continuum = np.apply_along_axis(axis_continuum, 0, iam_grid_models) iam_grid_models = iam_grid_models / iam_grid_continuum # RE-NORMALIZATION if chip == 4: # Quadratically renormalize anyway obs_spec = renormalization(obs_spec, iam_grid_models, normalize=True, method="quadratic") obs_flux = renormalization(obs_spec, iam_grid_models, normalize=norm, method=norm_method) if grid_slices: # Long execution plotting. plot_iam_grid_slices(obs_spec.xaxis, rvs, gammas, iam_grid_models, star=obs_spec.header["OBJECT"].upper(), xlabel="wavelength", ylabel="rv", zlabel="gamma", suffix="iam_grid_models", chip=chip) old_shape = iam_grid_models.shape # Arbitrary_normalization of observation iam_grid_models, arb_norm = arbitrary_rescale(iam_grid_models, *simulators.sim_grid["arb_norm"]) # print("Arbitrary Normalized iam_grid_model shape.", iam_grid_models.shape) assert iam_grid_models.shape == (*old_shape, len(arb_norm)) # Calculate Chi-squared obs_flux = np.expand_dims(obs_flux, -1) # expand on last axis to match rescale iam_norm_grid_chisquare = chi_squared(obs_flux, iam_grid_models, error=errors) # Take minimum chi-squared value along Arbitrary normalization axis iam_grid_chisquare, arbitrary_norms = arbitrary_minimums(iam_norm_grid_chisquare, arb_norm) npix = obs_flux.shape[0] # Number of pixels used if grid_slices: # Long execution plotting. plot_iam_grid_slices(rvs, gammas, arb_norm, iam_norm_grid_chisquare, star=obs_spec.header["OBJECT"].upper(), xlabel="rv", ylabel="gamma", zlabel="Arbitrary Normalization", suffix="iam_grid_chisquare", chip=chip) if not save_only: iam_grid_chisqr_vals[jj] = iam_grid_chisquare.ravel()[np.argmin(iam_grid_chisquare)] save_full_iam_chisqr(save_filename, params1, params2, inherent_alpha, rvs, gammas, iam_grid_chisquare, arbitrary_norms, npix, verbose=verbose) if save_only: return None else: return iam_grid_chisqr_vals def renormalization(spectrum: Union[ndarray, Spectrum], model_grid: ndarray, normalize: bool = False, method: Optional[str] = "scalar") -> ndarray: """Re-normalize the flux of spectrum to the continuum of the model_grid. Broadcast out spectrum to match the dimensions of model_grid. Parameters ---------- spectrum: Spectrum model_grid: np.ndarray normalize: bool method: str ("scalar", "linear") Returns ------- norm_flux: np.ndarray """ if normalize: if method not in ["scalar", "linear"]: raise ValueError("Renormalization method '{}' is not in ['scalar', 'linear']".format(method)) logging.info(__("{} Re-normalizing to observations!", method)) norm_flux = chi2_model_norms(spectrum.xaxis, spectrum.flux, model_grid, method=method) else: warnings.warn("Not Scalar Re-normalizing to observations!") norm_flux = spectrum.flux[:] # Extend dimensions of norm_flux until they match the grid. while norm_flux.ndim < model_grid.ndim: norm_flux = norm_flux[:, np.newaxis] assert np.allclose(norm_flux.ndim, model_grid.ndim) return norm_flux def observation_rv_limits(obs_spec: Spectrum, rvs: Union[int, List[int]], gammas: Union[int, List[int]]) -> List[ float64]: """Calculate wavelength limits needed to cover RV shifts used.""" delta = spec_max_delta(obs_spec, rvs, gammas) obs_min, obs_max = min(obs_spec.xaxis), max(obs_spec.xaxis) return [obs_min - 1.1 * delta, obs_max + 1.1 * delta] def prepare_iam_model_spectra(params1: Union[List[float], List[Union[int, float]]], params2: Union[List[float], List[Union[int, float]], Tuple[int, float, float]], limits: Union[List[float64], Tuple[int, int], List[int]], area_scale: bool = True, wav_scale: bool = True) -> Tuple[Spectrum, Spectrum]: """Load spectra with same settings.""" if not area_scale: warnings.warn("Not using area_scale. This is incorrect for paper.") if not wav_scale: warnings.warn("Not using wav_scale. This is incorrect for paper.") mod1_spec = load_starfish_spectrum(params1, limits=limits, hdr=True, normalize=False, area_scale=area_scale, flux_rescale=True, wav_scale=wav_scale) mod2_spec = load_starfish_spectrum(params2, limits=limits, hdr=True, normalize=False, area_scale=area_scale, flux_rescale=True, wav_scale=wav_scale) assert len(mod1_spec.xaxis) > 0 and len(mod2_spec.xaxis) > 0 assert np.allclose(mod1_spec.xaxis, mod2_spec.xaxis) # Check correct models are loaded assert mod1_spec.header["PHXTEFF"] == params1[0] assert mod1_spec.header["PHXLOGG"] == params1[1] assert mod1_spec.header["PHXM_H"] == params1[2] assert mod2_spec.header["PHXTEFF"] == params2[0] assert mod2_spec.header["PHXLOGG"] == params2[1] assert mod2_spec.header["PHXM_H"] == params2[2] return mod1_spec, mod2_spec def save_full_iam_chisqr(filename: str, params1: List[Union[int, float]], params2: List[Union[int, float]], alpha: Union[int, float64], rvs: Union[ndarray, List[int]], gammas: Union[ndarray, List[int]], iam_grid_chisquare: ndarray, arbitrary_norms: ndarray, npix: int, verbose: bool = False) -> None: """Save the iterations chisqr values to a cvs.""" rv_grid, g_grid = np.meshgrid(rvs, gammas, indexing='ij') # assert A.shape == rv_grid.shape assert rv_grid.shape == g_grid.shape assert g_grid.shape == iam_grid_chisquare.shape data = {"rv": rv_grid.ravel(), "gamma": g_grid.ravel(), "chi2": iam_grid_chisquare.ravel(), "arbnorm": arbitrary_norms.ravel()} columns = ["rv", "gamma", "chi2", "arbnorm"] len_c = len(columns) df = pd.DataFrame(data=data, columns=columns) # Update all rows with same value. for par, value in zip(["teff_2", "logg_2", "feh_2"], params2): df[par] = value columns = ["teff_2", "logg_2", "feh_2"] + columns if "[{0}_{1}_{2}]".format(params1[0], params1[1], params1[2]) not in filename: # Need to add the model values. for par, value in zip(["teff_1", "logg_1", "feh_1"], params1): df[par] = value columns = ["teff_1", "logg_1", "feh_1"] + columns df["alpha"] = alpha df["npix"] = npix columns = columns[:-len_c] + ["alpha", "npix"] + columns[-len_c:] df = df.round(decimals={"logg_2": 1, "feh_2": 1, "alpha": 4, "rv": 3, "gamma": 3, "chi2": 4}) exists = os.path.exists(filename) if exists: df[columns].to_csv(filename, sep=',', mode="a", index=False, header=False) else: # Add header at the top only df[columns].to_csv(filename, sep=',', mode="a", index=False, header=True) if verbose: print("Saved chi-squared values to {0}".format(filename)) return None def plot_iam_grid_slices(x, y, z, grid, xlabel=None, ylabel=None, zlabel=None, suffix=None, star=None, chip=None): """Slice up 3d grid and plot slices. This is very slow!""" os.makedirs(os.path.join(simulators.paths["output_dir"], star.upper(), "grid_plots"), exist_ok=True) x_grid, y_grid, z_grid = np.meshgrid(x, y, z, indexing="ij") if xlabel is None: xlabel = "x" if ylabel is None: ylabel = "y" if zlabel is None: zlabel = "z" if len(z) > 1: for ii, y_val in enumerate(y): plt.subplot(111) try: xii = x_grid[:, ii, :] zii = z_grid[:, ii, :] grid_ii = grid[:, ii, :] plt.contourf(xii, zii, grid_ii) except IndexError: print("grid.shape", grid.shape) print("shape of x, y, z", x.shape, y.shape, z.shape) print("shape of x_grid, y_grid, z_grid", x_grid.shape, y_grid.shape, z_grid.shape) print("index value", ii, "y_val ", y_val) raise plt.xlabel(xlabel) plt.ylabel(zlabel) plt.title("Grid slice for {0}={1}".format(ylabel, y_val)) plot_name = os.path.join(simulators.paths["output_dir"], star, "iam", "grid_plots", "y_grid_slice_{0}_chip-{1}_{2}_{3}_{4}_{5}_{6}_{7}.png".format(star, chip, xlabel, ylabel, zlabel, ii, suffix, datetime.datetime.now())) plt.savefig(plot_name) plt.close(plt.gcf()) for jj, z_val in enumerate(z): plt.subplot(111) try: xjj = x_grid[:, :, jj] yjj = y_grid[:, :, jj] grid_jj = grid[:, :, jj] plt.contourf(xjj, yjj, grid_jj) except IndexError: print("shape of x, y, z", x.shape, y.shape, z.shape) print("shape of x_grid, y_grid, z_grid", x_grid.shape, y_grid.shape, z_grid.shape) print("index value", jj, "y_val ", z_val) raise plt.xlabel(xlabel) plt.ylabel(ylabel) plt.title("Grid slice for {0}={1}".format(zlabel, z_val)) plot_name = os.path.join(simulators.paths["output_dir"], star, "iam", "grid_plots", "z__grid_slice_{0}_chip-{1}_{2}_{3}_{4}_{5}_{6}_{7}.png".format(star, chip, xlabel, ylabel, zlabel, jj, suffix, datetime.datetime.now())) plt.savefig(plot_name) plt.close(plt.gcf()) def target_params(params: Dict[str, Union[str, float, int]], mode: Optional[str] = "iam") -> Union[ Tuple[List[Union[int, float]], List[Union[int, float]]], List[Union[int, float]], Tuple[List[float], List[float]]]: """Extract parameters from dict for each target. Includes logic for handling missing companion logg/fe_h. """ host_params = [params["temp"], params["logg"], params["fe_h"]] # Specify the companion logg and metallicity in the parameter files. if params.get("comp_logg", None) is None: logging.warning(__("Logg for companion 'comp_logg' is not set for {0}", params.get("name", params))) print("mode in target params", mode) if mode == "iam": comp_logg = params.get("comp_logg", params["logg"]) # Set equal to host if not given comp_fe_h = params.get("comp_fe_h", params["fe_h"]) # Set equal to host if not given comp_temp = params.get("comp_temp", 999999) # Will go to largest grid comp_params = [comp_temp, comp_logg, comp_fe_h] return host_params, comp_params elif mode == "bhm": return host_params else: raise ValueError("Mode={} is invalid".format(mode))
45.450575
125
0.589247
2,462
19,771
4.532494
0.164094
0.023837
0.01631
0.010664
0.284613
0.234698
0.203423
0.159423
0.125818
0.125818
0
0.019843
0.296495
19,771
434
126
45.5553
0.782443
0.107177
0
0.186667
0
0.01
0.098256
0.01447
0
0
0
0
0.056667
1
0.04
false
0
0.063333
0
0.153333
0.036667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
4752834006b4c7e38581b00b04934cecb3b712df
4,910
py
Python
src/etl/transform.py
fmirani/etl_project
969990143c3075f193565cec309a2f0333038a8b
[ "MIT" ]
null
null
null
src/etl/transform.py
fmirani/etl_project
969990143c3075f193565cec309a2f0333038a8b
[ "MIT" ]
null
null
null
src/etl/transform.py
fmirani/etl_project
969990143c3075f193565cec309a2f0333038a8b
[ "MIT" ]
null
null
null
import pandas as pd from datetime import datetime, timedelta from bs4 import BeautifulSoup as bs from etl.logger import get_logger from etl.main import ETL logger = get_logger("transform") def transform_data(service: str, data_file: str) -> pd.DataFrame: """ Simple function to guide the request to the right function """ if service == "youtube": return transform_youtube_data(data_file) else: return transform_netflix_data(data_file) def transform_youtube_data(filename: str) -> pd.DataFrame: """ Function to fetch youtube data from the history file 1. Create a new dataframe to put data in 2. parse the html file to find required data 3. Format the data as needed 4. Populate the dataframe """ logger.info("Transforming YouTube data now") instance = ETL() simulated = instance.get_sim_status() simulate_offset = instance.get_simul_days() data = pd.DataFrame( columns=[ "Timestamp", "Source", "Type", "Name", "Season", "Episode", "Category", "Link", ] ) link = [] timestamp = [] # Open the watch history html file and parse through it for relevant data with open(filename, encoding="utf8") as f: soup = bs(f, "html.parser") tags = soup.find_all( "div", {"class": "content-cell mdl-cell mdl-cell--6-col mdl-typography--body-1"}, ) for i, tag in enumerate(tags): a_pointer = tag.find("a") dt = a_pointer.next_sibling.next_sibling date_time = datetime.strptime(str(dt)[:-4], "%b %d, %Y, %I:%M:%S %p") # If data fetching is simulated if ( simulated and date_time + timedelta(days=simulate_offset) > datetime.now() ): continue timestamp.append(date_time) link.append(a_pointer.text) # Populate the dataframe with the data data["Timestamp"] = timestamp data["Source"] = "YouTube" data["Type"] = "Video" data["Link"] = link # Log a warning if the DataFrame is being returned empty if data.shape[0] < 1: logger.warning(f"DataFrame does not contain any data") # Return dataframe return data def transform_netflix_data(filename: str) -> pd.DataFrame: """ Function to fetch netflix data from the history file 1. Create a new dataframe to put data in 2. parse the csv file to find required data 3. Format the data as needed 4. Populate the dataframe """ logger.info("Transforming Netflix data now") instance = ETL() simulated = instance.get_sim_status() simulate_offset = instance.get_simul_days() data = pd.DataFrame( columns=[ "Timestamp", "Source", "Type", "Name", "Season", "Episode", "Category", "Link", ] ) # Read csv data into a separate dataframe try: # Reading data from csv file nf_data = pd.read_csv(filename) except Exception as e: logger.error(f"Unable to read csv file '{filename}' : ", e) logger.warning(f"File does not contain valid data") return data # Import Timestamp column to our datadrame as datetime # Set "Source" column to "Netflix" # Import Name column to our dataframe data["Timestamp"] = pd.to_datetime(nf_data["Date"], format="%m/%d/%y") data["Source"] = "Netflix" data["Name"] = nf_data["Title"] # Keywords to identify if a title is a TV series keywds = ["Season", "Series", "Limited", "Part", "Volume", "Chapter"] # Set "Type" column to either "Movie" or "TV Series" data.loc[data["Name"].str.contains("|".join(keywds)), "Type"] = "TV Series" data.loc[data["Type"].isnull(), "Type"] = "Movie" # Wherever Type is "TV Series" split the Title column # in three: Name, Season and Episode data.loc[data["Type"] == "TV Series", "Name"] = nf_data["Title"].str.rsplit( ":", n=2, expand=True )[0] data.loc[data["Type"] == "TV Series", "Season"] = nf_data["Title"].str.rsplit( ":", n=2, expand=True )[1] data.loc[data["Type"] == "TV Series", "Episode"] = nf_data["Title"].str.rsplit( ":", n=2, expand=True )[2] # Some cleaning needed in Episode column data["Episode"] = data["Episode"].str.strip() # If data fetching is simulated if simulated: data = data.loc[ pd.to_datetime(data["Timestamp"]) < datetime.now() - timedelta(days=simulate_offset) ] # return DataFrame return data
31.075949
87
0.57169
597
4,910
4.628141
0.289782
0.020268
0.019906
0.021716
0.346363
0.332609
0.307637
0.281578
0.2519
0.217155
0
0.006213
0.311609
4,910
157
88
31.273885
0.811243
0.227495
0
0.323232
0
0
0.176172
0.006211
0
0
0
0
0
1
0.030303
false
0
0.050505
0
0.131313
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
0
0
0
1
0
4752de7c01e8d42225f7e14fb6052b77754c4e72
3,567
py
Python
student/urls.py
masoodazhar/-school-management-system
6525b3d29d12f03e05d362d81b7c5855806f57d9
[ "Apache-2.0" ]
1
2022-01-20T10:20:05.000Z
2022-01-20T10:20:05.000Z
student/urls.py
masoodazhar/-school-management-system
6525b3d29d12f03e05d362d81b7c5855806f57d9
[ "Apache-2.0" ]
null
null
null
student/urls.py
masoodazhar/-school-management-system
6525b3d29d12f03e05d362d81b7c5855806f57d9
[ "Apache-2.0" ]
1
2022-01-20T10:20:31.000Z
2022-01-20T10:20:31.000Z
from django.urls import path from academic.views import SectionCreate, SectionUpdate, SectionDelete from .views import ( StudentView, AttendanceMark, AttendanceSearch, AttendanceView, IndividualMarksView, AdmissionCreate, AdmissionView, AdmissionDelete, AdmissionUpdate, AdmissionDetail, StudentMarkSearch, StudentMarkCreate, MarkDistributionCreate, MarkDistributionUpdate, MarkDistributionDelete, ExamsView, ExamsDetail, ExamsCreate, ExamsUpdate, ExamsDelete, get_class_asignments, SendEmail_SaveData, SendEmailForExam, get_fee, get_subject_by_class, get_already_marks, getting_marks_from_calculated ) app_name = 'student' urlpatterns = [ path('', StudentView, name='student_view'), path('admission/create/', AdmissionCreate.as_view(), name='admission_create'), path('admission/view/', AdmissionView.as_view(), name='admission_view'), path('admission/view/<int:pk>/detail', AdmissionDetail.as_view(), name='admission_detail'), path('admission/view/<int:pk>/update', AdmissionUpdate.as_view(), name='admission_update'), path('admission/view/<int:pk>/delete', AdmissionDelete.as_view(), name='admission_delete'), path('createSection/', SectionCreate.as_view(), name='create_section'), path('updateSection/<int:pk>', SectionUpdate.as_view(), name='update_section'), path('deleteSection/<int:pk>/delete', SectionDelete.as_view(), name='delete_section'), path('viewexams/view', ExamsView.as_view(), name='view_exams'), path('createexams/', ExamsCreate.as_view(), name='create_exams'), path('detailexams/<int:pk>/detail', ExamsDetail.as_view(), name='detail_exams'), path('updateexams/<int:pk>/edit', ExamsUpdate.as_view(), name='update_exams'), path('deleteexams/<int:pk>/delete', ExamsDelete.as_view(), name='delete_exams'), path('SendEmail_SaveData/', SendEmail_SaveData, name='SendEmail_SaveData'), path('sendemailforexam/', SendEmailForExam.as_view(), name='sendemailforexam'), path('attendance/view', AttendanceView.as_view(), name='attendance_view'), path('attendance/search', AttendanceSearch.as_view(), name='attendance_search'), path('attendance/mark', AttendanceMark.as_view(), name='attendance_mark'), path('student_mark/search', StudentMarkSearch.as_view(), name='student_mark'), path('student_mark/add', StudentMarkCreate.as_view(), name='student_mark_add'), path('mark_distribution/create', MarkDistributionCreate.as_view(), name='mark_distribution_create'), path('mark_distribution/<int:pk>/update', MarkDistributionUpdate.as_view(), name='mark_distribution_update'), path('mark_distribution/<int:pk>/delete', MarkDistributionDelete.as_view(), name='mark_distribution_delete'), path('report/<int:student_name>/info', IndividualMarksView.as_view(), name='view_individual_marks'), path('report/<int:student_name>/info?year&tab', IndividualMarksView.as_view(), name='view_individual_marks2'), path('get_fee', get_fee, name="get_fee"), path('get_subject_by_class/', get_subject_by_class , name="get_subject_by_class"), path('get_already_marks/', get_already_marks , name="get_already_marks"), path('get_class_asignments/<int:pk>/class/<int:class_name>/subject/<int:subject>', get_class_asignments , name="get_class_asignments"), path('getting_marks_from_calculated/', getting_marks_from_calculated , name="getting_marks_from_calculated") ]
51.695652
140
0.724699
391
3,567
6.327366
0.199488
0.058205
0.097009
0.038399
0.168957
0.057397
0
0
0
0
0
0.000322
0.130642
3,567
68
141
52.455882
0.797485
0
0
0
0
0
0.352487
0.185249
0
0
0
0
0
1
0
false
0
0.046154
0
0.046154
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
0
0
0
1
0
47534f46ad8c13b23baa8376ad80237dfc62bd3c
827
py
Python
wenben_project/reco_sys/server/__init__.py
nameli0722/git-
29343ef0eec598aa262c59825d567044ef393f44
[ "MIT" ]
null
null
null
wenben_project/reco_sys/server/__init__.py
nameli0722/git-
29343ef0eec598aa262c59825d567044ef393f44
[ "MIT" ]
null
null
null
wenben_project/reco_sys/server/__init__.py
nameli0722/git-
29343ef0eec598aa262c59825d567044ef393f44
[ "MIT" ]
null
null
null
import happybase from settings.default import DefaultConfig import redis pool = happybase.ConnectionPool(size=10, host='hadoop-master', port=9090) # 召回数据 redis_client = redis.StrictRedis(host=DefaultConfig.REDIS_HOST, port=DefaultConfig.REDIS_PORT, db=10, decode_responses=True) # 用于缓存的Redis数据库 cache_client = redis.StrictRedis(host=DefaultConfig.REDIS_HOST, port=DefaultConfig.REDIS_PORT, db=8, decode_responses=True) from pyspark import SparkConf from pyspark.sql import SparkSession # spark配置 conf = SparkConf() conf.setAll(DefaultConfig.SPARK_GRPC_CONFIG) SORT_SPARK = SparkSession.builder.config(conf=conf).getOrCreate()
34.458333
73
0.629988
81
827
6.296296
0.481481
0.141176
0.086275
0.101961
0.298039
0.298039
0.298039
0.298039
0.298039
0.298039
0
0.015517
0.29867
827
24
74
34.458333
0.863793
0.031439
0
0.235294
0
0
0.016291
0
0
0
0
0
0
1
0
false
0
0.294118
0
0.294118
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
0
0
0
1
0
475a825b4f6b8ec63bbe41abb911aed22f74dd8a
11,153
py
Python
idarest/idarest_master.py
sfinktah/idarest75
ab2549b12e174aaef32ab6c933fe09b1232a8cce
[ "MIT" ]
null
null
null
idarest/idarest_master.py
sfinktah/idarest75
ab2549b12e174aaef32ab6c933fe09b1232a8cce
[ "MIT" ]
null
null
null
idarest/idarest_master.py
sfinktah/idarest75
ab2549b12e174aaef32ab6c933fe09b1232a8cce
[ "MIT" ]
null
null
null
import socket try: from .idarest_mixins import IdaRestConfiguration except: from idarest_mixins import IdaRestConfiguration # idarest_master_plugin_t.config['master_debug'] = False # idarest_master_plugin_t.config['master_info'] = False # idarest_master_plugin_t.config['api_prefix'] = '/ida/api/v1.0' # idarest_master_plugin_t.config['master_host'] = "127.0.0.1" # idarest_master_plugin_t.config['master_port'] = 28612 # hash('idarest75') & 0xffff MENU_PATH = 'Edit/Other' try: import idc import ida_idaapi import ida_kernwin import idaapi import idautils from PyQt5 import QtWidgets except: class idc: @staticmethod def msg(s): if idarest_master_plugin_t.config['master_debug']: print(s) class ida_idaapi: plugin_t = object PLUGIN_SKIP = PLUGIN_UNL = PLUGIN_KEEP = 0 class idarest_master_plugin_t(IdaRestConfiguration, ida_idaapi.plugin_t): flags = ida_idaapi.PLUGIN_UNL comment = "IDA Rest API Master Controller" help = "Keeps track of idarest75 clients" wanted_name = "idarest75 master" wanted_hotkey = "" def init(self): super(idarest_master_plugin_t, self).__init__() self.load_configuration() if idarest_master_plugin_t.config['master_info']: print("[idarest_master_plugin_t::init]") self.master = None if not idarest_master_plugin_t.test_bind_port(idarest_master_plugin_t.config['master_port']): if idarest_master_plugin_t.config['master_info']: print("[idarest_master_plugin_t::init] skipping (port is already bound)") return idaapi.PLUGIN_SKIP self.master = idarest_master() idarest_master_plugin_t.instance = self return idaapi.PLUGIN_KEEP def run(*args): pass def term(self): if self.master: self.master.stop() pass @staticmethod def test_bind_port(port): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: try: # s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((idarest_master_plugin_t.config['master_host'], port)) except socket.error as e: return False return True def idarest_master(): from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn import threading import urllib.request, urllib.error, urllib.parse as urlparse import requests import json import time import re def asBytes(s): if isinstance(s, str): return s.encode('utf-8') return s class HTTPRequestError(BaseException): def __init__(self, msg, code): self.msg = msg self.code = code class Handler(BaseHTTPRequestHandler): hosts = dict() def log_message(self, format, *args): return def register(self, args): host, port = args['host'], args['port'] key = host + ':' + port if key in self.hosts: if idarest_master_plugin_t.config['master_debug']: print("[idarest_master::Handler::register] replacing existing host {}".format(key)) self.hosts[key] = value = dict({ 'host': args['host'], 'port': args['port'], 'idb': args['idb'], 'alive': time.time(), 'failed': 0, }) return value def unregister(self, args): host, port = args['host'], args['port'] key = host + ':' + port if key in self.hosts: if idarest_master_plugin_t.config['master_debug']: print("[idarest_master::Handler::unregister] removing existing host {}".format(key)) value = self.hosts.pop(key) else: value = dict({ 'host': args['host'], 'port': args['port'], 'error': 'not registered', }) return value @staticmethod def get_json(hosts, args, readonly=False): # r = requests.post(self.url, data=self.args) results = dict() start = time.time() if readonly: for k, host in hosts.items(): if idarest_master_plugin_t.config['master_debug']: print("alive: {}".format(start - host['alive'])) if start - host['alive'] < 90: results[host['idb']] = 'http://{}:{}{}/'.format(host['host'], host['port'], idarest_master_plugin_t.config['api_prefix']) else: results[host['idb']] = start - host['alive'] return results for k, host in hosts.items(): start = time.time() url = 'http://{}:{}{}/echo'.format(host['host'], host['port'], idarest_master_plugin_t.config['api_prefix']) try: connect_timeout = 10 read_timeout = 10 r = requests.get(url, params=args, timeout=(connect_timeout, read_timeout)) if r.status_code == 200: hosts[k]['alive'] = start hosts[k]['rtime'] = r.elapsed.total_seconds() # hosts[k]['info'] = r.json() results[k] = host except Exception as e: results[k] = str(type(e)) hosts[k]['failed'] += 1 if hosts[k]['failed'] > 4: hosts.pop(k) return results def show(self, args): return self.get_json(self.hosts, {'ping': time.time()}, readonly=True) def _extract_query_map(self): query = urlparse.urlparse(self.path).query qd = urlparse.parse_qs(query) args = {} for k, v in qd.items(): if len(v) != 1: raise HTTPRequestError( "Query param specified multiple times : " + k, 400) args[k.lower()] = v[0] if idarest_master_plugin_t.config['master_debug']: print('args["{}"]: "{}"'.format(k.lower(), v[0])) return args def send_origin_headers(self): if self.headers.get('Origin', '') == 'null': self.send_header('Access-Control-Allow-Origin', self.headers.get('Origin')) self.send_header('Vary', 'Origin') def do_GET(self): try: args = self._extract_query_map() except HTTPRequestError as e: self.send_error(e.code, e.msg) return path = re.sub(r'.*/', '', urlparse.urlparse(self.path).path) if path == 'register': message = self.register(args) elif path == 'unregister': message = self.unregister(args) elif path == 'show': message = self.show(args) else: self.send_error(400, "unknown route: " + path) return self.send_response(200) self.send_origin_headers() self.end_headers() self.wfile.write(asBytes(json.dumps(message))) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): allow_reuse_address = True # https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread class Timer(threading.Thread): def __init__(self, *args, **kwargs): super(Timer, self).__init__(*args, **kwargs) self._stop_event = threading.Event() def run(self): if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Timer::run] started") while True: if self._stop_event.wait(60.0): break result = Handler.get_json(Handler.hosts, {'ping': time.time()}) if idarest_master_plugin_t.config['master_debug']: print("[idarest_master::Timer::run] {}".format(result)) if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Timer::run] stopped") # if not self.running: # self.running = True # while self.running: # time.sleep(60.0 - ((time.time() - self.starttime) % 60.0)) # if idarest_master_plugin_t.config['master_debug']: print(Handler.get_json(Handler.hosts, {'ping': time.time()})) # if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Timer::run] stopped") def stop(self): if self.is_alive(): if self.stopped(): if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Timer::stop] already stopping...") else: if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Timer::stop] stopping...") self._stop_event.set() else: if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Timer::stop] not running") def stopped(self): return self._stop_event.is_set() class Worker(threading.Thread): def __init__(self, host, port): threading.Thread.__init__(self) self.httpd = ThreadedHTTPServer((host, port), Handler) self.host = host self.port = port def run(self): if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Worker::run] master httpd starting...") self.httpd.serve_forever() if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Worker::run] master httpd started (well stopped now, i guess)") def stop(self): if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Worker::stop] master httpd shutdown...") self.httpd.shutdown() if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Worker::stop] master httpd server_close...") self.httpd.server_close() if idarest_master_plugin_t.config['master_info']: print("[idarest_master::Worker::stop] master httpd stopped") class Master: def __init__(self): self.worker = Worker('127.0.0.1', 28612) self.worker.start() self.test_worker = Timer() self.test_worker.start() def stop(self): self.worker.stop() self.test_worker.stop() def main(): if idarest_master_plugin_t.config['master_info']: print("[idarest_master::main] starting master") master = Master() # main.master = master return master return main() def PLUGIN_ENTRY(): globals()['instance'] = idarest_master_plugin_t() return globals()['instance'] if __name__ == "__main__": master = idarest_master()
38.725694
151
0.56505
1,247
11,153
4.837209
0.19567
0.118534
0.116545
0.122679
0.363893
0.339688
0.330736
0.288959
0.278017
0.263428
0
0.009671
0.313907
11,153
287
152
38.860627
0.77862
0.078992
0
0.202643
0
0
0.147859
0.048961
0
0
0
0
0
1
0.118943
false
0.008811
0.07489
0.013216
0.370044
0.0837
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
475b01893fd7ae3f1c364df0596288e775da3bcd
11,750
py
Python
wordbot.py
spyth/wordbot
8213d18fcd7602a5b2bab9c83898b9f29a1cf3d4
[ "MIT" ]
null
null
null
wordbot.py
spyth/wordbot
8213d18fcd7602a5b2bab9c83898b9f29a1cf3d4
[ "MIT" ]
null
null
null
wordbot.py
spyth/wordbot
8213d18fcd7602a5b2bab9c83898b9f29a1cf3d4
[ "MIT" ]
null
null
null
import logging import json from datetime import datetime from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, Job, CallbackQueryHandler) from telegram import (ChatAction, ParseMode, InlineKeyboardButton, InlineKeyboardMarkup) from peewee import fn import pytz from word import word_query from model import User, UserVocabularyMapping, Vocabulary, init as model_init logger = logging.getLogger(__name__) class WordBot(object): def __init__(self, BOT_TOKEN, COUNT_CHECK=5, timezone='Asia/Hong_Kong', notify_time='23:00'): self.updater = Updater(token=BOT_TOKEN) dispatcher = self.updater.dispatcher self.COUNT_CHECK = COUNT_CHECK start_handler = CommandHandler('start', self.start) test_handler = CommandHandler('test', self.test) review_handler = CommandHandler('review', self.review) query_handler = MessageHandler(Filters.text, self.query) dispatcher.add_handler(start_handler) dispatcher.add_handler(query_handler) dispatcher.add_handler(review_handler) dispatcher.add_handler(test_handler) dispatcher.add_handler(CallbackQueryHandler(self.reply_button_callback)) # add daily reminder if notify_time: try: tz = pytz.timezone(timezone) utc_now = pytz.utc.localize(datetime.utcnow()) tz_now = utc_now.astimezone(tz) hour, minute = tuple(map(int, notify_time.split(':'))) expect_time = tz_now.replace(hour=hour, minute=minute, second=0, microsecond=0) delay = (int((expect_time - tz_now).total_seconds()) + 24 * 60 * 60) % (24 * 60 * 60) self.updater.job_queue.run_daily(self.daily_remind, time=delay) except: logger.warning('oops, daily reminder start failed!') raise def run(self): self.updater.start_polling() self.updater.idle() @staticmethod def daily_remind(bot, job): for u in User.select(): bot.send_message(chat_id=u.tgid, text="👩‍🏫 Would you like to /review or /test vocabulary?") @staticmethod def start(bot, update): bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING) user, new_created = User.get_or_create(tgid=str(update.message.from_user.id)) if new_created: bot.send_message(chat_id=update.message.chat_id, text="Hi!") else: bot.send_message(chat_id=update.message.chat_id, text="Hi, nice to see you again.") @staticmethod def query(bot, update): bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING) vocabulary = word_query(update.message.text) if vocabulary is not None: response = str(vocabulary) else: response = '👽 500' bot.send_message(chat_id=update.message.chat_id, text=response, parse_mode=ParseMode.HTML) if vocabulary and vocabulary.audio: bot.send_audio(chat_id=update.message.chat_id, audio=open(vocabulary.audio, 'rb')) user, new_created = User.get_or_create(tgid=str(update.message.from_user.id)) if vocabulary is not None: mapping, new_created = UserVocabularyMapping.get_or_create(user=user, vocabulary=vocabulary) if (not new_created) and mapping.check_times > 0: mapping.update(check_times=0).execute() @staticmethod def review(bot, update): bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING) user, new_created = User.get_or_create(tgid=str(update.message.from_user.id)) if new_created or user.uservocabularymapping_set.count() == 0: bot.send_message(chat_id=update.message.chat_id, text="you don't have any vocabulary yet!") return None keyboard = [[InlineKeyboardButton('🔁', callback_data='{"command": "review", "type": "order", "arg": 0, "check": 0}'), InlineKeyboardButton('🔀', callback_data='{"command": "review", "type": "shuffle", "arg": 0, "check": 0}')]] reply_markup = InlineKeyboardMarkup(keyboard, one_time_keyboard=True) bot.send_message(chat_id=update.message.chat_id, text="🐰 OK! Let's start to review.\nPlease select the play mode.", reply_markup=reply_markup) @staticmethod def test(bot, update): # bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING) word = Vocabulary.select(Vocabulary.id, Vocabulary.word).order_by(fn.Random()).limit(1).first() reply = "**%s**?" % word.word keyboard = [[InlineKeyboardButton("❓", callback_data='{"command": "test", "type": "ask", "arg": %d}' % word.id), InlineKeyboardButton("✅", callback_data='{"command": "test", "type": "check", "arg": %d}' % word.id)]] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=update.message.chat_id, text=reply, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN) def reply_button_callback(self, bot, update): query = update.callback_query chat_id = query.message.chat_id try: data = json.loads(query.data) except: data = None if not (data and type(data) == dict and 'command' in data): bot.edit_message_text(text="unknown command🕴", chat_id=chat_id, message_id=query.message.message_id) logger.warning(query) return if data['command'] == 'review': # bot.sendChatAction(chat_id=chat_id, action=ChatAction.TYPING) _id = data['arg'] if data['check'] == 1: UserVocabularyMapping.update(check_times=UserVocabularyMapping.check_times + 1) \ .where(UserVocabularyMapping.id == _id).execute() mapping = UserVocabularyMapping.get(id=_id) if mapping.check_times >= self.COUNT_CHECK: reply_text = str(mapping.vocabulary) + '\n' + '🎉' * self.COUNT_CHECK else: reply_text = str(mapping.vocabulary) + '\n' + '⭐️' * mapping.check_times bot.edit_message_text(text=reply_text, chat_id=chat_id, message_id=query.message.message_id) else: # clear the previous reply button bot.edit_message_reply_markup(chat_id=chat_id, message_id=query.message.message_id) if data['type'] == 'order': mapping_query = UserVocabularyMapping.select().join(User) \ .where((UserVocabularyMapping.id > _id) & (User.tgid == str(chat_id)) \ & (UserVocabularyMapping.check_times < self.COUNT_CHECK)) \ .order_by(UserVocabularyMapping.id).limit(1) # repeat if _id > 0 and mapping_query.count() == 0: mapping_query = UserVocabularyMapping.select().join(User) \ .where((User.tgid == str(chat_id)) \ & (UserVocabularyMapping.check_times < self.COUNT_CHECK)) \ .order_by(UserVocabularyMapping.id).limit(1) if mapping_query.count() > 0: mapping = mapping_query[0] reply = str(mapping.vocabulary) keyboard = [[InlineKeyboardButton("✅", callback_data='{"command": "review", "type": "order", "arg": %d, "check": 1}' % mapping.id), InlineKeyboardButton("⏭", callback_data='{"command": "review", "type": "order", "arg": %d, "check": 0}' % mapping.id), ]] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=chat_id, text=reply, reply_markup=reply_markup) else: bot.send_message(chat_id=chat_id, text="end🕴") # shuffle else: mapping_query = UserVocabularyMapping.select().join(User) \ .where((User.tgid == str(chat_id)) \ & (UserVocabularyMapping.check_times < self.COUNT_CHECK)) \ .order_by(fn.Random()).limit(1) if mapping_query.count() > 0: mapping = mapping_query[0] reply = str(mapping.vocabulary) keyboard = [[InlineKeyboardButton("✅", callback_data='{"command": "review", "type": "shuffle", "arg": %d, "check": 1}' % mapping.id), InlineKeyboardButton("⏭", callback_data='{"command": "review", "type": "shuffle", "arg": %d, "check": 0}' % mapping.id), ]] reply_markup = InlineKeyboardMarkup(keyboard) bot.send_message(chat_id=chat_id, text=reply, reply_markup=reply_markup) else: bot.send_message(chat_id=chat_id, text="end🕴") elif data['command'] == 'test': if data['type'] == 'next': bot.edit_message_reply_markup(chat_id=chat_id, message_id=query.message.message_id) self.test(bot, query) else: try: _id = data['arg'] word = Vocabulary.get(id=_id) except Vocabulary.DoesNotExist: bot.edit_message_text(text='oops!', chat_id=chat_id, message_id=query.message.message_id) return user, _ = User.get_or_create(tgid=str(chat_id)) mapping, new_created = UserVocabularyMapping.get_or_create(user=user, vocabulary=word) if data['type'] == 'check': extra_msg = '\n' + '⭐️' * (mapping.check_times + 1) UserVocabularyMapping.update(check_times=UserVocabularyMapping.check_times + 1) \ .where(UserVocabularyMapping.id == mapping.id).execute() else: extra_msg = '\n' + '😆' if (not new_created) and mapping.check_times > 0: UserVocabularyMapping.update(check_times=0).where( UserVocabularyMapping.id == mapping.id).execute() keyboard = [[InlineKeyboardButton("⏭", callback_data='{"command": "test", "type": "next"}')]] reply_markup = InlineKeyboardMarkup(keyboard) bot.edit_message_text(text=str(word) + extra_msg, chat_id=chat_id, message_id=query.message.message_id, reply_markup=reply_markup) else: pass if __name__ == '__main__': logging.basicConfig(filename='spam.log', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) import os file_path = os.path.abspath(os.path.dirname(__file__)) if not os.path.exists(os.path.join(file_path, "audio")): os.mkdir(os.path.join(file_path, "audio")) if not os.path.isfile(os.path.join(file_path, 'bot.db')): model_init() import config bot = WordBot(config.BOT_TOKEN, timezone=config.TIMEZONE, notify_time=config.NOTIFY_TIME) bot.run()
50.213675
151
0.575149
1,267
11,750
5.148382
0.172849
0.046911
0.045838
0.030354
0.529664
0.458685
0.420972
0.401349
0.39721
0.382493
0
0.006031
0.308511
11,750
233
152
50.429185
0.793969
0.017362
0
0.335025
0
0.030457
0.082763
0
0.010152
0
0
0
0
1
0.040609
false
0.005076
0.055838
0
0.116751
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
0
0
0
1
0
475f6eec7136ec2401074e0d2a574922b79ef08a
1,829
py
Python
cosPreprints.py
leouieda/cospy
fa0994e5a41896cd17f76fdad08b20bdb4dd112a
[ "MIT" ]
null
null
null
cosPreprints.py
leouieda/cospy
fa0994e5a41896cd17f76fdad08b20bdb4dd112a
[ "MIT" ]
8
2019-06-10T12:56:56.000Z
2019-07-02T16:49:40.000Z
cosPreprints.py
leouieda/cospy
fa0994e5a41896cd17f76fdad08b20bdb4dd112a
[ "MIT" ]
null
null
null
import os import sys import utils import extras.downloadStats as stats import extras.downloadManuscript as dm import extras.unpaywall as up def main(): # get the configuration parameters from environment variables cosApiToken = os.environ['cosApiToken'] # for accessing COS API emailAddress = os.environ['emailAddress'] # for accessing Unpaywall API # command line inputs # downloadDir - directory to download papers to, also where logs are stored downloadDir = sys.argv[1] # print out status messages as we go along (True or False) verbose = sys.argv[2] # start date - YYYY-MM-DD we should start the index from startDate = sys.argv[3] endDate = sys.argv[4] df = utils.getProviders( cosApiToken ) # seperator for log file s1 = ';' # the API returns all preprints that were created # some papers may not be available for download # due to moderation problems or retraction # keep track of how many preprints we actually get numPreprints = 0 # check that the download directory includes # the trailing / lc = downloadDir[-1] if (lc != '/'): downloadDir += '/' # preprint provider provider = 'eartharxiv' # set up log files based on provider log = downloadDir + provider + '.log' # get the papers manuscripts = utils.getManuscripts(cosApiToken, provider, startDate, endDate, verbose) # example downloading PDF dm.download( manuscripts['downloadURL'][0], '/Users/narock/Desktop/test.pdf') # example getting download statistics downloads = stats.getDownloadStats( cosApiToken, manuscripts['cosID'][0] ) print( manuscripts['cosID'][0], 'downloaded', downloads, 'times') # example calling unpaywall manuscripts, statistics = up.callUnpaywall( manuscripts, emailAddress ) print( statistics ) main()
29.983607
89
0.708037
223
1,829
5.807175
0.565022
0.021622
0.026255
0
0
0
0
0
0
0
0
0.006882
0.205577
1,829
60
90
30.483333
0.884377
0.402406
0
0
0
0
0.098881
0.027985
0
0
0
0
0
1
0.035714
false
0
0.214286
0
0.25
0.107143
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0