repo_name
stringlengths
7
111
__id__
int64
16.6k
19,705B
blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
151
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_url
stringlengths
26
130
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
42
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
14.6k
687M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
12 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
10.2M
gha_stargazers_count
int32
0
178k
gha_forks_count
int32
0
88.9k
gha_open_issues_count
int32
0
2.72k
gha_language
stringlengths
1
16
gha_archived
bool
1 class
gha_disabled
bool
1 class
content
stringlengths
10
2.95M
src_encoding
stringclasses
5 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
10
2.95M
extension
stringclasses
19 values
num_repo_files
int64
1
202k
filename
stringlengths
4
112
num_lang_files
int64
1
202k
alphanum_fraction
float64
0.26
0.89
alpha_fraction
float64
0.2
0.89
hex_fraction
float64
0
0.09
num_lines
int32
1
93.6k
avg_line_length
float64
4.57
103
max_line_length
int64
7
931
ALGAWA/TFM1
4,595,615,033,821
eb517a3e3a90e7129db031c8dee9c51e61320d49
82757d751d9be290e7f45dd50c09eced8c03d930
/TFM1app/urls.py
44b83188d234f5bdc5d78e63964d260e4416464d
[]
no_license
https://github.com/ALGAWA/TFM1
bcedff86eb7d37c2d3af3630f1aea169ccb83792
db89522e566f4ad00bf6d58c9c1d8e4ddd759cad
refs/heads/master
2020-03-29T05:13:50.460825
2016-07-05T15:32:04
2016-07-05T15:32:04
61,032,371
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import url from . import views, viewbcn,viewIndex, viewfiltros from . import viewfiltrosbcn, viewActualizarbcn, ActualizarMad from TFM1app import viewIndexCreate, viewCrearmadrid, viewCrearbcn, viewsActualiza urlpatterns = [ url(r'^([\D]+)/$',viewfiltros.Por_tipo, name='Por_tipo'), url(r'^([\D]+)/b$',viewfiltrosbcn.Por_tipo, name='Por_tipo'), url(r'^crea/mad$', viewCrearmadrid.Crear_mad, name='Crear_mad'), url(r'^crea/bcn$',viewCrearbcn.Crear_bcn, name='Crear_bcn'), url(r'^crea$', viewIndexCreate.IndexCrear, name='IndexCrear'), url(r'^mad$', views.Activ_listmad, name='Activ_listmad'), url(r'^bcn$',viewbcn.Activ_listbcn, name='Activ_listbcn'), url(r'^actua$', viewsActualiza.IndexAdmin, name='IndexAdmin'), url(r'^actua/mad$', ActualizarMad.Actualizar_mad, name='Actualizar_mad'), url(r'^actua/bcn$',viewActualizarbcn.Obtenerdatosbcn, name='Obtenerdatosbcn'), url(r'^musica$',viewfiltros.Por_tipo_Musica, name='Por_tipo_Musica'), url(r'^cine$',viewfiltros.Por_tipo_cine, name='Por_tipo_cine'), url(r'^fiestas$',viewfiltros.Por_tipo_Fiestas, name='Por_tipo_Fiestas'), url(r'^cuentos$',viewfiltros.Por_tipo_CuentaCuentos, name='Por_tipo_CuentaCuentos'), url(r'^comemoraciones$',viewfiltros.Por_tipo_ComemoracionesHomenajes, name='Por_tipo_ComemoracionesHomenajes'), url(r'^destacada$',viewfiltros. Por_tipo_ProgramacionDestacada, name=' Por_tipo_ProgramacionDestacada'), url(r'^danza$',viewfiltros.Por_tipo_Danza, name='Por_tipo_Danza'), url(r'^conferencias$',viewfiltros.Por_tipo_Conferencias, name='Por_tipo_Conferencias'), url(r'^talleres$',viewfiltros.Por_tipo_CursosTalleres, name='Por_tipo_CursosTalleres'), url(r'^actividades$',viewfiltros.Por_tipo_Actividades, name='Por_tipo_Actividades'), url(r'^circo$',viewfiltros.Por_tipo_Circo, name='Por_tipo_Circo'), url(r'^concursos$',viewfiltros.Por_tipo_Cocursos, name='Por_tipo_Cocursos'), url(r'^congresos$',viewfiltros.Por_tipo_Congresos, name='Por_tipo_Congresos'), url(r'^excursiones$',viewfiltros.Por_tipo_Excursiones, name='Por_tipo_Excursiones'), url(r'^ferias$',viewfiltros.Por_tipo_Ferias, name='Por_tipo_Ferias'), url(r'^recitales$',viewfiltros.Por_tipo_Recitales, name='Por_tipo_Recitales'), url(r'^exposiciones$',viewfiltros.Por_tipo_Exposiciones, name='Por_tipo_Exposiciones'), url(r'^cinebarcelona$',viewfiltrosbcn.Por_tipo_cine, name='Por_tipoc_Cine'), url(r'^coloniasbcn$',viewfiltrosbcn.Por_tipo_Colonias, name='Por_tipo_Colonias'), url(r'^cogresosbcn$',viewfiltrosbcn.Por_tipo_Congresos, name='Por_tipo_Congresos'), url(r'^deportesbcn$',viewfiltrosbcn.Por_tipo_Deportes, name='Por_tipo_Deportes'), url(r'^Exposicionesbcn$',viewfiltrosbcn.Por_tipo_Exposiciones, name='Por_tipo_Exposiciones'), url(r'^feriasbcn$',viewfiltrosbcn.Por_tipo_Ferias, name='Por_tipo_Ferias'), url(r'^culturageneralbcn$',viewfiltrosbcn.Por_tipo_culturageneral, name='Por_tipo_culturageneral'), url(r'^fiestasbcn$',viewfiltrosbcn.Por_tipo_Fiestas, name='Por_tipo_Fiestas'), url(r'^juegosbcn$',viewfiltrosbcn. Por_tipo_Juegos, name=' Por_tipo_Juegos'), url(r'^Literaturabcn$',viewfiltrosbcn.Por_tipo_Literatura, name='Por_tipo_Literatura'), url(r'^modabcn$',viewfiltrosbcn.Por_tipo_Moda, name='Por_tipo_Moda'), url(r'^musicbcn$',viewfiltrosbcn.Por_tipo_Musica, name='Por_tipo_Musica'), url(r'^ninosbcn$',viewfiltrosbcn.Por_tipo_Ninos, name='Por_tipo_Ninos'), url(r'^premiosbcn$',viewfiltrosbcn.Por_tipo_Premios, name='Por_tipo_Premios'), url(r'^religiososbcn$',viewfiltrosbcn.Por_tipo_Religiosos, name='Por_tipo_Religiosos'), url(r'^solidaridadbcn$',viewfiltrosbcn.Por_tipo_Solidaridad, name='Por_tipo_Solidaridad'), url(r'^teatrobcn$',viewfiltrosbcn.Por_tipo_Teatro, name='Por_tipo_Teatro'), url(r'^visitasbcn$',viewfiltrosbcn.Por_tipo_Visitas, name='Por_tipo_Visitas'), url(r'', viewIndex.Index, name='Index') ]
UTF-8
Python
false
false
3,810
py
24
urls.py
14
0.754068
0.753806
0
64
58.3125
111
dbritto-dev/signxml_sunat
15,530,601,763,226
29614f3d4cf91fc72d7fac7b916dec0ef983a5e3
3ffe5b41b896c2cd044c7224ae5abab838ee25c0
/test/test.py
a2e8f265498c25490ebe6ba6896c942eda0fdcce
[ "MIT" ]
permissive
https://github.com/dbritto-dev/signxml_sunat
86b4be23a651ad2afcc76e1d803d9e207be9399c
1e9d1f3e6ae6d7ec01769fe355aa682648922764
refs/heads/master
2022-09-29T22:49:08.997238
2022-08-31T16:23:58
2022-08-31T16:23:58
153,178,740
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import unittest from lxml import etree from signxml_sunat import XMLSigner, XMLVerifier class TestSignXMLSunat(unittest.TestCase): def test_sign(self): signed_doc = XMLSigner().sign('doc.xml', 'rsakey.pem', 'rsacert.pem') signed_doc_str = etree.tostring(signed_xml, xml_declaration=True, encoding='ISO-8859-1', pretty_print=True) result_signed_doc_str = open('signed_doc.xml').read() self.assertEqual(signed_doc, result_signed_doc_str) def test_verify(self): verify = XMLVerifier().verify('sunat_signed.xml', 'rsapub.pem') self.assertTrue(verify) if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
655
py
7
test.py
4
0.674809
0.667176
0
19
33.526316
115
srgzyq/study
11,175,504,944,851
c70a77260fadd1a385488768c7dc241faa8e0451
faf187e47a0c01385592a3213c413542bf8f47bc
/PythonStudy/RegularExp/languageData.py
e37e57f0287440197f1a2112d5287df5cd9d2cd7
[]
no_license
https://github.com/srgzyq/study
8f3442b781b45408810f46ad5a6f935aef6f8c97
9cefd7b6db983c3c63e7268a98a00af276d8f90f
refs/heads/master
2021-01-10T20:59:06.176284
2020-03-26T13:54:11
2020-03-26T13:54:11
5,468,749
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding=utf-8 import re test ="[\'ChongzhiLongmai\']=\"寅时已过,龙脉重置,获得两个骰子\"", print test
UTF-8
Python
false
false
124
py
94
languageData.py
44
0.652174
0.641304
0
6
14
52
zhshtabibito/OTS-by-ZS-and-KYF
2,130,303,782,480
e4da8ff8d57528feffa448588a2327346802fc91
7aacd62854f49be73bb549533237c76dbf2ac1b8
/tools/make_comb_audio.py
7221cc694bef6e5d0bfa1266f495da766c4a8788
[]
no_license
https://github.com/zhshtabibito/OTS-by-ZS-and-KYF
66638c539746e3ce8c3582e8666a949ea5a364f9
7235e04f48523b4fc9b0678d4e23f63dacb83761
refs/heads/master
2020-04-13T05:55:43.893572
2019-01-08T12:36:25
2019-01-08T12:36:25
163,006,876
0
0
null
false
2019-01-08T12:36:27
2018-12-24T16:16:13
2018-12-25T08:39:55
2019-01-08T12:36:26
226,552
0
0
0
Python
false
null
import numpy as np import matplotlib.pyplot as plt import os, sys import glob import wave import struct import xml.dom.minidom import random # from dataHelper.Utils import read_video def comb_duet(label1, label2, no1, no2, path): # only horizontal cropping, crop1 and crop2 are like [x1,w1] savename = label1 + '_' + str(no1) + '_' + label2 + '_' + str(no2) if os.path.exists(path + savename) == False: os.mkdir(path + savename) ''' #if the videos are read, do not read them again read_video('dataset/videos/solo/'+label1,'dataset/audios/solo/'+label1,'dataset/images/solo/'+label1,1,no1) read_video('dataset/videos/solo/'+label2,'dataset/audios/solo/'+label2,'dataset/images/solo/'+label2,1,no2) ''' f1 = wave.open(u'F:/shiting/dataset/audios/cut/' + label1 + '/' + str(no1) + '.wav') params1 = f1.getparams() nchannels, sampwidth, framerate, nframes1 = params1[:4] strdata = f1.readframes(nframes1) wavedata = np.fromstring(strdata, dtype=np.int16) wavedata1 = wavedata * 1.0 / (max(abs(wavedata))) f2 = wave.open(u'F:/shiting/dataset/audios/cut/' + label2 + '/' + str(no2) + '.wav') params2 = f2.getparams() nchannels, sampwidth, framerate, nframes2 = params2[:4] strdata = f2.readframes(nframes2) wavedata = np.fromstring(strdata, dtype=np.int16) wavedata2 = wavedata * 1.0 / (max(abs(wavedata))) time = min(nframes1, nframes2) / framerate - 1 print(time) wavedata1 = wavedata1[:int(time * framerate)] wavedata2 = wavedata2[:int(time * framerate)] wavedata4 = wavedata1 / max(max(abs(wavedata1 + wavedata2)), 1) wavedata5 = wavedata2 / max(max(abs(wavedata1 + wavedata2)), 1) outwave = wave.open(path + savename + '/1.wav', 'wb') outwave.setparams((nchannels, sampwidth, framerate, time * framerate, 'NONE', 'not compressed')) for v in wavedata4: outwave.writeframes(struct.pack('h', int(v * 64000 / 2))) outwave.close() outwave = wave.open(path + savename + '/2.wav', 'wb') outwave.setparams((nchannels, sampwidth, framerate, time * framerate, 'NONE', 'not compressed')) for v in wavedata5: outwave.writeframes(struct.pack('h', int(v * 64000 / 2))) outwave.close() wavedata3 = (wavedata1 + wavedata2) / max(max(abs(wavedata1 + wavedata2)), 1) outwave = wave.open(path + savename + '/comb.wav', 'wb') outwave.setparams((nchannels, sampwidth, framerate, time * framerate, 'NONE', 'not compressed')) for v in wavedata3: outwave.writeframes(struct.pack('h', int(v * 64000 / 2))) outwave.close() def main(): audioPath = u'F:\\shiting\\dataset\\audios\\cut\\' pathTrain = u'F:\\shiting\\dataset\\audios\\mycomp_py_train\\' pathTest = u'F:\\shiting\\dataset\\audios\\mycomp_py_test\\' if os.path.exists(pathTrain) == False: os.mkdir(pathTrain) if os.path.exists(pathTest) == False: os.mkdir(pathTest) inss = ['accordion', 'acoustic_guitar', 'cello', 'flute', 'saxophone', 'trumpet', 'violin', 'xylophone'] global_cnt = 1 for a in range(7): in1 = inss[a] aNum = len(glob.glob(audioPath + in1 + '\\*.wav')) for b in range(a + 1, 8): in2 = inss[b] bNum = len(glob.glob(audioPath + in2 + '\\*.wav')) for cnt in range(72): x = random.randint(1, aNum - int(0.2*aNum)) y = random.randint(1, bNum - int(0.2*bNum)) comb_duet(in1, in2, x, y, pathTrain) print(global_cnt) global_cnt+=1 for cnt in range(2): x = random.randint(aNum-int(0.2 * aNum)+1, aNum) y = random.randint(bNum-int(0.2 * aNum)+1, bNum) comb_duet(in1, in2, x, y, pathTest) if __name__ == '__main__': main()
UTF-8
Python
false
false
3,819
py
24
make_comb_audio.py
16
0.611678
0.578686
0
87
42.896552
111
aravindsriraj/machine-learning-python-datacamp
1,202,590,851,381
02495e66a0783b345ca0b28bc9eba3fc29f9d6e0
72d88ac4ca463755a6653d7a2aa696b2dde0a648
/Machine Learning Scientist with Python Track/20. Hyperparameter Tuning in Python/ch1_exercises.py
5279a8e28f141119d589cd14338dc2acbacf951a
[ "MIT" ]
permissive
https://github.com/aravindsriraj/machine-learning-python-datacamp
125b915ef0f6c36de56d6aa5660b612adf5658d9
65c180163b1ad235c79d85d4926e586a15a5f78f
refs/heads/master
2023-03-18T05:12:53.574160
2020-09-14T00:23:50
2020-09-14T00:23:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Exercise_1 # Create a list of original variable names from the training DataFrame original_variables = X_train.columns # Extract the coefficients of the logistic regression estimator model_coefficients = log_reg_clf.coef_[0] # Create a dataframe of the variables and coefficients & print it out coefficient_df = pd.DataFrame({"Variable" : original_variables, "Coefficient": model_coefficients}) print(coefficient_df) # Print out the top 3 positive variables top_three_df = coefficient_df.sort_values(by='Coefficient', axis=0, ascending=False)[0:3] print(top_three_df) -------------------------------------------------- # Exercise_2 # Extract the 7th (index 6) tree from the random forest chosen_tree = rf_clf.estimators_[6] # Visualize the graph using the provided image imgplot = plt.imshow(tree_viz_image) plt.show() # Extract the parameters and level of the top (index 0) node split_column = chosen_tree.tree_.feature[0] split_column_name = X_train.columns[split_column] split_value = chosen_tree.tree_.threshold[0] # Print out the feature and level print("This node split on feature {}, at a value of {}".format(split_column_name, split_value)) -------------------------------------------------- # Exercise_3 #1 # Print out the old estimator, notice which hyperparameter is badly set print(rf_clf_old) # Get confusion matrix & accuracy for the old rf_model print("Confusion Matrix: \n\n {} \n Accuracy Score: \n\n {}".format( confusion_matrix(y_test, rf_old_predictions), accuracy_score(rf_old_predictions, y_test))) #2 # Print out the old estimator, notice which hyperparameter is badly set print(rf_clf_old) # Get confusion matrix & accuracy for the old rf_model print("Confusion Matrix: \n\n {} \n Accuracy Score: \n\n {}".format( confusion_matrix(y_test, rf_old_predictions), accuracy_score(y_test, rf_old_predictions))) # Create a new random forest classifier with better hyperparamaters rf_clf_new = RandomForestClassifier(n_estimators=500) # Fit this to the data and obtain predictions rf_new_predictions = rf_clf_new.fit(X_train, y_train).predict(X_test) #3 # Print out the old estimator, notice which hyperparameter is badly set print(rf_clf_old) # Get confusion matrix & accuracy for the old rf_model print("Confusion Matrix: \n\n {} \n Accuracy Score: \n\n {}".format( confusion_matrix(y_test, rf_old_predictions), accuracy_score(y_test, rf_old_predictions))) # Create a new random forest classifier with better hyperparamaters rf_clf_new = RandomForestClassifier(n_estimators=500) # Fit this to the data and obtain predictions rf_new_predictions = rf_clf_new.fit(X_train, y_train).predict(X_test) # Assess the new model (using new predictions!) print("Confusion Matrix: \n\n", confusion_matrix(y_test, rf_new_predictions)) print("Accuracy Score: \n\n", accuracy_score(y_test, rf_new_predictions)) -------------------------------------------------- # Exercise_4 # Build a knn estimator for each value of n_neighbours knn_5 = KNeighborsClassifier(n_neighbors=5) knn_10 = KNeighborsClassifier(n_neighbors=10) knn_20 = KNeighborsClassifier(n_neighbors=20) # Fit each to the training data & produce predictions knn_5_predictions = knn_5.fit(X_train, y_train).predict(X_test) knn_10_predictions = knn_10.fit(X_train, y_train).predict(X_test) knn_20_predictions = knn_20.fit(X_train, y_train).predict(X_test) # Get an accuracy score for each of the models knn_5_accuracy = accuracy_score(y_test, knn_5_predictions) knn_10_accuracy = accuracy_score(y_test, knn_10_predictions) knn_20_accuracy = accuracy_score(y_test, knn_20_predictions) print("The accuracy of 5, 10, 20 neighbours was {}, {}, {}".format(knn_5_accuracy, knn_10_accuracy, knn_20_accuracy)) -------------------------------------------------- # Exercise_5 # Set the learning rates & results storage learning_rates = [0.001,0.01,0.05,0.1,0.2,0.5] results_list = [] # Create the for loop to evaluate model predictions for each learning rate for lr in learning_rates: model = GradientBoostingClassifier(learning_rate=lr) predictions = model.fit(X_train, y_train).predict(X_test) # Save the learning rate and accuracy score results_list.append([lr, accuracy_score(y_test, predictions)]) # Gather everything into a DataFrame results_df = pd.DataFrame(results_list, columns=['learning_rate', 'accuracy']) print(results_df) -------------------------------------------------- # Exercise_6 # Set the learning rates & accuracies list learn_rates = np.linspace(0.01, 2, num=30) accuracies = [] # Create the for loop for learn_rate in learn_rates: # Create the model, predictions & save the accuracies as before model = GradientBoostingClassifier(learning_rate=learn_rate) predictions = model.fit(X_train, y_train).predict(X_test) accuracies.append(accuracy_score(y_test, predictions)) # Plot results plt.plot(learn_rates, accuracies) plt.gca().set(xlabel='learning_rate', ylabel='Accuracy', title='Accuracy for different learning_rates') plt.show() --------------------------------------------------
UTF-8
Python
false
false
5,281
py
94
ch1_exercises.py
92
0.668434
0.65177
0
232
21.198276
117
lin-river/python_notes
5,351,529,258,915
c3d9a88958a4d5505113fa944c6774a9a17b798a
2eaa1ece21ae0cb666dcd398a38250ac3f31ae04
/day6_class/1_class.py
687f23c96594fdb08e5d775360d5725bcd2d2f0e
[]
no_license
https://github.com/lin-river/python_notes
98bfe79ce5a18176d36c00a066254d660c461678
b9b29d14e966cf7c62e09d24415a1fd5f33bc98b
refs/heads/master
2020-03-16T09:59:33.332905
2018-05-08T16:22:37
2018-05-08T16:22:37
132,627,256
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author = "Hero_lws" class Dog: #定义狗类 def __init__(self,name): #传入参数 # 在创建对象时设置属性。这称为初始化对象。 self.name = name # self这个名字在Python中没有任何特殊的含义。只不过所有人都使用这个实例引用名。这也是让代码更易读的一个约定。 # 也可以把这个实例变量命名为你想要的任何名字,不过强烈建议你遵循这个约定,因为使用self 能减少混乱。 def call(self): #定义了一个类方法 print( "%s: 汪!" % self.name ) dog1 = Dog("旺财") dog1.call() #调用类方法 # 新增一些属性 dog1.newProperty = "Property" print( dog1.newProperty )
UTF-8
Python
false
false
784
py
130
1_class.py
110
0.619433
0.609312
0
22
20.545455
62
coddmajes/deep-learning
687,194,777,962
0756f4c497fe1088e6e77dcb2789cf18f54997d1
a67119a8a5104535ace2c05f3d1bf6dfa9ce7334
/deeplearning.py
789f8c2286c21907716611193839701d796c7acc
[]
no_license
https://github.com/coddmajes/deep-learning
8cd74ed73efb8bf72bae51b8794fe43280eb9aaa
f065845586d3eafb85106fe61c467b556d4a68ea
refs/heads/master
2022-06-09T19:09:21.346140
2021-10-21T07:54:11
2021-10-21T07:54:11
180,967,303
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"handwriting recognition" from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense,Activation #from keras.layers import Conv2D, MaxPooling2D,Flatten from keras.optimizers import SGD,Adam from keras.utils import np_utils import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import numpy as np def load_data(): (x_train, y_train), (x_test, y_test) = mnist.load_data() number = 10000 x_train = x_train[0:number] y_train = y_train[0:number] x_train = x_train.reshape(number,28*28) x_test = x_test.reshape(x_test.shape[0],28*28) x_train = x_train.astype('float32') x_test = x_test.astype('float32') y_train = np_utils.to_categorical(y_train,10) y_test = np_utils.to_categorical(y_test,10) x_train = x_train x_test = x_test #x_train = x_train/255 #x_test = x_test/255 return (x_train,y_train),(x_test,y_test) (x_train,y_train),(x_test,y_test) = load_data() model = Sequential() ''' model.add(Dense(input_dim = 28*28,units = 689, activation='sigmoid')) model.add(Dense(units = 689, activation='sigmoid')) model.add(Dense(units = 689, activation='sigmoid')) for i in range(0,10): model.add(Dense(units = 689, activation='sigmoid')) model.add(Dense(units = 10, activation='softmax')) ''' model.add(Dense(input_dim = 28*28,units = 689, activation='relu')) model.add(Dense(units = 689, activation='relu')) model.add(Dense(units = 689, activation='relu')) for i in range(0,10): model.add(Dense(units = 689, activation='relu')) model.add(Dense(units = 10, activation='softmax')) model.compile(loss='mse',optimizer=SGD(lr = 0.1),metrics=['accuracy']) #model.compile(loss='mse',optimizer=Adam(lr = 0.1),metrics=['accuracy']) #model.compile(loss='categorical_crossentropy',optimizer=SGD(lr = 0.1),metrics=['accuracy']) model.fit(x_train, y_train,batch_size=300, epochs = 20) #model.fit(x_train, y_train,batch_size=10, epochs = 10) #model.fit(x_train, y_train,batch_size=10000, epochs = 20) result = model.evaluate(x_train,y_train,batch_size = 300) print '\nTrain Acc:', result[1] result = model.evaluate(x_test,y_test,batch_size = 300) print '\nTest Acc:', result[1]
UTF-8
Python
false
false
2,132
py
5
deeplearning.py
1
0.704972
0.655722
0
70
29.442857
92
nick-anderson/demo
2,456,721,302,497
7a33e73473452f865b18039cb80842b9ee335abe
ec4fcb8f60823680a12ac7bc890ad8969e835324
/deploy.py
fe5cbde8b6424b728ea129403726113e250cd420
[]
no_license
https://github.com/nick-anderson/demo
1019c87f81e4248c014b682175cff1b72f60164f
ed1a33a75fb3b60259124a5ca14ed0f1b0922d2d
refs/heads/master
2017-10-06T15:28:22.854924
2017-06-27T20:40:26
2017-06-27T20:40:26
95,119,784
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import pandas as pd import pickle from optparse import OptionParser import json def load(filename): filename = pickle.load(open(filename,'rb')) return filename def pred(model,data): predictions = model.predict(data) return predictions if __name__ == "__main__": optparser = OptionParser() optparser.add_option('--data', '--inputFile', dest='test', help='testing data', default=[[4.4,2.9,1.4,0.2], [5.6,3.0,4.1,1.3]]) optparser.add_option('--model', '--model', dest='model', help='ml for choice', default='finalized_model.pkl') (options, args) = optparser.parse_args() try: array = json.loads(options.test) except: array = options.test filename = load(options.model) predictions = pred(filename,array) print 'Predictions: ',predictions
UTF-8
Python
false
false
827
py
8
deploy.py
3
0.660218
0.640871
0
36
21.972222
46
VicAve/pythonModule
14,620,068,694,130
b6275fe2afa953ba74785d6070d9289252a6de6c
33ea58a86e90874314e8a41a98d85daa32ecd0db
/basics.py
1eb1e7eaa49b2c67aa91e3c4e9c7d663bfb4bb2e
[]
no_license
https://github.com/VicAve/pythonModule
97abc5ab22d156552a86215457d71967834b1006
5d5cfeb549fd798099f6f7706e58d65509565ffd
refs/heads/master
2020-12-07T02:31:48.604995
2017-06-27T21:56:06
2017-06-27T21:56:06
95,484,103
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#This is a comment in python # x = 15 print("Exercise 1") if x % 5 == 0 and x % 3 == 0: print ("Rock Star") elif x % 3 == 0: print ("Rock") elif x % 5 == 0: print("Star") print("Exercise 2") x = [1,2,3,4,5] l = len(x) print("length: ",l) print("last num: ",x[-1]) for i in range(l): print(x[i]) print("Exercise 3") print("Begin: ",x) x.append(6) print("Append 6: ",x) x.remove(4) print("Remove 4: ",x) x.extend([7,8,9]) print("Extend [7,8,9]",x) x.insert(0,0) print("Insert 0 at index 0: ",x)
UTF-8
Python
false
false
514
py
8
basics.py
7
0.558366
0.494163
0
32
15.0625
32
li-phone/Nopimal
2,405,181,703,630
8de685f09a58aa5b69fdb39593dcb6f3147f9486
7fdab25ffbe3534d107d732c0b5329b232e6b004
/code/feature/main_feature.py
ae22be34dafdfb654a3a437b562003bc85525e11
[ "MIT" ]
permissive
https://github.com/li-phone/Nopimal
c39183fee2e6a716ba1c262595556c8c50d1e295
62d03f1ac2247ab984399a485dc699fb0debd0f5
refs/heads/master
2020-11-24T07:24:26.831729
2020-05-05T06:39:08
2020-05-05T06:39:08
228,028,115
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import pandas as pd import seaborn as sn import seaborn as sns import numpy as np import matplotlib.pyplot as plt from pandas.api.types import is_string_dtype, is_numeric_dtype, is_float_dtype, is_int64_dtype import matplotlib as mpl from pandas import json_normalize from tqdm import tqdm import warnings warnings.filterwarnings('ignore') mpl.rcParams['font.sans-serif'] = ['KaiTi'] mpl.rcParams['font.serif'] = ['KaiTi'] mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题,或者转换负号为字符串 def calcWOE(dataset, col, targe): subdata = pd.DataFrame(dataset.groupby(col)[col].count()) suby = pd.DataFrame(dataset.groupby(col)[targe].sum()) data = pd.DataFrame(pd.merge(subdata, suby, how="left", left_index=True, right_index=True)) b_total = data[targe].sum() total = data[col].sum() g_total = total - b_total data["bad"] = data.apply(lambda x: round(x[targe] / b_total, 3), axis=1) data["good"] = data.apply(lambda x: round((x[col] - x[targe]) / g_total, 3), axis=1) data["WOE"] = data.apply(lambda x: np.log(x.bad / x.good), axis=1) return data.loc[:, ["bad", "good", "WOE"]] def calcIV(dataset): dataset["IV"] = dataset.apply(lambda x: (x.bad - x.good) * x.WOE, axis=1) IV = sum(dataset["IV"]) return IV # 1: 查看新老用户 def analysis_new_ids(train_df, test_df, id_k='id', label_k='flag'): if isinstance(train_df, str): train_df = pd.read_csv(train_df) if isinstance(test_df, str): test_df = pd.read_csv(test_df) # 统计正负样本比例 if label_k in list(train_df.columns): p_cnt = len(train_df[train_df[label_k] == 1]) n_cnt = len(train_df[train_df[label_k] == 0]) print('train set: Pos / Neg = {}'.format(p_cnt / n_cnt)) # 统计测试集新用户和老用户 test_ids = list(np.unique(test_df[id_k])) train_ids = list(np.unique(train_df[id_k])) old_ids = set(train_ids) & set(test_ids) new_ids = set(test_ids) - old_ids print('new_ids = {}, old_ids = {}'.format(len(new_ids), len(old_ids))) # 统计训练集id重复度 train_rp_rate = len(train_ids) / len(train_df[id_k]) print('train_rp_rate = {}'.format(1 - train_rp_rate)) # 统计测试集id重复度 test_rp_rate = len(test_ids) / len(test_df[id_k]) print('test_rp_rate = {}'.format(1 - test_rp_rate)) # 2: 删除无关特征 def drop_ind_feature(data): drop_list = [] for i in data.columns: count = data[i].count() if len(list(data[i].unique())) in [1, count, count - 1]: drop_list.append(i) print(drop_list) data.drop(drop_list, axis=1, inplace=True) return data # 3: 删除缺失特征 def drop_null_feature(data): # 分析数值型数据缺失情况 for type in ['number', 'object']: data_num = data.select_dtypes(type).copy() data_num_miss_rate = 1 - (data_num.count() / len(data_num)) data_num_miss_rate.sort_values(ascending=False, inplace=True) miss_kv = dict(data_num_miss_rate) chose_cnt = -1 print(data_num_miss_rate[:]) data_num_miss_rate.plot() fig, ax1 = plt.subplots(figsize=(10, 6)) sns.barplot(list(range(1, len(miss_kv) + 1)), data_num_miss_rate[:].values, ax=ax1) ax1.set_title('特征缺失情况') ax1.set_xlabel('缺失特征排名') ax1.set_ylabel('缺失占比') plt.show() for k, v in miss_kv.items(): if v > 0.5: data.pop(k) return data # 4: 填充缺失特征 def fill_null_feature(data): # 数据处理 data_str = data.select_dtypes(exclude='number').copy() data_str.describe() for i in data_str.columns: data[i].fillna(data[i].mode()[0], inplace=True) data_num = data.select_dtypes(include='number').copy() data_num.describe() for i in data_num.columns: data[i].fillna(np.median(data[i]), inplace=True) return data # 5: 映射字符串特征 def map_feature(data): data_str = data.select_dtypes(exclude='number').copy() for i in data_str.columns: col = list(data[i]) uids = np.sort(np.unique(col)) if len(uids) >= 20: print('type', i, 'value', uids) m = {k: i + 1 for i, k in enumerate(uids)} data[i] = data[i].map(m) return data def process_type(df, k_v): for k, v in k_v.items(): if v == 'int': df = df[k].astype(np.int) elif v == 'float': df = df[k].astype(np.float) elif v == 'str': df = df[k].astype(np.str) else: raise Exception('No such {} type'.format(v)) return df def iv_feature(df, target_key='flag', bin_num=10, min_num=20): columns = list(df.columns) columns.remove(target_key) iv_keys = [] for i in columns: if len(df[i].unique()) > min_num: df[i] = pd.cut(df[i], bins=bin_num, labels=list(range(bin_num))) data_WOE = calcWOE(df, i, target_key) data_WOE['WOE'].fillna(0, inplace=True) data_WOE["WOE"] = data_WOE["WOE"].apply(lambda x: 0 if x == np.inf else x) # print(data_WOE) data_IV = calcIV(data_WOE) iv_keys.append(dict(key=i, iv=data_IV)) iv_keys = json_normalize(iv_keys) iv_keys = iv_keys.sort_values('iv', ascending=False) iv_keys = iv_keys[iv_keys['iv'] > 0.005] iv_keys = iv_keys[iv_keys['iv'] != np.inf] print('iv_key', str(iv_keys)) iv_keys = list(iv_keys['key']) # iv_keys.append(target_key) return iv_keys def make_feature(df, train=True): # 2: 删除无关特征 df = drop_ind_feature(df) # 了解数据整体情况 print(df.info()) # 3: 删除缺失特征 # df = drop_null_feature(df) # 4: 填充缺失特征 df = fill_null_feature(df) # 5: 映射字符串特征 df = map_feature(df) return df if __name__ == '__main__': DATA_DIR = '../../work_dirs/zsbank/data/' train_tag = pd.read_csv(DATA_DIR + 'train_tag.csv') train_trd_features = pd.read_csv(DATA_DIR + 'feature/train_trd_feature.csv') test_tag = pd.read_csv(DATA_DIR + 'test_tag.csv') test_trd_features = pd.read_csv(DATA_DIR + 'feature/test_trd_feature.csv') # 1: 查看新老用户 analysis_new_ids(train_tag, test_tag) analysis_new_ids(train_tag, train_trd_features) # 合并特征 # train_tag = pd.merge(train_tag, train_trd_features, on='id', how='left') # test_tag = pd.merge(test_tag, test_trd_features, on='id', how='left') # 0: 读取数据 train_tag.drop_duplicates(inplace=True) # 生成训练集特征 train_tag.pop('id') train_labels = train_tag.pop('flag') train_feature = make_feature(train_tag) train_feature['flag'] = train_labels # 1: 提取IV值特征 # iv_keys = iv_feature(train_feature) # train_feature = train_feature[iv_keys] train_feature['flag'] = train_labels train_feature.to_csv(DATA_DIR + 'feature/train_feature.csv', index=False) # 生成测试集特征 test_ids = test_tag.pop('id') test_feature = make_feature(test_tag) # test_feature = test_feature[iv_keys] test_feature['id'] = test_ids test_feature.to_csv(DATA_DIR + 'feature/test_feature.csv', index=False) # type_k_v = { # 'job_year': 'int', # # 'frs_agn_dt_cnt': 'int', 'fin_rsk_ases_grd_cd': 'int', # # 'confirm_rsk_ases_lvl_typ_cd': 'int', # } # train_tag = process_type(train_tag, type_k_v) # test_tag = process_type(test_tag, type_k_v) # tag_corr = train_tag.corr() # # # %% # str_names = { # 'cur_debit_crd_lvl': '招行借记卡持卡最高等级代码', # # 'hld_crd_card_grd_cd': '招行信用卡持卡最高等级代码', # 'crd_card_act_ind': '信用卡活跃标识', # 'l1y_crd_card_csm_amt_dlm_cd': '最近一年信用卡消费金额分层', # 'atdd_type': '信用卡还款方式', # 'perm_crd_lmt_cd': '信用卡永久信用额度分层', # 'gdr_cd': '性别', # 'mrg_situ_cd': '婚姻', # 'edu_deg_cd': '教育程度', # 'acdm_deg_cd': '学历', # 'deg_cd': '学位', # 'ic_ind': '工商标识', # 'fr_or_sh_ind': '法人或股东标识', # # 'dnl_mbl_bnk_ind': '下载并登录招行APP标识', # 'dnl_bind_cmb_lif_ind': '下载并绑定掌上生活标识', # 'hav_car_grp_ind': '有车一族标识', # 'hav_hou_grp_ind': '有房一族标识', # 'l6mon_agn_ind': '近6个月代发工资标识', # # 'vld_rsk_ases_ind': '有效投资风险评估标识', # # 'fin_rsk_ases_grd_cd': '用户理财风险承受能力等级代码', # # 'confirm_rsk_ases_lvl_typ_cd': '投资强风评等级类型代码', # # 'cust_inv_rsk_endu_lvl_cd': '用户投资风险承受级别', # 'l6mon_daim_aum_cd': '近6个月月日均AUM分层', # 'tot_ast_lvl_cd': '总资产级别代码', # 'pot_ast_lvl_cd': '潜力资产等级代码', # 'bk1_cur_year_mon_avg_agn_amt_cd': '本年月均代发金额分层', # 'loan_act_ind': '贷款用户标识', # 'pl_crd_lmt_cd': '个贷授信总额度分层', # } # train_feature['flag'] = train_tag['flag'] # for k, v in str_names.items(): # data = train_feature[['flag', k]] # ax = sns.barplot(x=k, y="flag", data=data) # plt.title(v) # plt.show() # %% # for x_name in list(train_tag.columns): # data = train_tag[['flag', x_name]] # ax = sns.scatterplot(x=x_name, y="flag", data=train_tag) # plt.show()
UTF-8
Python
false
false
9,526
py
33
main_feature.py
22
0.585268
0.578258
0
272
30.992647
95
bussiere/PirateBoxMessageBoard
2,662,879,726,083
f35e3a1f17961d8a4d45a9d205b7169a7add01e8
6d45ba4adff74b2cb1b6764dc684f37407b41ba9
/PirateBoxMessageBoard/message/forms.py
b3fcbd48a2a4cea507ac333c599047e345d8e20a
[]
no_license
https://github.com/bussiere/PirateBoxMessageBoard
bbf478af1886caf811f38802bde5528593bba2c4
8626a8a44d5bdbf06486fac65682a50e4209396d
refs/heads/master
2021-01-23T11:56:22.905167
2013-03-08T16:33:08
2013-03-08T16:33:08
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django import forms class MessageForm(forms.Form): Pseudo = forms.CharField(max_length=100) Description = forms.CharField(max_length=100) Message = forms.CharField(widget=forms.Textarea(attrs={'cols': 20, 'rows': 20}))
UTF-8
Python
false
false
237
py
14
forms.py
7
0.725738
0.683544
0
6
38.5
84
IsraelAbebe/intrinsics-network
15,728,170,270,915
c9aff4b1d9d7cc8b3d5d686d3f2db21a4df9ce13
9eab7164d9db5b1326666fe0bc12c48bc3198818
/shadethis.py
7200f5ba2485382ddb79f96bc81ec571d9069204
[]
no_license
https://github.com/IsraelAbebe/intrinsics-network
ac1e689e15f75a18b9276f12440f61bfe3b50a0f
746699935ef3cd73b2ecaed9c3143e86af3beb27
refs/heads/master
2021-09-07T09:48:04.082583
2018-02-21T06:16:11
2018-02-21T06:16:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys, os, argparse, torch import models, pipeline val_set = pipeline.IntrinsicDataset('dataset/output/','car_tarin',['input', 'mask', 'albedo', 'depth', 'normals', 'lights'], size_per_dataset=1) print ("is",type(val_set)) val_loader = torch.utils.data.DataLoader(val_set, batch_size=32, num_workers=4, shuffle=False) shader = models.Shader().cuda() # pipeline.visualize_shader(shader, val_loader, "saved/a.png",save_raw=True) for epoch in range(4): save_path = os.path.join('saved/shader/', str(epoch) + '.png') val_losses = pipeline.visualize_decomposer(shader, val_loader, "saved/a.png", 1,save_raw=True)
UTF-8
Python
false
false
623
py
1
shadethis.py
1
0.707865
0.698234
0
12
50.916667
144
Ssabarinath/MyBriefcase
16,862,041,644,299
a62f6b0dfedba411d14a40c22411a315b8aa2c4a
778750aa7ec68917c92b7749713f436d01ed1b1e
/Power of a Number.py
a89c724a1346ac255c35e45799ceff3f25e693f0
[]
no_license
https://github.com/Ssabarinath/MyBriefcase
d343eb5ea567eccd5682fc5425539c90b3388921
99bb174b9c6caf052ec77d77576fd3da8cdcea36
refs/heads/master
2020-07-03T00:55:00.780062
2019-08-14T00:45:24
2019-08-14T00:45:24
201,732,612
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
a = int(input("Enter an Number : ")) exponent = int(input("Enter Exponent Value : ")) power = 1 for i in range(1, exponent + 1): power = power * a print("The Result of {0} Power {1} = {2}".format(a, exponent, power))
UTF-8
Python
false
false
227
py
8
Power of a Number.py
8
0.60793
0.581498
0
8
27.375
69
printfoo/leetcode-python
1,778,116,504,814
324bc2c5e5dcfac664fc00aa90f11251b06fb621
7bc88986b141a49787bab67e6211d49d0c0fa16b
/problems/0973/k_closest_points_to_origin_better.py
0649ab02c4568527e46f0b080dd32d4379634c1c
[]
no_license
https://github.com/printfoo/leetcode-python
1b544021b5166ed6ba4ce80a7535d77eca1aafdc
e8169847b8dbdf049408658a0d77a5d59a736e7b
refs/heads/master
2021-01-20T07:00:18.133236
2019-11-17T03:37:20
2019-11-17T03:37:20
89,947,168
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Solution for K Closest Points to Origin, Time O(nlogK). Each heap push/pop is log(len(list)). The list is of length K. We did n pushes and K pops. Idea: Priority queue. The optimization is to realize that heap[0] always stores the smallest element. Instead of storing all n points, we need to store K. Because we can keep replacing the one with the maximum distance. Note 1: storing distance negatively. Note 2: although heap[0] is the smallest, heap[-1] is NOT the largest. """ from __future__ import annotations import heapq # solution class Solution: def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]: distance_heap = [] for point in points: d = point[0] ** 2 + point[1] ** 2 if len(distance_heap) < K: # if not full, push only. heapq.heappush(distance_heap, (-d, point)) else: # if full, push and pop. heapq.heappushpop(distance_heap, (-d, point)) return [_[1] for _ in distance_heap] # Main. if __name__ == "__main__": points = [[3,3],[5,-1],[-2,4]] K = 2 print(Solution().kClosest(points, K))
UTF-8
Python
false
false
1,138
py
188
k_closest_points_to_origin_better.py
181
0.626538
0.611599
0
35
31.514286
79
OLavrik/csp
13,288,628,855,201
59fe183ff38f796ec6959163b40135fcb70241ad
3939edf962255ac1a5720a1ea4af53676f657355
/models/patter_process.py
29e942c718ce55ce395325c404c7afed86f6404f
[]
no_license
https://github.com/OLavrik/csp
00ecc65e6c2e2ba69833a21e58c4ed447590ad3f
c04b9c8acf667b4a18752501ca078e6a19779bc8
refs/heads/master
2023-06-03T17:02:31.401250
2021-06-20T02:49:33
2021-06-20T02:49:33
378,006,544
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import numpy as np import matplotlib.pyplot as plt def detect_extr(arr): q25=np.quantile(arr, 0.25) q50=np.quantile(arr, 0.50) q75=np.quantile(arr, 0.75) IQR=q75-q25 min_extr=q25-1.5*IQR max_extr=q75+1.5*IQR r=[0 if (elem>min_extr and elem<max_extr) else 1 for elem in arr] return r def covert_quanlt(arr): q25 = np.quantile(arr, 0.25) q50 = np.quantile(arr, 0.50) q75 = np.quantile(arr, 0.75) IQR = q75 - q25 min_extr = q25 - 1.5 * IQR max_extr = q75 + 1.5 * IQR res = [] for elem in arr: if elem > q25 and elem < q75: res.append(0) continue if elem <= q25: res.append(1) continue if elem >= q75: res.append(-1) continue return res def clean_external(arr, val): extr=detect_extr(arr) res=[] for i, elem in enumerate(arr): if extr[i]==1: res.append(val) else: res.append(elem) return res def plot_gr(arr_src, arr_trg, time): arr_src=clean_external(arr_src, np.mean(arr_src)) arr_src=covert_quanlt(arr_src) # plt.plot(time, arr_src) # plt.plot(time, [elem for elem in arr_trg]) # plt.xlabel("Time (s)") # plt.ylabel("Src/Trg") # plt.show() return arr_src def plot_gr_test(arr_src, time): arr_src=clean_external(arr_src, np.mean(arr_src)) arr_src=covert_quanlt(arr_src) # plt.plot(time, arr_src) # plt.xlabel("Time (s)") # plt.ylabel("Src") # plt.show() return arr_src import pandas as pd import numpy as np import json def convert_to_dict(df): seq = {} for index, row in df.iterrows(): id_ = row["id"] if id_ not in list(seq.keys()): seq[row["id"]] = {} seq[row["id"]]["src"] = [] seq[row["id"]]["time"] = [] seq[row["id"]]["trg"] = [] seq[row["id"]]["src"].append(int(row["x"])) seq[row["id"]]["time"].append(int(row["time"])) seq[row["id"]]["trg"].append(int(row["y"])) return seq def convert_to_dict_test(df): seq = {} for index, row in df.iterrows(): id_ = row["id"] if id_ not in list(seq.keys()): seq[row["id"]] = {} seq[row["id"]]["src"] = [] seq[row["id"]]["time"] = [] seq[row["id"]]["y"] = [] seq[row["id"]]["src"].append(int(row["x"])) seq[row["id"]]["time"].append(int(row["time"])) return seq df = pd.read_csv('/Users/Olga.Lavrichenko/Documents/Olga/Untitled Folder/CardioSpike/data/train.csv') seq=convert_to_dict(df) for key in seq.keys(): seq[key]["src"]=plot_gr(seq[key]["src"], seq[key]["trg"], seq[key]["time"]) arr_mask=[] for key in seq.keys(): prev=0 res=[] for val, elem in zip(seq[key]["src"], seq[key]["trg"]): if elem==1 and prev==0: res.append(val) prev=1 continue if elem==1: res.append(val) continue if elem==0 and prev==1: arr_mask.append(res) res=[] prev=0 continue clean_arr=[] for arr in arr_mask: flag=True found=0 not_found=0 for key in seq.keys(): for i in range(0, len(seq[key]["src"])-len(arr)): if arr==seq[key]["src"][i:i+len(arr)]: if sum(seq[key]["trg"][i:i+len(arr)])>=len(seq[key]["trg"][i:i+len(arr)])*0.8: print(seq[key]["trg"][i:i+len(arr)]) print("_________") found+=1 else: not_found+=1 if not_found==0: clean_arr.append(arr) def make_result(seq, window_size): dict_itog={"id":[], "time":[], "y":[]} for key in seq.keys(): time=seq[key]["time"] y=seq[key]["y"] for t,y_ in zip(time, y): dict_itog["id"].append(int(key)) dict_itog["time"].append(int(t)) dict_itog["y"].append(int(y_)) df=pd.DataFrame(dict_itog) df.to_csv("./pattern_res.csv",index=False) return df df_test = pd.read_csv('/Users/Olga.Lavrichenko/Documents/Olga/Untitled Folder/cardio_spike/models/test_cardio.csv') seq_test=convert_to_dict(df_test) for key in seq_test.keys(): seq_test[key]["src"]=plot_gr_test(seq_test[key]["src"], seq_test[key]["time"]) for key in seq_test.keys(): for arr in clean_arr: for i in range(0, len(seq_test[key]["src"])-len(arr)): if arr == seq_test[key]["src"][i:i + len(arr)]: seq_test[key]["y"][i:i+len(arr)]=[1 for k in range(len(arr))] print("meow") make_result(seq_test, 2)
UTF-8
Python
false
false
4,675
py
36
patter_process.py
17
0.516364
0.497754
0
170
26.470588
115
Maxim0912/facilities
4,200,478,054,885
8d992292cfb993debec9f0189d6d3b79d585218b
39bc04f5e366920fdf467a591dfc2d1e23b0894d
/services/data_pars.py
cc747d1aba799eb6e3b6aaff22217e1866c8d5e3
[]
no_license
https://github.com/Maxim0912/facilities
faa38677f22beaaccf1e54768411b2d0bba3c22b
c33b3157bf6bd3b371e499a2e8618a6d3d7f7215
refs/heads/main
2022-12-28T10:04:12.288729
2020-10-14T16:56:59
2020-10-14T16:56:59
304,079,012
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import requests from bs4 import BeautifulSoup import csv def get_html(url): try: result = requests.get(url) result.raise_for_status() return result.text except(requests.RequestException, ValueError): print('Сетевая ошибка') return False def get_nutritives(): """ФУНКЦИЯ ПАРСЕНГА ДАННЫХ С САЙТА""" html = get_html(os.getenv('SITE_ADDRESS')) if html: soup = BeautifulSoup(html, 'html.parser') category = soup.findAll('table', class_="energy-res-tb") result = [] results = [] for item in category: products = item.findAll('tr') result.append(products) for nutritives in products: for i in nutritives: name = nutritives.find('th').text fats = nutritives.find('a', id="fat").text calories = nutritives.find('a', id="calories").text results.append({ "name": name, "fats": fats, "calories": calories }) return results def save(results, path): """ФУНКЦИЯ ЗАПИСИ СПАРСЕННЫХ ДАННЫХ В CSV ФАЙЛ""" with open(path, 'w') as csvfile: writer = csv.writer(csvfile) writer.writerow(('Количество на 100г продукта:', 'Жиры, г', 'Ккал')) for iter in results: writer.writerow((iter['name'], iter['fats'], iter['calories'])) if __name__ == "__main__": parse = get_nutritives() save(parse, 'calories.csv')
UTF-8
Python
false
false
1,668
py
22
data_pars.py
21
0.547954
0.545396
0
52
29.076923
76
hsgrewal/algorithms
18,631,568,135,567
b55ac3811aef807dc3b2dc076ad0db01aad9525e
4159244962c209fb5815945a5622335e13db1a88
/algorithmic-toolbox/week2_algorithmic_warmup/3_greatest_common_divisor/gcd.py
94d731e4d085a8f181195033bcddf50d9f5389d7
[ "MIT" ]
permissive
https://github.com/hsgrewal/algorithms
19be02ee4fa427dbf6f091507d21f3d8529fdacc
b7532cc14221490128bb6aa12b06d20656855b8d
refs/heads/main
2023-04-22T04:16:35.639385
2021-05-07T03:33:31
2021-05-07T03:33:31
354,602,945
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Uses python3 import random def gcd_naive(a, b): current_gcd = 1 for d in range(2, min(a, b) + 1): if a % d == 0 and b % d == 0: if d > current_gcd: current_gcd = d return current_gcd def gcd_fast(a, b): if b == 0: return a rem = a % b return gcd_fast(b, rem) def test_solution(): assert gcd_fast(18, 35) == 1 assert gcd_fast(1344, 217) == 7 assert gcd_fast(3918848, 1653264) == 61232 assert gcd_fast(28851538, 1183019) == 17657 for _ in range(20): a, b = random.randint(0, 100), random.randint(0, 100) assert gcd_fast(a, b) == gcd_naive(a, b) if __name__ == "__main__": a, b = map(int, input().split()) print(gcd_fast(a, b)) #print(gcd_naive(a, b)) #test_solution()
UTF-8
Python
false
false
795
py
13
gcd.py
12
0.530818
0.444025
0
34
22.382353
61
doorsas/rustusgid10
13,795,434,964,602
d5598900e68f113d7e001ba81e45faa7ff9de5cd
8687628d4be20c1261bf004ea035727081ea8918
/technikosnuoma/models.py
d1c763cc2c85361fc69fb1d8f30180050086e376
[ "MIT" ]
permissive
https://github.com/doorsas/rustusgid10
c4bb7d362cee08187485f2852305a2b8b9909cf5
6f1cfc16328ebb8a54590a327d7153fcfd487cf8
refs/heads/master
2023-03-14T07:41:12.036514
2021-03-07T10:08:14
2021-03-07T10:08:14
341,577,969
0
0
NOASSERTION
false
2021-03-04T10:20:21
2021-02-23T14:17:14
2021-03-04T09:35:28
2021-03-04T10:20:21
18,232
0
0
0
HTML
false
false
from django.db import models from accounts.models import CustomUser from django.urls import reverse class Technika(models.Model): title = models.CharField(max_length=255,verbose_name= 'Antraštė') title_tag = models.CharField(max_length=40,blank=True, verbose_name= 'Antraštės trumpinys') kategorija = models.CharField(max_length=100,verbose_name= 'Kategorija') author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name= 'Autorius') operatorius = models.BooleanField(verbose_name= 'Ar su operatorium ?') body = models.TextField(verbose_name= 'Aprašymas',default='Aprašymas') post_date = models.DateField(auto_now_add=True) webpuslapis = models.URLField(blank=True) epastas = models.EmailField(blank=True) <<<<<<< HEAD nuotrauka = models.ImageField(blank=True, null=True) ======= nuotrauka = models.ImageField(upload_to='technika/',blank=True) >>>>>>> fae690f7f52be2d23b7c830fab17e71186b382c5 kontaktas = models.CharField(max_length=50,verbose_name= 'Telefonas' ) class Meta: verbose_name_plural = "Technika" def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('technika_detaliau', kwargs={"pk": str(self.pk)}) # return reverse('blogas')
UTF-8
Python
false
false
1,317
py
40
models.py
25
0.704805
0.678871
0
31
41.225806
95
grzeprza/GitCommitMsgAnalyzer
12,618,613,938,699
62a83f0934a222891a31dbdec24eab9650888890
7022dc62092e3a6322e6edd1efcc47fbc6162c0d
/NLPmodule.py
0539213be41be3265e91db2f0b74a0890cd45431
[]
no_license
https://github.com/grzeprza/GitCommitMsgAnalyzer
e4fe21fb5a1c8d9d1b7511c01b3fba40cfbf7d7b
f78ceffa0003d74d14f265eced48a7f9359a7bd4
refs/heads/master
2020-03-19T10:26:03.000136
2018-07-02T17:59:18
2018-07-02T17:59:18
136,362,883
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from tokenize import group import nltk # nltk.download('punkt') # nltk.download('averaged_perceptron_tagger') def groupPartOfSpeech(tag): puntuaction = (".", ",", "?", "!", "'", "\"", ":", ";", "...", "[", "]", "(", ")", "#", "''", "`", "``") if str(tag).startswith(puntuaction): return '.' if str(tag).startswith("RB"): return 'Adverb' if str(tag).startswith("R"): return "Particle" if str(tag).startswith("VB"): return "Verb" if str(tag).startswith("JJ"): return "Adjective" if str(tag).startswith("NN"): return "Noun" if str(tag).startswith("PR"): return "Pronoun" return tag def getPartOfSpeechSummaryDict(commits): partOfSpeechDict = dict() for commit in commits: lines = "" for line in commit._all: lines += str(line[0]) # print(lines) wordos = nltk.word_tokenize(lines) # print(wordos) parsed = nltk.pos_tag(wordos) # print(parsed) tag = nltk.FreqDist(parsed) # print(tag.most_common()) for (tag, count) in tag.most_common(): groupedTag = groupPartOfSpeech(tag[1]) if partOfSpeechDict.get(groupedTag, 0) == 0: partOfSpeechDict.setdefault(groupedTag, count) else: partOfSpeechDict[groupedTag] = partOfSpeechDict.get(groupedTag) + count return partOfSpeechDict def isFirstWordImperative(sentence): #Problem: NLTK perceives VBP as NN #Solutions: insert "they" to force imperative mood #Source: https: // stackoverflow.com / questions / 9406093 / nltk - thinks - that - imperatives - are - nouns?utm_medium = organic & utm_source = google_rich_qa & utm_campaign = google_rich_qa1 wordos = nltk.word_tokenize("They "+sentence) # print(wordos) parsed = nltk.pos_tag(wordos) # print(parsed) if len(parsed) <= 1: return False word,tag = parsed[1] if tag == "VBP": return True else: return False
UTF-8
Python
false
false
2,042
py
10
NLPmodule.py
10
0.581783
0.574927
0
72
27.361111
197
MobilityTechnologies/bqdesc_backupper
13,099,650,266,679
b747ed0623b2a8c3191c730392a1b2aa80ce3346
ddf1aea889a45d1d767bd0c186c50828b675cd62
/src/main.py
4bc5fb3da1f92f30f8c575c854abe0af039a2957
[ "MIT" ]
permissive
https://github.com/MobilityTechnologies/bqdesc_backupper
c418c80531c452b3215c751d637dc61e138c707d
e81ea72da7d5f82fc3c4c44677beb5d20243d7c0
refs/heads/master
2023-07-05T15:23:42.007413
2020-02-05T05:35:17
2020-02-05T05:35:17
228,724,144
0
1
MIT
false
2021-08-13T06:26:09
2019-12-18T00:17:04
2021-07-08T03:38:03
2021-08-13T06:26:09
50
0
1
1
Python
false
false
import logging import os import sys app_home = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(os.path.join(app_home, "lib")) sys.path.append(os.path.join(app_home, "conf")) # load config from conf.config import Config config = Config() # load library from lib.controller import Controller from lib.firestore import Firestore from lib.bigquery import BqUpdateResult from lib.slack import Slack RESPONSE_HEADERS = {'Access-Control-Allow-Origin': '*'} # Logger setting from google.cloud import logging as cloud_logging from google.cloud.logging.handlers import CloudLoggingHandler client = cloud_logging.Client() handler = CloudLoggingHandler(client) logger = logging.getLogger('cloudLogger') logger.setLevel(logging.INFO) logger.addHandler(handler) controller = Controller(config, logger) firestore = Firestore(config, logger) slack = Slack(config, logger) def cloud_functions_main(request): """ this function is invoked by Cloud Functions """ param = request.get_json() try: msg = "ok" if param["action"] == "backup_table": table = param["table"] dataset = param["dataset"] controller.backup_table(table_id=table, dataset_id=dataset) elif param["action"] == "backup_dataset": dataset = param["dataset"] controller.backup_dataset(dataset_id=dataset) elif param["action"] == "backup_all": msg = controller.backup_all() elif param["action"] == "restore_table": table = param["table"] dataset = param["dataset"] controller.restore_table(table_id=table, dataset_id=dataset) elif param["action"] == "restore_dataset": dataset = param["dataset"] controller.restore_dataset(dataset_id=dataset) elif param["action"] == "restore_all": msg = controller.restore_all() elif param["action"] == "snapshot_make": firestore.make_db_snapshot() elif param["action"] == "snapshot_recover_table": table = param["table"] dataset = param["dataset"] snapshot_id = param["snapshot"] firestore.recover_table_from_snapshot(dataset, table, snapshot_id) elif param["action"] == "snapshot_recover_dataset": dataset = param["dataset"] snapshot_id = param["snapshot"] firestore.recover_dataset_from_snapshot(dataset, snapshot_id) else: raise Exception("unknown action: " + param["action"]) return (msg, 200, RESPONSE_HEADERS) except Exception as e: logger.exception(e) if config.enable_slack_notify: import traceback except_str = traceback.format_exc() slack.post_error("bqdesc_backupper Error\n" + except_str) return (f"Exception : {e}", 500, RESPONSE_HEADERS)
UTF-8
Python
false
false
2,915
py
23
main.py
17
0.639108
0.63705
0
83
34.120482
84
rustyworks/100-days-of-code
16,484,084,484,970
c309004ab464704b7a7e567c1c6eb5962699350a
cb5461f6143374d151280debf65965b7c67c5df8
/fractal/fractal.py
ba334453ec7f4fb345ab8bad071b1e240d332f83
[ "MIT" ]
permissive
https://github.com/rustyworks/100-days-of-code
f8b302afad5c64fac852d046f51cb657b5abec1b
4f45f67a3bd1659f85d1a9ca0d68a5ba8aad1240
refs/heads/master
2021-01-02T08:30:08.769806
2018-07-23T02:44:14
2018-07-23T02:44:14
99,013,586
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from turtle import * class Fractal(): def __init__(self): shape('turtle') speed(5) color('blue', 'turquoise') def draw(self): begin_fill() sharp_counter = 1 dull_counter = 0 is_dull = False while True: if is_dull: dull_counter += 1 if dull_counter == 3: is_dull = False dull_counter = 0 self.dull() else: self.sharp() self.dull() if sharp_counter == 3: is_dull = True sharp_counter = 0 sharp_counter += 1 if abs(pos()) < 1: break end_fill() done() def sharp(self): forward(25) left(135) def dull(self): forward(25) right(60) if __name__ == '__main__': fractal = Fractal() fractal.draw()
UTF-8
Python
false
false
977
py
12
fractal.py
5
0.400205
0.380757
0
48
19.354167
38
Aptitudetech/awsadmin
8,229,157,346,754
66f039db01b56708941429cde82a3a75606c158d
1ff5b4c34000542a570a01a537ac442000a61ec0
/usr/share/python-stanford-awsadmin/scripts/describe_elb.py
abdd5c03b9fffd9e0f12b0cd459b0f392678e143
[]
no_license
https://github.com/Aptitudetech/awsadmin
a59068c399ebaf3fe3d740ec795b9faeb4979c3c
a91b45c339cc2757d0c2044f24f809d183b74ca4
refs/heads/master
2020-03-21T03:03:40.432872
2018-08-09T04:24:51
2018-08-09T04:24:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # # Copyright 2014 # The Board of Trustees of the Leland Stanford Junior University """Describe load balancer This script describes a load-balancer. Options: -n, --name=<value> load-balancer name. -h / --help Print this message and exit """ __author__ = 'sfeng@stanford.edu' import sys import getopt import time import string import random import re import commands import json import paths import awsadmin_cfg import ConfigParser from lib.Utils import sys_exit def short_desc(): return "Describes a load-balancer." def my_print(data): elb_data = json.loads(data) groups = elb_data["LoadBalancerDescriptions"] for group in groups: for i in ('LoadBalancerName','CreatedTime','AvailabilityZones', 'Instances'): if i is 'Instances': instances = group['Instances'] for inst in instances: for k,v in inst.items(): print '{0:23s}: {1:20s}'.format(k, v) elif i is 'AvailabilityZones': for z in group['AvailabilityZones']: print '{0:23s}: {1:20s}'.format(i, z) else: print '{0:23s}: {1:20s}'.format(i, group[i]) def main(*args): """ Print a load-balancer's information """ # Parse command line options try: opts, args = getopt.getopt(args, 'hn:', ['help','name='] ) except getopt.error, msg: sys_exit(1, msg) name='' instances = False # Process options for option, arg in opts: if option in ('-n', '--name'): name=(arg) elif option in ('-h', '--help'): sys_exit(0,__doc__) if not name: print "load balancer name is required." sys.exit(1) # Get load-balancer information elb_cmd = 'aws elb describe-load-balancers' exec_cmd = ' '.join([elb_cmd,'--load-balancer-name',name, '--output json']) (status,output) = commands.getstatusoutput(exec_cmd) if status != 0: print output sys.exit(1) my_print(output) sys.exit(0) # Only execute the code when it's called as a script, not just imported. if __name__ == '__main__': main(*sys.argv[1:])
UTF-8
Python
false
false
2,324
py
30
describe_elb.py
29
0.563253
0.550775
0
91
24.538462
72
abogaevski/washing-app
16,355,235,481,948
38e296e35ad170ecb54808845f85f187b3257c95
9be76772fe6fa9477b6712882bc34c9d99eae094
/app/migrations/0021_epospayment_payment_id.py
8a5ec4c3c981bfced2d1e941ef56ab4a0f895871
[]
no_license
https://github.com/abogaevski/washing-app
48afd97d3746a0a877914b4125f05c0387627d99
5db6d1c29c7d6b69371b8dbe9f6c4c457b0b9a55
refs/heads/master
2022-04-10T15:18:46.682973
2020-03-17T08:01:31
2020-03-17T08:01:31
202,484,273
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 2.2 on 2019-12-19 09:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0020_auto_20191213_1452'), ] operations = [ migrations.AddField( model_name='epospayment', name='payment_id', field=models.CharField(default=1, max_length=20, unique=True, verbose_name='ИД платежа'), preserve_default=False, ), ]
UTF-8
Python
false
false
483
py
93
0021_epospayment_payment_id.py
52
0.601266
0.531646
0
19
23.947368
101
sabal202/python_examples
19,327,352,832,445
51ccf80badd0a91c91d0a26c2953ad403304d187
9e518397a2cff3778f9dd878cda1ce21fb07625f
/VOOH(VseSib)/2017-2018/otbor1/A_estafeta.py
f0db987760a07ef284280d44fae41f113ec70c43
[]
no_license
https://github.com/sabal202/python_examples
24f8e2f5ff739bdfc0d1289df92340fe9af4df7c
3149c0a7bbef2468af6b41547285b483634bd54b
refs/heads/master
2021-09-15T06:06:19.101712
2018-05-27T14:56:26
2018-05-27T14:56:26
106,803,273
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import sys, codecs save_stdin = sys.stdin save_stdout = sys.stdout sys.stdin = codecs.open("input.txt", "r", "utf-8") sys.stdout = codecs.open("output.txt", "w+") N, I = list(map(int, input().split())) # TODO decrease time times = [] for __ in range(N): times.append(list(map(int, input().split()))) # # times2 = [[0 for __ in range(N)] for __ in range(3)] # times3 = [[0 for __ in range(N)] for __ in range(3)] # for j in range(3): # for i in range(N): # times3[j][i] = times[i][j] # times2[j][i] = {times[i][j]: i} # times3[j].sort() shtafs = [0 for __ in range(N)] for i in range(3): for j in range(N): for k in range(N): if times[j][i] > times[k][i]: shtafs[j] += 1 if i < 2: for j in range(N): times[j][i + 1] += times[j][i] x = shtafs[I - 1] shtafs.sort() print(shtafs.index(x) + 1)
UTF-8
Python
false
false
886
py
98
A_estafeta.py
92
0.525959
0.505643
0
35
24.314286
54
linrakesh/python
5,128,190,990,591
4bafeec48d8bdf50358e88d83e28ab049c587c5e
f2d2122c3b304e123e1b366d5a0ac45eaae4ac10
/webscraper/first.py
817f08f7fabc2a5e0f5725ea0a13a40c099b33a0
[]
no_license
https://github.com/linrakesh/python
5f4de9b49ab942b912aeecf6a97ea92b372db5ed
a27ee070aab2c8f8f147aa58538156385f1debe9
refs/heads/master
2021-06-14T17:43:55.855566
2021-02-03T08:12:53
2021-02-03T08:12:53
129,482,333
1
2
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests res = requests.get('https://automatetheboringstuff.com/files/rj.txt') #print(res.text) file = open("abcd.txt","w") file.write(res.text) file.close()
UTF-8
Python
false
false
164
py
303
first.py
280
0.737805
0.737805
0
6
26.5
69
FoosN/generic_bricks
19,628,000,571,437
66960c1f342cca4650feb272e6611487c6285965
33f8b111094cd27e0e6acc19319295f0ca1072fe
/TestWalkinDir.py
77dbac12dcdbe43d08ca2d180de5fe5852928755
[]
no_license
https://github.com/FoosN/generic_bricks
711ab1ce62e3a859565e502c7871248da21792cb
10b8679caeecd63f190a34399c5b15780991ec2a
refs/heads/master
2021-01-17T08:29:35.813079
2016-07-01T14:12:00
2016-07-01T14:12:00
22,097,245
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue Jun 7 15:51:06 2016 @author: foos """ import sys import os maninput_files = [] for arg in sys.argv[1:]: path= os.path.abspath(arg) for root, dirs, files in os.walk(path): for filename in files: if filename == "GXPARM.XDS": maninput_files.append(os.path.join(root, filename)) print "ok this is maninput :" + str(maninput_files)
UTF-8
Python
false
false
413
py
5
TestWalkinDir.py
5
0.617433
0.585956
0
18
22
63
HarshaVardhan-Kaki/DP-1
12,094,627,916,564
3b15ec6298af0b98b6a31d8e013a10ed414777cd
16d71371ef3fdf656468d5f229bec93c7ba02c98
/house_robber.py
4c5507d646c39a2584ffb5381abc1e676cc16822
[]
no_license
https://github.com/HarshaVardhan-Kaki/DP-1
3e205f50f2f1f356485d48550cbc8c616294c2ec
71f1111f95f528558f29b0a6bca176a2ffad7756
refs/heads/master
2023-02-26T03:56:35.106435
2021-02-05T20:32:47
2021-02-05T20:32:47
297,878,790
0
0
null
true
2020-09-23T06:46:56
2020-09-23T06:46:55
2020-06-29T01:28:39
2020-09-23T05:19:47
3
0
0
0
null
false
false
# O(N) TIME AND O(1) SPACE WHERE N IS LEN(NUMS) class Solution: def rob(self, nums: List[int]) -> int: if len(nums) == 0: return 0 if len(nums) == 1: return nums[0] nonAdjacentSum = nums[0] adjacentSum = max(nums[0],nums[1]) for i in range(2,len(nums)): currentMax = max(adjacentSum,nums[i] + nonAdjacentSum) nonAdjacentSum = adjacentSum adjacentSum = currentMax return adjacentSum
UTF-8
Python
false
false
511
py
2
house_robber.py
2
0.536204
0.518591
0
15
32.533333
66
marazmiki/django-users
5,609,227,327,539
c95f6d5aec666e46c91e6d783830e9b2abe9bb17
bb630e876278b25659dc70a74ed5efe46ecea4ff
/setup.py
a51c273191eeddac2d2b2b981cb8049d088e3dc1
[]
no_license
https://github.com/marazmiki/django-users
cba476c3aa1ce4ab3078a17e510a3cfa5e52b7a5
ee7d775f5f65cbe43a163bca20a16ae0fa8e7b0a
refs/heads/master
2020-05-30T11:51:50.089242
2012-03-13T02:33:30
2012-03-13T02:33:30
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import setuptools import django_users def rel(*x): return os.path.normpath(os.path.join(os.path.dirname(__file__), *x)) PACKAGE_NAME = 'django-users' CLASSIFIERS = [ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django' ] setuptools.setup( name = PACKAGE_NAME, version = django_users.get_version(), description = 'This is a applications set that provides quick and flexible way to manage users in Django projects', long_description = open(rel('README.rst')).read(), author = 'marazmiki', author_email = 'marazmiki@gmail.com', platforms = ['OS Independent'], classifiers = CLASSIFIERS, license = 'MIT license', url = 'http://pypi.python.org/pypi/django-users', download_url = 'https://github.com/marazmiki/django-users/zipball/master', install_requires = [ 'Django>=1.3.1', 'django-guardian', ], packages = setuptools.find_packages(exclude=['test_project', 'test_project.*']), include_package_data = True, zip_safe = False )
UTF-8
Python
false
false
1,288
py
32
setup.py
26
0.628106
0.624224
0
41
30.365854
124
sbalan7/charting-Gaia
7,395,933,730,070
712c0383d93051236f6dcac595eebe11fd18bd2b
d61d157167e5a32f158ee21777a82cf3a040b316
/central_density.py
4f809eed8577a19e33494070a918b4d5731e9c7e
[]
no_license
https://github.com/sbalan7/charting-Gaia
b84f1780931e89a9b465a5e0563c3dbeb125e6f5
8cee27c610c8091769eddeab1d6f39ab8a3e1301
refs/heads/main
2023-04-12T09:43:03.427474
2021-05-07T18:06:47
2021-05-07T18:06:47
325,546,281
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from utils import find_mass_fn, plot_cmd, load_data import matplotlib.pyplot as plt import pandas as pd import numpy as np import json import os with open('select.json') as f: data = json.load(f) for cluster_name, subdata in data.items(): if subdata['cluster_r'] == 0: continue path = os.getcwd() + '/clusters/' + cluster_name.replace(' ', '_') + '.csv' clu_df = pd.read_csv(path) clu_df = clu_df[clu_df['Rad_Dist']<subdata['cluster_r']] poly = np.poly1d(subdata["mass_fn"]) clu_df["Mass"] = poly(clu_df['Gmag']) avg_mass = clu_df["Mass"].mean() d = int(subdata['distance']) iso_df, _ = load_data(cluster_name) ag, bprp = subdata['AG'], subdata['E_BP-RP'] tup = (ag, float(subdata['g_corr']), bprp, float(subdata['b_corr']), float(subdata['diff_corr'])) (fig, ax), sc, (p1, p2), cleaned_clu = plot_cmd(cluster_name, tup, d, clu_df, iso_df) ax.set_title(f'Star Distribution in {cluster_name} \nAge {data[cluster_name]["isochrone"]}, ' f'Metallicity {data[cluster_name]["metallicity"]}, Avg Mass {avg_mass}') plt.show() red_clu_df = clu_df[clu_df['Rad_Dist']<subdata['central_r']] (fig, ax), sc, (p1, p2), cleaned_clu = plot_cmd(cluster_name, tup, d, red_clu_df, iso_df) central_mass = red_clu_df['Mass'].sum() parsec_rad = (subdata['central_r']/60)*(np.pi/180)*d central_vol = (4/3) * np.pi * (parsec_rad ** 3) central_density = central_mass / central_vol ax.set_title(f'Central Distribution of {cluster_name} \nTotal Mass {central_mass}, ' f'Central Density {central_density}') print(f'{cluster_name} - {len(red_clu_df)}/{len(clu_df)} stars in core, Mass {central_mass} Density {central_density}') plt.show()
UTF-8
Python
false
false
1,778
py
20
central_density.py
12
0.609674
0.6018
0
44
39.318182
123
hrk-fujii/LAMP
4,277,787,455,043
d84f9474ed9f95e0c73eb1e6c080f8ce36ec2bb1
35a4d8fa522cbfb55b9bc6c566bf5b5f0065152a
/views/loadErrorDialog.py
3468b855308f250bb697703f1fb59d908f747476
[]
no_license
https://github.com/hrk-fujii/LAMP
e883b8e058e1d9de893d190a6c62eb995687d112
34e2f77da36ac78fa480dc92fbadd7cdb5c61c31
refs/heads/master
2021-04-07T17:09:33.378914
2021-03-10T06:59:55
2021-03-10T06:59:55
248,692,433
3
2
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # load error dialog # Copyright (C) 2020 Hiroki Fujii <hfujii@hisystron.com> import wx import os import globalVars import fxManager import views.ViewCreator from logging import getLogger from views.baseDialog import * def run(errorList, notFoundList): if globalVars.app.config.getboolean("notification", "ignoreError", True): return d = Dialog("loadErrorDialog") d.Initialize(errorList, notFoundList) fxManager.error() return d.Show() class Dialog(BaseDialog): def Initialize(self, errorList, notFoundList): self.title = _("読み込みエラー") self.error = errorList self.notFound = notFoundList self.log.debug("created") super().Initialize(self.app.hMainView.hFrame,self.title) self.InstallControls() return True def InstallControls(self): """いろんなwidgetを設置する。""" self.creator=views.ViewCreator.ViewCreator(self.viewMode,self.panel,self.sizer,wx.VERTICAL,20, style=wx.ALL, margin=20) self.creator.staticText(_("以下のファイルは、読み込むことができませんでした。")) er, erl = self.creator.virtualListCtrl(_("対応していないファイル") + " (" + str(len(self.error)) + _("件") + ")", style=wx.LC_NO_HEADER | wx.LC_SINGLE_SEL, sizerFlag=wx.EXPAND) nf, nfl = self.creator.virtualListCtrl(_("見つからなかったファイル") + " (" + str(len(self.notFound)) + _("件") + ")", style=wx.LC_NO_HEADER | wx.LC_SINGLE_SEL, sizerFlag=wx.EXPAND) er.AppendColumn("") nf.AppendColumn("") error = [] for s in self.error: error.append([s]) er.setList(error) notFound = [] for s in self.notFound: notFound.append([s]) nf.setList(notFound) er.SetColumnWidth(0, wx.LIST_AUTOSIZE_USEHEADER) nf.SetColumnWidth(0, wx.LIST_AUTOSIZE_USEHEADER) self.creator=views.ViewCreator.ViewCreator(self.viewMode,self.panel,self.sizer,wx.HORIZONTAL,20,"",wx.ALIGN_RIGHT) self.bOk = self.creator.cancelbutton("OK") self.bOk.SetDefault() self.bOk.SetFocus() def GetData(self): return None
UTF-8
Python
false
false
2,218
py
70
loadErrorDialog.py
62
0.650672
0.644434
0
55
36.872727
176
CuiHaoXuan/EMBERS
10,531,259,848,702
126162c33b88498d25974d543771945d8558e2cc
dea096f745595870170058b5b7025e6939a22946
/src/embers/kindle/waterfall_single.py
d5222ba1199a889808d7968c8f65768e391093ce
[ "MIT", "Python-2.0" ]
permissive
https://github.com/CuiHaoXuan/EMBERS
f105da50d146c0e968c34b3df23a277054d8e830
f9e8de353e7eddf28ed715c01d7d3fb5336f0f18
refs/heads/master
2023-02-10T22:48:31.112214
2021-01-05T11:07:54
2021-01-05T11:07:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
""" Waterfall Single ---------------- """ import argparse from pathlib import Path from embers.rf_tools.rf_data import single_waterfall def main(): """Saves a single waterfall plot with a raw RF data file using the :func:`~embers.rf_tools.rf_data.single_waterfall` function. .. code-block:: console $ waterfall_single --help """ _parser = argparse.ArgumentParser( description=""" Saved a single waterfall plot """ ) _parser.add_argument( "--rf_file", metavar="\b", default="tiles_data/S06XX/2019-10-10/S06XX_2019-10-10-02:30.txt", help="Path to raw rf data file. Default=tiles_data/S06XX/2019-10-10/S06XX_2019-10-10-02:30.txt", ) _parser.add_argument( "--out_dir", metavar="\b", default="embers_out/rf_tools", help="Dir where colormap sample plot is saved. Default=./embers_out/rf_tools", ) _args = _parser.parse_args() _rf_file = _args.rf_file _out_dir = _args.out_dir print(f"Waterfall plot saved to ./{_out_dir}/{Path(_rf_file).stem}.png") single_waterfall(_rf_file, _out_dir)
UTF-8
Python
false
false
1,144
py
110
waterfall_single.py
76
0.603147
0.561189
0
46
23.869565
130
snpster/hawkthorne-journey
7,997,229,148,669
bbb8df26f58311a8d1c44da57d1f1c96f2325085
d97fd246c7d9819a63e469e05f3ae847d88a04e6
/scripts/generate_travis.py
fb00fbe10e5580b53085976441231e89cfa2672f
[ "MIT", "CC-BY-NC-3.0" ]
permissive
https://github.com/snpster/hawkthorne-journey
e9bd50f2c249e1a674258cb73a72df495afe631d
123632f84602f34b51fc514106fdde2d296ebc15
refs/heads/master
2021-01-18T08:56:47.075871
2018-12-26T09:08:58
2018-12-26T09:08:58
4,634,571
0
0
MIT
true
2018-12-26T09:08:59
2012-06-12T07:45:13
2013-01-09T15:30:26
2018-12-26T09:08:58
18,625
1
0
0
Lua
false
null
import os import jinja2 import subprocess ENVVARS = [ 'MIXPANEL_TOKEN', 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'BRITTA_BOT_USER', 'BRITTA_BOT_PASS', 'BRITTA_BOT_ACCESS_SECRET', 'BRITTA_BOT_CONSUMER_SECRET', ] def encrypt(variable): return subprocess.check_output(['travis', 'encrypt', variable + "=" + os.environ[variable]]) def main(): template = jinja2.Template(open('templates/travis.yml').read()) print template.render(envvars=map(encrypt, ENVVARS)) if __name__ == "__main__": main()
UTF-8
Python
false
false
547
py
585
generate_travis.py
18
0.645338
0.641682
0
27
19.259259
96
Nafisa-Tasneem/Problem-solving
5,403,068,877,739
6ae24a1f315bbb5bdb3e789e4944e2059bbc0b71
97ea3634bf20946565190fd56b1332861714296e
/practice.py
ec8569d41b83435a607de8f58ebe5ca2808bcac3
[]
no_license
https://github.com/Nafisa-Tasneem/Problem-solving
7fd45172115ae90e2b082f4d7dfddfcfb413a714
0817544331203fab0b3a9fecfa3c633804930087
refs/heads/master
2022-12-15T15:08:05.010674
2020-09-12T14:25:08
2020-09-12T14:25:08
285,991,249
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class student: def __init__(self, initial_name, roll): self.name = initial_name self.roll = roll def get(self): print (self.name) print (self.roll) def changename(self, newname): self.name = newname a = student('Nafisa', 1509032) a.get() b = student('Tahia', 10000) b.get() array = [a, b] array[0].get()
UTF-8
Python
false
false
361
py
46
practice.py
44
0.573407
0.537396
0
17
20.058824
43
Naavi/onme
19,696,720,020,585
1be5719d611e472e0c52d7e36759bab92cde1115
88e3996172f2b342485319ab3388b897289c2deb
/api/urls.py
50479683bf0efd79801970f9d4b9902c2f19ba80
[]
no_license
https://github.com/Naavi/onme
8e2418981740f9f4e32d08596ce9dabb8d0bdc79
c06541674fee97583dd7b0ab23343ee83964b4fc
refs/heads/master
2018-02-25T18:45:35.641636
2014-01-16T17:41:55
2014-01-16T17:41:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^1.0/', include('api.v1_0.urls')), url(r'^', 'api.views.version', name='version'))
UTF-8
Python
false
false
176
py
27
urls.py
24
0.647727
0.625
0
5
34.4
51
auvsi-suas/interop
12,386,685,699,261
6909b51a0c3eead713f1404635b65e47212368ab
6c487f2bf31bc489b80446e754dd249a22ae0395
/server/auvsi_suas/models/takeoff_or_landing_event_test.py
1f799f86a047454761bc14a41fe918a12d055c6a
[ "Apache-2.0" ]
permissive
https://github.com/auvsi-suas/interop
87fb2a36ac89dc323db4cc25a3812279691f6626
7453c89b155b40dc4b36ce2237efb7e2f7393422
refs/heads/master
2022-06-20T23:44:45.101421
2022-06-04T21:09:55
2022-06-04T21:09:55
42,521,702
179
111
Apache-2.0
false
2022-06-04T21:09:56
2015-09-15T13:38:54
2022-06-04T11:08:31
2022-06-04T21:09:55
50,448
144
80
2
Python
false
false
"""Tests for the takeoff_or_landing_event module.""" import datetime from auvsi_suas.models.aerial_position import AerialPosition from auvsi_suas.models.gps_position import GpsPosition from auvsi_suas.models.mission_config import MissionConfig from auvsi_suas.models.takeoff_or_landing_event import TakeoffOrLandingEvent from auvsi_suas.models.time_period import TimePeriod from auvsi_suas.models.waypoint import Waypoint from auvsi_suas.models.access_log_test import TestAccessLogMixinCommon class TestTakeoffOrLandingEventModel(TestAccessLogMixinCommon): """Tests the TakeoffOrLandingEvent model.""" def setUp(self): super(TestTakeoffOrLandingEventModel, self).setUp() # Mission pos = GpsPosition() pos.latitude = 10 pos.longitude = 100 pos.save() apos = AerialPosition() apos.latitude = 10 apos.longitude = 100 apos.altitude_msl = 1000 apos.save() wpt = Waypoint() wpt.latitude = 10 wpt.longitude = 100 wpt.altitude_msl = 1000 wpt.order = 10 wpt.save() self.mission = MissionConfig() self.mission.home_pos = pos self.mission.lost_comms_pos = pos self.mission.emergent_last_known_pos = pos self.mission.off_axis_odlc_pos = pos self.mission.map_center_pos = pos self.mission.map_height_ft = 1 self.mission.air_drop_pos = pos self.mission.ugv_drive_pos = pos self.mission.save() self.mission.mission_waypoints.add(wpt) self.mission.search_grid_points.add(wpt) self.mission.save() # Mission 2 self.mission2 = MissionConfig() self.mission2.home_pos = pos self.mission2.lost_comms_pos = pos self.mission2.emergent_last_known_pos = pos self.mission2.off_axis_odlc_pos = pos self.mission2.map_center_pos = pos self.mission2.map_height_ft = 1 self.mission2.air_drop_pos = pos self.mission2.ugv_drive_pos = pos self.mission2.save() self.mission2.mission_waypoints.add(wpt) self.mission2.search_grid_points.add(wpt) self.mission2.save() self.ten_minutes = datetime.timedelta(minutes=10) def create_event(self, time, uas_in_air, mission=None): """Create a TakeoffOrLandingEvent for test user.""" if mission is None: mission = self.mission event = TakeoffOrLandingEvent(user=self.user1, mission=mission, uas_in_air=uas_in_air) event.save() event.timestamp = time event.save() return event def evaluate_periods(self, expected): """Check actual periods against expected.""" periods = TakeoffOrLandingEvent.flights(self.mission, self.user1) self.assertSequenceEqual(expected, periods) def test_basic_flight_period(self): """Single flight reported as period.""" self.create_event(self.year2000, True) self.create_event(self.year2000 + self.ten_minutes, False) self.evaluate_periods([ TimePeriod(self.year2000, self.year2000 + self.ten_minutes), ]) def test_flight_period_missing_takeoff(self): """Missing takeoff reported as None.""" self.create_event(self.year2000, False) self.evaluate_periods([ TimePeriod(None, self.year2000), ]) # yapf: disable def test_flight_period_missing_landing(self): """Missing landing reported as None.""" self.create_event(self.year2000, True) self.evaluate_periods([ TimePeriod(self.year2000, None), ]) # yapf: disable def test_flight_period_multiple_flights(self): """Multiple flight reported together.""" self.create_event(self.year2000, True) self.create_event(self.year2000 + self.ten_minutes, False) self.create_event(self.year2001, True) self.create_event(self.year2001 + self.ten_minutes, False) self.evaluate_periods([ TimePeriod(self.year2000, self.year2000 + self.ten_minutes), TimePeriod(self.year2001, self.year2001 + self.ten_minutes), ]) def test_flight_period_multiple_flights_order(self): """Multiple flights listed in chronological order.""" self.create_event(self.year2001, True) self.create_event(self.year2001 + self.ten_minutes, False) self.create_event(self.year2000, True) self.create_event(self.year2000 + self.ten_minutes, False) self.evaluate_periods([ TimePeriod(self.year2000, self.year2000 + self.ten_minutes), TimePeriod(self.year2001, self.year2001 + self.ten_minutes), ]) def test_flight_period_specific_mission(self): """Tests that it only includes flights for specified mission.""" self.create_event(self.year2000, True) self.create_event(self.year2000 + self.ten_minutes, False) self.create_event(self.year2001, True, self.mission2) self.create_event(self.year2001 + self.ten_minutes, False, self.mission2) self.evaluate_periods([ TimePeriod(self.year2000, self.year2000 + self.ten_minutes), ]) def test_flight_period_missing_multiple(self): """Multiple flight can be missing details.""" # Forgot takeoff self.create_event(self.year2000, False) # Normal self.create_event(self.year2001, True) self.create_event(self.year2001 + self.ten_minutes, False) # Forgot landing self.create_event(self.year2002, True) self.evaluate_periods([ TimePeriod(None, self.year2000), TimePeriod(self.year2001, self.year2001 + self.ten_minutes), TimePeriod(self.year2002, None), ]) def test_flight_period_multiple_landing(self): """Double landing ignored""" self.create_event(self.year2000, True) self.create_event(self.year2000 + self.ten_minutes, False) # Land again? Ignored self.create_event(self.year2000 + 2 * self.ten_minutes, False) self.create_event(self.year2001, True) self.create_event(self.year2001 + self.ten_minutes, False) self.evaluate_periods([ TimePeriod(self.year2000, self.year2000 + self.ten_minutes), TimePeriod(self.year2001, self.year2001 + self.ten_minutes), ]) def test_flight_period_multiple_takeoff(self): """Double takeoff ignored.""" self.create_event(self.year2000, True) # Take off again? Ignored self.create_event(self.year2000 + self.ten_minutes, True) # Land self.create_event(self.year2000 + 2 * self.ten_minutes, False) self.create_event(self.year2001, True) self.create_event(self.year2001 + self.ten_minutes, False) self.evaluate_periods([ TimePeriod(self.year2000, self.year2000 + 2 * self.ten_minutes), TimePeriod(self.year2001, self.year2001 + self.ten_minutes), ]) def test_user_in_air_no_logs(self): """Not in-air without logs.""" self.assertFalse(TakeoffOrLandingEvent.user_in_air(self.user1)) def test_user_in_air_before_landing(self): """In-air before landing.""" self.create_event(self.year2000, True) self.assertTrue(TakeoffOrLandingEvent.user_in_air(self.user1)) def test_user_in_air_after_landing(self): """Not in-air after landing.""" self.create_event(self.year2000, True) self.create_event(self.year2000 + self.ten_minutes, False) self.assertFalse(TakeoffOrLandingEvent.user_in_air(self.user1)) def test_user_in_air_second_flight(self): """In-air during second flight.""" self.create_event(self.year2000, True) self.create_event(self.year2000 + self.ten_minutes, False) self.create_event(self.year2001, True) self.assertTrue(TakeoffOrLandingEvent.user_in_air(self.user1)) def test_user_in_air_time(self): """In-air base time check.""" self.create_event(self.year2000, True) self.create_event(self.year2000 + 2 * self.ten_minutes, False) time = self.year2000 + self.ten_minutes self.assertTrue( TakeoffOrLandingEvent.user_in_air(self.user1, time=time))
UTF-8
Python
false
false
8,462
py
128
takeoff_or_landing_event_test.py
95
0.637202
0.599858
0
231
35.632035
76
stefan-wolfsheimer/py-socket-server
17,798,344,507,635
c243c2107f6b27bd3537a63abc6f2176c33a777e
71c953587964eb6a85c6a391c5ef805f261d5c6f
/setup.py
69d556e042765b20e2707900b7f55298c14b4f52
[ "Apache-2.0" ]
permissive
https://github.com/stefan-wolfsheimer/py-socket-server
b2dfdbbe36c92999f53600d2fbe0cf1be811fec3
ab2230af0b403f7514d507fc265beef198637099
refs/heads/master
2020-03-27T13:29:16.490838
2018-09-12T12:27:13
2018-09-12T12:27:13
146,612,446
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python from distutils.core import setup setup(name='py-socket-server', version='0.1', description='Framework for a Unix Domain Socket based daemon application', author='Stefan Wolfsheimer', author_email='s.wolfsheimer@surfsara.nl', packages=['socket_server'], install_requires=[])
UTF-8
Python
false
false
334
py
6
setup.py
5
0.682635
0.676647
0
11
29.363636
80
shellox/bcfg2
14,568,529,096,362
c6d2e7f461caa05f82384266c22803eac25508a9
c7e63558317db96d7a806b824b28235787fc00a8
/src/sbin/bcfg2-info
ac4c3af138c187c3c92c86c408ebf0f8f6337e2a
[ "mpich2", "BSD-2-Clause" ]
permissive
https://github.com/shellox/bcfg2
ae53a5c3cdc3e171e4b1d5a200f8f8d14624d454
a8f39eaee5ba711862df619639fcc48519a14103
HEAD
2017-04-30T02:44:52.234378
2013-04-25T15:26:48
2013-04-25T15:26:48
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """This tool loads the Bcfg2 core into an interactive debugger.""" import os import re import sys import cmd import getopt import fnmatch import logging import lxml.etree import traceback from code import InteractiveConsole import Bcfg2.Logger import Bcfg2.Options import Bcfg2.Server.Core import Bcfg2.Server.Plugin import Bcfg2.Client.Tools.POSIX try: try: import cProfile as profile except ImportError: import profile import pstats HAS_PROFILE = True except ImportError: HAS_PROFILE = False class MockLog(object): """ Fake logger that just discards all messages in order to mask errors from builddir being unable to chown files it creates """ def error(self, *args, **kwargs): """ discard error messages """ pass def warning(self, *args, **kwargs): """ discard warning messages """ pass def info(self, *args, **kwargs): """ discard info messages """ pass def debug(self, *args, **kwargs): """ discard debug messages """ pass class FileNotBuilt(Exception): """Thrown when File entry contains no content.""" def __init__(self, value): Exception.__init__(self) self.value = value def __str__(self): return repr(self.value) def print_tabular(rows): """Print data in tabular format.""" cmax = tuple([max([len(str(row[index])) for row in rows]) + 1 for index in range(len(rows[0]))]) fstring = (" %%-%ss |" * len(cmax)) % cmax fstring = ('|'.join([" %%-%ss "] * len(cmax))) % cmax print(fstring % rows[0]) print((sum(cmax) + (len(cmax) * 2) + (len(cmax) - 1)) * '=') for row in rows[1:]: print(fstring % row) def display_trace(trace): """ display statistics from a profile trace """ stats = pstats.Stats(trace) stats.sort_stats('cumulative', 'calls', 'time') stats.print_stats(200) def load_interpreters(): """ Load a dict of available Python interpreters """ interpreters = dict(python=lambda v: InteractiveConsole(v).interact()) best = "python" try: import bpython.cli interpreters["bpython"] = lambda v: bpython.cli.main(args=[], locals_=v) best = "bpython" except ImportError: pass try: # whether ipython is actually better than bpython is # up for debate, but this is the behavior that existed # before --interpreter was added, so we call IPython # better import IPython # pylint: disable=E1101 if hasattr(IPython, "Shell"): interpreters["ipython"] = lambda v: \ IPython.Shell.IPShell(argv=[], user_ns=v).mainloop() best = "ipython" elif hasattr(IPython, "embed"): interpreters["ipython"] = lambda v: IPython.embed(user_ns=v) best = "ipython" else: print("Unknown IPython API version") # pylint: enable=E1101 except ImportError: pass interpreters['best'] = interpreters[best] return interpreters class InfoCore(cmd.Cmd, Bcfg2.Server.Core.BaseCore): """Main class for bcfg2-info.""" def __init__(self, setup): cmd.Cmd.__init__(self) Bcfg2.Server.Core.BaseCore.__init__(self, setup=setup) self.prompt = '> ' self.cont = True def _get_client_list(self, hostglobs): """ given a host glob, get a list of clients that match it """ # special cases to speed things up: if '*' in hostglobs: return self.metadata.clients has_wildcards = False for glob in hostglobs: # check if any wildcard characters are in the string if set('*?[]') & set(glob): has_wildcards = True break if not has_wildcards: return hostglobs rv = set() clist = set(self.metadata.clients) for glob in hostglobs: for client in clist: if fnmatch.fnmatch(client, glob): rv.update(client) clist.difference_update(rv) return list(rv) def _get_usage(self, func): """ get the short usage message for a given function """ return "Usage: " + re.sub(r'\s+', ' ', func.__doc__).split(" - ", 1)[0] def do_loop(self): """Looping.""" self.cont = True while self.cont: try: self.cmdloop('Welcome to bcfg2-info\n' 'Type "help" for more information') except SystemExit: raise except Bcfg2.Server.Plugin.PluginExecutionError: continue except KeyboardInterrupt: print("Ctrl-C pressed exiting...") self.do_exit([]) except: self.logger.error("Command failure", exc_info=1) def do_debug(self, args): """ debug [-n] [-f <command list>] - Shell out to native python interpreter """ try: opts, _ = getopt.getopt(args.split(), 'nf:') except getopt.GetoptError: print(str(sys.exc_info()[1])) print(self._get_usage(self.do_debug)) return self.cont = False scriptmode = False interactive = True for opt in opts: if opt[0] == '-f': scriptmode = True spath = opt[1] elif opt[0] == '-n': interactive = False if scriptmode: console = InteractiveConsole(locals()) for command in [c.strip() for c in open(spath).readlines()]: if command: console.push(command) if interactive: interpreters = load_interpreters() if self.setup['interpreter'] in interpreters: print("Dropping to %s interpreter; press ^D to resume" % self.setup['interpreter']) interpreters[self.setup['interpreter']](locals()) else: self.logger.error("Invalid interpreter %s" % self.setup['interpreter']) self.logger.error("Valid interpreters are: %s" % ", ".join(interpreters.keys())) def do_quit(self, _): """ quit|exit - Exit program """ self.shutdown() os._exit(0) # pylint: disable=W0212 do_EOF = do_quit do_exit = do_quit def do_help(self, _): """ help - Print this list of available commands """ print(USAGE) def do_update(self, _): """ update - Process pending filesystem events""" self.fam.handle_events_in_interval(0.1) def do_build(self, args): """ build [-f] <hostname> <filename> - Build config for hostname, writing to filename""" alist = args.split() path_force = False for arg in alist: if arg == '-f': alist.remove('-f') path_force = True if len(alist) == 2: client, ofile = alist if not ofile.startswith('/tmp') and not path_force: print("Refusing to write files outside of /tmp without -f " "option") return lxml.etree.ElementTree(self.BuildConfiguration(client)).write( ofile, encoding='UTF-8', xml_declaration=True, pretty_print=True) else: print(self._get_usage(self.do_build)) def help_builddir(self): """Display help for builddir command.""" print("""Usage: builddir [-f] <hostname> <output dir> Generates a config for client <hostname> and writes the individual configuration files out separately in a tree under <output dir>. The <output dir> directory must be rooted under /tmp unless the -f argument is provided, in which case it can be located anywhere. NOTE: Currently only handles file entries and writes all content with the default owner and permissions. These could be much more permissive than would be created by the Bcfg2 client itself.""") def do_builddir(self, args): """ builddir [-f] <hostname> <dirname> - Build config for hostname, writing separate files to dirname""" alist = args.split() path_force = False if '-f' in args: alist.remove('-f') path_force = True if len(alist) == 2: client, odir = alist if not odir.startswith('/tmp') and not path_force: print("Refusing to write files outside of /tmp without -f " "option") return client_config = self.BuildConfiguration(client) if client_config.tag == 'error': print("Building client configuration failed.") return for struct in client_config: for entry in struct: if entry.tag == 'Path': entry.set('name', odir + '/' + entry.get('name')) posix = Bcfg2.Client.Tools.POSIX.POSIX(MockLog(), self.setup, client_config) states = dict() posix.Inventory(states) posix.Install(list(states.keys()), states) else: print('Error: Incorrect number of parameters.') self.help_builddir() def do_buildall(self, args): """ buildall <directory> [<hostnames*>] - Build configs for all clients in directory """ alist = args.split() if len(alist) < 1: print(self._get_usage(self.do_buildall)) return destdir = alist[0] try: os.mkdir(destdir) except OSError: err = sys.exc_info()[1] if err.errno != 17: print("Could not create %s: %s" % (destdir, err)) if len(alist) > 1: clients = self._get_client_list(alist[1:]) else: clients = self.metadata.clients for client in clients: self.do_build("%s %s" % (client, os.path.join(destdir, client + ".xml"))) def do_buildallfile(self, args): """ buildallfile <directory> <filename> [<hostnames*>] - Build config file for all clients in directory """ try: opts, args = getopt.gnu_getopt(args.split(), '', ['altsrc=']) except getopt.GetoptError: print(str(sys.exc_info()[1])) print(self._get_usage(self.do_buildallfile)) return altsrc = None for opt in opts: if opt[0] == '--altsrc': altsrc = opt[1] if len(args) < 2: print(self._get_usage(self.do_buildallfile)) return destdir = args[0] filename = args[1] try: os.mkdir(destdir) except OSError: err = sys.exc_info()[1] if err.errno != 17: print("Could not create %s: %s" % (destdir, err)) if len(args) > 2: clients = self._get_client_list(args[1:]) else: clients = self.metadata.clients if altsrc: args = "--altsrc %s -f %%s %%s %%s" % altsrc else: args = "-f %s %s %s" for client in clients: self.do_buildfile(args % (os.path.join(destdir, client), filename, client)) def do_buildfile(self, args): """ buildfile [-f <outfile>] [--altsrc=<altsrc>] <filename> <hostname> - Build config file for hostname (not written to disk)""" try: opts, alist = getopt.gnu_getopt(args.split(), 'f:', ['altsrc=']) except getopt.GetoptError: print(str(sys.exc_info()[1])) print(self.do_buildfile.__doc__) return altsrc = None outfile = None for opt in opts: if opt[0] == '--altsrc': altsrc = opt[1] elif opt[0] == '-f': outfile = opt[1] if len(alist) != 2: print(self.do_buildfile.__doc__) return fname, client = alist entry = lxml.etree.Element('Path', type='file', name=fname) if altsrc: entry.set("altsrc", altsrc) try: metadata = self.build_metadata(client) self.Bind(entry, metadata) data = lxml.etree.tostring(entry, xml_declaration=False).decode('UTF-8') except Exception: print("Failed to build entry %s for host %s: %s" % (fname, client, traceback.format_exc().splitlines()[-1])) raise try: if outfile: open(outfile, 'w').write(data) else: print(data) except IOError: err = sys.exc_info()[1] print("Could not write to %s: %s" % (outfile, err)) print(data) def do_buildbundle(self, args): """ buildbundle <bundle> <hostname> - Render a templated bundle for hostname (not written to disk) """ if len(args.split()) != 2: print(self._get_usage(self.do_buildbundle)) return 1 bname, client = args.split() try: metadata = self.build_metadata(client) bundle = self.plugins['Bundler'].entries[bname] print(lxml.etree.tostring(bundle.get_xml_value(metadata), xml_declaration=False, pretty_print=True).decode('UTF-8')) except KeyError: print("No such bundle %s" % bname) except: # pylint: disable=W0702 err = sys.exc_info()[1] print("Failed to render bundle %s for host %s: %s" % (bname, client, err)) def do_automatch(self, args): """ automatch [-f] <propertyfile> <hostname> - Perform automatch on a Properties file """ alist = args.split() force = False for arg in alist: if arg == '-f': alist.remove('-f') force = True if len(alist) != 2: print(self._get_usage(self.do_automatch)) return if 'Properties' not in self.plugins: print("Properties plugin not enabled") return pname, client = alist automatch = self.setup.cfp.getboolean("properties", "automatch", default=False) pfile = self.plugins['Properties'].store.entries[pname] if (not force and not automatch and pfile.xdata.get("automatch", "false").lower() != "true"): print("Automatch not enabled on %s" % pname) else: metadata = self.build_metadata(client) print(lxml.etree.tostring(pfile.XMLMatch(metadata), xml_declaration=False, pretty_print=True).decode('UTF-8')) def do_bundles(self, _): """ bundles - Print out group/bundle info """ data = [('Group', 'Bundles')] groups = list(self.metadata.groups.keys()) groups.sort() for group in groups: data.append((group, ','.join(self.metadata.groups[group][0]))) print_tabular(data) def do_clients(self, _): """ clients - Print out client/profile info """ data = [('Client', 'Profile')] for client in sorted(self.metadata.list_clients()): imd = self.metadata.get_initial_metadata(client) data.append((client, imd.profile)) print_tabular(data) def do_config(self, _): """ config - Print out the current configuration of Bcfg2""" output = [ ('Description', 'Value'), ('Path Bcfg2 repository', self.setup['repo']), ('Plugins', self.setup['plugins']), ('Password', self.setup['password']), ('Server Metadata Connector', self.setup['mconnect']), ('Filemonitor', self.setup['filemonitor']), ('Server address', self.setup['location']), ('Path to key', self.setup['key']), ('Path to SSL certificate', self.setup['cert']), ('Path to SSL CA certificate', self.setup['ca']), ('Protocol', self.setup['protocol']), ('Logging', self.setup['logging'])] print_tabular(output) def do_probes(self, args): """ probes [-p] <hostname> - Get probe list for the given host, in XML (the default) or human-readable pretty (with -p) format""" alist = args.split() pretty = False if '-p' in alist: pretty = True alist.remove('-p') if len(alist) != 1: print(self._get_usage(self.do_probes)) return hostname = alist[0] if pretty: probes = [] else: probes = lxml.etree.Element('probes') metadata = self.build_metadata(hostname) for plugin in self.plugins_by_type(Bcfg2.Server.Plugin.Probing): for probe in plugin.GetProbes(metadata): probes.append(probe) if pretty: for probe in probes: pname = probe.get("name") print("=" * (len(pname) + 2)) print(" %s" % pname) print("=" * (len(pname) + 2)) print("") print(probe.text) print("") else: print(lxml.etree.tostring(probes, xml_declaration=False, pretty_print=True).decode('UTF-8')) def do_showentries(self, args): """ showentries <hostname> <type> - Show abstract configuration entries for a given host """ arglen = len(args.split()) if arglen not in [1, 2]: print(self._get_usage(self.do_showentries)) return client = args.split()[0] try: meta = self.build_metadata(client) except Bcfg2.Server.Plugin.MetadataConsistencyError: print("Unable to find metadata for host %s" % client) return structures = self.GetStructures(meta) output = [('entrytype', 'name')] if arglen == 1: for item in structures: for child in item.getchildren(): output.append((child.tag, child.get('name'))) if arglen == 2: etype = args.split()[1] for item in structures: for child in item.getchildren(): if child.tag in [etype, "Bound%s" % etype]: output.append((child.tag, child.get('name'))) print_tabular(output) def do_groups(self, _): """ groups - Print out group info """ data = [("Groups", "Profile", "Category")] grouplist = list(self.metadata.groups.keys()) grouplist.sort() for group in grouplist: if self.metadata.groups[group].is_profile: prof = 'yes' else: prof = 'no' cat = self.metadata.groups[group].category data.append((group, prof, cat)) print_tabular(data) def do_showclient(self, args): """ showclient <client> [<client> ...] - Show metadata for the given hosts """ if not len(args): print(self._get_usage(self.do_showclient)) return for client in args.split(): try: client_meta = self.build_metadata(client) except Bcfg2.Server.Plugin.MetadataConsistencyError: print("Client %s not defined" % client) continue fmt = "%-10s %s" print(fmt % ("Hostname:", client_meta.hostname)) print(fmt % ("Profile:", client_meta.profile)) group_fmt = "%-10s %-30s %s" header = False for group in list(client_meta.groups): category = "" for cat, grp in client_meta.categories.items(): if grp == group: category = "Category: %s" % cat break if not header: print(group_fmt % ("Groups:", group, category)) header = True else: print(group_fmt % ("", group, category)) if client_meta.bundles: print(fmt % ("Bundles:", list(client_meta.bundles)[0])) for bnd in list(client_meta.bundles)[1:]: print(fmt % ("", bnd)) if client_meta.connectors: print("Connector data") print("=" * 80) for conn in client_meta.connectors: if getattr(client_meta, conn): print(fmt % (conn + ":", getattr(client_meta, conn))) print("=" * 80) def do_mappings(self, args): """ mappings <type*> <name*> - Print generator mappings for optional type and name """ # Dump all mappings unless type specified data = [('Plugin', 'Type', 'Name')] arglen = len(args.split()) for generator in self.plugins_by_type(Bcfg2.Server.Plugin.Generator): if arglen == 0: etypes = list(generator.Entries.keys()) else: etypes = [args.split()[0]] if arglen == 2: interested = [(etype, [args.split()[1]]) for etype in etypes] else: interested = [(etype, generator.Entries[etype]) for etype in etypes if etype in generator.Entries] for etype, names in interested: for name in [name for name in names if name in generator.Entries.get(etype, {})]: data.append((generator.name, etype, name)) print_tabular(data) def do_event_debug(self, _): """ event_debug - Display filesystem events as they are processed """ self.fam.debug = True def do_packageresolve(self, args): """ packageresolve <hostname> <package> [<package>...] - Resolve the specified set of packages """ arglist = args.split(" ") if len(arglist) < 2: print(self._get_usage(self.do_packageresolve)) return if 'Packages' not in self.plugins: print("Packages plugin not enabled") return self.plugins['Packages'].toggle_debug() indep = lxml.etree.Element("Independent") structures = [lxml.etree.Element("Bundle", name="packages")] for arg in arglist[1:]: lxml.etree.SubElement(structures[0], "Package", name=arg) hostname = arglist[0] metadata = self.build_metadata(hostname) # pylint: disable=W0212 self.plugins['Packages']._build_packages(metadata, indep, structures) # pylint: enable=W0212 print("%d new packages added" % len(indep.getchildren())) if len(indep.getchildren()): print(" %s" % "\n ".join(lxml.etree.tostring(p) for p in indep.getchildren())) def do_packagesources(self, args): """ packagesources <hostname> - Show package sources """ if not args: print(self._get_usage(self.do_packagesources)) return if 'Packages' not in self.plugins: print("Packages plugin not enabled") return try: metadata = self.build_metadata(args) except Bcfg2.Server.Plugin.MetadataConsistencyError: print("Unable to build metadata for host %s" % args) return collection = self.plugins['Packages'].get_collection(metadata) print(collection.sourcelist()) def do_query(self, args): """ query <-g group|-p profile|-b bundle> - Query clients """ if len(args) == 0: print("\n".join(self.metadata.clients)) return arglist = args.split(" ") if len(arglist) != 2: print(self._get_usage(self.do_query)) return qtype, qparam = arglist if qtype == '-p': res = self.metadata.get_client_names_by_profiles(qparam.split(',')) elif qtype == '-g': res = self.metadata.get_client_names_by_groups(qparam.split(',')) elif qtype == '-b': res = self.metadata.get_client_names_by_bundles(qparam.split(',')) else: print(self._get_usage(self.do_query)) return print("\n".join(res)) def do_profile(self, arg): """ profile <command> <args> - Profile a single bcfg2-info command """ if not HAS_PROFILE: print("Profiling functionality not available.") return if len(arg) == 0: print(self._get_usage(self.do_profile)) return prof = profile.Profile() prof.runcall(self.onecmd, arg) display_trace(prof) def run(self, args): # pylint: disable=W0221 try: self.load_plugins() self.fam.handle_events_in_interval(1) if args: self.onecmd(" ".join(args)) else: self.do_loop() finally: self.shutdown() def _daemonize(self): pass def _run(self): pass def _block(self): pass def build_usage(): """ build usage message """ cmd_blacklist = ["do_loop", "do_EOF"] usage = dict() for attrname in dir(InfoCore): attr = getattr(InfoCore, attrname) # shim for python 2.4, __func__ is im_func funcattr = getattr(attr, "__func__", getattr(attr, "im_func", None)) if (funcattr is not None and funcattr.func_name not in cmd_blacklist and funcattr.func_name.startswith("do_") and funcattr.func_doc): usage[attr.__name__] = re.sub(r'\s+', ' ', attr.__doc__) return "Commands:\n" + "\n".join(usage[k] for k in sorted(usage.keys())) USAGE = build_usage() def main(): optinfo = dict(profile=Bcfg2.Options.CORE_PROFILE, interactive=Bcfg2.Options.INTERACTIVE, interpreter=Bcfg2.Options.INTERPRETER) optinfo.update(Bcfg2.Options.INFO_COMMON_OPTIONS) setup = Bcfg2.Options.OptionParser(optinfo) setup.hm = "\n".join([" bcfg2-info [options] [command <command args>]", "Options:", setup.buildHelpMessage(), USAGE]) setup.parse(sys.argv[1:]) if setup['debug']: level = logging.DEBUG elif setup['verbose']: level = logging.INFO else: level = logging.WARNING Bcfg2.Logger.setup_logging('bcfg2-info', to_syslog=False, level=level) if setup['args'] and setup['args'][0] == 'help': print(setup.hm) sys.exit(0) elif setup['profile'] and HAS_PROFILE: prof = profile.Profile() loop = prof.runcall(InfoCore, setup) display_trace(prof) else: if setup['profile']: print("Profiling functionality not available.") loop = InfoCore(setup) loop.run(setup['args']) if __name__ == '__main__': sys.exit(main())
UTF-8
Python
false
false
28,048
117
bcfg2-info
89
0.519609
0.514154
0
788
34.593909
79
tomysky/scrapy-project
627,065,244,001
43edde73e505253d63de374fdc265502cb1af1d3
355f6bfb6eceddb9fbfdfbbbbaa59886b51464c6
/tencent/tencent/spiders/hr.py
23bbfe3b9c7ca48359de2e410023bfe0525e50c2
[]
no_license
https://github.com/tomysky/scrapy-project
a627c89956f93b0c4e6517e4bc66367e35ed9523
ffe15bea438376410cd061d6d36e61f6b5576b92
refs/heads/main
2023-05-08T07:10:33.621802
2021-05-30T21:29:06
2021-05-30T21:29:06
371,614,692
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import scrapy from tencent.items import TencentItem from copy import deepcopy import time class HrSpider(scrapy.Spider): name = 'hr' allowed_domains = ['tencent.com'] start_urls = [] #自定义第一次请求的api def start_requests(self): url = "https://careers.tencent.com/tencentcareer/api/post/Query?timestamp={}&countryId=1&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=&keyword=&pageIndex=1&pageSize=10&language=zh-cn&area=cn".format(str(int(time.time()*1000))) self.headers = { 'authority': 'careers.tencent.com', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36', 'referer': 'https://careers.tencent.com/search.html?query=co_1&index=2&sc=1' } yield scrapy.Request(url=url,callback=self.parse_list,headers=self.headers) def parse_list(self, response): item = TencentItem() post_list = response.json()['Data']['Posts'] #解析json()数据 for post in post_list: item['PostId'] = post['RecruitPostId'] item['PostName'] = post['RecruitPostName'] item['CountryName'] = post['CountryName'] item['LocationName'] = post['LocationName'] item['BGName'] = post['BGName'] item['CategoryName'] = post['CategoryName'] item['Responsibility'] = post['Responsibility'].replace("\n","") item['LastUpdateTime'] = post['LastUpdateTime'] item['PostURL'] = post['PostURL'] item['BGName'] = post['BGName'] item['BGName'] = post['BGName'] #解析详情页 yield scrapy.Request(url=item['PostURL'],headers=self.headers,callback=self.parse_detail,meta={"item":deepcopy(item)}) #翻页操作 if response.meta.get("page",1)==1: response.meta["page"] = 2 url = "https://careers.tencent.com/tencentcareer/api/post/Query?timestamp={}&countryId=1&cityId=&bgIds=&productId=&categoryId=&parentCategoryId=&attrId=&keyword=&pageIndex={}&pageSize=10&language=zh-cn&area=cn".format(str(int(time.time()*1000)),str(response.meta["page"])) print("第{}页:{}".format(str(response.meta["page"]),url)) headers = { 'authority': 'careers.tencent.com', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36', 'referer': 'https://careers.tencent.com/search.html?query=co_1&index={}&sc=1'.format(str(response.meta["page"]-1)) } next_url = response.meta["page"]+1 #调用自己来解析 yield scrapy.Request(url=url,callback=self.parse_list,headers=headers,meta={"page":next_url}) #解析详情页 def parse_detail(self,response): item = response.meta['item'] headers = { 'authority': 'careers.tencent.com', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36', 'referer': item['PostURL'] } #拼接url,访问requirement url = "https://careers.tencent.com/tencentcareer/api/post/ByPostId?timestamp={}&postId={}&language=zh-cn".format(str(int(time.time()*1000)),item['PostId']) yield scrapy.Request(url=url,headers=headers,callback=self.parse_requirement,meta={"item":deepcopy(item)}) #解析职位要求 def parse_requirement(self,response): item = response.meta['item'] item['Requirement'] = response.json()['Data']['Requirement'].replace("\n","") yield item
UTF-8
Python
false
false
3,708
py
10
hr.py
9
0.622856
0.590758
0
71
49.901408
280
WunschK/flat_search_automation
4,269,197,525,747
d0d55e4c1a92f1fb40c46c7d5cbe4a7a7db3afee
af71b2921537bf63ac2feedefafab6692edb4b24
/main.py
6b5f6e071b4ee0b8d511f020b90069bd108a976d
[]
no_license
https://github.com/WunschK/flat_search_automation
6d1990e1290d390021779765c1c13e2464c0d7ad
24bb2a8340cab6d0f5f620a305f71bce33a3d3ec
refs/heads/master
2023-03-24T13:37:18.439336
2021-03-15T12:51:46
2021-03-15T12:51:46
335,703,878
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# This is my main file # v0.5 Everything in main.py # Roadmap v1.0 scraping OOP everything import time import requests as r from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options where = "https://www.openrent.co.uk/properties-to-rent/soho-north-west-london?term=Soho%20(north%20west),%20London&prices_min=1000&prices_max=1500&bedrooms_min=1&bedrooms_max=2" response = r.get(where) site = response.text soup = BeautifulSoup(site, "html.parser") elems = soup.select("a.pli.clearfix") # List of all entry-links base_address = "https://www.openrent.co.uk/" # print(property_links) property_links = [base_address + elem['href'] for elem in elems] property_price_list = soup.select("div.pim.pl-title h2") # print(property_price_list) property_prices = [price.text.split()[0] for price in property_price_list] # property address-list prop_address_list = soup.select("span.banda.pt.listing-title") property_addresses = [prop_address.text.split(",")[1] + "," + prop_address.text.split(",")[2] for prop_address in prop_address_list] # print(property_links) # print(property_prices) # print(property_addresses) # Create list of dicts where each dict is one property prop = [] for i in range(len(property_links) - 1): prop.append({'address': property_addresses[i], 'price': property_prices[i], 'link': property_links[i]}) i += 1 # Selenium-stuff chrome_driver_path = "path to chromedriver.exe" form = "specify form link here" options = Options() options.add_argument('--headless'); driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options) driver.get(form) for prop in prop: time.sleep(2) address = driver.find_element_by_xpath( '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[1]/div/div/div[2]/div/div[1]/div/div[1]/input') price = driver.find_element_by_xpath( '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[2]/div/div/div[2]/div/div[1]/div/div[1]/input') link = driver.find_element_by_xpath( '//*[@id="mG61Hd"]/div[2]/div/div[2]/div[3]/div/div/div[2]/div/div[1]/div/div[1]/input') address.send_keys(prop['address']) price.send_keys(prop['price']) link.send_keys(prop['link']) button = driver.find_element_by_xpath('//*[@id="mG61Hd"]/div[2]/div/div[3]/div[1]/div/div') button.click() print(prop) driver.get(form) # use selenium to enter the form for each listing
UTF-8
Python
false
false
2,439
py
2
main.py
1
0.689627
0.666257
0
75
31.52
177
pingf/go-raml
214,748,412,278
08ff5ba7d903c69f75a26b3dfc408d032eea5308
2f2e4b709a326aaf744b412cf963dfa5428f8f9c
/docs/tutorial/python/client/client.py
c5372cc9fea6c58118659b3bd029b63513a72a99
[ "BSD-2-Clause" ]
permissive
https://github.com/pingf/go-raml
bb848eabe5c4ad6b8c40d0f6087977304d3cb124
0a7662c0b14c0f47e290a59b64b3dfd94b26c233
refs/heads/master
2020-06-30T23:34:35.704908
2016-11-18T14:28:51
2016-11-18T14:28:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests BASE_URI = "http://localhost:5000" class Client: def __init__(self): self.url = BASE_URI self.session = requests.Session() self.auth_header = '' def set_auth_header(self, val): ''' set authorization header value''' self.auth_header = val def users_get(self, headers=None, query_params=None): """ Get list of all developers It is method for GET /users """ if self.auth_header: self.session.headers.update({"Authorization":self.auth_header}) uri = self.url + "/users" return self.session.get(uri, headers=headers, params=query_params) def users_post(self, data, headers=None, query_params=None): """ Add user It is method for POST /users """ if self.auth_header: self.session.headers.update({"Authorization":self.auth_header}) uri = self.url + "/users" return self.session.post(uri, data, headers=headers, params=query_params) def users_byUsername_get(self, username, headers=None, query_params=None): """ Get information on a specific user It is method for GET /users/{username} """ if self.auth_header: self.session.headers.update({"Authorization":self.auth_header}) uri = self.url + "/users/"+username return self.session.get(uri, headers=headers, params=query_params)
UTF-8
Python
false
false
1,467
py
24
client.py
12
0.5985
0.595774
0
50
28.34
81
Deepomatic/dmake
11,364,483,480,210
d6cf438ebde3b78214b1af44c724aa1b9ab0b41b
95653a12deff429bf7a2d3e9ee63dd41f6b0f9aa
/dmake/cli.py
dd2dd5192cd4fd7d6f546ad2523557db8f0deb32
[ "MIT" ]
permissive
https://github.com/Deepomatic/dmake
488ef5acfb7db80602c5eca6995400096d8e9c73
ce274178a03751ff204e15b6ab65b3f2174b9ae7
refs/heads/master
2023-07-24T10:56:28.646848
2023-03-02T15:42:59
2023-03-02T15:42:59
73,611,438
39
4
MIT
false
2023-07-05T23:23:37
2016-11-13T11:27:21
2022-12-14T22:39:16
2023-07-05T23:23:35
1,606
38
3
123
Python
false
false
import sys import os import argcomplete import argparse import dmake.commands as commands import dmake.core as core import dmake.common as common def check_is_git_repo(): try: common.run_shell_command('git rev-parse --abbrev-ref HEAD') return True except common.ShellError as e: common.logger.error("Current directory is not a Git repository:\n%s" % str(e)) return False def add_argument(parsers, *args, **kwargs): for parser in parsers: parser.add_argument(*args, **kwargs) def completion_action(args): print(argcomplete.shellcode(['dmake'], shell=args.shell)) # Find root try: root_dir, sub_dir = common.find_repo_root() except common.ShellError as e: common.logger.error("Current directory is not a Git repository:\n%s" % str(e)) sys.exit(1) os.chdir(root_dir) # Defines command line parser argparser = argparse.ArgumentParser(prog='dmake') argparser.add_argument('--debug-graph', default=False, action='store_true', help="Generate dmake steps DOT graph for debug purposes.") argparser.add_argument('--debug-graph-and-exit', default=False, action='store_true', help="Generate dmake steps DOT graph for debug purposes then exit.") argparser.add_argument('--debug-graph-group-by', default='command', choices=['command', 'height'], help="Group nodes by <> in generated DOT graph.") argparser.add_argument('--debug-graph-pretty', '--no-debug-graph-pretty', default=True, action=common.FlagBooleanAction, help="Pretty or raw output for debug graph.") argparser.add_argument('--debug-graph-output-filename', help="The generated DOT graph filename. Defaults to 'dmake-services.debug.{group_by}.gv'") argparser.add_argument('--debug-graph-output-format', default='png', help="The generated DOT graph format (`png`, `svg`, `pdf`, ...).") subparsers = argparser.add_subparsers(dest='cmd', title='Commands') subparsers.required = True parser_test = subparsers.add_parser('test', help="Launch tests for the whole repo or, if specified, an app or one of its services.") parser_build = subparsers.add_parser('build', help="Launch the build for the whole repo or, if specified, an app or one of its services.") parser_run = subparsers.add_parser('run', help="Launch the application or only one of its services.") parser_stop = subparsers.add_parser('stop', help="Stop the containers started by dmake for the current repository and branch. Usually by 'dmake run', but can also be useful to cleanup aborted executions of dmake.") parser_shell = subparsers.add_parser('shell', help="Run a shell session withing a docker container with the environment set up for a given service.") parser_deploy = subparsers.add_parser('deploy', help="Deploy specified apps and services.") parser_release = subparsers.add_parser('release', help="Create a Github release (with changelog) of the app based on a previously created git tag.") parser_graph = subparsers.add_parser('graph', help="Generate a visual graph of the app services dependencies (dot/graphviz format).") parser_generate_doc = subparsers.add_parser('generate-doc', help="Generate DMake documentation.") # "service" argument for parser in [parser_deploy]: parser.add_argument("service", nargs='?', default='*', help="Apply command to the full repository or, if specified, to the app/service. When specifying a service, you may skip the app if there is no ambiguity, otherwise, you need to specify 'app/service'.").completer = core.service_completer for parser in [parser_test]: parser.add_argument("service", nargs='?', default='*', help="Apply command to the full repository (`*`) or to changed services (`+`), or the specified app/service. When specifying a service, you may skip the app if there is no ambiguity, otherwise, you need to specify 'app/service'.").completer = core.service_completer for parser in [parser_shell]: parser.add_argument("service", nargs='?', default='.', help="Run a shell session withing the docker base image for the given service. You may skip the app if there is no ambiguity, otherwise, you need to specify 'app/service'.").completer = core.service_completer for parser in [parser_run]: parser.add_argument("service", help="Run an application or a service. When specifying a service, you may skip the app if there is no ambiguity, otherwise, you need to specify 'app/service'.").completer = core.service_completer for parser in [parser_build]: parser.add_argument("service", help="Build an application or a service. Use `+` to build only changed services. When specifying a service, you may skip the app if there is no ambiguity, otherwise, you need to specify 'app/service'.").completer = core.service_completer parser_shell.add_argument("-c", '--command', help="Pass to `docker run` specified command instead of `docker.command` defined in `dmake.yml` (default: `bash`).") add_argument([parser_shell, parser_run, parser_test, parser_deploy], "-d", "--dependencies", "--no-dependencies", "-s", "--standalone", required=False, default=True, dest='with_dependencies', action=common.DependenciesBooleanAction, help="These options control if dependencies are run/tested/deployed. By default, the service is run/tested/deployed alongside its dependencies (service and link dependencies), recursively.") add_argument([parser_shell, parser_run, parser_test, parser_deploy, parser_stop], "-b", "--branch", required=False, default=None, help="Overwrite the git branch name used to select the dmake environment") parser_run.add_argument("--docker-links-volumes-persistence", "--no-docker-links-volumes-persistence", required=False, default=False, dest='with_docker_links_volumes_persistence', action=common.FlagBooleanAction, help="Control persistence of docker-links volumes (default: non-persistent (for dmake run)).") parser_release.add_argument("app", help="DMake app to release (must match the github project name under github owner)") parser_release.add_argument('-t', '--tag', nargs='?', help="The git tag from which the release will be created.") parser_generate_doc.add_argument("kind", choices=['usage', 'format', 'example']) parser_graph.add_argument('--output', default='dmake-services.gv', help="The generated DOT graph filename.") parser_graph.add_argument('--format', default='png', help="The generated DOT graph format (`png`, `svg`, `pdf`, ...).") parser_test.set_defaults(func=core.make) parser_run.set_defaults(func=core.make) parser_build.set_defaults(func=core.make) parser_stop.set_defaults(func=commands.stop.entry_point) parser_shell.set_defaults(func=core.make) parser_deploy.set_defaults(func=core.make) parser_release.set_defaults(func=commands.release.entry_point) parser_graph.set_defaults(func=commands.graph.entry_point) parser_generate_doc.set_defaults(func=commands.generate_doc.entry_point) # Shell completion parser_completion = subparsers.add_parser('completion', help="Output shell completion code for bash (may work for zsh)", formatter_class=argparse.RawDescriptionHelpFormatter, description=""" This command can generate shell autocompletions. e.g. $ dmake completion Can be sourced as such $ source <(dmake completion) ./install.sh should have already installed everything in: - ${HOME}/.dmake/completion.bash.inc - ${HOME}/.dmake/config.sh - ${HOME}/.bashrc """, ) parser_completion.add_argument("shell", nargs='?', default='bash', choices=['bash'], help="Shell to emit completion for") parser_completion.set_defaults(func=completion_action)
UTF-8
Python
false
false
7,678
py
133
cli.py
81
0.726752
0.726622
0
120
62.983333
324
sedativo/movie-trailer-page
8,091,718,426,015
2a37a6dfd20473893707c6d42425a5127624ce04
0a99cafb5e30d4d42de088b2abc64eebcb91aed4
/app/bootstrap.py
9fe7f91fbd7bd19686a89827dfa62de522082c92
[]
no_license
https://github.com/sedativo/movie-trailer-page
2ea3bfb001f8ed869d1940922c1f284bb80382f1
6f859458376c46f32c2d9e9d643f3d762262777a
refs/heads/master
2016-09-21T17:29:23.814942
2016-09-08T01:51:59
2016-09-08T01:51:59
67,657,072
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import api import fresh_tomatoes import media import time def create_movies_array(data): movies = [] for item in data: # add domain and api key to poster_path image_url = api.API_IMAGE_URL+'w342//'+item['poster_path']+'?'+api.API_KEY # add domain and api key tp background image path background_url = api.API_IMAGE_URL+'original//'+item['backdrop_path']+'?'+api.API_KEY # create movie instances from data and append to array # unfortunately the call to get the trailer id's slows down this loop # since we have to call the API for each item in the data list # ideally we would have a route that the client side could call to get # the movie id when the user clicks to watch a trailer movies.append(media.Movie(item['title'], item['overview'], image_url, background_url, api.get_trailer_by_id(item['id']) )) return movies; # get current year current_year = time.strftime('%Y') # get a list of movies defaulted to current year # this year value should probably be dynamic and come from a route param # if we had routes, but we don't, so it's hard coded. # to get movies from other years replace current_year variable with # another date, get_movies_by_year takes a string value as a param movies = api.get_movies_by_year(current_year) # create an array of movie objects from movies JSON movie_array = create_movies_array(movies) # render and open movies page from movie_array fresh_tomatoes.open_movies_page(movie_array)
UTF-8
Python
false
false
1,683
py
5
bootstrap.py
4
0.636364
0.634581
0
46
35.586957
93
rd11490/NBA_Tutorials
8,358,006,397,793
a5641957b483283a8da1e7354f7ccd23ab6d42d0
9ecbe4f1ad7dde4d57cd73e3fef1c289cb384422
/small_sample_rapm/adjust_possessions_21_22.py
4a9257d7d57bb61eb93f23b8673c5710a6abdaf7
[ "MIT" ]
permissive
https://github.com/rd11490/NBA_Tutorials
a13dc8cd78a563b794f1073cb7c140688ea1a443
e5cd532329cb0e78fdf255b0d1cee7f8e1816506
refs/heads/master
2022-09-25T17:42:56.084654
2022-09-09T22:47:43
2022-09-09T22:47:43
163,886,452
150
44
MIT
false
2022-09-09T22:47:44
2019-01-02T20:29:40
2022-08-24T17:43:13
2022-09-09T22:47:43
67,828
124
37
3
Python
false
false
import pandas as pd # Display options for printing padas Dataframes pd.set_option('display.max_columns', 500) pd.set_option('display.max_rows', 500) pd.set_option('display.width', 1000) # Change a missed 3 in the first quarter into a made 3 in the second quarter def change_possessions(group): # take the team id of the first row team1 = group['offenseTeamId1'].values[0] # filter to only possessions where the chosen team is on offense team1_poss = group[group['offenseTeamId1'] == team1] # Find the index of the first 3 made by the chosen team in the first quarter made_ind = team1_poss[(team1_poss['threePtAttempts'] == 1) & (team1_poss['period'] == 1) & (team1_poss['threePtMade'] == 1)].head(1).index # Find the index of the first 3 missed by the chosen team in the second quarter missed_ind = team1_poss[(team1_poss['threePtAttempts'] == 1) & (team1_poss['period'] == 2) & (team1_poss['threePtMade'] == 0)].head(1).index # flip the adjusted points group.loc[made_ind, 'adjustedPoints'] = 0.0 group.loc[missed_ind, 'adjustedPoints'] = 3.0 return group # Read the possession data for the 2021-22 season data = pd.read_csv('data/luck_adjusted_one_way_possessions_2021-22.csv') # Filter out 0 possession rows data = data[data['possessions'] > 0] # Create a new column for adjusted points data['adjustedPoints'] = data['points'] # Group by gameId and apply our adjustement data = data.groupby(by='gameId').apply(change_possessions).reset_index() # Save the data data.to_csv('data/adjusted_possessions_per_game_21_22.csv', index=False)
UTF-8
Python
false
false
1,605
py
101
adjust_possessions_21_22.py
36
0.702804
0.666667
0
41
37.926829
144
blodemaster/knee
10,703,058,543,693
9824c977be6613bb6aa01d37dac95020a7a3d5bd
ec6fbcff7399d1d24cebe31079faf3407a9a2df9
/generate_mask.py
05a13a73f4f0840d03d74fe3aff3f51afae64939
[]
no_license
https://github.com/blodemaster/knee
d9713b1fce284ba05da39aa70c4b7fe39d2d44d1
f64c13da7953c774b72a4605e0c177a0e27e9bdf
refs/heads/master
2021-07-17T19:53:48.900135
2017-10-20T10:12:39
2017-10-20T10:12:39
107,658,238
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from sampling import create_boundary from file_operation import find_corresponding_file_path import scipy.io as sio import glob, os label_name = 'MedialTibialCartilage' target_paths = glob.glob('valid_data/*.mat') output_dir = 'valid_mask/' if not os.path.exists(output_dir): os.mkdir(output_dir) for path in target_paths: data = sio.loadmat(path) labels = data[label_name].squeeze() regions = [1] mask_data = create_boundary(labels, regions) mask_data[mask_data > 0] = 1 mask = {} mask['label'] = mask_data output_path = find_corresponding_file_path(path, output_dir) sio.savemat(output_path, mask)
UTF-8
Python
false
false
648
py
11
generate_mask.py
10
0.692901
0.688272
0
27
23
64
jasondu7297/Ecotracker
8,280,696,946,737
075157ae621e083dcd4d54cebe204a5a3bc1d6c7
fa5286245686180a2dd9d3878289c9ccf41b112a
/Ecotracker/main/models.py
b72ee5529fc77e2d73db906cce3bf6bfc4b7ea38
[]
no_license
https://github.com/jasondu7297/Ecotracker
492ec4431860c7abb4a5f85b828e9d88e3be55bb
6460365bcda805a191eb6ef047c12a7b59f7e251
refs/heads/main
2023-06-05T14:17:51.061070
2021-06-27T15:37:02
2021-06-27T15:37:02
380,476,547
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.db import models class Automobile(models.Model): vehicle_type = models.CharField(max_length=255) combined = models.FloatField() emission = models.FloatField(default=0) carbon_rating = models.FloatField() smog_rating = models.FloatField() thumbnail = models.CharField(default="https://www.solidbackgrounds.com/images/950x350/950x350-vermilion-cinnabar-solid-color-background.jpg", max_length=255)
UTF-8
Python
false
false
434
py
21
models.py
10
0.75576
0.711982
0
10
42.4
161
vimalkurup/py-practice
3,315,714,759,397
f1837858b292c7984d28af96a3dce4b90ff0b760
828cd64529ad1917b92cd89cd8b585f721a04a0a
/lesson1/list_range.py
582bae0b55a180faef9ab12dd28407dae7dfbe53
[]
no_license
https://github.com/vimalkurup/py-practice
10a42c0b464f5b2b278b8dd53faf93a30d65ab53
6427d36a6e88e1b6be6d1bf1659a2a4b46190a69
refs/heads/master
2018-01-11T21:59:10.542132
2016-03-22T04:45:20
2016-03-22T04:45:20
53,025,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
this_list = range(10) print this_list this_list = list(range(10)) print this_list this_list = list([0,1,2,3,4,5,6,7,8,9]) print this_list
UTF-8
Python
false
false
141
py
15
list_range.py
15
0.673759
0.574468
0
8
16.5
39
andelgado53/interviewProblems
9,122,510,577,851
910daf75dbcccccd4ca3db6c7cf66441ca6beca2
57f0b32efce06681a18cfcc078121947092fc356
/MergeSort.py
b73c61000aa8bc4c53f4f4692ee3cf9d52838683
[]
no_license
https://github.com/andelgado53/interviewProblems
17dd1874f80d5ad166a897d18e5903987698a907
984af08366186867c6f339d44b5655c2df8162b6
refs/heads/master
2020-05-21T05:16:37.173148
2019-09-15T04:40:29
2019-09-15T04:40:29
185,917,353
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
data = [5, 3, 4, 1, 9, 7, 8, 2, 6] def merge_sort(data, start, end): mid = (start + end) // 2 if len(data[start:end]) > 1: merge_sort(data, start, mid) merge_sort(data, mid, end) left = data[start: mid] right = data[mid: end] left_index = 0 right_index = 0 data_index = start while left_index < len(left) and right_index < len(right): if left[left_index] < right[right_index]: data[data_index] = left[left_index] left_index += 1 else: data[data_index] = right[right_index] right_index += 1 data_index += 1 while left_index < len(left) and data_index < len(data): data[data_index] = left[left_index] left_index += 1 data_index += 1 while right_index < len(right) and data_index < len(data): data[data_index] = right[right_index] right_index += 1 data_index += 1 print('unsorted data ' + str(data)) merge_sort(data, 0 , len(data)) print(data)
UTF-8
Python
false
false
1,123
py
117
MergeSort.py
117
0.503117
0.484417
0
35
31.057143
66
BinetReseau/chocapix-server
13,812,614,853,550
a3a625a0c0a1e549ee683b0537302fb4580f9029
3971b112156883d84d0f437ec81106b3978ffd79
/bars_core/tests.py
fa2ca908a993cada1aeb8af9d9b06981ebd77a40
[]
no_license
https://github.com/BinetReseau/chocapix-server
1b5b56dcf6f33ce4a04f3116e0568f778dd67f9c
7e464d4398e14b94d5b802bbd73c563639b5f125
refs/heads/develop
2020-04-05T03:14:49.689120
2017-06-21T18:29:50
2017-06-21T18:30:44
23,322,367
2
10
null
false
2017-06-07T19:29:25
2014-08-25T17:28:55
2017-02-20T23:00:42
2017-06-07T19:29:25
570
3
6
1
Python
null
null
from rest_framework.test import APITestCase from bars_django.utils import get_root_bar from bars_core.models.bar import Bar, BarSerializer, BarSettingsSerializer from bars_core.models.user import User, UserSerializer from bars_core.models.role import Role from bars_core.models.account import Account, AccountSerializer def reload(obj): return obj.__class__.objects.get(pk=obj.pk) class BackendTests(APITestCase): @classmethod def setUpTestData(self): super(BackendTests, self).setUpTestData() User.objects.create_user("test", "test") def test_login(self): data = {'username': 'test', 'password': 'test'} response = self.client.post('/api-token-auth/', data, format='json') self.assertEqual(response.status_code, 200) token = response.data["token"] auth = 'JWT {0}'.format(token) response = self.client.get('/user/me/', HTTP_AUTHORIZATION=auth, format='json') self.assertEqual(response.status_code, 200) self.assertEqual(response.data['username'], "test") def test_login_wrong_password(self): data = {'username': 'test', 'password': 'sdgez'} response = self.client.post('/api-token-auth/', data, format='json') self.assertEqual(response.status_code, 400) def test_login_wrong_user(self): data = {'username': 'not_admin', 'password': 'test'} response = self.client.post('/api-token-auth/', data, format='json') self.assertEqual(response.status_code, 400) def test_add_superuser(self): u = User.objects.create_superuser("su", "su") self.assertTrue(u.is_superuser) self.assertTrue(u.is_staff) class BarTests(APITestCase): @classmethod def setUpTestData(self): super(BarTests, self).setUpTestData() get_root_bar._cache = None # Workaround root_bar = get_root_bar() self.manager, _ = User.objects.get_or_create(username="manager") Role.objects.get_or_create(bar=root_bar, user=self.manager, name="admin") self.manager = reload(self.manager) # prevent role caching self.bar, _ = Bar.objects.get_or_create(id="barrouje") serializer = BarSerializer(self.bar) self.data = serializer.data self.data['name'] = "barjone" self.bar_url = '/bar/%s/' % self.bar.id def setUp(self): self.bar.name = "barrouje" self.bar.save() def test_get_bar_not_authed(self): # Not authenticated response = self.client.get(self.bar_url) self.assertEqual(response.status_code, 200) def test_get_bar_authed(self): # Authenticated self.client.force_authenticate(user=User()) response = self.client.get(self.bar_url) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['name'], self.bar.name) def test_change_bar_no_perms(self): # Not authenticated self.client.force_authenticate(user=User()) response = self.client.put(self.bar_url, self.data) self.assertEqual(response.status_code, 403) def test_change_bar_admin(self): # Authenticated as manager self.client.force_authenticate(user=self.manager) response = self.client.put(self.bar_url, self.data) self.assertEqual(response.status_code, 200) self.assertEqual(reload(self.bar).name, self.data['name']) class BarSettingsTests(APITestCase): @classmethod def setUpTestData(self): super(BarSettingsTests, self).setUpTestData() self.bar, _ = Bar.objects.get_or_create(id="barjone") self.manager, _ = User.objects.get_or_create(username="manager") self.manager.role_set.all().delete() Role.objects.get_or_create(bar=self.bar, user=self.manager, name="staff") self.manager = reload(self.manager) # prevent role caching self.barsettings = self.bar.settings serializer = BarSettingsSerializer(self.barsettings) self.data = serializer.data del self.data['next_scheduled_appro'] self.data['agios_enabled'] = True self.barsettings_url = '/barsettings/%s/' % self.barsettings.pk def setUp(self): self.barsettings.agios_enabled = False self.barsettings.save() def test_get_not_authed(self): # Not authenticated response = self.client.get(self.barsettings_url) self.assertEqual(response.status_code, 200) def test_get_authed(self): # Authenticated self.client.force_authenticate(user=User()) response = self.client.get(self.barsettings_url) self.assertEqual(response.status_code, 200) self.assertEqual(reload(self.barsettings).agios_enabled, response.data['agios_enabled']) def test_change_no_perms(self): # Not authenticated self.client.force_authenticate(user=User()) response = self.client.put(self.barsettings_url, self.data) self.assertEqual(response.status_code, 403) def test_change_admin(self): # Authenticated as manager self.client.force_authenticate(user=self.manager) response = self.client.put(self.barsettings_url, self.data) self.assertEqual(response.status_code, 200) self.assertEqual(reload(self.barsettings).agios_enabled, self.data['agios_enabled']) class UserTests(APITestCase): @classmethod def setUpTestData(self): super(UserTests, self).setUpTestData() get_root_bar._cache = None # Workaround root_bar = get_root_bar() self.manager, _ = User.objects.get_or_create(username="manager") Role.objects.get_or_create(bar=root_bar, user=self.manager, name="admin") self.manager = reload(self.manager) # prevent role caching self.user, _ = User.objects.get_or_create(username="bob") self.user.set_password("password") self.user.email = "bob@chocapix.org" self.user.save() serializer = UserSerializer(self.user) self.data = serializer.data self.user_url = '/user/%d/' % self.user.id def setUp(self): self.data['username'] = "bob" self.data['email'] = "bob@chocapix.org" self.user.username = "bob" self.user.save() def test_get_user_not_authed(self): # Not authenticated response = self.client.get(self.user_url) self.assertEqual(response.status_code, 401) def test_get_user_authed(self): # Authenticated self.client.force_authenticate(user=User()) response = self.client.get(self.user_url) self.assertEqual(response.status_code, 200) self.assertEqual(response.data['username'], self.data['username']) def test_create_user_no_perms(self): # Not authenticated data = {'username': "charles1"} self.client.force_authenticate(user=User()) response = self.client.post('/user/', data) self.assertEqual(response.status_code, 403) def test_create_user_admin(self): # Authenticated as admin data = {'username': "charles2", 'email': "blabla@m4x.org"} self.client.force_authenticate(user=self.manager) response = self.client.post('/user/', data) self.assertEqual(response.status_code, 201) def test_change_user_no_perms(self): # Not authenticated self.client.force_authenticate(user=User()) self.data['username'] = 'alice' response = self.client.put(self.user_url, self.data) self.assertEqual(response.status_code, 403) def test_change_user_admin(self): # Authenticated as manager self.data['username'] = 'alice' self.client.force_authenticate(user=self.manager) response = self.client.put(self.user_url, self.data) self.assertEqual(response.status_code, 200) self.assertEqual(reload(self.user).username, self.data['username']) def test_change_user_self(self): # Authenticated as self self.data['username'] = 'alice' self.client.force_authenticate(user=self.user) response = self.client.put(self.user_url, self.data) self.assertEqual(response.status_code, 200) self.assertEqual(reload(self.user).username, self.data['username']) def test_change_password(self): self.client.force_authenticate(user=self.user) self.assertTrue(self.user.check_password('password')) data = {'old_password': 'password', 'password': '123456'} response = self.client.put('/user/change_password/', data) self.assertEqual(response.status_code, 200) user_reloaded = User.objects.get(pk=self.user.pk) self.assertTrue(user_reloaded.check_password('123456')) def test_change_password_wrong_password(self): self.client.force_authenticate(user=self.user) data = {'old_password': 'wrong_password', 'password': '123456'} response = self.client.put('/user/change_password/', data) self.assertEqual(response.status_code, 403) class AccountTests(APITestCase): @classmethod def setUpTestData(self): super(AccountTests, self).setUpTestData() self.bar, _ = Bar.objects.get_or_create(id='natationjone') Bar.objects.get_or_create(id='avironjone') self.user, _ = User.objects.get_or_create(username='nadrieril') self.user2, _ = User.objects.get_or_create(username='ntag') Role.objects.get_or_create(name='admin', bar=self.bar, user=self.user2) self.user2 = reload(self.user2) self.create_data = {'owner': self.user2.id} self.account, _ = Account.objects.get_or_create(owner=self.user, bar=self.bar) self.update_data = AccountSerializer(self.account).data self.update_data['deleted'] = True def setUp(self): self.account.deleted = False self.account.save() def test_get_account(self): response = self.client.get('/account/') self.assertEqual(len(response.data), Account.objects.all().count()) self.assertEqual(response.data[0]['deleted'], self.account.deleted) def test_create_account(self): # Unauthenticated response = self.client.post('/account/?bar=natationjone', self.create_data) self.assertEqual(response.status_code, 401) def test_create_account1(self): # Wrong permissions self.client.force_authenticate(user=self.user) response = self.client.post('/account/?bar=natationjone', self.create_data) self.assertEqual(response.status_code, 403) def test_create_account2(self): # Correct permissions self.client.force_authenticate(user=self.user2) response = self.client.post('/account/?bar=natationjone', self.create_data) self.assertEqual(response.status_code, 201) def test_create_account3(self): # Wrong bar self.client.force_authenticate(user=self.user2) response = self.client.post('/account/?bar=avironjone', self.create_data) self.assertEqual(response.status_code, 403) def test_change_account(self): # Unauthenticated response = self.client.put('/account/%d/?bar=natationjone' % self.account.id, self.update_data) self.assertEqual(response.status_code, 401) self.assertEqual(reload(self.account).deleted, self.account.deleted) def test_change_account2(self): # Wrong permissions self.client.force_authenticate(user=self.user) response = self.client.put('/account/%d/?bar=natationjone' % self.account.id, self.update_data) self.assertEqual(response.status_code, 403) self.assertEqual(reload(self.account).deleted, self.account.deleted) def test_change_account4(self): # Correct permissions self.client.force_authenticate(user=self.user2) response = self.client.put('/account/%d/?bar=natationjone' % self.account.id, self.update_data) self.assertEqual(response.status_code, 200) self.assertEqual(reload(self.account).deleted, self.update_data['deleted']) def test_change_account5(self): # Wrong bar self.client.force_authenticate(user=self.user2) response = self.client.put('/account/%d/?bar=avironjone' % self.account.id, self.update_data) self.assertEqual(response.status_code, 403) self.assertEqual(reload(self.account).deleted, self.account.deleted) class RoleTests(APITestCase): @classmethod def setUpTestData(self): super(RoleTests, self).setUpTestData() get_root_bar._cache = None # Workaround self.bar, _ = Bar.objects.get_or_create(id='natationjone') Bar.objects.get_or_create(id='avironjone') self.user, _ = User.objects.get_or_create(username='nadrieril') self.user2, _ = User.objects.get_or_create(username='ntag') self.root, _ = User.objects.get_or_create(username='root') Role.objects.get_or_create(name='admin', bar=self.bar, user=self.user2) self.user2 = reload(self.user2) Role.objects.get_or_create(name='admin', bar=get_root_bar(), user=self.root) self.root = reload(self.root) self.create_data = {'user': self.user.id, 'name': 'customer'} self.create_data_root = {'user': self.user.id, 'name': 'usermanager'} def test_get_role(self): response = self.client.get('/role/') self.assertEqual(len(response.data), Role.objects.count()) def test_create_role(self): # Unauthenticated response = self.client.post('/role/?bar=natationjone', self.create_data) self.assertEqual(response.status_code, 401) def test_create_role1(self): # Wrong permissions self.client.force_authenticate(user=self.user) response = self.client.post('/role/?bar=natationjone', self.create_data) self.assertEqual(response.status_code, 403) def test_create_role2(self): # Correct permissions self.client.force_authenticate(user=self.user2) response = self.client.post('/role/?bar=natationjone', self.create_data) self.assertEqual(response.status_code, 201) def test_create_role3(self): # Wrong bar self.client.force_authenticate(user=self.user2) response = self.client.post('/role/?bar=avironjone', self.create_data) self.assertEqual(response.status_code, 403) def test_create_role_root(self): self.client.force_authenticate(user=self.user2) response = self.client.post('/role/?bar=root', self.create_data_root) self.assertEqual(response.status_code, 403) def test_create_role_root2(self): self.client.force_authenticate(user=self.root) response = self.client.post('/role/?bar=root', self.create_data_root) self.assertEqual(response.status_code, 201)
UTF-8
Python
false
false
14,877
py
77
tests.py
67
0.656181
0.645829
0
391
37.048593
103
Novandev/fine-web
5,274,219,849,750
5f4a86283c584f3a11fbf845e1b3dbf2aaf92994
f73875707726e49d79772f3b4555a9d6b1a8a130
/test_folder/graphanddb.py
103cd69e71f1df36cd52a4c594a8e9d8dbfec733
[]
no_license
https://github.com/Novandev/fine-web
9af52753955159f09c14da20c4bbe6aac28d48b9
8e7d80406fb7f80cf5eb5d2cc749ec5818f7c8fc
refs/heads/master
2022-12-09T22:53:37.162984
2018-08-15T09:37:12
2018-08-15T09:37:12
144,828,454
0
0
null
false
2022-12-08T02:46:22
2018-08-15T08:42:32
2018-08-15T09:41:54
2022-12-08T02:46:21
6
0
0
5
Python
false
false
from py2neo import Graph, Node, Relationship # the access to the db is at http://localhost:7474/ password is...well ya know # # practice_graph_db_conn = Graph("http://localhost:7474") print("\n\t\tDatabase has the configuration settings:\n {}\n\n".format(practice_graph_db_conn.database)) practice_graph = practice_graph_db_conn.begin() def random_sampler(): '''This function takes in a string file name and fills nodes with the pertinent information'''
UTF-8
Python
false
false
462
py
3
graphanddb.py
2
0.738095
0.718615
0
12
37.5
104
haizhupan/TVDI
3,676,492,019,947
831ca257f15d2f48426d95d62f1e03b1a6e50720
901f1503da675ac70e964b3bb36c39e88861e572
/TVDI.py
457265adc006ec0ae8955ebe15a3becd30a12fcc
[]
no_license
https://github.com/haizhupan/TVDI
e21bd6f2279f2c8b7071caf1a62dbb01fe7eeea0
e010031b13ff8835d57d0e170be4c806af89b2ac
refs/heads/master
2020-04-06T20:25:23.656155
2017-06-14T08:15:49
2017-06-14T08:15:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# TVDI # Author: Lorena Villano, Leo Kris Palao, and Jorrel Aunario # Function that will calculate and produce the TVDI values and image, plus graph of the NDVI-LST triangle and scatter plot """ Author: Lorie Villano Revised by: Leo Kris Palao parameters in the function: ndviFile - filename of the ndvi image lstFile -filename of the LST image sPlot - filename for the output plot tvdiFile - filename of the output TVDI image """ # import necessary libraries and packages import gdal, gdalnumeric from matplotlib import pyplot as plt from numpy import polyfit import numpy as np import glob import itertools, os def array_to_raster(array,filename): dst_filename = filename proj=ds.GetProjection() x_pixels = ds.RasterXSize # number of pixels in x y_pixels = ds.RasterYSize # number of pixels in y PIXEL_SIZE = dsTrans[1] # size of the pixel... x_min = dsTrans[0] y_max = dsTrans[3] # x_min & y_max are like the "top left" corner. wkt_projection = proj driver = gdal.GetDriverByName('GTiff') dataset = driver.Create(dst_filename,x_pixels,y_pixels,1,gdal.GDT_Float32, ) #GDT_Float32,gdal.GDT_Int16 dataset.SetGeoTransform((x_min,PIXEL_SIZE,0,y_max,0,-PIXEL_SIZE)) dataset.SetProjection(wkt_projection) dataset.GetRasterBand(1).WriteArray(array) dataset.FlushCache() print os.path.basename(filename) return dataset def calcTVDI(ndviFile, lstFile, sPlot, tvdiname): # image file to array arrNdvi = gdalnumeric.LoadFile(ndviFile) #.astype(np.dtype(float)) # image file to array arrLst = gdalnumeric.LoadFile(lstFile) # mask out the temperature values <0 -erroneous values from converting temp from Kelvin to Celsius in ENVI maskLST = np.where((arrLst>=0), 1, 0) arrLSTm = np.choose(maskLST, (np.nan, arrLst)) vNdvi = np.ravel(arrNdvi) # image file to 1D array a.k.a flatten array vLst = np.ravel(arrLst) # image file to 1D array a.k.a flatten array # Check if NDVI and LST have the same dimension lenNdvi = np.size(arrNdvi) lenLst = np.size(arrLst) dims = lenNdvi == lenLst if not dims == True: raise IOError("The dimension of NDVI and LST are not the same.\ Please check number of cols and rows") """ Calculate the dry and wet edges """ #Compute for slope and intercept from relationship of NDVI and LST # Compute for LSTmax mask = np.where((vNdvi >= 0.3) & (vNdvi <= 0.8), 1, 0) # set threshold for NDVI values for LSTmax calculation rNdvi = np.choose(mask, (np.nan, vNdvi)) # mask the selected NDVI Nmax = np.nanmax(rNdvi) # maximum NDVI value Nmin = np.nanmin(rNdvi) # minimum NDVI value print "NDVI threshold for LSTmax calculation : 0.3 to 0.8" # set the step interval for the edges step =0.025 UpPercentile = 99 # the upper percentile of LST for calculating LSTmax per interval LoPercentile = 1 # the lower percentile of LST for calculating LSTmin per interval nObsMin = 20 # minimum no. of observation for every step interval print "Upper percentile of LST for calculating LSTmax: 99th percentile" print "Lower percentile of LST for calculating LSTmin: 1st percentile" print "Step interval used: 0.025" # get the no. of interval for the computation ni = int(round((Nmax - Nmin)/0.025))+1 idxValue = [] # list for the mid NDVI value within an interval LSTmin=[] # list of the 1st percentile LST for every NDVI interval LSTmax = [] # list of the 95th percentile LST for every NDVI interval # for every step within NDVI interval: for r in range(0,ni-1): rMin = r*step + Nmin # minimum interval value rMax = r*step + Nmin + step # maximum interval value SelNdvi = np.where((vNdvi >= rMin) & (vNdvi <= rMax), 1, 0) #filter pixels with NDVI value within the interval temp_ = np.extract(SelNdvi, vLst) # get equivalent LST pixels of the filtered NDVIs temp = temp_[~np.isnan(temp_)] if np.size(temp)> nObsMin: # check the number of pixels observations greater than 20 LSTmaxpt = np.percentile(temp, UpPercentile) #get the LST 99th percentile LSTminpt = np.percentile(temp, LoPercentile) #get the LST 1st percentile LSTmax.append(LSTmaxpt) # put the 99th percentile value on a list - LSTmax for the regression line calculation LSTmin.append(LSTminpt) # put the 1st percentile value on a list - LST min for the wet edge calculation midNdvi = (rMax - rMin)*2 + rMax # get the mid value of the NDVI interval idxValue.append(midNdvi) # put mid value NDVI on a list - NDVI for the regression line calculation else: print "There is not enough LST observations in this interval." # message if number of observations is less than 20 # compute for the dry edge regression line # polyfit, with 1 degree polynomial computes for a linear fit, same with an ordinary least square regression OLS) b,a = polyfit(idxValue, LSTmax, 1) # returns the slope (b) and the intercept (a), respectively print "Dry edge = {}".format(a), " + ({}".format(b), " * NDVI)" # Compute the dry edge from OLS regression Dry_edge = a + (b * np.array(vNdvi)) # Compute for cold edge (LSTmin) - the minimum among the 1st percentile of LST Cold_edge = np.min(LSTmin) # Minimum of the 10th percentile LST for every NDVI interval print "Cold edge = %3f" % Cold_edge # mask the NDVI and the LST values for the scatter plot - showing the acceptable range Nmask = np.where((vNdvi > 0.1) & (vNdvi <= 1), 1, 0) Lmask = np.where((vLst > 0) & (vLst <= 70), 1, 0) Cmask = Nmask * Lmask NMasked = np.choose(Cmask, (np.nan, vNdvi)) LMasked = np.choose(Cmask, (np.nan, vLst)) # plot NDVI vs LST, dry edge and cold edge plt.scatter(NMasked, LMasked, c='green', alpha=0.3, s=1, zorder=1) plt.plot(vNdvi,Dry_edge, '-', color = 'red', zorder=2) #plt.hlines(Cold_edge, 0.3, midNdvi, color='blue') plt.hlines(Cold_edge, 0.0, 1.0, color='blue', zorder=3) plt.scatter(idxValue, LSTmax, c='red', marker='.', alpha=1, s=45, zorder=4) #- this will show the scatter plot for the dry edge points plt.scatter(idxValue, LSTmin, c='blue', marker='v', alpha=1, s=45, zorder=5) # - this will show the scatter plot for the wet edge points plt.minorticks_on() plt.grid(alpha=1) plt.gcf() plt.xlabel('Normalized Difference Vegetation Index') plt.xlim([0,1]) plt.ylabel('Land Surface Temperature ($^\circ$C)') plt.ylim([10,55]) plt.savefig(sPlot) #plt.show() plt.close() """ TVDI calculation """ #outData = np.empty((rows_Ndvi, cols_Ndvi), np.dtype(float)) # create an empty array for the output data outData = (arrLSTm - Cold_edge) / (a + b*arrNdvi - Cold_edge) # calculate TVDI array_to_raster(outData,tvdiname) ################################################################################################## Dir = "D:\z_To_delete\hh" # directory of NDVI and LST files srcdir = os.path.abspath(Dir) # setting the default directory as working directory os.chdir(srcdir) # search for ndvi and lst files ndvifiles = glob.glob("*NDVI.tif") lstfiles = glob.glob("*LST.tif") ds = gdal.Open(ndvifiles[0]) dsTrans = ds.GetGeoTransform() outDir = srcdir+"\\outTVDI" if not os.path.exists(outDir): os.mkdir(outDir) # calculate TVDI for all matching NDVI-LST input files for n,l in itertools.izip(ndvifiles,lstfiles): MOD, yr, doy, tile, name = n.split("_") #MOD_yr2015_doy001_h30v08_LST.ti print "Processing TVDI for %s & %s" %(n,l) plotname = outDir + "%s_%s_%s_%s_plot.png" %(MOD, yr, doy, tile) tvdiname = outDir + "%s_%s_%s_%s_TVDI.tif" %(MOD, yr, doy, tile) calcTVDI(n, l, plotname,tvdiname)
UTF-8
Python
false
false
7,865
py
1
TVDI.py
1
0.664336
0.648697
0
177
43.435028
140
babamba/sideAppServer
3,856,880,681,239
3f9fb6e5c6a263e88d4ffbbd73f1822332eecbb9
7958401b2fb438f6bbc518e6b536cc8ec28bd559
/TodaySalary/notifications/migrations/0006_auto_20190327_0231.py
e3a65e335c6af4ba7035c42515dcd5ed0bfa7028
[ "MIT" ]
permissive
https://github.com/babamba/sideAppServer
db49a209802b90cbbade70aaa23d0cce1f4c2208
607d61cbea9d05fe902b9f8e772bbd9f7baca28c
refs/heads/master
2022-12-13T12:52:15.944602
2019-03-31T03:07:49
2019-03-31T03:07:49
174,468,137
0
0
MIT
false
2022-12-09T15:04:51
2019-03-08T04:19:03
2019-03-31T03:08:00
2022-12-09T15:04:50
8,042
0
0
31
JavaScript
false
false
# Generated by Django 2.0.9 on 2019-03-26 17:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notifications', '0005_auto_20181018_1731'), ] operations = [ migrations.AlterField( model_name='notification', name='notification_type', field=models.CharField(choices=[('today', 'Today Complete'), ('month', 'Month Complete'), ('holi', 'Today Holiday')], max_length=20), ), ]
UTF-8
Python
false
false
504
py
41
0006_auto_20190327_0231.py
35
0.609127
0.543651
0
18
27
145
saitou1978/p5
14,620,068,724,706
b68199af70bc81ab0105ecef163dafbe14aacc9d
17f6de0d564f2ba380058afa8ef82e103975075f
/p5/get_page.py
778dba3757756896e28df8f3e610c7e35977f596
[]
no_license
https://github.com/saitou1978/p5
e4a021823a189fbf9ca7d3eb523a776b8de22336
670165cc0fefbd6d20ebe9e2a3956cc2fd32f7c2
refs/heads/master
2018-03-24T10:21:09.249263
2016-08-08T17:31:19
2016-08-08T17:31:19
27,379,565
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- # python 2.7.8 import sys import codecs reload(sys) sys.setdefaultencoding('utf-8') import httplib2 import httplib import urllib2 import lxml.html import socket import ssl import hashlib from timeout import on_timeout import time def handler_func(msg): print msg # 実際は適切な通知処理を行う class GetHTTPContent: def __init__(self, url): self.url = url self.cachedata = httplib2.Http('.cache') userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:36.0) Gecko/20100101 Firefox/36.0' self.headers = { 'User-Agent': userAgent } @on_timeout(limit=4, handler=handler_func, hint=u'長い! get_page') def get_page(self): try: resp = urllib2.urlopen(self.url,timeout=4) self.url = resp.geturl() self.http_response, self.html_content = self.cachedata.request(self.url, headers=self.headers) except httplib2.ServerNotFoundError as e: self.http_response, self.html_content = e, '1' # html_contentの値は暫定 except httplib2.RelativeURIError as e: self.http_response, self.html_content = e, '3' except KeyError as e: self.http_response, self.html_content = e, '4' except urllib2.HTTPError as e: self.http_response, self.html_content = e, '5' except (urllib2.URLError,socket.timeout) as e: self.http_response, self.html_content = e, '6' except httplib2.SSLHandshakeError as e: self.http_response, self.html_content = e, '7' except socket.timeout as e: self.http_response, self.html_content = e, '8' except ssl.SSLError as e: self.http_response, self.html_content = e, '9' except httplib.http_responseNotReady as e: self.http_response, self.html_content = e, '2' return self.http_response, self.html_content def get_all_links(self): lxml_doc = lxml.html.fromstring(self.html_content) try: links = lxml_doc.xpath('//a') except indexError: links = [] return links """ def get_html_content_hash(self): html_content_hash = hashlib.sha224(self.html_content).hexdigest() return html_content_hash """ if __name__ == '__main__': URL = "http://viruupaaksa.com/" page = GetHTTPContent(URL) http_response, html_content = page.get_page() print "# %s %s" % (URL, http_response) print "%s" % html_content for link in page.get_all_links(): print link.attrib['href'],link.text
UTF-8
Python
false
false
2,610
py
6
get_page.py
4
0.619844
0.601167
0
77
32.363636
106
p-chambers/VAMPzero
12,163,347,382,878
60fe4fb1a1176b620244384d4a8482ad64734287
82ca891008793f570668a7f2c760ae0f22d40494
/src/build.py
94b0155572bed4f94e07be8791c92c9b11e4649a
[ "Apache-2.0" ]
permissive
https://github.com/p-chambers/VAMPzero
22f20415e83140496b1c5702b6acbb76a5b7bf52
4b11d059b1c7a963ec7e7962fa12681825bc2f93
refs/heads/master
2021-01-19T10:49:06.393888
2015-06-24T10:33:41
2015-06-24T10:33:41
82,208,448
1
0
null
true
2017-02-16T17:42:55
2017-02-16T17:42:55
2016-08-01T05:06:12
2015-06-24T10:34:34
12,089
0
0
0
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Copyright: Deutsches Zentrum fuer Luft- und Raumfahrt e.V., 2015 (c) Contact: daniel.boehnke@dlr.de and jonas.jepsen@dlr.de ''' import sys import os import shutil from VAMPzero import version as VAMPversion import argparse from VAMPzero.Lib.Utilities import zipdir import zipfile class Usage(Exception): def __init__(self, msg): self.msg = msg def main(argv=None): # to be able to use main() in interactive mode if argv is None: argv = sys.argv try: try: usage = "usage: %prog [options] arg1 arg2\n\ttype '%prog --help' for help" parser = argparse.ArgumentParser(description='Build VAMPzero') parser.add_argument("--doc", help="creating VAMPzeros documentation", action='store_true') parser.add_argument("--exe", help="compiling VAMPzero to executable", action='store_true') parser.add_argument("--win32", help="creating a zipfile containing the win32 binary package", action='store_true') parser.add_argument("--win64", help="creating a zipfile containing the win64 binary package", action='store_true') parser.add_argument("--src", help="creating a zipfile containing VAMPzeros source code", action='store_true') parser.add_argument("--all", help="do the complete build process", action='store_true') parser.add_argument("--clean", help="removes all temporary build files", action='store_true') parser.add_argument("--test", help="perform tests for VAMPzero", action='store_true') parser.add_argument("--removeDoublesFromBin", help="removes all files in bin which are also produced by py2exe", action='store_true') args = parser.parse_args() if args.all: make_all() else: ''' The order of the following arguments is important since some functions rely on the output of others. ''' if args.test: run_tests() if args.clean: clean() if args.doc: make_doc_html() zip_doc() if args.exe or args.win32 or args.win64: make_exe() if args.removeDoublesFromBin: removeDoublesfromBin() if args.win32 or args.win64: make_bin() if args.win32: make_bin_win32() if args.win64: make_bin_win64() if args.src: make_src() except (Exception), msg: raise Usage(msg) except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 PATH_TO_TOP = ".." CWD = os.getcwd() ZIPNAME_COMPLETE = "../VAMPzero" + VAMPversion + "bin-complete.zip" def run_tests(): path = os.path.split(os.path.abspath(__file__))[0] os.system("python {}".format(os.path.join(path, '../test/run_tests.py'))) def make_doc_html(): ''' Calculates script to calculate sensitivities for VAMPzeros parameters. Create VAMPzero documentation in html format using Sphinx's make process. ''' print("Creating documentation via sphinx...") path_to_doc = "VAMPzero/doc" try: os.system("python VAMPzeroDoc.py") os.chdir(path_to_doc) os.system("make html") finally: os.chdir(CWD) def zip_doc(): ''' Compresses VAMPzeros documentation into a zip file. This function does not update the documentation and therefore needs make_doc_html to run up-front. An existing zip file will be deleted. This function uses pure python code to work on different OS. ''' print("Creating documenation zip file...") path_to_html = "VAMPzero/doc/_build/html" try: zipname = PATH_TO_TOP + "/VAMPzero" + VAMPversion + "Doc_html.zip" zipdir.zipdir(path_to_html, zipname) finally: os.chdir(CWD) def make_exe(): ''' Creates VAMPzeros binary by using the py2exe setup script. ''' print("Executing py2exe ...") os.system("python setup_py2exe.py py2exe") def make_bin(): ''' Creates a zip file with all files for binary distribution. Including 32bit and 64bit versions of files. Needs compiled binaries as created by make_exe(). ''' print("Creating binary zip file...") try: zipFile = zipdir.ZipFileExt(ZIPNAME_COMPLETE, "w", zipfile.ZIP_DEFLATED) # get prepared files zipFile.addDirToZip('../bin') # get compiled files zipFile.addDirToZip('../src/bin') # add mapping files zipFile.addFileToZip('mappingInputRaw.xsl') zipFile.addFileToZip('mappingOutput.xml') zipFile.close() except Exception as e: print("Error while building bin:", e) finally: os.chdir(CWD) def make_bin_win32(): ''' Creates a zip file of VAMPzeros win32 binary. Needs compiled binaries as created by make_exe(). ''' print("Creating win32 zip file...") try: zipname = PATH_TO_TOP + "/VAMPzero" + VAMPversion + "bin-win32.zip" zin = zipdir.ZipFileExt(ZIPNAME_COMPLETE, 'r') zout = zipdir.ZipFileExt(zipname, 'w') for item in zin.infolist(): myBuffer = zin.read(item.filename) print item.filename if item.filename.endswith('vampzerostandalone_64.jar'): continue else: zout.writestr(item, myBuffer) zout.close() zin.close() except Exception as e: print("Error while building win32:", e) finally: os.chdir(CWD) def make_bin_win64(): ''' Creates a zip file of VAMPzeros win32 binary. Needs compiled binaries as created by make_exe(). ''' print("Creating win64 zip file...") try: zipname = PATH_TO_TOP + "/VAMPzero" + VAMPversion + "bin-win64.zip" zin = zipdir.ZipFileExt(ZIPNAME_COMPLETE, 'r') zout = zipdir.ZipFileExt(zipname, 'w') for item in zin.infolist(): myBuffer = zin.read(item.filename) print item.filename if item.filename.endswith('vampzerostandalone_64.jar'): continue else: zout.writestr(item, myBuffer) zout.close() zin.close() except Exception as e: print("Error while building win64:", e) finally: os.chdir(CWD) def make_src(): ''' Creates a zip file of the source code version of VAMPzero. ''' print("Creating source zip file...") includeFiles = ['setup.py', 'README.txt', 'NOTICE', 'VAMPzero.ico', 'VAMPzero.jpg', 'VAMPzero.py', 'VAMPzeroCPACS.py', 'VAMPzeroDoc.py', 'mappingInputRaw.xsl', 'mappingOutput.xml', 'ToolInput/toolInput.xml'] emptyDirs = ['ToolOutput', 'ReturnDirectory'] try: zipname = "../VAMPzero" + VAMPversion + "src.zip" zipout = zipdir.ZipFileExt(zipname, 'w') zipout.add_exclude('.pyc') zipout.addDirToZip('./VAMPzero', "VAMPzero") for filePath in includeFiles: zipout.write(filePath, filePath) for emptyDir in emptyDirs: zipInfo = zipfile.ZipInfo(emptyDir + os.path.sep) zipout.writestr(zipInfo, "") zipout.close() # os.system("touch ../" + zipname) # os.system("rm ../" + zipname) # # get compiled files # # exclude all files in bin, build, and all *.pyc files in top directory and subdirs # os.system("zip -r ../" + zipname + " * -x bin/\* build/\* \*/\*.pyc \*.pyc") finally: os.chdir(CWD) def clean(): ''' A function to clean VAMPzero from all temp files of the build process. This includes .pyc files, the src/bin directory as well as the created html doc. ''' # make sure the current directory is the right one # otherwise the wrong stuff could be deleted path = os.path.split(os.path.abspath(__file__))[0] binPath = os.path.join(path, 'bin') buildPath = os.path.join(path, 'build') if os.path.exists(binPath) and os.path.exists(buildPath): print("Removing {}".format(binPath)) shutil.rmtree(binPath) print("Removing {}".format(buildPath)) shutil.rmtree(buildPath) def make_all(): ''' Starts the complete build process. ''' #clean() make_doc_html() zip_doc() make_exe() make_bin_win32() make_bin_win64() make_src() def removeDoublesfromBin(): path = os.path.split(os.path.abspath(__file__))[0] binDirUpper = os.path.join(path, '../bin') binDirLower = os.path.join(path, 'bin') def trimPath(filePath, rootPath): ''' Removes the root path from the beginning of filePath. ''' filePath = os.path.abspath(filePath) rootPath = os.path.abspath(rootPath) tmpList = os.path.abspath(filePath).split(os.path.sep) rootList = os.path.abspath(rootPath).split(os.path.sep) rootPathLength = len(rootList) return os.path.sep.join(tmpList[rootPathLength:]) print("Removing redundant files...") upperList = [] for (dirpath, dirnames, filenames) in os.walk(binDirUpper): for filename in filenames: upperList.append(trimPath(os.path.join(dirpath, filename), binDirUpper)) lowerList = [] for (dirpath, dirnames, filenames) in os.walk(binDirLower): for filename in filenames: lowerList.append(trimPath(os.path.join(dirpath, filename), binDirLower)) removeList = [] for item in upperList: if item in lowerList: removeList.append(os.path.abspath(os.path.join(binDirUpper, item))) for item in removeList: print("removing: {}".format(item)) os.remove(item) # remove empty directories emptyDirsList = [] for (dirpath, dirnames, filenames) in os.walk(binDirUpper): if not filenames and not dirnames: emptyDirsList.append(dirpath) for item in emptyDirsList: print("removing empty dir: {}".format(item)) os.removedirs(item) if __name__ == "__main__": sys.exit(main())
UTF-8
Python
false
false
11,098
py
545
build.py
217
0.595873
0.589025
0
313
34.456869
145
suppureme/FisherEmbeddingFinal
2,396,591,784,478
e024fdeb4454ebd27385e2b9385f9e4c909c6289
3facdefca75155161d8a1a1c7ddfaf10f3f2c6fe
/venv/Lib/site-packages/pyluach/hebrewcal.py
bfbe34ecb93dbd05754d59fcfb3d4193c37dfb29
[ "Apache-2.0" ]
permissive
https://github.com/suppureme/FisherEmbeddingFinal
b0b171c4757e456046224dcdcc3418889dcaccfc
0d07f09931658c838988c987cd6d8db5376ff715
refs/heads/master
2023-07-06T19:47:26.755177
2021-08-10T06:04:47
2021-08-10T06:04:47
394,538,875
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
"""The hebrewcal module implements classes for representing a Hebrew year and month. It also has functions for getting the holiday or fast day for a given date. """ from collections import deque from numbers import Number from functools import lru_cache from pyluach.dates import GregorianDate, HebrewDate from pyluach import utils from pyluach.gematria import _num_to_str from pyluach.utils import _holiday, _fast_day_string, _festival_string def fast_day(date, hebrew=False): """Return name of fast day or None. Parameters ---------- date : ``HebrewDate``, ``GregorianDate``, or ``JulianDay`` Any date that implements a ``to_heb()`` method which returns a ``HebrewDate`` can be used. hebrew : bool, optional ``True`` if you want the fast_day name in Hebrew letters. Default is ``False``, which returns the name transliterated into English. Returns ------- str or ``None`` The name of the fast day or ``None`` if the given date is not a fast day. """ return _fast_day_string(date, hebrew) def festival(date, israel=False, hebrew=False): """Return Jewish festival of given day. This method will return all major and minor religous Jewish holidays not including fast days. Parameters ---------- date : ``HebrewDate``, ``GregorianDate``, or ``JulianDay`` Any date that implements a ``to_heb()`` method which returns a ``HebrewDate`` can be used. israel : bool, optional ``True`` if you want the festivals according to the Israel schedule. Defaults to ``False``. hebrew : bool, optional ``True`` if you want the festival name in Hebrew letters. Default is ``False``, which returns the name transliterated into English. Returns ------- str or ``None`` The name of the festival or ``None`` if the given date is not a Jewish festival. """ return _festival_string(date, israel, hebrew) def holiday(date, israel=False, hebrew=False): """Return Jewish holiday of given date. The holidays include the major and minor religious Jewish holidays including fast days. Parameters ---------- date : ``HebrewDate``, ``GregorianDate``, or ``JulianDay`` Any date that implements a ``to_heb()`` method which returns a ``HebrewDate`` can be used. israel : bool, optional ``True`` if you want the holidays according to the israel schedule. Defaults to ``False``. hebrew : bool, optional ``True`` if you want the holiday name in Hebrew letters. Default is ``False``, which returns the name transliterated into English. Returns ------- str or ``None`` The name of the holiday or ``None`` if the given date is not a Jewish holiday. """ return _holiday(date, israel, hebrew) class Year: """A Year object represents a Hebrew calendar year. It provided the following operators: ===================== ================================================ Operation Result ===================== ================================================ year2 = year1 + int New ``Year`` ``int`` days after year1. year2 = year1 - int New ``Year`` ``int`` days before year1. int = year1 - year2 ``int`` equal to the absolute value of the difference between year2 and year1. bool = year1 == year2 True if year1 represents the same year as year2. bool = year1 > year2 True if year1 is later than year2. bool = year1 >= year2 True if year1 is later or equal to year2. bool = year1 < year2 True if year 1 earlier than year2. bool = year1 <= year2 True if year 1 earlier or equal to year 2. ===================== ================================================ Parameters ---------- year : int A Hebrew year. Attributes ---------- year : int The hebrew year. leap : bool True if the year is a leap year else false. """ def __init__(self, year): if year < 1: raise ValueError('Year {0} is before creation.'.format(year)) self.year = year self.leap = utils._is_leap(year) def __repr__(self): return 'Year({0})'.format(self.year) def __len__(self): return utils._days_in_year(self.year) def __eq__(self, other): if isinstance(other, Year) and self.year == other.year: return True return False def __add__(self, other): """Add int to year.""" try: return Year(self.year + other) except TypeError: raise TypeError('You can only add a number to a year.') def __sub__(self, other): """Subtract int or Year from Year. If other is an int return a new Year other before original year. If other is a Year object, return delta of the two years as an int. """ if isinstance(other, Year): return abs(self.year - other.year) else: try: return Year(self.year - other) except TypeError: raise TypeError('Only an int or another Year object can' ' be subtracted from a year.') def __gt__(self, other): if self.year > other.year: return True return False def __ge__(self, other): if self == other or self > other: return True return False def __lt__(self, other): if self.year < other.year: return True return False def __le__(self, other): if self < other or self == other: return True return False def __iter__(self): """Yield integer for each month in year.""" months = [7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6] if not self.leap: months.remove(13) for month in months: yield month def itermonths(self): """Yield Month instance for each month of the year. Yields ------ ``Month`` The next month in the Hebrew calendar year as a ``luachcal.hebrewcal.Month`` instance beginning with Tishrei and ending with Elul. """ for month in self: yield Month(self.year, month) def iterdays(self): """Yield integer for each day of the year. Yields ------ int An integer beginning with 1 representing the next day of the year. """ for day in range(1, len(self) + 1): yield day def iterdates(self): """Yield HebrewDate instance for each day of the year. Yields ------ HebrewDate The next date of the Hebrew calendar year starting with the first of Tishrei. """ for month in self.itermonths(): for day in month: yield HebrewDate(self.year, month.month, day) @classmethod def from_date(cls, date): """Return Year object that given date occurs in. Parameters ---------- date : ``HebrewDate``, ``GregorianDate``, or ``JulianDay`` Any one of the ``pyluach`` date types. Returns ------- Year """ return cls(date.to_heb().year) @classmethod def from_pydate(cls, pydate): """Return Year object from python date object. Parameters ---------- pydate : ``datetime.date`` A python standard library date object Returns ------- Year The Hebrew year the given date occurs in """ return cls.from_date(HebrewDate.from_pydate(pydate)) def year_string(self, thousands=False): """Return year as a Hebrew string. Parameters ---------- thousands: bool, optional ``True`` to prefix the year with the thousands place. default is ``False``. Examples -------- >>> year = Year(5781) >>> year.year_string() תשפ״א >>> year.year_string(True) ה׳תשפ״א """ return _num_to_str(self.year, thousands) class Month: """A Month object represents a month of the Hebrew calendar. It provides the same operators as a `Year` object. Parameters ---------- year : int month : int The month as an integer starting with 7 for Tishrei through 13 if necessary for Adar Sheni and then 1-6 for Nissan - Elul. Attributes ---------- year : int The Hebrew year. month : int The month as an integer starting with 7 for Tishrei through 13 if necessary for Adar Sheni and then 1-6 for Nissan - Elul. name : str The name of the month. .. deprecated:: 1.3.0 `name` attribute will be removed in pyluach 2.0.0, it is replaced by `month_name` method, because the latter allows a `hebrew` parameter. The month_name also uses slightly different transliteration. """ _monthnames = {7: 'Tishrei', 8: 'Cheshvan', 9: 'Kislev', 10: 'Teves', 11: 'Shvat', 13:'Adar Sheni', 1: 'Nissan', 2: 'Iyar', 3: 'Sivan', 4: 'Tamuz', 5: 'Av', 6: 'Elul'} def __init__(self, year, month): if year < 1: raise ValueError('Year is before creation.') self.year = year leap = utils._is_leap(self.year) yearlength = 13 if leap else 12 if month < 1 or month > yearlength: raise ValueError('''Month must be between 1 and 12 for a normal year and 13 for a leap year.''') self.month = month self.name = utils._month_name(self.year, self.month, False) def __repr__(self): return 'Month({0}, {1})'.format(self.year, self.month) def __len__(self): return utils._month_length(self.year, self.month) def __iter__(self): for day in range(1, len(self) + 1): yield day def __eq__(self, other): if( isinstance(other, Month) and self.year == other.year and self.month == other.month): return True return False def __add__(self, other): yearmonths = list(Year(self.year)) index = yearmonths.index(self.month) leftover_months = len(yearmonths[index + 1:]) try: if other <= leftover_months: return Month(self.year, yearmonths[index + other]) return Month(self.year + 1, 7).__add__(other - 1 - leftover_months) except (AttributeError, TypeError): raise TypeError('You can only add a number to a year.') def __sub__(self, other): if isinstance(other, Number): yearmonths = list(Year(self.year)) index = yearmonths.index(self.month) leftover_months = index if other <= leftover_months: return Month(self.year, yearmonths[index - other]) return Month(self.year - 1, deque(Year(self.year - 1), maxlen=1).pop()).__sub__( other - 1 - leftover_months ) # Recursive call on the last month of the previous year. try: return abs(self._elapsed_months() - other._elapsed_months()) except AttributeError: raise TypeError('''You can only subtract a number or a month object from a month.''') def __gt__(self, other): if ( self.year > other.year or (self.year == other.year and self.month > other.month) ): return True return False def __ge__(self, other): if self > other or self == other: return True return False def __lt__(self, other): if ( self.year < other.year or (self.year == other.year and self.month < other.month) ): return True return False def __le__(self, other): if self < other or self == other: return True return False @classmethod def from_date(cls, date): """Return Month object that given date occurs in. Parameters ---------- date : ``HebrewDate``, ``GregorianDate``, or ``JulianDay`` Any ``pyluach`` date type Returns ------- Month The Hebrew month the given date occurs in """ heb = date.to_heb() return Month(heb.year, heb.month) @classmethod def from_pydate(cls, pydate): """Return Month object from python date object. Parameters ---------- pydate : ``datetime.date`` A python standard library date object Returns ------- Month The Hebrew month the given date occurs in """ return cls.from_date(HebrewDate.from_pydate(pydate)) def month_name(self, hebrew=False): """Return the name of the month. Replaces `name` attribute. Parameters ---------- hebrew : bool, optional `True` if the month name should be written with Hebrew letters and False to be transliterated into English using the Ashkenazic pronunciation. Default is `False`. Returns ------- str """ return utils._month_name(self.year, self.month, hebrew) def month_string(self, thousands=False): """Return month and year in Hebrew. Parameters ---------- thousands : bool, optional ``True`` to prefix year with thousands place. Default is ``False``. Returns ------- str The month and year in Hebrew in the form ``f'{month} {year}'``. """ return '{} {}'.format( self.month_name(True), _num_to_str(self.year, thousands) ) def starting_weekday(self): """Return first weekday of the month. Returns ------- int The weekday of the first day of the month starting with Sunday as 1 through Saturday as 7. """ return HebrewDate(self.year, self.month, 1).weekday() def _elapsed_months(self): '''Return number of months elapsed from beginning of calendar''' yearmonths = tuple(Year(self.year)) months_elapsed = ( utils._elapsed_months(self.year) + yearmonths.index(self.month) ) return months_elapsed def iterdates(self): """Return iterator that yields an instance of HebrewDate. Yields ------ ``HebrewDate`` The next Hebrew Date of the year starting the first day of Tishrei through the last day of Ellul. """ for day in self: yield HebrewDate(self.year, self.month, day) def molad(self): """Return the month's molad. Returns ------- dict A dictionary in the form {weekday: int, hours: int, parts: int} Note ----- This method does not return the molad in the form that is traditionally announced in the shul. This is the molad in the form used to calculate the length of the year. See Also -------- molad_announcement: The molad as it is traditionally announced. """ months = self._elapsed_months() parts = 204 + months*793 hours = 5 + months*12 + parts//1080 days = 2 + months*29 + hours//24 weekday = days % 7 or 7 return {'weekday': weekday, 'hours': hours % 24, 'parts': parts % 1080} def molad_announcement(self): """Return the months molad in the announcement form. Returns a dictionary in the form that the molad is traditionally announced. The weekday is adjusted to change at midnight and the hour of the day and minutes are given as traditionally announced. Note that the hour is given as in a twenty four hour clock ie. 0 for 12:00 AM through 23 for 11:00 PM. Returns ------- dict A dictionary in the form:: { weekday: int, hour: int, minutes: int, parts: int } """ molad = self.molad() weekday = molad['weekday'] hour = 18 + molad['hours'] if hour < 24: if weekday != 1: weekday -= 1 else: weekday = 7 else: hour -= 24 minutes = molad['parts'] // 18 parts = molad['parts'] % 18 return { 'weekday': weekday, 'hour': hour, 'minutes': minutes, 'parts': parts }
UTF-8
Python
false
false
17,166
py
421
hebrewcal.py
49
0.540632
0.530955
0
563
29.470693
79
REYGCAETANO/projetoFinalFaculdade
3,728,031,615,287
6971061346825c680292db15cc8547812bb9f1de
6482f25f0ad31fc6201d4ba5d763c0d2d6a7b6ec
/apps/gradehoraria/migrations/0019_auto_20201111_2104.py
5fb800cde813b881ec4a9abb174c85c7d2a8968d
[]
no_license
https://github.com/REYGCAETANO/projetoFinalFaculdade
e9b04e24c607e487e69596210d6a933e1f8f57cf
23ecce465ed98f337ba906090f6c2df2aa4dc130
refs/heads/master
2023-01-31T20:48:19.053421
2020-12-08T12:45:37
2020-12-08T12:45:37
303,847,232
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 2.1.2 on 2020-11-12 00:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gradehoraria', '0018_auto_20201030_2352'), ] operations = [ migrations.AlterUniqueTogether( name='gene', unique_together={('id_gene', 'cd_professor', 'cd_horario', 'cd_sala', 'oferta')}, ), ]
UTF-8
Python
false
false
410
py
57
0019_auto_20201111_2104.py
39
0.595122
0.519512
0
19
20.578947
93
hiwaylon/tornado-baseline
9,363,028,756,327
3f81b730eef7e3b23d59e054eae5a5e6002fab3e
091482e7ae622acce3670602d6942c1a47b6461c
/api/handlers/scores_handler.py
e54b55a40931f289aad306bfb6252e8f895510b3
[]
no_license
https://github.com/hiwaylon/tornado-baseline
4af0ac84133d0f6c618166207f6f06e65bf7a3f5
2280b04ec007fc341e9669b375361c3f682e59d0
refs/heads/master
2020-04-19T04:05:32.405132
2013-09-19T11:58:46
2013-09-19T11:58:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
"""Example request handler.""" from tornado import web from api.handlers import mixins from api.utils import routes @routes.route("/api/v1/scores") class ScoresHandler(web.RequestHandler, mixins.ResourceCreationMixin): def post(self): """Handles requests for diet quality scores.""" request_data = self.request.to_dict() score = self.create_resource(request_data) self.set_status(201) self.write(score.simple_view()) def _validate_internal(self, request_data): return True def _create_internal(self, request_data): pass
UTF-8
Python
false
false
594
py
16
scores_handler.py
15
0.680135
0.673401
0
22
26
70
amreshk005/car
11,493,332,513,749
a7591b6bb20929f0e103941dd11a25def0d6a96c
8ee1ec51c3041dc48893f978e20add4e9a8c90b2
/fixx/car/urls.py
4f0101f2757ecd6a4e6d10aa6dd9849ec6698bff
[]
no_license
https://github.com/amreshk005/car
dce04b1c8721f0b8a09f15b7e50fdf024a7cb2a9
076e52c4d58589fbfdd4f4530ec57726b4934bad
refs/heads/master
2020-05-01T09:31:09.436211
2019-04-30T06:58:20
2019-04-30T06:58:20
177,402,082
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.urls import path,include from . import views app_name='car' urlpatterns = [ path('',views.register,name='index'), path('privacy',views.privacy,name='privacy') ]
UTF-8
Python
false
false
185
py
8
urls.py
5
0.686486
0.686486
0
9
19.333333
48
jrodal98/PDF-Packages
16,011,638,118,181
c71dbbb85626c1dc6ab0ddc3c73d5afb3ac63e2b
4e4cb7ac592846f2736f4653646cfb319b7a2e1f
/ScrollableFrame.py
2704e8be08b83ffe2b14df67efd37b5e51f3231f
[ "MIT" ]
permissive
https://github.com/jrodal98/PDF-Packages
f72fddd10f40fc6db0b0c11d9643d37bb7a50965
188e44b24c8e73c23a12e93c806d03adff727e0a
refs/heads/master
2020-03-21T01:01:11.798176
2019-10-27T15:55:34
2019-10-27T15:55:34
137,920,188
0
0
MIT
false
2019-12-20T02:11:32
2018-06-19T16:53:51
2019-10-27T15:55:37
2019-10-27T15:55:38
27,674
0
0
0
Python
false
false
import tkinter as tk from tkinter import ttk class ScrollableFrame(ttk.Frame): def __init__(self, master): """Creates a tk GUI Frame with parameters specified below.""" ttk.Frame.__init__(self, master) # call super constructor self.master = master # initializing all of the fields # next few lines (used for scrollbar) are from # https://stackoverflow.com/questions/3085696/adding-a-scrollbar-to-a-group-of-widgets-in-tkinter/3092341 # #3092341 self.canvas = tk.Canvas(self, borderwidth=0, background="SlateGray1") self.frame = ttk.Frame(self.canvas) self.vsb = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.canvas.pack(side="left", fill="both", expand=True) self.canvas.create_window((4, 4),window=self.frame, anchor="nw", tags="self.frame") self.frame.bind("<Configure>", self.on_frame_configure) # prevents scrolling from going beyond the borders of the frame self.frame.bind_all("<MouseWheel>", self.on_mousewheel, add=self.on_frame_configure) def on_frame_configure(self, event): # from https://stackoverflow.com/questions/3085696/adding-a-scrollbar-to-a-group-of-widgets-in-tkinter # /3092341#3092341 self.canvas.configure(scrollregion=self.canvas.bbox("all")) def on_mousewheel(self, event): self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
UTF-8
Python
false
false
1,606
py
10
ScrollableFrame.py
8
0.65193
0.620797
0
31
50.83871
113
kirillmakhonin/kirahhe
10,797,547,791,118
406da26ad40dd530300ccd927ac5a2a6715f900a
cf0bf3cdb24906079c086d29b9a65e64cbbfce3e
/bin/kirahhe
1ec5758b05459d4623aba5de22afb67ad05fee26
[ "MIT" ]
permissive
https://github.com/kirillmakhonin/kirahhe
bd7dd07055873b16fdd1651aeab231d9bd1c8ef0
ee9a7712d795773a4ea7dcf610fc2a0dffff7944
refs/heads/master
2020-03-28T06:54:33.795754
2018-09-10T12:21:11
2018-09-10T12:21:11
147,868,603
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python """ Package's entrypoint """ import argparse import logging import kirahhe if __name__ == '__main__': parser = argparse.ArgumentParser( description='Process stack trace analyzer') parser.add_argument('--verbose', help='verbose log output', action='store_true') parser.add_argument('--filter', type=str, help='Process CLI CMD filter') parser.add_argument('--timeout', type=int, help='Delta between checks in seconds', default=1) parser.add_argument('--command', default='strace -p {pid} -o {time}-{pid}.log', type=str, help='Command that should be executed after new process') args = parser.parse_args() if args.verbose: log_level = logging.DEBUG else: log_level = logging.ERROR logging.basicConfig(level=log_level, format='%(asctime)s - %(levelname)s - %(message)s') kirahhe.observe(args.filter, args.timeout, args.command)
UTF-8
Python
false
false
1,062
3
kirahhe
3
0.582863
0.581921
0
35
29.342857
92
SylviaLe/Simple-HTML-Generator
1,606,317,811,408
6b0a0597799e650185834b79a02561031fc5a37d
5b382cd795905c8869a8a42a6e6d4c0f6a4a673d
/generateHTML.py
45794e259be1cff3ba847920aec3f0f2e0f92211
[]
no_license
https://github.com/SylviaLe/Simple-HTML-Generator
61a809a7d95eb00fa8e8d9ecc82d21a32ee25835
a845c6979dc2992814d11d35faf1a1bd8d9ee6b8
refs/heads/master
2023-05-28T20:17:51.885635
2021-06-13T09:03:00
2021-06-13T09:03:00
340,359,251
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#Sylvia Le, Jack Zimmerman, Hang Nguyen, Melissa Alexander #Programming Assignment 1 #File: generateHTML.py #Date: 02-23-2021 #this program will create a helper program for users who do not know how to use HTML #import libraries. re for regular expression import re from random import randrange import datetime def wrap(tag, word): #Wrap the string with the HTML tag temp = '<{0}>{1}</{2}>'.format(tag, word, tag) #Check if the end tag has components like 'id' or 'class' (we assume only these two are used at the moment) pattern = re.compile(r'</.+?>') #use regex to find the end tag endtag = pattern.findall(temp)[0] openpart = temp[:temp.find(endtag)] #string slicing to keep the opening tag result = '' if ('id' in endtag): #if the word 'id' is found substr = endtag[endtag.find('id'):-1] #find its index in the end tag new_endtag = endtag.replace(substr, '') #then remove it result = openpart + new_endtag #the new string with HTML tag wrap around return result elif ('class' in pattern.findall(temp)[0]): substr = temp[temp.find('class'):-1] new_endtag = endtag.replace(substr, '') result = openpart + new_endtag return result else: #if no 'id' or 'class' found, return the 1st result return temp def table_gen(row, col): #Generate a blank HTML table, with the designate number of row and column table = '' k = 0 #the index for the table cell, used for formatting later for i in range(row): table_row = '' for j in range(col): #generate the <td> tag. Number of <td> tag inside a <tr> = col table_row += '<td>{' + str(k) + '}</td>' #The {} is for inserting value later, using format() k += 1 table_row = wrap('tr', table_row) #wrap the chunk of <td> with the <tr> tag table += table_row #concatenate all the table row together result = wrap('table', table) #wrap the entire thing with the <table> tag return result def letter_table(row, col): #Create an HTML table filled with randomly generated letter #The number of row and col is specified temp = random_let(row, col) letters = [] for l in temp: ptag = wrap('p class="table"', l) #extra step to wrap the letter inside a p tag to style it letters.append(ptag) letters = tuple(letters) #create a tuple of letters table = table_gen(row, col) #generate a blank table result = table.format(*letters) #insert the letters return result def pic_table(row, col, img_list): #Create an HTML table filled with image specified imgs_tag = [] for i in range(len(img_list)): #generate a list of <img> tag given the images source list tag = "<img src='" + img_list[i] + "'>" #since img is a self-closing tag, we don't need to use wrap here imgs_tag.append(tag) imgs_tup = tuple(imgs_tag) #turn that list into a tuple table = table_gen(row, col) #create a blank table result = table.format(*imgs_tup) #insert the image link return result def random_let(row, col): #Generate random letter for the random letter table and return a tuple of random letter n = row*col + 2 #+2 because redundant is better than not enough letter_list = [] for i in range(n): index = randrange(65, 123) while index in range(91, 97): index = randrange(65, 123) #because the character from 91 to 97 is not a letter, so if index in that range, redo letter_list.append(chr(index)) #from number to corresponding character result = tuple(letter_list) #turn the letter list into a tuple return result def main(): #THE FIRST HTML CHUNK, CONTAINING CSS AND THE TABLE TITLE #NOTE: css_str = ''' <!DOCTYPE html> <html> <head> <style type="text/css"> body {{ background-color: {0}; }} h1{{ text-align: center; font-size: 36px; font-weight: 600; }} table{{ border: {1}px solid {2}; text-align:center; border-collapse:collapse; margin-left: auto; margin-right: auto; width: 60% }} tr td {{ border: {1}px solid {2}; background-color: {3}; vertical-align: middle; padding: 20px; }} tr:nth-child(even) td:nth-child(odd), tr:nth-child(odd) td:nth-child(even){{ background-color: {4}; }} p {{ text-align: center; font-size: 21px; font-weight: 600; }} p.table{{ text-align: center; font-size: 21px; font-style: bold; }} img{{ min-width = 100px !important; max-height = 100px !important; object-fit: contain; }} </style> </head> <body> <h1>{5}</h1> ''' css_values =[] #THE SECOND HTML CHUNK, THE TABLE BEGINS table_str = '''''' #THE THIRD HTML CHUNK, THE AUTHORS AND END TAGS authors_str = ''' <p>Created automatically for COM214 HW1 on {0}</p> <p>Authors: {1}</p> </body> </html> ''' authors_values = [] #code for reading the file with open('config1.txt', 'r') as f: bodybg = f.readline() bodybg = bodybg[bodybg.find('\t'):].strip() cell1 = f.readline() cell1 = cell1[cell1.find('\t'):].strip() cell2 = f.readline() cell2 = cell2[cell2.find('\t'):].strip() bordercolor = f.readline() bordercolor = bordercolor[bordercolor.find('\t'):].strip() borderpx = f.readline() borderpx = borderpx[borderpx.find('\t'):].strip() authors = f.readline() authors = authors[authors.find('\t'):].strip() title = f.readline() title = title[title.find('\t'):].strip() mode = f.readline().lower().strip() date = datetime.datetime.now() #footnote require info about time create the document date_str = date.strftime(('%a %b %d %I:%M:%S %Y')) #format for creating a datetime string #append the values in the list for 1st HTML chunk (CSS) css_values.append(bodybg) css_values.append(borderpx) css_values.append(bordercolor) css_values.append(cell1) css_values.append(cell2) css_values.append(title) #append the values in the list for 3rd HTML chunk (authors authors_values.append(date_str) authors_values.append(authors) #insert the values in css_str = css_str.format(*tuple(css_values)) authors_str = authors_str.format(*tuple(authors_values)) rows, cols = 0, 0 if mode == 'images': #if the user specifies he want a table of images imgs = f.readlines() #get the table dimension row = len(imgs) col = imgs[0].count('\t') + 1 #create a list of image link imgsList = [] for item in imgs: line = item.split() imgsList += line #create a table of images table_str = pic_table(row, col, imgsList) elif mode == 'letters': #get the table dimension dimension = f.readline().split('x') row, col = int(dimension[0]), int(dimension[1]) #create a table of random letters table_str = letter_table(row, col) result = css_str + table_str + authors_str #concatenate the generated HTML string print(result) #print it on the shell to check with open('Your Custom Site.html', 'w') as file: #write to file file.write(result) main()
UTF-8
Python
false
false
7,936
py
6
generateHTML.py
1
0.571321
0.559098
0
239
32.205021
125
francisss-s/INFO229
18,370
c6dc7da2810d629472d25272f848f6705aabc5f9
5255e44333794daaecbf9b07e12ccd2a3630febb
/Tutorial_4_PyTest_TDD/ejercicio1/minimo.py
1bcebb4ce0afabe43bd06b67a56e4e83296a2d39
[]
no_license
https://github.com/francisss-s/INFO229
5e0a3cb7d9600bf0956005c4ed88058582859d08
3ef7e3918949f9a195214042c54320f4434b9573
refs/heads/main
2023-02-15T07:49:29.501596
2021-01-11T01:56:14
2021-01-11T01:56:14
311,709,939
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
def get_min(values): return min(values)
UTF-8
Python
false
false
43
py
33
minimo.py
18
0.697674
0.697674
0
2
21
22
z-funfan/opencv-face-recognize
2,027,224,606,028
15f9b18420e3738406cd7df440528f8f16f05f23
379928689aa9a5e65c91163caa23272594b40c90
/my-face-recognize/main.py
aa034d9cb9a55298c0494ae47459c8bb6d1312a4
[ "MIT" ]
permissive
https://github.com/z-funfan/opencv-face-recognize
d18d5bec1bcc7e62651af86bd038d33fc80c2b2d
40ce3873cfd74b2a2b7f2c15ce4e39e801d195d2
refs/heads/master
2022-12-07T01:28:22.000743
2021-05-23T05:53:02
2021-05-23T05:53:02
204,168,705
3
0
MIT
false
2022-11-22T04:12:45
2019-08-24T14:31:29
2021-05-23T05:53:04
2022-11-22T04:12:44
3,140
2
0
5
Python
false
false
from flask import Flask, render_template, Response import cv2 import sys import os import json # from faceDetection import detectFaces from face_detect_v2 import detectFaces from flow_counting import getCounts outputPath = 'output/image' if len(sys.argv) >= 2: outputPath = sys.argv[1] resourcePath = '' cascPath = 'haarcascade_frontalface_alt.xml' if len(sys.argv) >= 3: resourcePath = sys.argv[2] cascPath = resourcePath + '/' + cascPath print("resourcePath: " + resourcePath) app = Flask(__name__, template_folder = resourcePath) @app.route('/') # 主页 def index(): # jinja2模板,具体格式保存在index.html文件中 return render_template('index.html') @app.route('/video_feed') # 这个地址返回视频流响应 def video_feed(): # 从默认摄像头获取视频流 print("Starting camera...") print("Output Path: " + outputPath) video_captures = cv2.VideoCapture(0) return Response(detectFaces(video_captures, outputPath, cascPath), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/total_count') # 客流统计接口 def total_count(): #统计文件夹下文件个数 return Response(json.dumps(getCounts()),'text/plain') if __name__ == '__main__': app.run(host='0.0.0.0', debug=False, port=5000)
UTF-8
Python
false
false
1,325
py
9
main.py
5
0.681706
0.66776
0
44
26.659091
75
hanzg2014/IT_BOOKS
9,766,755,655,716
8986c796570d075fa2f6f15037967e843f162d5b
471e6dc0d258b88a1e5e4a6322b8b6da86d2374b
/Effective_Python/example_code/item_14.py
bb00554d6c1d0428da238d8de31de8acff053461
[]
no_license
https://github.com/hanzg2014/IT_BOOKS
c77e08a5b7b92a39c3f29e88e11a79372a711089
233343d58156ddb6966899621fb96bd5785af24d
refs/heads/master
2021-07-09T14:14:59.221110
2017-10-06T12:26:17
2017-10-06T12:26:17
83,967,488
2
2
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 # Copyright 2014 Brett Slatkin, Pearson Education Inc. # # 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. # Preamble to mimick book environment import logging from pprint import pprint from sys import stdout as STDOUT # Example 1 def divide(a, b): try: return a / b except ZeroDivisionError: return None assert divide(4, 2) == 2 assert divide(0, 1) == 0 assert divide(3, 6) == 0.5 assert divide(1, 0) == None # Example 2 x, y = 1, 0 result = divide(x, y) if result is None: print('Invalid inputs') else: print('Result is %.1f' % result) # Example 3 x, y = 0, 5 result = divide(x, y) if not result: print('Invalid inputs') # This is wrong! else: assert False # Example 4 def divide(a, b): try: return True, a / b except ZeroDivisionError: return False, None # Example 5 x, y = 5, 0 success, result = divide(x, y) if not success: print('Invalid inputs') # Example 6 x, y = 5, 0 _, result = divide(x, y) if not result: print('Invalid inputs') # This is right x, y = 0, 5 _, result = divide(x, y) if not result: print('Invalid inputs') # This is wrong # Example 7 def divide(a, b): try: return a / b except ZeroDivisionError as e: raise ValueError('Invalid inputs') from e # Example 8 x, y = 5, 2 try: result = divide(x, y) except ValueError: print('Invalid inputs') else: print('Result is %.1f' % result)
UTF-8
Python
false
false
1,955
py
908
item_14.py
479
0.662916
0.640921
0
96
19.364583
74
superstack/nova
8,134,668,105,670
cb9a5e34d061e2a06ce9bb44e175077895145cd5
e97cc0c495fd30d79834053414f4d76a7d015a63
/nova/tests/api/openstack/test_shared_ip_groups.py
c2bd7e45a1244f46408794630820b01ad51ec9be
[ "Apache-2.0" ]
permissive
https://github.com/superstack/nova
152b91f98d7c148d41cf085a1c7cde638f52cee9
6f3f188e4ca9136f293ecf4b9813a7615c7a5929
refs/heads/master
2021-01-19T18:11:36.263062
2011-05-24T23:10:40
2011-05-24T23:10:40
1,328,514
1
1
null
false
2014-03-12T12:24:44
2011-02-04T15:53:24
2014-02-02T12:48:52
2011-05-24T23:15:25
52,361
5
0
0
Python
null
null
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 OpenStack LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import stubout import webob from nova import test from nova.api.openstack import shared_ip_groups from nova.tests.api.openstack import fakes class SharedIpGroupsTest(test.TestCase): def setUp(self): super(SharedIpGroupsTest, self).setUp() self.stubs = stubout.StubOutForTesting() fakes.FakeAuthManager.reset_fake_data() fakes.FakeAuthDatabase.data = {} fakes.stub_out_auth(self.stubs) def tearDown(self): self.stubs.UnsetAll() super(SharedIpGroupsTest, self).tearDown() def test_get_shared_ip_groups(self): req = webob.Request.blank('/v1.0/shared_ip_groups') res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 501) def test_create_shared_ip_group(self): req = webob.Request.blank('/v1.0/shared_ip_groups') req.method = 'POST' res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 501) def test_update_shared_ip_group(self): req = webob.Request.blank('/v1.0/shared_ip_groups/12') req.method = 'PUT' res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 501) def test_delete_shared_ip_group(self): req = webob.Request.blank('/v1.0/shared_ip_groups/12') req.method = 'DELETE' res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 501) def test_deprecated_v11(self): req = webob.Request.blank('/v1.1/shared_ip_groups') res = req.get_response(fakes.wsgi_app()) self.assertEqual(res.status_int, 404)
UTF-8
Python
false
false
2,289
py
57
test_shared_ip_groups.py
54
0.671909
0.653561
0
64
34.765625
78
iamjackg/md2cf
549,755,832,141
17b5908108071b2d83245515d963846aeab2dab4
e1e88cebde89d6e2f3a0b4842f21081e6b1e8f8b
/test_package/unit/test_ignored_files.py
ecdcc13a753ae315a323024417e75c30ec801e24
[ "MIT" ]
permissive
https://github.com/iamjackg/md2cf
2abcb9ae10fb5dff905e6e5f794534e16c8b6331
18c9b1fd186f967b775f87c20c9931fcdface223
refs/heads/master
2023-08-18T02:12:25.868751
2023-08-06T19:00:51
2023-08-06T19:00:51
159,075,371
80
41
MIT
false
2023-08-30T13:04:50
2018-11-25T21:16:06
2023-08-17T17:26:35
2023-08-06T19:01:20
242
74
36
17
Python
false
false
from pathlib import Path from pyfakefs.fake_filesystem import FakeFilesystem from md2cf.ignored_files import GitRepository README = """# Title Lorem ipsum """ GITIGNORE = """README.md """ ROOT_GITIGNORE = """subdir_root_ignore/README.md """ def _create_test_project(fs: FakeFilesystem, root_path: Path): """ Create a test project with: * A root README that should be parsed, * A subdir_included with a readme that should be parsed * A subdir_local_ignore with a README and a .gitignore that ignores that README * A subdir_root_ignore with a README that is ignored in the root .gitignore """ fs.create_dir(root_path / ".git") fs.create_file(root_path / "README.md", contents=README) fs.create_file(root_path / ".gitignore", contents=ROOT_GITIGNORE) fs.create_file(root_path / "subdir_included/README.md", contents=README) fs.create_file(root_path / "subdir_root_ignore/README.md", contents=README) fs.create_file(root_path / "subdir_local_ignore/README.md", contents=README) fs.create_file(root_path / "subdir_local_ignore/.gitignore", contents=GITIGNORE) def test_collect_gitignores(fs): root_path = Path("/repo") _create_test_project(fs, root_path) git_repo = GitRepository(root_path) expected_root_gitignore = root_path / ".gitignore" expected_subdir_gitignore = root_path / "subdir_local_ignore/.gitignore" gitignores = git_repo.collect_gitignores(root_path) assert gitignores == [expected_root_gitignore] gitignores = git_repo.collect_gitignores(root_path / "subdir_included") assert gitignores == [expected_root_gitignore] gitignores = git_repo.collect_gitignores(root_path / "subdir_root_ignore") assert gitignores == [expected_root_gitignore] gitignores = git_repo.collect_gitignores(root_path / "subdir_local_ignore") assert gitignores == [expected_subdir_gitignore, expected_root_gitignore] def test_is_ignored(fs): root_path = Path("/repo") _create_test_project(fs, root_path) git_repo = GitRepository(root_path) assert not git_repo.is_ignored(root_path / "README.md") assert not git_repo.is_ignored(root_path / "subdir_included/README.md") assert git_repo.is_ignored(root_path / "subdir_root_ignore/README.md") assert git_repo.is_ignored(root_path / "subdir_local_ignore/README.md") def test_is_ignored_with_disabled_gitignores(fs): root_path = Path("/repo") _create_test_project(fs, root_path) git_repo = GitRepository(root_path, use_gitignore=False) assert not git_repo.is_ignored(root_path / "README.md") assert not git_repo.is_ignored(root_path / "subdir_included/README.md") assert not git_repo.is_ignored(root_path / "subdir_root_ignore/README.md") assert not git_repo.is_ignored(root_path / "subdir_local_ignore/README.md")
UTF-8
Python
false
false
2,829
py
27
test_ignored_files.py
18
0.709791
0.709438
0
78
35.269231
84
mtnsat/ics-release-dids
15,238,543,993,845
48c35d321279a9ff6c02bac31a0f2e0ca53b45dc
d8031842e4a261983dcbeda7e71a8630cceb5c09
/celery_settings.py
caf52f00e9aa184e714cdafa7018e999099b7bc6
[ "MIT" ]
permissive
https://github.com/mtnsat/ics-release-dids
86a0087c1629cf2e9f267e0424846eba685ef515
6df32716958bacc000005f61a7acd817a961fe70
refs/heads/master
2018-11-24T20:57:17.518793
2018-09-17T19:30:53
2018-09-17T19:30:53
81,139,314
0
1
MIT
false
2018-09-17T19:30:54
2017-02-06T22:15:44
2018-09-04T17:45:08
2018-09-17T19:30:54
41
0
1
0
Python
false
null
import os accept_content = ['json'] broker_url = os.getEnv('BROKER_URL', 'redis://localhost/0') result_backend = os.getEnv('RESULT_BACKEND', 'redis://localhost/0') worker_concurrency = os.getEnv('WORKER_CONCURRENCY', 1)
UTF-8
Python
false
false
222
py
28
celery_settings.py
14
0.711712
0.698198
0
7
30.714286
67
Kaushal54/DRFBharatTherapati
2,147,483,690,285
85552b1b5fdb99d939b9cdb51bf1ffa60972400d
7d3fcbdaa070586fd04f46cafd4a7761f6347862
/firstProject/firstApp/task.py
8a9eca4d50f266af7927bf41a1c2502be2740d01
[]
no_license
https://github.com/Kaushal54/DRFBharatTherapati
a7bab9e25e299cbfba1ee5d91a7315872fb756e7
f9ba4839e35643e1917db52104a3b0b85a9ee533
refs/heads/main
2022-12-26T06:00:01.964385
2020-10-06T21:55:00
2020-10-06T21:55:00
301,862,375
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
def json_response(request,status,status_code,data,message): response = { 'status':status, 'status_code':status_code, 'data':data, 'message':message } return response
UTF-8
Python
false
false
211
py
12
task.py
12
0.592417
0.592417
0
9
22.444444
59
HendwanAbozide/DSP--Task1
12,506,944,794,749
14d4ebc5bfd90139b980998a431c5c13feccfe5f
a326c1731f6095e309253b7c343853b69901d1eb
/Task1.py
5734c239d463a188b38f3b1608dce7c828b1261f
[]
no_license
https://github.com/HendwanAbozide/DSP--Task1
37bf29b585543c320865ea67b1a500278c6faff4
e66ef7b462c933d76a7fa355477025b5c59cacbb
refs/heads/master
2021-01-09T01:33:10.516922
2020-02-21T18:26:29
2020-02-21T18:26:29
242,204,397
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from PyQt5 import QtCore, QtGui, QtWidgets, uic import os, sys import numpy as np import csv from pathlib import Path from QTbegin import Ui_MainWindow import time import numpy as np import pandas as pd class ApplicationWindow(QtWidgets.QMainWindow): def __init__(self): super(ApplicationWindow, self).__init__() self.ui = Ui_MainWindow() self.stop=0 self.ui.setupUi(self) self.setGeometry(600, 300, 400, 200) self.setWindowTitle('Multiple Browse') self.ui.pushButton_5.clicked.connect(self.SingleBrowse) self.timer=QtCore.QTimer(self) self.timer.setInterval(20) self.timer.timeout.connect(self.plotthis) self.whatever=0 # self.ui.pushButton_2.clicked.connect(self.Play) # self.ui.pushButton_4.clicked.connect(self.Pause) # self.PauseGraph = 0 self.ui.pushButton_4.clicked.connect(self.pause) self.ui.pushButton_2.clicked.connect(self.play) self.show() self.x=[] self.y=[] self.xcsv=[] self.ycsv=[] # self.xlsx=[] # self.ylsx=[] def play(self): self.stop = 0 self.timer.start() def pause(self): self.stop = 1 self.timer.stop() def update_plot_data(self): if self.stop ==0: self.play() if self.stop==1: print ("s") self.pause() def plotthis(self): if self.ext == ".txt": if self.stop==0: self.play() self.ui.graphicsView.plot(self.x,self.y, label='loadedfile') QtCore.QCoreApplication.processEvents() else: self.pause() elif self.ext == ".csv": if self.stop==0: self.play() self.ui.graphicsView_2.plot(self.xcsv,self.ycsv, label='loadedfile',pen='r') QtCore.QCoreApplication.processEvents() else: self.pause() # elif self.ext==".xlsx" : # self.ui.graphicsView_3.plot(self.xlsx,self.ylsx,label = 'ya mosahel',pen ='r') def SingleBrowse(self): filePaths = QtWidgets.QFileDialog.getOpenFileNames(self, 'Open File',"~/Desktop/sigViews",'*.txt && *.csv && *.xlsx') for filePath in filePaths: for f in filePath: print('filePath',f, '\n') if f == '*': break self.ext = os.path.splitext(f)[-1].lower() if self.ext == ".txt": print( "is an txt!") # fileHandle = open(f, 'r') with open(f,'r')as csvfile: self.plots=np.genfromtxt(csvfile, delimiter=' ') for row in self.plots: # self.ui.graphicsView.clear() self.x.append(float (row[0])) self.y.append(float (row[1])) self.arraylength=len(self.x) self.plotthis() elif self.ext == ".csv": print ("this is .csv") with open(f,'r')as csvfile: plots=csv.reader(csvfile, delimiter=',') for row in plots: self.ui.graphicsView.clear() self.xcsv.append(float (row[0])) self.ycsv.append(float (row[1])) self.plotthis() # elif self.ext==".xlsx": # self.df =pd.read_excel('emg_healthy.xlsx', sheet_name='emg_healthy') # self.ui.graphicsView_3.plot(self.df['Column1'], self.df['Column2'], pen='r') # QtCore.QCoreApplication.processEvents() # self.plotthis() # self.ui.graphicsView.clear() def main(): app = QtWidgets.QApplication(sys.argv) application = ApplicationWindow() application.show() app.exec_() if __name__ == '__main__': main()
UTF-8
Python
false
false
4,375
py
2
Task1.py
1
0.471086
0.462171
0
140
29.25
125
llooker/looker_deployer
7,395,933,702,139
e251a9ef03970f6c65ca871f2680169a1ba2e8ef
2e46243bef33617c6f83d67ccfab1d1a6367a609
/tests/test_user_attributes.py
5edb6716a3397e4f4534f54b14fd81d71e458a63
[ "Apache-2.0" ]
permissive
https://github.com/llooker/looker_deployer
f8ef521a4ea511c89f5fb2220d2bf63021f8a72b
552a78d45f1979a6d0dcf93a3dc85e9df41b6995
refs/heads/main
2023-08-22T14:02:29.378813
2023-07-06T18:43:53
2023-07-06T18:43:53
232,376,318
13
8
null
null
null
null
null
null
null
null
null
null
null
null
null
from looker_deployer.commands import deploy_user_attributes from looker_sdk import methods40 as methods, models40 as models class mockSettings: base_url = "taco" class mockAuth: settings = mockSettings() def mock_responses(responses, default_response=None): return lambda input: responses[input] \ if input in responses else default_response sdk = methods.Looker40SDK(mockAuth(), "bar", "baz", "bosh", "bizz") source_sdk = methods.Looker40SDK(mockAuth(), "bar", "baz", "bosh", "bizz") target_sdk = methods.Looker40SDK(mockAuth(), "bar", "baz", "bosh", "bizz") def test_get_filtered_user_attributes(mocker): user_attribute_list = [ models.UserAttribute(name="Cheese", id="1", label="Cheese", type="string"), models.UserAttribute(name="Sauce", id="2", label="Cheese", type="string") ] mocker.patch.object(sdk, "all_user_attributes") sdk.all_user_attributes.return_value = user_attribute_list user_attributes = deploy_user_attributes.get_filtered_user_attributes(sdk) assert user_attributes == user_attribute_list def test_get_filtered_user_attributes_filter(mocker): user_attribute_list = [ models.UserAttribute(name="Cheese", id="1", label="Cheese", type="string"), models.UserAttribute(name="Sauce", id="2", label="Cheese", type="string") ] mocker.patch.object(sdk, "all_user_attributes") sdk.all_user_attributes.return_value = user_attribute_list user_attributes = deploy_user_attributes.get_filtered_user_attributes( sdk, "Cheese") assert user_attributes == [user_attribute_list[0]] def test_write_user_attributes_new(mocker): user_attribute_list = [ models.UserAttribute(name="Cheese", id="1", label="Cheese", type="string", is_system=False) ] user_attribute_group_list = [models.UserAttributeGroupValue( id="1", group_id="1", user_attribute_id="1")] group_1 = models.Group(name="Taco", id="1") group_2 = models.Group(name="Taco Supreme", id="2") groups_list = [group_1, group_2] role_1 = models.Role(name="Explorer", id="1") role_list = [role_1] mocker.patch.object(source_sdk, "all_roles") mocker.patch.object(source_sdk, "all_groups") mocker.patch.object(source_sdk, "group") mocker.patch.object(source_sdk, "all_user_attributes") mocker.patch.object(source_sdk, "all_user_attribute_group_values") mocker.patch.object(target_sdk, "all_roles") mocker.patch.object(target_sdk, "all_groups") mocker.patch.object(target_sdk, "all_user_attributes") mocker.patch.object(target_sdk, "create_user_attribute") mocker.patch.object(target_sdk, "set_user_attribute_group_values") source_sdk.all_roles.return_value = role_list target_sdk.all_roles.return_value = role_list source_sdk.all_groups.return_value = groups_list target_sdk.all_groups.return_value = groups_list source_sdk.group.return_value = group_1 source_sdk.all_user_attributes.return_value = user_attribute_list source_sdk.all_user_attribute_group_values.side_effect = mock_responses( { "1": user_attribute_group_list, "2": [] } ) deploy_user_attributes.write_user_attributes(source_sdk, target_sdk) target_sdk.create_user_attribute.assert_called_once_with( models.WriteUserAttribute(name="Cheese", label="Cheese", type="string")) def test_write_user_attributes_update_group_value(mocker): user_attribute_list = [ models.UserAttribute(name="Cheese", id="1", label="Cheese", type="string"), models.UserAttribute(name="Sauce", id="2", label="Cheese", type="string") ] user_attribute_group_list = [models.UserAttributeGroupValue( id="1", group_id="1", user_attribute_id="1")] group_1 = models.Group(name="Taco", id="1") group_2 = models.Group(name="Taco Supreme", id="2") groups_list = [group_1, group_2] role_1 = models.Role(name="Explorer", id="1") role_list = [role_1] mocker.patch.object(source_sdk, "all_roles") mocker.patch.object(source_sdk, "all_groups") mocker.patch.object(source_sdk, "group") mocker.patch.object(source_sdk, "all_user_attributes") mocker.patch.object(source_sdk, "all_user_attribute_group_values") mocker.patch.object(target_sdk, "all_roles") mocker.patch.object(target_sdk, "all_groups") mocker.patch.object(target_sdk, "all_user_attributes") mocker.patch.object(target_sdk, "create_user_attribute") mocker.patch.object(target_sdk, "set_user_attribute_group_values") source_sdk.all_roles.return_value = role_list target_sdk.all_roles.return_value = role_list source_sdk.all_groups.return_value = groups_list target_sdk.all_groups.return_value = groups_list source_sdk.group.return_value = group_1 source_sdk.all_user_attributes.return_value = user_attribute_list source_sdk.all_user_attribute_group_values.side_effect = mock_responses( { "1": user_attribute_group_list, "2": [] } ) target_sdk.create_user_attribute.return_value = user_attribute_list[0] deploy_user_attributes.write_user_attributes(source_sdk, target_sdk) target_sdk.set_user_attribute_group_values.assert_called_once_with( user_attribute_id="1", body=user_attribute_group_list)
UTF-8
Python
false
false
5,329
py
35
test_user_attributes.py
29
0.683055
0.673672
0
133
39.067669
99
Congitron/mapmaker
9,156,870,324,688
36b158b0941c4ed09be21c132dff77e706d7ce8a
bbe17eeaf43cc93c8c5d7e9d6d5e7220344ec952
/misc/backup.py
66d64d4845c24329564c372584b81e3e809e72d8
[]
no_license
https://github.com/Congitron/mapmaker
0f327fb97d1f47470b5f8a0894cf5f1890b0f9a2
2f1c94b75c13dc57f9e979ddf0bd86b817e86dfe
refs/heads/master
2016-09-05T13:39:37.302603
2015-04-01T17:37:39
2015-04-01T17:37:39
33,154,475
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # generated by wxGlade 0.6.3 on Tue Apr 6 17:03:54 2010 import wx import Image import sys # begin wxGlade: extracode # end wxGlade class MyDialog1(wx.Dialog): def __init__(self, *args, **kwds): # begin wxGlade: MyDialog1.__init__ kwds["style"] = wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, *args, **kwds) self.bitmap_4 = wx.StaticBitmap(self, -1, wx.Bitmap("/home/matt/code/Citrus/mapmaker/logo.jpg", wx.BITMAP_TYPE_ANY)) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyDialog1.__set_properties self.SetTitle("Map") self.SetSize((314, 303)) # end wxGlade def __do_layout(self): # begin wxGlade: MyDialog1.__do_layout sizer_4 = wx.BoxSizer(wx.HORIZONTAL) sizer_4.Add(self.bitmap_4, 0, wx.ADJUST_MINSIZE, 0) self.SetSizer(sizer_4) self.Layout() # end wxGlade # end of class MyDialog1 class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.notebook_1 = wx.Notebook(self, -1, style=0) self.notebook_1_pane_1 = wx.Panel(self.notebook_1, -1) # Menu Bar self.frame_1_menubar = wx.MenuBar() self.file = wx.Menu() self.new = wx.MenuItem(self.file, wx.NewId(), "&New", "", wx.ITEM_NORMAL) self.file.AppendItem(self.new) self.open = wx.MenuItem(self.file, wx.NewId(), "&Open", "", wx.ITEM_NORMAL) self.file.AppendItem(self.open) self.save = wx.MenuItem(self.file, wx.NewId(), "&Save", "", wx.ITEM_NORMAL) self.file.AppendItem(self.save) self.file.AppendSeparator() self.exit = wx.MenuItem(self.file, wx.NewId(), "&Exit", "", wx.ITEM_NORMAL) self.file.AppendItem(self.exit) self.frame_1_menubar.Append(self.file, "&File") wxglade_tmp_menu = wx.Menu() self.frame_1_menubar.Append(wxglade_tmp_menu, "&Edit") self.SetMenuBar(self.frame_1_menubar) # Menu Bar end self.button_1 = wx.Button(self.notebook_1_pane_1, -1, "Random") self.button_3 = wx.Button(self.notebook_1_pane_1, -1, "button_3") self.button_4 = wx.Button(self.notebook_1_pane_1, -1, "button_4") self.notebook_1_pane_2 = wx.Panel(self.notebook_1, -1) self.notebook_1_pane_3 = wx.Panel(self.notebook_1, -1) self.notebook_1_pane_4 = wx.Panel(self.notebook_1, -1) self.__set_properties() self.__do_layout() self.Bind(wx.EVT_MENU, self.onNew, self.new) self.Bind(wx.EVT_MENU, self.onOpen, self.open) self.Bind(wx.EVT_MENU, self.onSave, self.save) self.Bind(wx.EVT_MENU, self.OnExit, self.exit) self.Bind(wx.EVT_BUTTON, self.OnBtn1, self.button_1) # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("Citrus Map Maker") self.SetSize((400, 300)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_3 = wx.BoxSizer(wx.HORIZONTAL) sizer_3.Add(self.button_1, 0, wx.ADJUST_MINSIZE, 0) sizer_3.Add(self.button_3, 0, wx.ADJUST_MINSIZE, 0) sizer_3.Add(self.button_4, 0, wx.ADJUST_MINSIZE, 0) self.notebook_1_pane_1.SetSizer(sizer_3) self.notebook_1.AddPage(self.notebook_1_pane_1, "Height Map") self.notebook_1.AddPage(self.notebook_1_pane_2, "Terrain") self.notebook_1.AddPage(self.notebook_1_pane_3, "Biome") self.notebook_1.AddPage(self.notebook_1_pane_4, "Population") sizer_1.Add(self.notebook_1, 1, wx.EXPAND, 0) self.SetSizer(sizer_1) self.Layout() self.SetSize((400, 300)) # end wxGlade def OnBtn2(self, event): # wxGlade: MyFrame.<event_handler> print "Button 2" event.Skip() def OnExit(self, event): # wxGlade: MyFrame.<event_handler> sys.exit() event.Skip() def onNew(self, event): # wxGlade: MyFrame.<event_handler> print "File->New" event.Skip() def onOpen(self, event): # wxGlade: MyFrame.<event_handler> print "File->Open" filename = "" # Use filename as a flag dlg = wx.FileDialog(self, message="Choose a file") if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() dlg.Destroy() if filename: print str(filename) event.Skip() def onSave(self, event): # wxGlade: MyFrame.<event_handler> print "File->Save" event.Skip() def OnBtn1(self, event): # wxGlade: MyFrame.<event_handler> #Button 1: "Random" #Create a random static image to build a heightmap from #self.dialog_1.bitmap_4 = wx.StaticBitmap(self, -1, wx.Bitmap("/home/matt/Pictures/earth.jpg", wx.BITMAP_TYPE_ANY)) event.Skip() # end of class MyFrame if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() app.MainLoop()
UTF-8
Python
false
false
5,345
py
13
backup.py
11
0.595171
0.570653
0
155
33.470968
124
mfefunk/covid_19
12,945,031,451,740
a4013fd3ba41b5d4fda277dcea3211fe1e834239
9488270a786672b912a7e66c422890ff82875d8b
/scrapers/scrape_ge_common.py
1502992e28cfd29ca6aa1b711e64de9b2adc38c1
[ "CC-BY-4.0" ]
permissive
https://github.com/mfefunk/covid_19
bf9dedf55e25de445faddd6af4ee1ef9ebf59345
c82c0f840628e1d5d0187c0b0a11d0b911c494a6
refs/heads/master
2023-02-12T16:02:55.930074
2021-01-15T16:02:24
2021-01-15T16:02:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import time from bs4 import BeautifulSoup import scrape_common as sc def get_latest_ge_weekly_pdf_url(): return get_ge_weekly_pdf_urls()[0] def get_ge_weekly_pdf_urls(): d = sc.download('https://www.ge.ch/document/covid-19-bilan-epidemiologique-hebdomadaire', silent=True) soup = BeautifulSoup(d, 'html.parser') links = soup.find_all('a', title=re.compile(r"\.pdf$")) result = [] for link in links: pdf_url = link.get('href') assert pdf_url, "pdf URL is empty" if not pdf_url.startswith('http'): pdf_url = f'https://www.ge.ch{pdf_url}' if pdf_url not in result: result.append(pdf_url) return result def get_link_from_element(driver, element_id): # the xls download links do not appear immediately for some reason # add some delay to get it. for _ in range(10): elem = driver.find_element_by_id(element_id) url = elem.get_attribute('href') if url != '': return url time.sleep(1) return ''
UTF-8
Python
false
false
1,096
py
41
scrape_ge_common.py
4
0.616788
0.608577
0
38
27.842105
106
kaveeshaile/ITP-Project-python-
14,757,507,660,220
34e3edcb0ab24017ab33a725e30436fa0726a829
414b2d87d7b96c70641306e41dbce9cb079330b8
/Voltage/payment/urls.py
e294c0ab89645ce8032b92d7fc1616e605848b08
[]
no_license
https://github.com/kaveeshaile/ITP-Project-python-
02e60a14e896aee911b5901db4ce0eec0375bd75
0c7d033acb029f600a6c9a2c71d5c01fb1521f96
refs/heads/master
2023-01-28T23:42:28.273479
2020-12-11T05:46:19
2020-12-11T05:46:19
320,478,968
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.urls import path from.import views urlpatterns = [ path('',views.payment,name = 'payment') ]
UTF-8
Python
false
false
117
py
93
urls.py
59
0.65812
0.65812
0
10
10.8
43
javi-gv94/benchmarking-data-model-v0.4
15,178,414,426,717
971e5ca37f9cc20dc33d185f62ba5ee5c6fa5f03
5de3d084e550eade95e0b72e89167014e02305c0
/TCGA/get_assessment_schemas.py
7707a75328fb7afd359de0e6acdc6e96a17f8175
[]
no_license
https://github.com/javi-gv94/benchmarking-data-model-v0.4
5e6717bad2178ac28bffe7a71d7542f7551bb83e
c80009f038504bbefb81818f2016033d5043dfbd
refs/heads/master
2018-11-08T11:44:26.465502
2018-08-23T10:51:28
2018-08-23T10:51:28
145,582,814
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import os import pandas import math from datauri import DataURI import json cancer_types = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "DLBC", "ESCA"] data = pandas.read_csv("../cancer_names.tsv", sep="\t", comment="#", header=None) long_names = {} for index, row in data.iterrows(): long_names[row[0]] = row[1] def compute_metrics(input_dir, gold_standard, cancer_type): participants_datasets = {} for participant in os.listdir(input_dir + "participants/"): if os.path.isfile(input_dir + "participants/" + participant + "/" + cancer_type + ".txt") == False: continue data = pandas.read_csv(input_dir + "participants/" + participant + "/" + cancer_type + ".txt", sep='\t', comment="#", header=0) #filter data by q-value if participant == "MutSig2CV": filtered_data = data.loc[data['qvalue'] <= 0.1] predicted_genes = filtered_data.iloc[:, 0].values elif participant == "ActiveDriver": filtered_data = data.loc[data['qvalue'] <= 0.0001] predicted_genes = filtered_data.iloc[:, 0].values elif participant == "MuSiC": filtered_data = data.loc[data['pvalue'] <= math.exp(-8)] filtered_data = filtered_data[filtered_data['info'] == "FILTER=PASS"] predicted_genes = filtered_data.iloc[:, 0].values else: filtered_data = data.loc[data['qvalue'] <= 0.05] predicted_genes = filtered_data.iloc[:, 0].values # predicted_genes = data.iloc[:, 0].values # TRUE POSITIVE RATE overlapping_genes = set(predicted_genes).intersection(gold_standard) TPR = len(overlapping_genes)/len(gold_standard) #ACCURACY/ PRECISION if len(predicted_genes) == 0: acc = 0 else: acc = len(overlapping_genes) / len(predicted_genes) participants_datasets[participant] = [TPR, acc] return participants_datasets for cancer in cancer_types: data = pandas.read_csv("/home/jgarrayo/PycharmProjects/TCGA_benchmark/input/"+ cancer + ".txt", comment="#", header=None) gold_standard = data.iloc[:, 0].values participants_datasets = compute_metrics("/home/jgarrayo/PycharmProjects/TCGA_benchmark/input/", gold_standard, cancer) for participant in os.listdir("/home/jgarrayo/PycharmProjects/TCGA_benchmark/input/participants"): #get data-uri value of the 2 metrics metric1 = DataURI.make('application/json', charset='us-ascii', base64=True, data=json.dumps(participants_datasets[participant][0])) metric2 = DataURI.make('application/json', charset='us-ascii', base64=True, data=json.dumps(participants_datasets[participant][1])) #print metrics1 assesment file info = { "_id":"TCGA:2018-04-05_" + cancer + "_A_TPR_" + participant, "description":"Assessment dataset for applying Metric 'True Positive Rate' to " + participant + " predictions in " + long_names[cancer], "dates":{ "creation":"2018-04-05T00:00:00Z", "modification":"2018-04-05T14:00:00Z" }, "type":"assessment", "datalink":{ "uri":metric1, "attrs":"inline", "status":"ok", "validation_date":"2018-04-05T00:00:00Z" }, "depends_on":{ "tool_id":"TCGA:" + participant, "metrics_id":"TCGA:TPR", "rel_dataset_ids":[ { "dataset_id":"TCGA:2018-04-05_" + cancer + "_I", "role":"input" }, { "dataset_id":"TCGA:2018-04-05_" + cancer + "_M", "role":"metrics_reference" } ] }, "_schema":"https://www.elixir-europe.org/excelerate/WP2/json-schemas/0.4/Dataset", "community_id":"TCGA", "version":"1", "name":"Assesment of Metric TPR in " + participant, "dataset_contact_ids":[ "Matthew.Bailey", "Eduard.Porta", "Collin.Tokheim" ] } # print info filename = "Dataset_assessment_" + cancer + "_" + participant + "_TPR.json" # print filename with open("out/" + filename, 'w') as f: json.dump(info, f, sort_keys=True, indent=4, separators=(',', ': ')) # print metrics2 assessment file info = { "_id": "TCGA:2018-04-05_" + cancer + "_A_precision_" + participant, "description": "Assessment dataset for applying Metric 'Positive Predictive Value' to " + participant + " predictions in " + long_names[cancer], "dates": { "creation": "2018-04-05T00:00:00Z", "modification": "2018-04-05T14:00:00Z" }, "type": "assessment", "datalink": { "uri": metric2, "attrs": "inline", "status": "ok", "validation_date": "2018-04-05T00:00:00Z" }, "depends_on": { "tool_id": "TCGA:" + participant, "metrics_id": "TCGA:PPV", "rel_dataset_ids": [ { "dataset_id": "TCGA:2018-04-05_" + cancer + "_I", }, { "dataset_id": "TCGA:2018-04-05_" + cancer + "_M", } ] }, "_schema": "https://www.elixir-europe.org/excelerate/WP2/json-schemas/0.4/Dataset", "community_id": "TCGA", "version": "1", "name": "Assesment of Metric precision-PPV in " + participant, "dataset_contact_ids": [ "Matthew.Bailey", "Eduard.Porta", "Collin.Tokheim" ] } # print info filename = "Dataset_assessment_" + cancer + "_" + participant + "_precision.json" # print filename with open("out/" + filename, 'w') as f: json.dump(info, f, sort_keys=True, indent=4, separators=(',', ': '))
UTF-8
Python
false
false
6,342
py
6
get_assessment_schemas.py
5
0.512457
0.48439
0
179
34.430168
147
Gurmie12/MedHacks2020
1,219,770,751,362
e803ec263c0c62ad182804e4f96d3647b7fefeb0
0706745ebd68f4e754183e49c893fafda649b8d9
/MedHacks/backend/predictions/admin.py
2a3d4e96f34eb1d673bd44c7f2456cc2e9e7f151
[]
no_license
https://github.com/Gurmie12/MedHacks2020
c26ef62c18fece78bf173d97954edd45805b0cab
a9292a9a64726544002a60c1da95f57d5984f451
refs/heads/master
2022-12-14T01:57:29.639314
2020-09-16T05:01:09
2020-09-16T05:01:09
293,169,489
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from django.contrib import admin from .models import Patient, Prediction # Register your models here. admin.register(Patient) admin.register(Prediction)
UTF-8
Python
false
false
153
py
22
admin.py
14
0.823529
0.823529
0
6
24.666667
39
cms-sw/cmssw-cfipython
7,627,861,953,407
38934a6afda71409b11d2eef6b44f935014a96be
3996539eae965e8e3cf9bd194123989741825525
/GeneratorInterface/GenFilters/MCParticleModuloFilter_cfi.py
2401959d0722031d0b423e930b5bc6e5cdd09779
[]
no_license
https://github.com/cms-sw/cmssw-cfipython
01990ea8fcb97a57f0b0cc44a8bf5cde59af2d98
25ee4c810103c4a507ca1b949109399a23a524c5
refs/heads/CMSSW_11_2_X
2023-09-01T16:56:00.658845
2022-06-20T22:49:19
2022-06-20T22:49:19
136,184,115
1
0
null
false
2022-10-19T14:04:01
2018-06-05T13:47:28
2022-06-20T22:49:26
2022-10-19T13:48:13
1,145
1
1
0
Python
false
false
import FWCore.ParameterSet.Config as cms MCParticleModuloFilter = cms.EDFilter('MCParticleModuloFilter', moduleLabel = cms.InputTag('generator', 'unsmeared'), particleIDs = cms.vint32(), multipleOf = cms.uint32(1), absID = cms.bool(False), min = cms.uint32(0), status = cms.int32(0), mightGet = cms.optional.untracked.vstring )
UTF-8
Python
false
false
343
py
838
MCParticleModuloFilter_cfi.py
838
0.728863
0.696793
0
11
30.181818
63
humantom88/geekbrains-data-scraping
7,395,933,723,012
3f8f64ef9c19722d26e08e7248a7eb13c76d779d
d2a9ff16cdbcc97a65ae01cdcd79be4d560ef7c9
/homework8/instaparser/instaparser/spiders/instagram.py
cc97697ad18bb76178187e23552801c04de8b51b
[]
no_license
https://github.com/humantom88/geekbrains-data-scraping
af3d7231f83ceb86992f01956b9d2184aa560b28
b02d68788be8a4d500b5433ec6a89f5583864061
refs/heads/master
2022-11-06T10:14:25.515797
2020-06-28T14:08:54
2020-06-28T14:08:54
268,997,676
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- import scrapy from scrapy.http import HtmlResponse from instaparser.items import InstaparserItem import re import json from urllib.parse import urlencode from copy import deepcopy class InstagramSpider(scrapy.Spider): # атрибуты класса name = 'instagram' allowed_domains = ['instagram.com'] start_urls = ['https://instagram.com/'] insta_login = 'stepan_scientist' insta_pwd = '#PWD_INSTAGRAM_BROWSER:' inst_login_link = 'https://www.instagram.com/accounts/login/ajax/' usernames_to_parse = ['humantom88', 'slava_popova'] # Пользователь, у которого собираем посты. Можно указать список graphql_url = 'https://www.instagram.com/graphql/query/?' posts_hash = 'eddbde960fed6bde675388aac39a3657' # hash для получения данных по постах с главной страницы user_followers_hash = 'c76146de99bb02f6415203be841dd25a' user_subscriptions_hash = 'd04b0a864b4b54837c0d870b0e77e076' def parse(self, response: HtmlResponse): # Первый запрос на стартовую страницу csrf_token = self.fetch_csrf_token(response.text) # csrf token забираем из html yield scrapy.FormRequest( # заполняем форму для авторизации self.inst_login_link, method='POST', callback=self.login_user, formdata={ 'username': self.insta_login, 'enc_password': self.insta_pwd }, headers={ 'X-CSRFToken': csrf_token } ) def login_user(self, response: HtmlResponse): j_body = json.loads(response.text) if j_body['authenticated']: # Проверяем ответ после авторизации for username in self.usernames_to_parse: yield response.follow( # Переходим на желаемую страницу пользователя. Сделать цикл для кол-ва пользователей больше двух f'/{username}', callback=self.parse_userdata, cb_kwargs={'username': username} ) def parse_userdata(self, response: HtmlResponse, username): user_id = self.fetch_user_id(response.text, username) # Получаем id пользователя variables = { "id": user_id, "include_reel": True, "fetch_mutual": False, "first": 50 } # Followers user_followers_url = f'{self.graphql_url}query_hash={self.user_followers_hash}&{urlencode(variables)}' yield response.follow( user_followers_url, callback=self.parse_user_info, cb_kwargs={ 'username': username, 'user_id': user_id, 'variables': variables, 'followed_by': True } ) # Subscriptions user_subscriptions_url = f'{self.graphql_url}query_hash={self.user_subscriptions_hash}&{urlencode(variables)}' yield response.follow( user_subscriptions_url, callback=self.parse_user_info, cb_kwargs={ 'username': username, 'user_id': user_id, 'variables': variables } ) def parse_user_info(self, response: HtmlResponse, username, user_id, variables, followed_by=False): data = json.loads(response.text) page_info = data.get('data').get('user').get('edge_followed_by' if followed_by else 'edge_follow') if page_info is None: return page_info = page_info.get('page_info') if page_info is not None else None if page_info.get('has_next_page'): variables['after'] = page_info['end_cursor'] user_followers_url = f'{self.graphql_url}query_hash={self.user_followers_hash}&{urlencode(variables)}' yield response.follow( user_followers_url, callback=self.parse_user_info, cb_kwargs={ 'username': username, 'user_id': user_id, 'variables': variables } ) users = data.get('data').get('user').get('edge_followed_by' if followed_by else 'edge_follow').get('edges') # Сами подписчики for user in users: # Перебираем подписчиков, собираем данные item = InstaparserItem( user_id=user.get('node').get('id'), user_name = user.get('node').get('username'), full_name = user.get('node').get('full_name'), photo = user.get('node').get('profile_pic_url'), is_followed_by = user_id if followed_by else None, follows = None if followed_by else user_id ) yield item # Получаем токен для авторизации def fetch_csrf_token(self, text): matched = re.search('\"csrf_token\":\"\\w+\"', text).group() return matched.split(':').pop().replace(r'"', '') # Получаем id желаемого пользователя def fetch_user_id(self, text, username): matched = re.search( '{\"id\":\"\\d+\",\"username\":\"%s\"}' % username, text ).group() return json.loads(matched).get('id')
UTF-8
Python
false
false
5,620
py
25
instagram.py
22
0.575379
0.563088
0
139
36.460432
134
onesuper/Hazard
5,866,925,350,933
d740fe1d19a84765696010d70eb15bfd56d45b70
9c25fcef2b0d0eedadc818d8a8bc8f6098d13b49
/multicycle/test.py
8f8c9885dc4bdd61538d7b81a97b7752e31a103e
[]
no_license
https://github.com/onesuper/Hazard
655b5147991fa5996fb8898749e128fb578dec1c
d322217c68fa70f5581987c3ba8024f0c720eb60
refs/heads/master
2021-01-13T16:10:11.928782
2013-04-27T14:44:42
2013-04-27T14:44:42
8,702,599
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from exe import Exe from datapath import Datapath from lazy import addi, add, sub, lw, sw, and_, or_, beq, slt, j exe = Exe() exe.data_section = [77, 99] # by word exe.text_section = [addi('$t0', '$zero', 15), #0x00400000 addi('$t1', '$zero', 12), add('$t2', '$t0', '$t1'), #27 sub('$t3', '$t0', '$t1'), #3 lw('$t4', '$gp', 0), lw('$t5', '$gp', 4), sw('$t2', '$gp', 8), #27 in the data and_('$t6', '$t1', '$t2'), or_('$t7', '$t1', '$t2'), #beq('$s0', '$s1', -2), slt('$s1', '$t2', '$t3'), slt('$s1', '$t3', '$t2'), j(0x100000), ] d = Datapath() d.memory.load(exe) d.step(Debug=('fsm', 'pc', 'IR', 'cycle')) d.step(Debug=('fsm', 'rs', 'rt', 'pc', 'cycle', 'ALUOut')) d.step(Debug=('fsm', 'pc', 'cycle')) d.step(Debug=('fsm', 'pc', 'cycle')) d.step(Debug=('fsm', 'pc', 'cycle')) print d.memory.show_data()
UTF-8
Python
false
false
1,091
py
24
test.py
22
0.384968
0.331806
0
36
29.25
65
Chubek/wodeveryday.com
1,468,878,840,503
29813335b66c06a52cc2358fee8d0252353e074c
16765dcc1d455167b0ceb6ec0f46b66a71478d0d
/back/core/migrations/0004_remove_gymdetails_photos.py
ba9700190e8b8e4d1aa010ed1ba9f7279073016a
[]
no_license
https://github.com/Chubek/wodeveryday.com
0ba37eb023ec17a84208b9506ec0ce597b93144f
b318a59e7d52b97e7a362930c790394ea5bf045b
refs/heads/master
2022-11-23T12:45:23.489978
2020-07-23T20:15:12
2020-07-23T20:15:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.0.4 on 2020-07-07 01:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0003_gymdetails_photos'), ] operations = [ migrations.RemoveField( model_name='gymdetails', name='photos', ), ]
UTF-8
Python
false
false
328
py
57
0004_remove_gymdetails_photos.py
26
0.582317
0.52439
0
17
18.294118
47
codeWithDiki/marketplace
6,365,141,551,748
afe4ca6afd7db62f1e4922e4dd50a823ddd36b8f
4088fc77a6c78f3fc6f3bec521e404b2a351a6de
/products/migrations/0011_auto_20210628_0054.py
8b5a93bc46e7007a6f52a792c86bf5cd641cfedb
[]
no_license
https://github.com/codeWithDiki/marketplace
268fc93c38c7544492152303e6c830e29e256b89
68fef492f30d1cbe863089ee44d7b94abf5742ed
refs/heads/main
2023-06-25T18:34:22.755274
2021-07-03T20:37:39
2021-07-03T20:37:39
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# Generated by Django 3.2.3 on 2021-06-27 17:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0010_productimages'), ] operations = [ migrations.AlterField( model_name='products', name='product_media', field=models.JSONField(blank=True, null=True), ), migrations.DeleteModel( name='ProductImages', ), ]
UTF-8
Python
false
false
476
py
27
0011_auto_20210628_0054.py
20
0.579832
0.539916
0
21
21.666667
58
miyuchina/compiler
10,608,569,261,299
e5612372f84cda79aaa311f94a6884dc11b88950
e259caa04b3c54c49948c90ceb7fcb05a4fc5029
/gone/parser.py
0a62ce53b69ea415d1e53c7e66280e8519458b9e
[]
no_license
https://github.com/miyuchina/compiler
dcedd1fd8382de6469ea49e1238a968119ec81b3
50e80555fb9786f1b2e5a4ea9db9b653b5fd89b5
refs/heads/master
2021-09-04T22:42:44.052134
2018-01-22T20:41:22
2018-01-22T20:42:17
117,863,789
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# gone/parser.py ''' Project 2: Write a parser ========================== In this project, you write the basic shell of a parser for Gone. A formal BNF of the language follows. Your task is to write parsing rules and build the AST for this grammar using SLY. The following grammar is partial. More features get added in later projects. program : statements | empty statements : statements statement | statement statement : const_declaration | var_declaration | assign_statement | print_statement const_declaration : CONST ID = expression ; var_declaration : VAR ID datatype ; | VAR ID datatype = expression ; assign_statement : location = expression ; print_statement : PRINT expression ; expression : + expression | - expression | expression + expression | expression - expression | expression * expression | expression / expression | ( expression ) | location | literal literal : INTEGER | FLOAT | CHAR location : ID ; datatype : ID ; empty : To do the project, follow the instructions contained below. ''' # ---------------------------------------------------------------------- # parsers are defined using SLY. You inherit from the Parser class # # See http://sly.readthedocs.io/en/latest/ # ---------------------------------------------------------------------- from sly import Parser # ---------------------------------------------------------------------- # The following import loads a function error(lineno,msg) that should be # used to report all error messages issued by your parser. Unit tests and # other features of the compiler will rely on this function. See the # file errors.py for more documentation about the error handling mechanism. from .errors import error # ---------------------------------------------------------------------- # Import the lexer class. It's token list is needed to validate and # build the parser object. from .tokenizer import GoneLexer # ---------------------------------------------------------------------- # Get the AST nodes. # Read instructions in ast.py from .ast import * class GoneParser(Parser): # Same token set as defined in the lexer tokens = GoneLexer.tokens # ---------------------------------------------------------------------- # Operator precedence table. Operators must follow the same # precedence rules as in Python. Instructions to be given in the project. precedence = ( ('left', 'OR'), ('left', 'AND'), ('nonassoc', 'LE', 'GE', 'LT', 'GT', 'EQ', 'NE'), ('left', 'PLUS', 'MINUS'), ('left', 'TIMES', 'DIVIDE'), ('right', 'NOT'), ) # ---------------------------------------------------------------------- # YOUR TASK. Translate the BNF in the string below into a collection # of parser functions. For example, a rule such as : # # program : statements # # Gets turned into a Python method like this: # # @_('statements') # def program(self, p): # return Program(p.statements) # # For symbols such as '(' or '+', you'll need to replace with the name # of the corresponding token such as LPAREN or PLUS. # # In the body of each rule, create an appropriate AST node and return it # as shown above. # # For the purposes of lineno number tracking, you should assign a line number # to each AST node as appropriate. To do this, I suggest pulling the # line number off of any nearby terminal symbol. For example: # # @_('PRINT expr SEMI') # def print_statement(self, p): # return PrintStatement(p.expr, lineno=p.lineno) # # STARTING OUT # ============ # The following grammar rules should give you an idea of how to start. # Try running this file on the input Tests/parsetest0.g # # Afterwards, add features by looking at the code in Tests/parsetest1-6.g @_('statements', 'empty') def block(self, p): return p[0] @_('statements statement') def statements(self, p): p.statements.append(p.statement) return p.statements @_('statement') def statements(self, p): return [p.statement] @_('assignment_statement SEMI', 'const_statement SEMI', 'var_statement SEMI', 'if_statement', 'while_statement', 'for_statement', 'func_statement', 'break_statement', 'continue_statement', 'return_statement', 'print_statement SEMI') def statement(self, p): return p[0] @_('location AUG_PLUS expression', 'location AUG_MINUS expression', 'location AUG_TIMES expression', 'location AUG_DIVIDE expression') def assignment_statement(self, p): expr = BinOp(p[1][0], ReadLocation(p.location, lineno=p.lineno), p.expression) return Assignment(p.location, expr, lineno=p.lineno) @_('location INCR', 'location DECR',) def assignment_statement(self, p): expr = BinOp(p[1][0], ReadLocation(p.location, lineno=p.lineno), IntegerLiteral(1, lineno=p.lineno)) return Assignment(p.location, expr, lineno=p.lineno) @_('location ASSIGN expression') def assignment_statement(self, p): return Assignment(p.location, p.expression, lineno=p.lineno) @_('CONST location ASSIGN expression') def const_statement(self, p): return ConstDeclaration(p.location, p.expression, lineno=p.lineno) @_('VAR location datatype ASSIGN expression') def var_statement(self, p): return VarDeclaration(p.location, p.datatype, p.expression, lineno=p.lineno) @_('VAR location datatype') def var_statement(self, p): return VarDeclaration(p.location, p.datatype, None, lineno=p.lineno) @_('PRINT expression') def print_statement(self, p): return PrintStatement(p.expression, lineno=p.lineno) @_('ID') def datatype(self, p): return SimpleType(p.ID, lineno=p.lineno) @_('expression PLUS expression', 'expression MINUS expression', 'expression TIMES expression', 'expression DIVIDE expression') def expression(self, p): return BinOp(p[1], p.expression0, p.expression1, lineno=p.lineno) @_('PLUS expression', 'MINUS expression') def expression(self, p): return UnaryOp(p[0], p.expression, lineno=p.lineno) @_('LPAREN expression RPAREN') def expression(self, p): return p.expression @_('expression LE expression', 'expression GE expression', 'expression LT expression', 'expression GT expression', 'expression EQ expression', 'expression NE expression', 'expression AND expression', 'expression OR expression') def expression(self, p): return BinOp(p[1], p.expression0, p.expression1, lineno=p.lineno) @_('NOT expression') def expression(self, p): return UnaryOp(p.NOT, p.expression, lineno=p.lineno) @_('function_call') def expression(self, p): return p.function_call @_('location') def expression(self, p): return ReadLocation(p.location, lineno=p.location.lineno) @_('literal') def expression(self, p): return p.literal @_('IF expression LCBRACE block RCBRACE ELSE LCBRACE block RCBRACE') def if_statement(self, p): return IfStatement(p.expression, p.block0, p.block1, lineno=p.lineno) @_('IF expression LCBRACE block RCBRACE') def if_statement(self, p): return IfStatement(p.expression, p.block, [], lineno=p.lineno) @_('WHILE expression LCBRACE block RCBRACE') def while_statement(self, p): return WhileStatement(p.expression, p.block, lineno=p.lineno) @_('FOR LPAREN statement expression SEMI statement RPAREN LCBRACE block RCBRACE') def for_statement(self, p): return ForStatement(p.statement0, p.expression, p.statement1, p.block, lineno=p.lineno) @_('FOR statement expression SEMI statement LCBRACE block RCBRACE') def for_statement(self, p): return ForStatement(p.statement0, p.expression, p.statement1, p.block, lineno=p.lineno) # functions =============================================================== @_('FUNC ID LPAREN arguments RPAREN datatype LCBRACE block RCBRACE') def func_statement(self, p): return FuncDeclaration(p.ID, p.arguments, p.datatype, p.block, lineno=p.lineno) @_('BREAK SEMI') def break_statement(self, p): return BreakStatement(p.BREAK, lineno=p.lineno) @_('CONTINUE SEMI') def continue_statement(self, p): return ContinueStatement(p.CONTINUE, lineno=p.lineno) @_('RETURN expression SEMI') def return_statement(self, p): return ReturnStatement(p.expression, lineno=p.lineno) @_('RETURN SEMI') def return_statement(self, p): return ReturnStatement(None, lineno=p.lineno) @_('arguments COMMA argument') def arguments(self, p): p.arguments.append(p.argument) return p.arguments @_('argument') def arguments(self, p): return [p.argument] @_('empty') def arguments(self, p): return [] @_('ID datatype') def argument(self, p): return FuncArgument(p.ID, p.datatype, lineno=p.lineno) @_('location LPAREN call_arguments RPAREN') def function_call(self, p): return FunctionCall(p.location, p.call_arguments, lineno=p.lineno) @_('call_arguments COMMA expression') def call_arguments(self, p): p.call_arguments.append(p.expression) return p.call_arguments @_('expression') def call_arguments(self, p): return [p.expression] @_('empty') def call_arguments(self, p): return [] # ========================================================================= @_('ID') def location(self, p): return SimpleLocation(p.ID, lineno=p.lineno) @_('INTEGER') def literal(self, p): return IntegerLiteral(int(p.INTEGER), lineno=p.lineno) @_('FLOAT') def literal(self, p): return FloatLiteral(float(p.FLOAT), lineno=p.lineno) @_('CHAR') def literal(self, p): return CharLiteral(eval(p.CHAR), lineno=p.lineno) @_('TRUE', 'FALSE') def literal(self, p): return BoolLiteral(eval(p[0].title()), lineno=p.lineno) @_('') def empty(self, p): return [] # ---------------------------------------------------------------------- # DO NOT MODIFY # # catch-all error handling. The following function gets called on any # bad input. p is the offending token or None if end-of-file (EOF). def error(self, p): if p: error(p.lineno, "Syntax error in input at token '%s'" % p.value) else: error('EOF','Syntax error. No more input.') # ---------------------------------------------------------------------- # DO NOT MODIFY ANYTHING BELOW HERE # ---------------------------------------------------------------------- def parse(source): ''' Parse source code into an AST. Return the top of the AST tree. ''' lexer = GoneLexer() parser = GoneParser() ast = parser.parse(lexer.tokenize(source)) return ast def main(): ''' Main program. Used for testing. ''' import sys if len(sys.argv) != 2: sys.stderr.write('Usage: python3 -m gone.parser filename\n') raise SystemExit(1) # Parse and create the AST ast = parse(open(sys.argv[1]).read()) # Output the resulting parse tree structure for depth, node in flatten(ast): print('%s: %s%s' % (getattr(node, 'lineno', None), ' '*(4*depth), node)) if __name__ == '__main__': main()
UTF-8
Python
false
false
11,949
py
14
parser.py
9
0.578542
0.576031
0
380
30.444737
108
MariaAfanaseva/messenger_kivy
18,245,021,099,186
b08f08cb29169464aa8af5126df54b1ba6da7f9f
d686c26b7a1647fb55a7ca446688354fb1c48b4d
/client/gui_kivy/create_diagram.py
1c67f380a78a0fceca39e01abb6ac70b623dd4cc
[]
no_license
https://github.com/MariaAfanaseva/messenger_kivy
8f6a52ae008a2e290c6227f51f4cf4ac30c691e1
1978f31d702e5ffc004bbf7ad6b44eb59dd42fa3
refs/heads/master
2021-07-13T03:33:00.348852
2021-02-17T10:03:25
2021-02-17T10:03:25
236,340,649
0
0
null
false
2021-01-23T19:12:38
2020-01-26T16:32:54
2020-01-26T16:32:57
2021-01-23T19:12:38
277
0
0
0
null
false
false
from matplotlib import pyplot import numpy from common.variables import get_path_diagram class CreateDiagram: def __init__(self, database): self.database = database def diagram_all_messages(self): labels = [] in_direction = [] out_direction = [] info_lst = self.database.get_col_messages() for i, data in enumerate(info_lst): if i % 2 == 0: labels.append(data[2]) in_direction.append(data[0]) else: out_direction.append(data[0]) x = numpy.arange(len(labels)) width = 0.35 fig, ax = pyplot.subplots() rects1 = ax.bar(x - width / 2, in_direction, width, label='Incoming message') rects2 = ax.bar(x + width / 2, out_direction, width, label='Outgoing message') ax.set_ylabel('Count') ax.set_title('All messages') ax.set_xticks(x) ax.set_xticklabels(labels) ax.legend() def autolabel(rects): """Attach a text label above each bar in *rects*, displaying its height.""" for rect in rects: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(rects1) autolabel(rects2) fig.tight_layout() fig.savefig(get_path_diagram('all_messages.jpg'))
UTF-8
Python
false
false
1,618
py
59
create_diagram.py
46
0.529666
0.518541
0
48
32.708333
87
sanjaradylov/moleculegen-ml
7,799,660,614,413
d951c111262f9a8b1c4f8e1cae9260ff63fcb0f6
ae2d5b98fdb0604b11dd258a267185af572bacda
/scripts/process_stage1_data.py
66c39592082ca0275fa5534267c7e82d80de332b
[ "BSD-3-Clause" ]
permissive
https://github.com/sanjaradylov/moleculegen-ml
01de1047812d529fc06034e81fc10cdd296fc232
ecbc3d0e436f0c35ee17c4eac1b585f28bf6a90c
refs/heads/master
2022-05-29T04:46:25.726069
2022-05-23T06:23:39
2022-05-23T06:23:39
227,586,884
4
2
BSD-3-Clause
false
2022-05-23T05:51:13
2019-12-12T11:04:58
2022-02-08T22:01:20
2022-05-23T05:51:12
478
3
2
2
Python
false
false
#!/usr/bin/env python3 """ Load, post-process, and save SMILES strings for Stage 1. """ import argparse import datetime import functools import os import sqlite3 from typing import Callable, Coroutine, Generator, TextIO, Union from rdkit.Chem import MolFromSmiles, MolToSmiles from rdkit.RDLogger import DisableLog # Some useful constants to define file names. DATE = datetime.datetime.now().strftime('%m_%d_%H_%M') DIRECTORY = os.path.dirname(os.path.abspath(__file__)) DATA_DIRECTORY = os.path.join(os.path.dirname(DIRECTORY), 'data') OUT_FILENAME = os.path.join(DATA_DIRECTORY, 'sets', f'stage1__{DATE}.csv') SQL_FILENAME = os.path.join(DATA_DIRECTORY, 'queries', 'stage1_smiles.sql') def main(): """The main function: load SMILES data from a database, process the data using filters (length restriction, canonical SMILES validation), and save resulting SMILES to an output file. """ options = process_options() pipe = consume_valid_smiles(options.output_f) pipe = filter_valid_length( minimum=options.minimum_length, maximum=options.maximum_length, receiver=pipe, ) pipe = filter_valid_structure(receiver=pipe) produce_query_results( query_filename=options.sql_f, db_filename=options.database_f, receiver=pipe, ) pipe.close() def produce_query_results( query_filename: Union[str, TextIO], db_filename: Union[str, TextIO] = os.environ.get('DB_FILENAME'), *, receiver: Coroutine, ): """Fetch Stage1 data from `db_filename` using query from `query_filename`. Parameters ---------- receiver : callable Coroutine. query_filename : str or file-like Path to SQL file with query. db_filename : str, file-like, default $DB_FILENAME Path to database. Raises ------ FileNotFoundError If specified file paths do not exist. """ if db_filename is None or not os.path.exists(db_filename): raise FileNotFoundError('database does not exist.') if not os.path.exists(query_filename): raise FileNotFoundError('query file does not exist.') with sqlite3.connect(db_filename) as connection: cursor = connection.cursor() with open(query_filename) as query_fh: query = query_fh.read() cursor.execute(query) for smiles, in cursor.fetchall(): receiver.send(smiles) def coroutine(function: Callable) -> Callable: """Decorator that accepts a coroutine and explicitly calls `next` on it to commence execution. Parameters ---------- function : callable Coroutine. Returns ------- wrapped_function : callable """ @functools.wraps(function) def wrapper(*args, **kwargs) -> Generator: generator = function(*args, **kwargs) next(generator) return generator return wrapper @coroutine def filter_valid_length( minimum: int = 15, maximum: int = 100, *, receiver: Coroutine, ) -> Coroutine: """Send only SMILES with length >= `minimum` and <= `maximum`. Parameters ---------- receiver : coroutine Receiver coroutine (either filter or consumer). minimum : int, default 15 Minimum length. maximum : int, default 100 Maximum length. """ try: while True: smiles = (yield) if minimum <= len(smiles) <= maximum: receiver.send(smiles) except GeneratorExit: receiver.close() @coroutine def filter_valid_structure( *, receiver: Coroutine, ) -> Coroutine: """Send only valid and canonical SMILES. Parameters ---------- receiver : coroutine Receiver coroutine (either filter or consumer). """ try: while True: smiles = (yield) molecule = MolFromSmiles(smiles) if molecule is not None: receiver.send(MolToSmiles(molecule)) except GeneratorExit: receiver.close() @coroutine def consume_valid_smiles(out_filename: Union[TextIO, str]) -> Coroutine: """Save pipe results to `out_filename`. Parameters ---------- out_filename : str or file-like File to save results. """ with open(out_filename, 'w') as file_handler: try: while True: smiles = (yield) file_handler.write(f'{smiles}\n') except GeneratorExit: pass def process_options() -> argparse.Namespace: """Process command line arguments. """ parser = argparse.ArgumentParser( description='Run SQL query from file and save results.', formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) file_options = parser.add_argument_group('input/output arguments') file_options.add_argument( '-s', '--sql_f', help='Path to file w/ SQL query.', default=SQL_FILENAME, ) file_options.add_argument( '-d', '--database_f', help='Path to database.', default=os.environ.get('DB_FILENAME'), ) file_options.add_argument( '-o', '--output_f', help='File to save results.', default=OUT_FILENAME, ) filter_options = parser.add_argument_group('filter arguments') filter_options.add_argument( '-a', '--minimum_length', help='Lower bound for SMILES string length.', type=int, default=15, ) filter_options.add_argument( '-b', '--maximum_length', help='Upper bound for SMILES string length.', type=int, default=100, ) return parser.parse_args() if __name__ == '__main__': DisableLog('rdApp.*') main()
UTF-8
Python
false
false
5,783
py
49
process_stage1_data.py
44
0.611793
0.607989
0
222
25.04955
78
MohnishVS/Guvi-Tasks
19,232,863,588,486
3559187cbd9e3ea57b914cadc7e8ceab330068ed
04188efd3bc52538bc1e704ab49cd3f5b01e8bc3
/guessanumber.py
e00d5cd966db5e4a7bd450d7ea6f03a747ec2abd
[]
no_license
https://github.com/MohnishVS/Guvi-Tasks
c5fc1840842e03db77392497872ee8fcc86ccfd5
6d614d7b9e883fd8da58ec72e7c0a0471230e9f3
refs/heads/master
2021-07-22T02:27:02.977161
2020-08-19T14:19:36
2020-08-19T14:19:36
236,750,559
0
2
null
false
2021-01-17T16:55:57
2020-01-28T14:12:24
2020-08-19T14:20:28
2020-08-19T14:20:25
24
0
1
1
Jupyter Notebook
false
false
import random f=True while(f==True): a=random.randint(1,10) b=int(input("Guess a number between 1-10:")) if a==b: print ("You Won") else: print ("You Lose number is ",a) i=input('enter anything to continue:') if i=='n': f=False else: f=True continue
UTF-8
Python
false
false
317
py
9
guessanumber.py
7
0.539432
0.520505
0
15
20.2
48
dotpot/pushit
7,962,869,367,598
7aa34abd16ffede338c4e91faadfd0219e1ecbeb
132b9e186373eab18b2b9447f8a9b7f933da012f
/pushit/android/__init__.py
7f72f26847515e8d8f7c9a54d81d25e325a77274
[ "MIT" ]
permissive
https://github.com/dotpot/pushit
8a64c17a81f961c2066b1e3b673c7839b0400c52
4714aa356b95929a252bac2bcb97abecb097c9e2
refs/heads/master
2021-01-25T04:14:04.339878
2017-08-14T10:45:10
2017-08-14T10:45:10
93,408,291
1
1
null
false
2017-08-14T10:45:11
2017-06-05T13:44:36
2017-06-13T09:29:09
2017-08-14T10:45:11
21
0
1
0
Python
null
null
""" android related util. """ from .gcm import ( GCM2, GCMAuthenticationException, GCMConnectionException, GCMException, GCMInvalidRegistrationException, GCMInvalidTtlException, GCMMalformedJsonException, GCMMessageTooBigException, GCMMismatchSenderIdException, GCMMissingRegistrationException, GCMNotRegisteredException, GCMTooManyRegIdsException, GCMUnavailableException, group_response, urlencode_utf8, ) __all__ = ( "GCM2", "GCMAuthenticationException", "GCMConnectionException", "GCMException", "GCMInvalidRegistrationException", "GCMInvalidTtlException", "GCMMalformedJsonException", "GCMMessageTooBigException", "GCMMissingRegistrationException", "GCMMismatchSenderIdException", "GCMNotRegisteredException", "GCMTooManyRegIdsException", "GCMUnavailableException", "group_response", "urlencode_utf8", )
UTF-8
Python
false
false
930
py
9
__init__.py
6
0.735484
0.731183
0
36
24.833333
38
scopeInfinity/CaptureTheFlag
8,658,654,092,069
c2b06ade2167cbb35c3035797582f1f37bda5809
e986be8ead4c17ab90a273c403325a1b4762665c
/game_ctf/views.py
44ecedca01ab11ef24832faa38e981970a132285
[]
no_license
https://github.com/scopeInfinity/CaptureTheFlag
56c270e3b1ce96e2f79dcf8ae1742476c1068968
f35cdf3b3034f85986619bfc6def6722cd6462db
refs/heads/master
2021-01-10T04:08:42.343499
2016-01-11T13:49:31
2016-01-11T13:49:31
49,274,865
1
2
null
false
2016-01-10T20:34:18
2016-01-08T13:56:33
2016-01-09T05:15:14
2016-01-10T20:34:18
513
1
2
0
Python
null
null
# # @author:metastableB # views.py # from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib import messages from django.core.urlresolvers import resolve, Resolver404, is_valid_path from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.contrib import messages from django.template import loader from models import Question, QuestionStatus, TeamDetail from .settings import QUESTIONS_DIR, info_messages, template_path @login_required def home(request): questions = Question.objects.all().filter(valid=True) try: score = TeamDetail.objects.get(team = request.user).points except ObjectDoesNotExist: messages.add_message(request, info_messages['normal user page'][0],info_messages['normal user page'][1]) return HttpResponseRedirect(reverse('user_session:logout')) team_name = request.user.username _questions = [] for ques in questions: question_status_obj = QuestionStatus.objects.filter(team_id = request.user).filter(question_id = ques).filter(question_status = 'AW') if len(question_status_obj) == 1 : _questions.append( ( ques.pk,True) ) #Solved else: _questions.append( ( ques.pk,False) ) #Unsolved return render(request, template_path['home'],{'teamname':team_name,'questions':_questions, 'score':score, 'team_name' :team_name}) @login_required def submit_answer(request,question_id): try: question = Question.objects.get(pk = question_id) if request.method == 'POST' and 'answer' in request.POST: try: question = Question.objects.get(pk = question_id) except ObjectDoesNotExist: return HttpResponse("invalid") question_status_obj = QuestionStatus.objects.filter(team_id = request.user).filter(question_id = question).filter(question_status = 'AW') if len(question_status_obj) !=0 : return HttpResponse("as") answer = request.POST['answer'] if question.answer == answer: qs = QuestionStatus( team_id = request.user, question_id = question, question_status = 'AW') qs.save() team = TeamDetail.objects.filter(team = qs.team_id)[0]; team.points+=qs.question_id.points; team.save() return HttpResponse("wow") else: return HttpResponse("tryagain") return HttpResponse("error") except ObjectDoesNotExist: pass return HttpResponse("error") @login_required def question_page(request,question_id): try: question = Question.objects.get(pk = question_id) except ObjectDoesNotExist: messages.add_message(request, info_messages['question does not exist'][0],info_messages['question does not exist'][1]) question_status_obj = QuestionStatus.objects.filter(team_id = request.user).filter(question_id = question).filter(question_status = 'AW') if len(question_status_obj) == 1 : messages.add_message(request, info_messages['question already solved'][0],info_messages['question already solved'][1]) return HttpResponseRedirect(reverse('game_ctf:home')) return render(request, QUESTIONS_DIR + question.source_file) def leaderboard(request): template = loader.get_template('game_ctf/leaderboard.html') rlist_ = TeamDetail.objects.all().order_by('-points')[:20]; rlist = [] rank = 1 for row in rlist_: rlist.append( ( rank,row.team.username,row.points) ) rank+=1 content = { 'ranklist' : rlist } return render(request, template_path['leaderboard'],content) def rules(request): return render(request, template_path['rules'])
UTF-8
Python
false
false
3,610
py
11
views.py
8
0.733795
0.729086
0
107
32.738318
141
cash2one/xai
4,466,765,997,711
dcae60d3d083bf73b1328aeeae0dccf9bfa191e0
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_sanitariums.py
d2f64a9ecdcec8337ddf52a186d797f41e6c4af7
[ "MIT" ]
permissive
https://github.com/cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#calss header class _SANITARIUMS(): def __init__(self,): self.name = "SANITARIUMS" self.definitions = sanitarium self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['sanitarium']
UTF-8
Python
false
false
238
py
37,275
_sanitariums.py
37,266
0.62605
0.62605
0
13
17.153846
31
silhouetteMn/blog
8,899,172,276,925
aaa9e90dd85248e1e36a093560599e81a00f42cd
45c556e06a3156f029216a72604b59e4b6f16984
/app/models/role.py
430bd22ed03c1adcd2524252e694f8a4c5316d13
[]
no_license
https://github.com/silhouetteMn/blog
3af98a086522d3383626f4ef2e10e6a66f8d0af0
e52a8b3c090d4a688784fd4b3b579acd92e6a2d7
refs/heads/master
2020-04-27T17:00:53.466187
2019-03-18T08:19:11
2019-03-18T08:19:11
174,501,327
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from . import Model """ 用户权限功能,为每个用户赋予角色,每个角色可配置相应权限 关注 0x01 评论 0x02 发帖 0x04 管理评论 0x08 管理员权限 0x80 Role字段 name : Stranger(0x00) NormalUser(0x07) Admin(0x88) permissions: default: 新注册用户给赋值哪种Role属性 """ class Role(Model): __fields__ = Model.__fields__ + [ ('name', str, ''), ('permission', int, 0), ('default', bool, False), ] # 添加配置Role @classmethod def insert_roles(cls): roles = [{ 'name': 'User', 'permission': Permission.FOLLOW | Permission.COMMENT | Permission.WRITE, 'default': True, }, { 'name': 'Administrator', 'permission': 0xff, 'default': False, } ] for r in roles: query_form = { 'name': r['name'], } cls.upsert(query_form, r) class Permission: FOLLOW = 0x01 COMMENT = 0x02 WRITE = 0x04 MODERATE_COMMENTS = 0x08 ADMINISTER = 0x80
UTF-8
Python
false
false
1,156
py
28
role.py
24
0.494197
0.454545
0
50
19.68
88
FlorianBury/talos
19,396,072,329,352
c788cde8dabfc41b5fc3846d5f56a4a0759a8b20
6956964a5d1eab088b6134b5591318bd752efcc8
/talos/model/shapes.py
0ca4119f349a0e7359a7c1d556802be909b74510
[ "MIT" ]
permissive
https://github.com/FlorianBury/talos
2e3b34a3bd295c7310d30cf4570b805d5b97e541
30f7af4d1f628364f8e8a2e983f72b2631cee6d9
refs/heads/master
2021-06-25T22:03:06.198180
2020-08-25T13:14:25
2020-08-25T13:14:25
167,014,128
0
0
MIT
true
2019-01-22T15:07:13
2019-01-22T15:07:13
2019-01-21T07:41:23
2019-01-20T14:01:08
581
0
0
0
null
false
null
import math as m def shapes(params, last_neuron): '''Handles shapes for the case where hidden layers are used as an optimization parameter. Available shapes are: 'funnel', 'long_funnel', 'rhombus', 'brick', 'diamond', 'hexagon', 'triangle', 'stairs' ''' layers = params['hidden_layers'] shape = params['shapes'] neuron_max = params['first_neuron'] neuron_previous = neuron_max neuron_last = last_neuron neuron_count = [] l = [] if shape == 'funnel': neuron_count.append(neuron_max) for i in range(layers - 1): neuron_count.append((neuron_previous + neuron_last) / 2) neuron_previous = neuron_count[i+1] if shape == 'rhombus': neuron_count.append(1) a = neuron_max * 2 - 1 k = 0 if a < layers: k = layers - a val = layers - k else: val = layers if (val % 2) == 0: n = int((val - 2) / 2) for i in range(int(n)): neuron_count.append(int(neuron_max * (i+1) * 2 / val)) l = neuron_count[::-1] neuron_count.append(neuron_max) for i in range(int(n)): neuron_count.append(l[i]) else: n = (val - 1) / 2 for i in range(int(n) - 1): neuron_count.append(int(neuron_max * (3 + 2 * i) / val)) l = neuron_count[::-1] neuron_count.append(neuron_max) for i in range(int(n)): neuron_count.append(l[i]) if k != 0: for i in range(int(n)): neuron_count.append(1) if shape == 'long_funnel': n = layers / 2 if (layers % 2 == 0): for i in range(int(n)): neuron_count.append(neuron_max) elif (layers % 2 == 1): for i in range(int(n) + 1): neuron_count.append(neuron_max) for i in range(int(n)): neuron_count.append((neuron_previous + neuron_last) / 2) neuron_previous = neuron_count[i + int(n)] if shape == 'brick': for i in range(layers): neuron_count.append(neuron_max) if shape == 'diamond': n = layers / 2 if (layers % 2 == 0): for i in range(int(n) - 1): neuron_count.append(int(m.ceil(neuron_max * layers + i) / 2.0) / (layers - 1)) neuron_count.append(neuron_max) else: for i in range(int(n)): neuron_count.append(int(m.ceil(neuron_max * layers + i) / 2.0) / (layers - 1)) for i in range(1): neuron_count.append(neuron_max) for i in range(int(n)): neuron_count.append((neuron_previous + neuron_last) / 2) neuron_previous = neuron_count[i + int(n)] if shape == 'hexagon': neuron_count.append(1) if (layers == 4): for i in range(layers - 1): neuron_count.append(neuron_max) else: n = layers / 3 for i in range(int(n)): l.append((neuron_previous + neuron_last) / 2) neuron_previous = l[i] l = l[::-1] if (layers % 3 == 0): for i in range(int(n) - 1): neuron_count.append(l[i]) if (layers % 3 == 1): for i in range(int(n)): neuron_count.append(l[i]) if (layers % 3 == 2): for i in range(int(n)): neuron_count.append(l[i]) neuron_count.append(neuron_max) l = l[::-1] for i in range(int(n)): neuron_count.append(neuron_max) for i in range(int(n)): neuron_count.append(l[i]) if shape == 'triangle': neuron_count.append(1) for i in range(layers - 2): l.append((neuron_previous + neuron_last) / 2) neuron_previous = l[i] l = l[::-1] for i in range(layers - 2): neuron_count.append(l[i]) neuron_count.append(neuron_max) if shape == 'stairs': if (layers >= 5): if (layers % 2 == 1): neuron_count.append(neuron_max) else: for i in range(2): neuron_count.append(neuron_max) n = layers / 2 for i in range(int(n)): if neuron_previous >= 3: neuron_previous -= 2 for j in range(2): neuron_count.append(neuron_previous) else: for i in range(layers): neuron_count.append(neuron_previous) neuron_previous -= 1 return [int(i) for i in neuron_count]
UTF-8
Python
false
false
4,882
py
35
shapes.py
27
0.465998
0.451864
0
206
22.699029
94
liyocee/textblob-aptagger
3,169,685,909,582
df0b1f1a939a69b296e319893cc181782e3254b3
1155d72c730cb071b4ccddb892412a237118d68a
/tests/test_taggers.py
29d8d1d7d76194cc9ac0bc6af216324925c53ece
[ "MIT" ]
permissive
https://github.com/liyocee/textblob-aptagger
a6da73ff8fe542b2c93677242f9140baae8c6b13
0de770b183da596f66c425925f35877b9390ab46
refs/heads/master
2021-01-16T18:35:36.675958
2013-10-28T03:22:31
2013-10-28T03:22:54
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from nose.tools import * # PEP8 asserts from nose.plugins.attrib import attr from textblob.base import BaseTagger from textblob.blob import TextBlob from textblob.exceptions import MissingCorpusException from textblob_aptagger import PerceptronTagger class TestPerceptronTagger(unittest.TestCase): def setUp(self): self.text = ("Simple is better than complex. " "Complex is better than complicated.") self.tagger = PerceptronTagger(load=False) def test_init(self): tagger = PerceptronTagger(load=False) assert_true(isinstance(tagger, BaseTagger)) def test_train(self): sentences = _read_tagged(_wsj_train) nr_iter = 5 self.tagger.train(sentences, nr_iter=nr_iter) nr_words = sum(len(words) for words, tags in sentences) # Check that the model has 'ticked over' once per instance assert_equal(nr_words * nr_iter, self.tagger.model.i) # Check that the tagger has a class for every seen tag tag_set = set() for _, tags in sentences: tag_set.update(tags) assert_equal(len(tag_set), len(self.tagger.model.classes)) for tag in tag_set: assert_true(tag in self.tagger.model.classes) @attr("slow") def test_tag(self): trained_tagger = PerceptronTagger() tokens = trained_tagger.tag(self.text) assert_equal([w for w, t in tokens], ['Simple', 'is', 'better', 'than', 'complex', '.', 'Complex', 'is', 'better', 'than', 'complicated', '.']) @attr("slow") def test_tag_textblob(self): trained_tagger = PerceptronTagger() blob = TextBlob(self.text, pos_tagger=trained_tagger) # Punctuation is excluded assert_equal([w for w, t in blob.tags], ['Simple', 'is', 'better', 'than', 'complex', 'Complex', 'is', 'better', 'than', 'complicated']) def test_loading_missing_file_raises_missing_corpus_exception(self): tagger = PerceptronTagger(load=False) assert_raises(MissingCorpusException, tagger.load, 'missing.pickle') def _read_tagged(text, sep='|'): sentences = [] for sent in text.split('\n'): tokens = [] tags = [] for token in sent.split(): word, pos = token.split(sep) tokens.append(word) tags.append(pos) sentences.append((tokens, tags)) return sentences _wsj_train = ("Pierre|NNP Vinken|NNP ,|, 61|CD years|NNS old|JJ ,|, will|MD " "join|VB the|DT board|NN as|IN a|DT nonexecutive|JJ director|NN " "Nov.|NNP 29|CD .|.\nMr.|NNP Vinken|NNP is|VBZ chairman|NN of|IN " "Elsevier|NNP N.V.|NNP ,|, the|DT Dutch|NNP publishing|VBG " "group|NN .|. Rudolph|NNP Agnew|NNP ,|, 55|CD years|NNS old|JJ " "and|CC former|JJ chairman|NN of|IN Consolidated|NNP Gold|NNP " "Fields|NNP PLC|NNP ,|, was|VBD named|VBN a|DT nonexecutive|JJ " "director|NN of|IN this|DT British|JJ industrial|JJ conglomerate|NN " ".|.\nA|DT form|NN of|IN asbestos|NN once|RB used|VBN to|TO make|VB " "Kent|NNP cigarette|NN filters|NNS has|VBZ caused|VBN a|DT high|JJ " "percentage|NN of|IN cancer|NN deaths|NNS among|IN a|DT group|NN " "of|IN workers|NNS exposed|VBN to|TO it|PRP more|RBR than|IN " "30|CD years|NNS ago|IN ,|, researchers|NNS reported|VBD .|.") if __name__ == '__main__': unittest.main()
UTF-8
Python
false
false
3,620
py
2
test_taggers.py
1
0.609669
0.60663
0
88
40.136364
83
mszpunar/Differential-Evolution-Experiments
8,117,488,215,846
95b164d7fd4cda14de1a4cc73ab913556b5c8678
5297a06ccaed90b6bf7527a5d6fe1855a273426e
/DE.py
53aea09f61f3be4b9af991ba778c76208ddbeb72
[]
no_license
https://github.com/mszpunar/Differential-Evolution-Experiments
a00e10ee0f9013dc2bf1fcb2bb84c92d6fbd938d
f782595ccc212f3ecf3cff73e4c69b907b83ce42
refs/heads/main
2023-05-29T02:39:23.329450
2021-06-13T15:39:50
2021-06-13T15:39:50
356,058,849
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from typing import Optional import numpy as np from numpy.random import random from collections import namedtuple from MinorClasses import Point from MinorClasses import EndConditions from Consts import * Result = namedtuple( 'Result', ['best_point', 'end_reason', 'iteration_num']) class DifferentialEvolution: DEFAULT_CR = 0.5 DEFAULT_F = 0.8 def __init__(self, objective_fun, lbd: int, max_iter: int = MAX_ITER, tolerance: float = MAX_TOL, f: float = DEFAULT_F, cr: float = DEFAULT_CR, crossover_method: str = 'BIN', selection_method: str = 'RAND'): self.objective_fun = objective_fun self.population = None self.point_dim = self.objective_fun.dim self.max_iter = max_iter self.tolerance = tolerance self.end_reason: Optional[str] = None self.iterations = 0 # ALGORITHM PARAMS self.cr = cr self.f = f self.lbd = lbd # ALGORITHM METHODS if crossover_method == 'EXP': self.crossover = self._exp_crossover else: self.crossover = self._bin_crossover if selection_method == 'RAND': self.selection_method = self._rand_selection elif selection_method == 'BEST': self.selection_method = self._best_selection elif selection_method == 'MEAN': self.selection_method = self._mean_selection elif selection_method == 'MEAN_VEC': self.selection_method = self._mean_vector_base_selection else: self.selection_method = self._rand_mean_selection # ------- PRIVATE METHODS ------- # def _get_best(self): # create an array of objective function values val_array = np.array([p.value for p in self.population]) # Get the indices of minimum element min_index = np.where(val_array == np.amin(val_array)) # minindex[0][0], because the value returned by np.where is a bit weird return self.population[min_index[0][0]] def _get_mean(self): # arrange population into matrix, where rows are points population_matrix = np.asmatrix(np.array([p.coordinates for p in self.population])) mean_point = np.asarray(population_matrix.mean(axis=0))[0] return Point(coordinates=mean_point, objective_fun=self.objective_fun) def _check_end_cond(self, prev_best): end_conditions = EndConditions.check_end_conditions(iteration=self.iterations, vec1=prev_best, vec2=self._get_best(), obj_fun=self.objective_fun, max_iter=self.max_iter, tol=self.tolerance) if self.iterations != 0 and any(end_conditions.values()): reason = next((i for i, j in enumerate( end_conditions.values()) if j), None) self.end_reason = list(end_conditions.keys())[reason] return True else: return False def _gen_random_population(self, size=None, scaler=1): if not size: size = self.lbd generated = scaler * np.random.uniform( size=(size, np.random.randint(low=self.point_dim, high=self.point_dim + 1))) raw_population = np.array([Point( coordinates=generated[i], objective_fun=self.objective_fun) for i in range(len(generated))]) if self.objective_fun.bounds: self.population = self.objective_fun.repair_points(raw_population) else: self.population = raw_population # ------- CROSSOVER METHODS ------- # def _bin_crossover(self, x, y): z = np.empty(x.shape[0]) for i in range(x.shape[0]): a = random() if a < self.cr: z[i] = y[i] else: z[i] = x[i] return z def _exp_crossover(self, x, y): z = np.empty(x.shape[0]) i, n = 0, x.shape[0] while i < n: a = random() if a < self.cr: z[i] = y[i] i += 1 else: i += 1 break while i < n: z[i] = x[i] i += 1 return z # --------- SELECTION METHODS --------- # def _rand_selection(self): # generates a random distinct 3 points points = np.random.choice(self.population, size=3, replace=False) r = points[0] d_e = points[1:] return r, d_e def _best_selection(self): # picks a best point and then picks two different random points r = self._get_best() d_e = np.random.choice(self.population, size=2, replace=False) while d_e[0] == r or d_e[1] == r: d_e = np.random.choice(self.population, size=2, replace=False) return r, d_e def _mean_selection(self): # picks a mean point and then picks two different random points r = self._get_mean() d_e = np.random.choice(self.population, size=2, replace=False) while d_e[0] == r or d_e[1] == r: d_e = np.random.choice(self.population, size=2, replace=False) return r, d_e def _rand_mean_selection(self): # picks two random points and avg of a third random point and a mean point r, d_e = self._rand_selection() mean = self._get_mean() new_coords = np.mean(np.array([r.coordinates, mean.coordinates]), axis=0) return Point(coordinates=new_coords, objective_fun=self.objective_fun), d_e def _mean_vector_base_selection(self): # picks two random points and a mean point r, d_e = self._rand_selection() d_e[0] = self._get_mean() return r, d_e # --------- GENERAL METHODS --------- # def _tournament(self, x, y): res = self.objective_fun.compare(x, y) if res > 0: return y elif res < 0: return x else: if random() >= 0.5: return x else: return y def _single_iteration(self): next_population = self.population for i in range(0, np.size(self.population, axis=0)): # SELECTION r, d_e = self.selection_method() # MUTATION and CROSSOVER m = r.coordinates + self.f * \ (d_e[1].coordinates - d_e[0].coordinates) o = Point(self.crossover(self.population[i].coordinates, m)) if self.objective_fun.bounds: o = self.objective_fun.repair_point(o) o.update(self.objective_fun) # SUCCESSION next_population[i] = self._tournament(self.population[i], o) prev_best = self._get_best() self.population = next_population self.iterations += 1 return prev_best def run(self): # INITIALIZE self.iterations = 0 self._gen_random_population(size=self.lbd) prev_best = self._get_best() # MAIN LOOP while not self._check_end_cond(prev_best): prev_best = self._single_iteration() print(prev_best.value) return Result(best_point=self._get_best(), end_reason=self.end_reason, iteration_num=self.iterations)
UTF-8
Python
false
false
7,476
py
7
DE.py
6
0.545746
0.539326
0
212
34.264151
104
RiddhimGupta/Python
11,854,109,760,079
88d14df29e6ac26da44d219491018f528679ed3d
50530db39b76448914b731c48a08ca0d8ac56dcc
/problem11send.py
c716e50f2109d2bd583e4e7cf84f49b9366e0a3f
[]
no_license
https://github.com/RiddhimGupta/Python
bbfb21a088cf00e68c13ab1d09b8c04b043a12d6
ac75eeeabd779c8a7b140ad610278da1cef184b4
refs/heads/master
2021-07-14T12:16:10.088006
2020-08-27T15:26:11
2020-08-27T15:26:11
191,228,349
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import socket recv_ip='127.0.0.1' recv_port=4444 s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: msg=input("Enter message: ") s.sendto(msg.encode('ascii'),(recv_ip,recv_port)) if msg=='q': exit() s.close()
UTF-8
Python
false
false
227
py
18
problem11send.py
12
0.687225
0.643172
0
10
21.5
50
smurashov/rally
5,248,450,082,250
b0dc9732b1bcb6c9e5e4abdc5236d42595520d5e
26b0bcdeea175b10491a935856c3248f9635ff2b
/tests/benchmark/scenarios/ceilometer/test_utils.py
2f94c979a059ebd1dbe1fd2bed80486d02b3e6e5
[ "Apache-2.0" ]
permissive
https://github.com/smurashov/rally
f84624b89e70288d0c22293f7101dff7b03b0bfe
bbc6fd57b62790592bfda74c632eae872de2d668
refs/heads/master
2020-12-25T01:50:56.866857
2014-10-10T08:03:43
2014-10-10T08:03:43
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from rally.benchmark.scenarios.ceilometer import utils from tests.benchmark.scenarios import test_utils from tests import test UTILS = "rally.benchmark.scenarios.ceilometer.utils" class CeilometerScenarioTestCase(test.TestCase): def _test_atomic_action_timer(self, atomic_actions_time, name): action_duration = test_utils.get_atomic_action_timer_value_by_name( atomic_actions_time, name) self.assertIsNotNone(action_duration) self.assertIsInstance(action_duration, float) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__list_alarm(self, mock_clients): """Test _list_alarms when alarm_id is passed to it.""" fake_alarms = ['fake_alarm'] mock_clients("ceilometer").alarms.get.return_value = fake_alarms scenario = utils.CeilometerScenario() alarms = scenario._list_alarms("FAKE_ALARM_ID") self.assertEqual(fake_alarms, alarms) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__list_alarms(self, mock_clients): """Test _list_alarms when no alarm_id is passed to it.""" fake_alarms = [] mock_clients("ceilometer").alarms.list.return_value = fake_alarms scenario = utils.CeilometerScenario() alarms = scenario._list_alarms() self.assertEqual(fake_alarms, alarms) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__create_alarm(self, mock_clients): """Test _create_alarm returns alarm.""" fake_alarm = mock.MagicMock() fake_alarm_dict = dict() mock_clients("ceilometer").alarms.create.return_value = fake_alarm scenario = utils.CeilometerScenario() created_alarm = scenario._create_alarm("fake_meter_name", "fake_threshold", fake_alarm_dict) self.assertEqual(fake_alarm, created_alarm) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__delete_alarms(self, mock_clients): """Test if call to alarms.delete is made to ensure alarm is deleted.""" scenario = utils.CeilometerScenario() scenario._delete_alarm("FAKE_ALARM_ID") mock_clients("ceilometer").alarms.delete.assert_called_once_with( "FAKE_ALARM_ID") @mock.patch(UTILS + '.CeilometerScenario.clients') def test__update_alarms(self, mock_clients): """Test if call to alarms.update is made to ensure alarm is updated.""" fake_alarm_dict_diff = {"description": "Changed Test Description"} scenario = utils.CeilometerScenario() scenario._update_alarm("FAKE_ALARM_ID", fake_alarm_dict_diff) mock_clients("ceilometer").alarms.update.assert_called_once_with( "FAKE_ALARM_ID", **fake_alarm_dict_diff) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__list_meters(self, mock_clients): """Test _list_meters.""" fake_meters = [] mock_clients("ceilometer").meters.list.return_value = fake_meters scenario = utils.CeilometerScenario() meters = scenario._list_meters() self.assertEqual(fake_meters, meters) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__list_resources(self, mock_clients): """Test _list_resources.""" fake_resources = [] mock_clients("ceilometer").resources.list.return_value = fake_resources scenario = utils.CeilometerScenario() resources = scenario._list_resources() self.assertEqual(fake_resources, resources) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__get_stats(self, mock_clients): """Test _get_stats function.""" fake_stats = mock.MagicMock() mock_clients("ceilometer").statistics.list.return_value = fake_stats scenario = utils.CeilometerScenario() stats = scenario._get_stats("fake_name") self.assertEqual(fake_stats, stats) @mock.patch(UTILS + '.CeilometerScenario.clients') def test__create_meter(self, mock_clients): """Test _create_meter returns meter.""" fake_meter = mock.MagicMock() kwargs = mock.MagicMock() mock_clients("ceilometer").samples.create.return_value = [fake_meter] scenario = utils.CeilometerScenario() created_meter = scenario._create_meter(**kwargs) self.assertEqual(fake_meter, created_meter)
UTF-8
Python
false
false
5,041
py
38
test_utils.py
27
0.659393
0.658599
0
113
43.610619
79
zhxiaohe/starwars_api
8,117,488,207,546
b5a0a02c2e165febefaf4ac51169c360c88dda43
2a51fdbb2e1c2eae4e47b7be49871c03fbe4c3e2
/cmdb/config.py
5ee36d723421e88d712a566bb1ad48077e6a6772
[ "MIT" ]
permissive
https://github.com/zhxiaohe/starwars_api
6ae557959ccf425ab6bc1238d4ea0b88d31fbf79
f1b729e819eb19e5eb59630bed56b13127eb1ef2
refs/heads/master
2020-06-18T17:55:14.330319
2017-03-30T05:30:39
2017-03-30T05:30:39
74,750,556
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
from werkzeug.exceptions import HTTPException import os from flask.ext.restful import fields import json basedir = os.path.abspath(os.path.dirname(__file__)) # Mysql Connect Config MysqlHost = '10.1.15.131' MysqlUser = 'root' MysqlPass = 'unfae2016' MysqlDB = 'ops' SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://%s:%s@%s/%s' % (MysqlUser, MysqlPass, MysqlHost, MysqlDB) SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') #Redis Configuration RedisHost = '10.1.15.93' RedisPost = '6379' SECRET_KEY = '\xa8H\xe4;R@pi:Mo\x92\xe4M\xa7*E\x80\n\x8d\xfav3\xd8' TIMEOUT = 3600 # Config Logging from app import app app.debug = True import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler('/tmp/flask.log') file_handler.setLevel(logging.DEBUG) logging_format = logging.Formatter( '%(asctime)s %(levelname)s: %(message)s ' ) file_handler.setFormatter(logging_format) app.logger.addHandler(file_handler) class UserOrPassIsNone(HTTPException): code = 402 description = 'User or Password is None' class ToJson(fields.Raw): def format(self, value): return json.dumps(value) my_response_fields = { 'code' : fields.Integer(default = 200), 'result' : fields.Boolean, 'message' : fields.String(default= 'Success'), 'data' : ToJson(default= 'Null'), } ERRORS = { 'Unauthorized': { 'message': "Not Authorized.", 'status': 401, }, 'FORBIDDEN': { 'message': "No Permission.", 'status': 403, }, 'NotFound': { 'message': "The requested URL was not found on the server.", 'status': 404, }, 'RequestTimeout': { 'message': "Request Token Timeout.", 'status': 408, }, 'Conflict': { 'message': "A user with that username already exists.", 'status': 409, }, 'Gone': { 'data':'Null', 'message': "ID is not exist.", 'code': 410, 'status': 410, }, }
UTF-8
Python
false
false
1,995
py
11
config.py
9
0.634085
0.601504
0.004511
79
24.253165
100
jesson20121020/myRobot
13,615,046,356,566
2d51d4166dc1060260be60c0033fa07172c4c84b
c97f3ab8f5ad88c502b21c3ba6200ca0ad960263
/train_system/test.py
2486cefc6bdffd2b0daab6d3fcfb4a84ca92ef27
[ "Apache-2.0" ]
permissive
https://github.com/jesson20121020/myRobot
b7f1da79d72435e137b02bad6d98e6928fb5c42e
667213f6b21ac69dddeff453c4ec663e3e082e73
refs/heads/master
2021-01-12T06:08:14.568338
2016-12-25T04:46:13
2016-12-25T04:46:13
77,310,733
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#coding:utf-8 import os def execCmd(cmd): r = os.popen(cmd) text = r.read() r.close() return text print execCmd('python tickets.py -g 上海 西安 2016-12-28')
UTF-8
Python
false
false
180
py
26
test.py
22
0.622093
0.569767
0
11
14.636364
54
brunocosouza/RoboticBruno
16,166,256,916,503
199d4246cffc0efea3935856b5064ebdcb1341eb
45c6bf00ee62e5b1de38d5576af00f85c0435c43
/dynamicProgrammingUp.py
1d22150dc1668c90624fe619cd06c8f0eee17732
[]
no_license
https://github.com/brunocosouza/RoboticBruno
a419edce2e7079e52b8388af160dd4be677c038a
41f4099c792f78d4daf111bf18c7e9021940cbd1
refs/heads/main
2023-01-14T14:55:48.885231
2020-11-24T22:18:29
2020-11-24T22:18:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
<<<<<<< HEAD # ---------- # User Instructions: # # Implement the function optimum_policy2D below. # # You are given a car in grid with initial state # init. Your task is to compute and return the car's # optimal path to the position specified in goal; # the costs for each motion are as defined in cost. # # There are four motion directions: up, left, down, and right. # Increasing the index in this array corresponds to making a # a left turn, and decreasing the index corresponds to making a # right turn. import numpy as np forward = [[-1, 0], # go up [ 0, -1], # go left [ 1, 0], # go down [ 0, 1]] # go right forward_name = ['up', 'left', 'down', 'right'] # action has 3 values: right turn, no turn, left turn action = [-1, 0, 1] action_name = ['R', '#', 'L'] # EXAMPLE INPUTS: # grid format: # 0 = navigable space # 1 = unnavigable space grid = [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1]] init = [4, 3, 0] # given in the form [row,col,direction] # direction = 0: up # 1: left # 2: down # 3: right goal = [2, 0] # given in the form [row,col] cost = [2, 1, 20] # cost has 3 values, corresponding to making # a right turn, no turn, and a left turn # EXAMPLE OUTPUT: # calling optimum_policy2D with the given parameters should return # [[' ', ' ', ' ', 'R', '#', 'R'], # [' ', ' ', ' ', '#', ' ', '#'], # ['*', '#', '#', '#', '#', 'R'], # [' ', ' ', ' ', '#', ' ', ' '], # [' ', ' ', ' ', '#', ' ', ' ']] # ---------- # ---------------------------------------- # modify code below # ---------------------------------------- def optimum_policy2D(grid,init,goal,cost): value = [[[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))]] policy = [[[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))]] policy2D = [[999 for row in range(len(grid[0]))] for col in range(len(grid))] flag = True while flag: flag = False #Calcula todos os valores de cada celula for x in range(len(grid)): for y in range(len(grid[0])): for orientation in range(4): if x == goal[0] and y == goal[1]: if value[orientation][x][y] > 0: change = True value[orientation][x][y] = 0 policy[orientation][x][y] = '*' elif grid[x][y] == 0: for i in range(3): o2 = (orientation + action[i]) % 4 x2 = x + forward[o2][0] y2 = y + forward[o2][1] if x2 >= 0 and x2 ...: v2 = value[o2][x2][y2] + cost[i] if v2 < value[orientation][x][y]: value[orientation][x][y] = v2 policy[orinetation][x][y] = action_name[i] change = True return policy2D optimum_policy2D(grid,init,goal,cost) ======= # ---------- # User Instructions: # # Implement the function optimum_policy2D below. # # You are given a car in grid with initial state # init. Your task is to compute and return the car's # optimal path to the position specified in goal; # the costs for each motion are as defined in cost. # # There are four motion directions: up, left, down, and right. # Increasing the index in this array corresponds to making a # a left turn, and decreasing the index corresponds to making a # right turn. import numpy as np forward = [[-1, 0], # go up [ 0, -1], # go left [ 1, 0], # go down [ 0, 1]] # go right forward_name = ['up', 'left', 'down', 'right'] # action has 3 values: right turn, no turn, left turn action = [-1, 0, 1] action_name = ['R', '#', 'L'] # EXAMPLE INPUTS: # grid format: # 0 = navigable space # 1 = unnavigable space grid = [[1, 1, 1, 0, 0, 0], [1, 1, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 1, 1], [1, 1, 1, 0, 1, 1]] init = [4, 3, 0] # given in the form [row,col,direction] # direction = 0: up # 1: left # 2: down # 3: right goal = [2, 0] # given in the form [row,col] cost = [2, 1, 20] # cost has 3 values, corresponding to making # a right turn, no turn, and a left turn # EXAMPLE OUTPUT: # calling optimum_policy2D with the given parameters should return # [[' ', ' ', ' ', 'R', '#', 'R'], # [' ', ' ', ' ', '#', ' ', '#'], # ['*', '#', '#', '#', '#', 'R'], # [' ', ' ', ' ', '#', ' ', ' '], # [' ', ' ', ' ', '#', ' ', ' ']] # ---------- # ---------------------------------------- # modify code below # ---------------------------------------- def optimum_policy2D(grid,init,goal,cost): value = [[[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))]] policy = [[[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))], [[999 for row in range(len(grid[0]))] for col in range(len(grid))]] policy2D = [[999 for row in range(len(grid[0]))] for col in range(len(grid))] flag = True while flag: flag = False #Calcula todos os valores de cada celula for x in range(len(grid)): for y in range(len(grid[0])): for orientation in range(4): if x == goal[0] and y == goal[1]: if value[orientation][x][y] > 0: change = True value[orientation][x][y] = 0 policy[orientation][x][y] = '*' elif grid[x][y] == 0: for i in range(3): o2 = (orientation + action[i]) % 4 x2 = x + forward[o2][0] y2 = y + forward[o2][1] if x2 >= 0 and x2 ...: v2 = value[o2][x2][y2] + cost[i] if v2 < value[orientation][x][y]: value[orientation][x][y] = v2 policy[orinetation][x][y] = action_name[i] change = True return policy2D optimum_policy2D(grid,init,goal,cost) >>>>>>> d61a01d5ac8986ab997795e019df004d0302c58b
UTF-8
Python
false
false
7,982
py
2
dynamicProgrammingUp.py
1
0.435981
0.401278
0
207
37.067633
83
DemocracyClub/UK-Polling-Stations
18,107,582,140,771
07a9f2c46e82e79988d246a5f98b7ef493c5c2e1
f39ae1d934b14d55e4969beef9c0c1cf7e71ae88
/polling_stations/apps/data_importers/management/commands/import_waltham_forest.py
371ea441a42a0ce1803b98bc72bf26e65b004a9d
[]
permissive
https://github.com/DemocracyClub/UK-Polling-Stations
6f675ab13fdf730344eb53855b19ef291d58bbb1
6bbd7ddf5aa49bd5ec248d94697f9b6a4c3c4d46
refs/heads/master
2023-09-01T20:17:15.038918
2023-08-23T17:36:43
2023-08-23T20:45:12
31,439,953
31
33
BSD-3-Clause
false
2023-09-14T19:25:36
2015-02-27T21:28:04
2023-05-04T14:17:45
2023-09-14T19:25:31
171,462
30
28
134
Python
false
false
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = "WFT" addresses_name = ( "2022-05-05/2022-03-09T16:58:40.436212/Democracy_Club__05May2022.tsv" ) stations_name = ( "2022-05-05/2022-03-09T16:58:40.436212/Democracy_Club__05May2022.tsv" ) elections = ["2022-05-05"] csv_delimiter = "\t" def address_record_to_dict(self, record): uprn = record.property_urn.strip().lstrip("0") if uprn in [ "10009149436", # 24 PENNANT TERRACE, LONDON "10024418210", # 5A ELY ROAD, LONDON "10024421904", # FLAT B 372-374 HIGH ROAD LEYTON, LEYTON, E10 6QE "200001425453", # 112 FARMILO ROAD, LONDON "200001425453", # GROUND FLOOR FLAT 1 27 QUEENS ROAD, LEYTONSTONE "100022517750", # 316C LEA BRIDGE ROAD, LONDON "100023696171", # 3 OAKLANDS, 37 WEST AVENUE, LONDON "10009143272", # FLAT 1, 58 BORTHWICK ROAD, LONDON "100022597338", # FLAT 5 85 WHIPPS CROSS ROAD, LEYTONSTONE ]: return None if record.addressline6 in [ "E17 7EA", "E17 6HT", "E17 3DU", "E17 4ED", "E17 4PE", "E17 5JY", "E17 3NL", "E11 3DT", "E4 9DP", "E17 3DA", "E11 3PY", "E10 5PW", "E11 1LJ", ]: return None return super().address_record_to_dict(record) def station_record_to_dict(self, record): # Mission Grove (South Site) 108 Edinburgh Road Walthamstow London E17 7QB if record.polling_place_id == "5968": record = record._replace(polling_place_easting="536937") record = record._replace(polling_place_northing="188842") return super().station_record_to_dict(record)
UTF-8
Python
false
false
1,964
py
731
import_waltham_forest.py
601
0.566701
0.428208
0
56
34.071429
82
RoboJackets/onken
13,829,794,694,441
c88c0f3fb426b224f03860cdf0e8a4be13281183
8f47cef03ea025c04395332683e1e125f530bec4
/onken/public/api_views.py
16fa60311ab155eb5c4bf04f1c05cb5b752fbe0b
[ "Apache-2.0" ]
permissive
https://github.com/RoboJackets/onken
8161de517a187bebf0ee4d0ab919e31a40312b3c
43b5ff13e5f19fa4a9d5ffb37b585bf3c37ca05b
refs/heads/master
2021-06-04T01:02:02.806533
2018-10-18T15:33:25
2018-10-18T15:33:25
95,968,171
2
2
Apache-2.0
false
2019-05-10T23:21:55
2017-07-01T14:13:03
2018-10-18T15:33:28
2019-05-10T23:21:53
109
2
2
38
Python
false
false
from django.contrib.auth.models import Group from django.contrib.auth import get_user_model from rest_framework import viewsets from onken.public.serializers import UserSerializer, GroupSerializer, WorkspaceSerializer, DomainSerializer from onken.public.models import Workspace, Domain class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = get_user_model().objects.all() serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all() serializer_class = GroupSerializer class WorkspaceViewSet(viewsets.ModelViewSet): """ API endpoint that allows workspaces to be viewed or edited """ queryset = Workspace.objects.all() serializer_class = WorkspaceSerializer class DomainViewSet(viewsets.ModelViewSet): """ API endpoint that allows domains to be viewed or edited """ queryset = Domain.objects.all() serializer_class = DomainSerializer
UTF-8
Python
false
false
1,092
py
27
api_views.py
19
0.741758
0.741758
0
37
28.513514
107
acarta/flowplots
16,260,746,217,549
ccf1c75e93542c4c6d593545a4304c8e827c11fc
ac6f8f7a1dfbc708c7100b1847a70e423312fe5e
/flowplots/isosurface.py
2e82434edd6c011b92befc0acf6291e85e18364c
[]
no_license
https://github.com/acarta/flowplots
f5894624ab631fdad17f44f44d144d783afec011
3525f4a4d292651f01bc45161ab11700c9413efe
refs/heads/master
2018-10-20T18:10:16.872152
2018-07-24T07:11:32
2018-07-24T07:11:32
101,100,271
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np from netCDF4 import Dataset from mayavi import mlab import os from subprocess import call def rgb_convert(color): # Colors (x,y,z) correspond to RGB decimal codes 255*(x,y,z) return tuple(np.divide(color, 255.0)) def plot(file_name, contour_level, save_name="", dim=0, title="", figure=0): if len(title) == 0: title="{0}, dim = {1}, level = {2}".format(file_name[:-3], dim, contour_level) white = rgb_convert((255, 255, 255)) gray = rgb_convert((128, 128, 128)) yellow = rgb_convert((255, 255, 0)) orange = rgb_convert((255, 165, 0)) red = rgb_convert((255, 0, 0)) green = rgb_convert((0, 128, 0)) blue = rgb_convert((0, 0, 255)) data = Dataset(file_name, mode="r") x, y, z = np.mgrid[ -data.Lx/2 : data.Lx/2 : data.Nx*1j, data.a : data.b : data.Ny*1j, -data.Lz/2 : data.Lz/2 : data.Nz*1j, ] fig = mlab.figure(figure, size=(800, 600), bgcolor=white, fgcolor=gray ) mlab.clf() #FIXME Probably needs exception handling if len(data.variables.keys()) == 4: Q = np.flip(data["{0}".format("Component_0")][:].T, 1) mlab.contour3d(x, y, z, Q, contours=[contour_level], figure=fig, color=orange ) print("Max value is {0}".format(Q.max())) elif len(data.variables.keys()) == 6: if dim == 0: vel = np.flip(data["{0}".format("Velocity_X")][:].T, 1) mlab.contour3d(x, y, z, vel, contours=[contour_level], figure=fig, color=red ) elif dim == 1: vel = np.flip(data["{0}".format("Velocity_Y")][:].T, 1) mlab.contour3d(x, y, z, vel, contours=[contour_level], figure=fig, color=green ) elif dim == 2: vel = np.flip(data["{0}".format("Velocity_Z")][:].T, 1) mlab.contour3d(x, y, z, vel, contours=[contour_level], figure=fig, color=green ) mlab.contour3d(x, y, z, vel, contours=[-contour_level], figure=fig, color=yellow ) print("Max value is {0}".format(vel.max())) mlab.title("{0}".format(title), size=0.3) mlab.axes( extent=[-data.Lx/2, data.Lx/2, data.a, data.b, -data.Lz/2, data.Lz/2], ranges=[-data.Lx/2, data.Lx/2, data.a, data.b, -data.Lz/2, data.Lz/2], ) mlab.view( azimuth=45, elevation=45, roll=0, distance="auto" ) if save_name: mlab.savefig(save_name) def make_frames(data_dir, frame_dir, start_time, end_time, contour_level, label="Q", off_screen=False): mlab.options.offscreen=off_screen for t in np.arange(start_time, end_time + 1): print("Making frame {0}".format(t)) plot("{0}/{1}{2}.nc".format(data_dir, label, t), contour_level, save_name="{0}/{1}{2}.png".format(frame_dir, label, t)) def make_movie(frame_dir, label="Q", out_name="", frame_rate=1, size="800x600"): if not out_name: out_name = "{0}.mp4".format(label) call([ "ffmpeg", "-r", "{0}".format(frame_rate), "-s", "{0}".format(size), "-i", "{0}/{1}%d.png".format(frame_dir, label), "{0}".format(out_name) ]) def main(): channel_sim_dir = "{0}/simulations/channel".format(os.environ["HOME"]) sim_dir = "{0}/4_2/sz/Ubulk_1.0/Re_2000/128_192_128/force_0.5Lx_0.5Lz_1e-4_1e-3_1e-4/CFL_0.4_0.6".format(channel_sim_dir) file_name = "{0}/data/Q26.nc".format(sim_dir) plot_isosurface(file_name, 30) if __name__ == "__main__": main()
UTF-8
Python
false
false
4,093
py
10
isosurface.py
9
0.486685
0.444417
0
146
27.034247
125
thomascjw30/ML-Engineer-Capstone-Project
7,000,796,697,872
fceddf73ee5480fb770d01a52cacee13c17c8822
4b36a015eae0c41f5ade2da93829f66e70d92a1a
/endpoint.py
bffc1a9b09e7721f9e2ec79f7ea852ecc5f8a1ed
[]
no_license
https://github.com/thomascjw30/ML-Engineer-Capstone-Project
7d34f85d57ccd8d4addfcfdb8ce4b3f491030ed5
a92f0af815c1c8b1a0dc99d5174adfd11e6e4e74
refs/heads/main
2023-06-27T21:17:02.662689
2021-07-31T17:14:56
2021-07-31T17:14:56
388,497,045
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import requests import json # URL for the web service, should be similar to: # scoring_uri and key are found in the deployed model data and allow any api/web interface to access as req'd. scoring_uri = 'http://bc43d9a7-3650-4f5f-a71e-f602b038012a.eastus2.azurecontainer.io/score' # If the service is authenticated, set the key or token # key = 'Ptv8wKeDcTKCod1qO02pyaJRxZqksGf2' # Endpoint.py is used to pass new data to the scoring uri as defined by the deployed model. # The format has to be in the format (wrangled,pipeline) as per the orignal model input # Two sets of data to score, so we get two results back # in the case of this dataset the original file included passing it through clean data, and the finalised clean data # needs to be passed through to this model. It is then encoded, again we need to pass new encoded information through. # a simple way to find out how to interact with the model is to download the deployed model endpoint swagger ui (swagger.json) # file into a swagger directory with the swagger.sh and serve.py python script. The serve.py script allows the swagger run # to access the local directory and enables access tl localhost:9000 and http://localhost:8000/swagger.json. This will provide # examples of outputs which the below input data needs to match (post method) # define data as required for the model. # two sets of data to score data = data = {"data": [ { "gender" :"Female", "SeniorCitizen" :0, "Partner" :0, "Dependents" :0, "tenure" :1, "PhoneService" :0, "MultipleLines" :"No phone service", "InternetService" :"DSL", "OnlineSecurity" :0, "OnlineBackup" :0, "DeviceProtection" :0, "TechSupport" :0, "StreamingTV" :0, "StreamingMovies" :0, "Contract" :"Month-to-month", "PaperlessBilling" :1, "PaymentMethod" :"Electronic check", "MonthlyCharges" :29.85, "TotalCharges" :29.85, }, { "gender" :"Male", "SeniorCitizen" :0, "Partner" :0, "Dependents" :0, "tenure" :0, "PhoneService" :1, "MultipleLines" :"No phone service", "InternetService" :"DSL", "OnlineSecurity" :0, "OnlineBackup" :0, "DeviceProtection" :0, "TechSupport" :0, "StreamingTV" :0, "StreamingMovies" :0, "Contract" :"Month-to-month", "PaperlessBilling" :0, "PaymentMethod" :"Electronic check", "MonthlyCharges" :20.50, "TotalCharges" :20.50, } ]} # Convert to JSON string input_data = json.dumps(data) with open("data.json", "w") as _f: _f.write(input_data) # Set the content type headers = {'Content-Type': 'application/json'} # If authentication is enabled, set the authorization header # headers['Authorization'] = f'Bearer {key}' # Make the request and display the response resp = requests.post(scoring_uri, input_data, headers=headers) print(resp.json())
UTF-8
Python
false
false
3,222
py
9
endpoint.py
2
0.613904
0.590627
0
84
37.369048
128
ColinPython/SZ-Programming-Education
8,959,301,811,770
f09deabde1e23b8fda836487555544fc5ab0eee6
0ab5a5cc807faef297b7b6f6d94090f4b7e74069
/code_archive程序归档/Turtle_创意绘图/多彩小世界.py
98001390432d829266dd225e096c29ac03c20949
[]
no_license
https://github.com/ColinPython/SZ-Programming-Education
89d27e04d50c1a2fb0c432c3a68894d2454cbf58
1d291b48b53af89b40f9b87f1ba34cf83ace2fa7
refs/heads/master
2022-06-03T18:34:50.425492
2020-05-02T15:35:09
2020-05-02T15:35:09
257,779,109
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
from turtle import * from random import * def onecloud(): hideturtle() speed(0) pensize(6) pencolor("#b0e0e6") fillcolor("#b0e0e6") begin_fill() seth(7) for i in range(randint(18, 23)): speed(0) fd(i) left(1) seth(90) for n in range(3): speed(0) circle(25, 200) right(60) end_fill() hideturtle() def clouds(): speed(0) for m in range(5): speed(0) x, y = randint(-50, 90), randint(90, 140) up() goto(x, y) down() onecloud() up() goto(0, 0) down() seth(0) def ground(): hideturtle() speed(0) for i in range(300): speed(0) pensize(randint(1, 3)) x, y = randint(-260, 260), randint(-160, -50) r, g, b = -y / 280, -y / 280, -y / 280 pencolor(choice(["#778899", "#2F4F4F", "#808000"])) penup() goto(x, y) down() fd(randint(25, 30)) def sun(): hideturtle() for i in range(6): speed(0) up() goto(randint(-300, -190), randint(130, 170)) down() pensize(25) pencolor('#f0e68c') for n in range(randint(18, 24)): speed('fast') fd(2) left(2) fd(4) right(2) up() goto(-290, 167) down() pensize(5) pencolor('gold') fillcolor('yellow') begin_fill() for i in range(12): speed(0) circle(15, 90) right(120) end_fill() def rainbow(): hideturtle() speed(0) up() pensize(2) goto(-480, -350) down() right(100) speed(0) for i in range(9): pencolor('#F41900') circle(1000) right(0.1) for i in range(9): pencolor('#FF9919') circle(1000) right(0.1) for i in range(9): pencolor('#FFFF19') circle(1000) right(0.1) for i in range(9): pencolor('#3CB371') circle(1000) right(0.1) for i in range(9): pencolor('#98FB98') circle(1000) right(0.1) for i in range(9): pencolor('#6495ED') circle(1000) right(0.1) for i in range(9): pencolor('#6A5ACD') circle(1000) right(0.1) def dandelion(n): seth(90) pensize(2) pencolor('#191970') fd(2.5) pensize(n) pencolor('#004D66') fd(10) seth(150) pencolor('#FFB3CC') for i in range(9): speed(0) fd(11) backward(11) right(15) up() seth(0) down() pensize(1) def dandelions(): for i in range(15): speed(0) ls = [1, 1.5, 2] up() goto(randint(-250, 250), randint(-80, 150)) down() dandelion(choice(ls)) up() goto(0, 0) seth(0) down() def kite(): hideturtle() up() goto(50, -165) seth(0) down() pensize(1) pencolor('black') fillcolor('black') begin_fill() for i in range(9): speed(0) fd(i) left(1) seth(93) for i in range(13): speed(0) fd(i) left(1) seth(180) for i in range(6): speed(0) fd(i) right(1) seth(-97) for i in range(13): speed(0) fd(i) right(1) end_fill() up() goto(71, -77) down() pencolor('#87cefa') pensize(1) for i in range(9): speed(0) circle(-20, 50) circle(20, -50) up() goto(62, -147) down() pencolor('black') pensize(1) seth(40) for i in range(23): speed(0) fd(i) left(0.5) seth(-80) pencolor('plum') fillcolor('#dc143c') begin_fill() fd(20) left(120) fd(30) left(120) fd(20) end_fill() seth(-40) up() fd(15) down() pensize(3) for i in range(14): speed(0) fd(i) left(1) up() goto(0, 0) down() seth(0) pensize(1) def grass(): speed(0) for i in range(170): speed(0) pensize(randint(2, 4)) y = randint(-200, -160) pencolor(choice(['#90ee90', '#228b22', '#32cd32', '#8fbc8f'])) penup() goto(randint(-300, 300), y) seth(0) pendown() left(90) circle(-50, randint(40, 120)) up() goto(0, 0) seth(0) pensize(1) pencolor('white') down() def oneflower(x, y): hideturtle() up() goto(x, y) down() speed(0) pensize(3) colors = ['#ffdead', '#db7093'] fillcolor('#dda0dd') begin_fill() for i in range(64): speed(0) circle(i / 16, 140) pencolor(colors[i % 2]) right(90) end_fill() pencolor('#00ff33') fillcolor('#00ff33') begin_fill() pensize(2) seth(-90) circle(-100, 20) seth(135) circle(-60, 10) seth(-45) circle(60, 10) seth(45) circle(-60, 10) seth(-135) circle(-60, 15) end_fill() up() goto(0, 0) down() seth(0) def flowers(): for i in range(5): speed(0) oneflower(randint(-190, 190), randint(-190, -150)) up() goto(0, 0) seth(0) pensize(1) pencolor('#ffffff') down() def tree(length, level): speed(0) pensize(8) pencolor(choice(lstree)) if level < 0: return fd(length) left(45) tree(0.6 * length, level - 1) right(90) tree(0.6 * length, level - 1) left(45) backward(length) return def leaves(): speed(0) hideturtle() pensize(1) pencolor('#00fa9a') for i in range(150): speed(0) up() goto(randint(-160, -55) + randint(0, 3), randint(20, 55) + randint(0, 2)) down() fillcolor(choice(['#3CB371', '#7FFFAA', '#90EE90', '#32CD32'])) begin_fill() circle(randint(15, 25), 60) left(120) circle(randint(15, 25), 60) end_fill() hideturtle() speed(0) clouds() sun() rainbow() dandelions() ground() kite() grass() flowers() lstree = [ 'orange', 'coral', 'salmon', 'black', 'green', 'violet', 'grey', 'gold', 'pink', 'darkgreen'] up() goto(-100, -70) down() seth(90) tree(70, 8) leaves() done()
UTF-8
Python
false
false
6,365
py
32
多彩小世界.py
30
0.467871
0.379419
0
368
16.296196
71