blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
e26d4a6c0313fa49abae436161120ce69cc63449
f1c41d441f31f82e44a32e69cf697594e6f81f03
/homeassistant/components/risco/const.py
23d29bc11a9dd23d33edf461dac5f0325694f5c5
[ "Apache-2.0" ]
permissive
titilambert/home-assistant
363240782fb74b47251ccb5f2e518ab5ff790aa9
a2651845f379992231fd7b9c8458828036296ee0
refs/heads/dev
2023-01-23T04:19:40.006676
2020-08-26T16:03:03
2020-08-26T16:03:03
56,938,172
4
0
Apache-2.0
2023-01-13T06:01:54
2016-04-23T19:56:36
Python
UTF-8
Python
false
false
214
py
"""Constants for the Risco integration.""" DOMAIN = "risco" DATA_COORDINATOR = "risco" DEFAULT_SCAN_INTERVAL = 30 CONF_CODE_ARM_REQUIRED = "code_arm_required" CONF_CODE_DISARM_REQUIRED = "code_disarm_required"
[ "noreply@github.com" ]
noreply@github.com
8428e1f7302c80613880cf8d8a664368691cd001
58340a96d36013df5f7978c3f9b98e6a7badd65e
/python_multilabel_train/train/data_layer.py
a91c254514e7fdcbf540ae2c989d525ec98a74b6
[]
no_license
lvchigo/caffe_multilabel
00427974aebdf1a31943f0af92a4fd14e6be97da
c3f6b3a5af859fe4653546a83b5796f42cc94d54
refs/heads/master
2020-04-12T23:48:56.425307
2016-12-21T07:39:15
2016-12-21T07:39:15
68,178,965
1
0
null
null
null
null
UTF-8
Python
false
false
3,224
py
import sys sys.path.insert(0, '/home/xiaotian/caffe/python') import caffe import numpy as np import cv2 import copy import img_process import config class DataLayerTrain(caffe.Layer): def setup(self, bottom, top): self._batch_size = config.BATCH_SIZE self._class_num = config.CLASS_NUM self._image_width = config.IMAGE_WIDTH self._image_hight = config.IMAGE_HIGHT self._index = 0 file = config.TRAIN_FILE self._data = [] with open(file) as f: for line in f.readlines(): line = line.strip() arr = line.split(',') l = np.zeros(self._class_num, dtype=float) for i in xrange(1, len(arr), 1): index = int(arr[i]) l[index] = 1.0 self._data.append([arr[0], l]) np.random.shuffle(self._data) top[0].reshape(self._batch_size, 3, self._image_hight, self._image_width) top[1].reshape(self._batch_size, self._class_num) def forward(self, bottom, top): imgs_blob = [] labels_blob = [] if (self._index + self._batch_size > len(self._data)): np.random.shuffle(self._data) self._index = 0 while (len(imgs_blob) < self._batch_size): img = cv2.imread(self._data[self._index][0]) label = self._data[self._index][1] if (img is None) or (len(img) < 32) or (len(img[0]) < 32): self._index += 1 continue randint = np.random.randint(2) if randint == 1: img = img[:,::-1,:] imgs_blob.append(img_process.img_to_blob(img, self._image_hight, self._image_width)) labels_blob.append(label) self._index += 1 top[0].data[...] = np.array(imgs_blob) top[1].data[...] = np.array(labels_blob) def backward(self, top, propagate_down, bottom): pass def reshape(self, bottom, top): pass class DataLayerTest(caffe.Layer): def setup(self, bottom, top): self._batch_size = config.BATCH_SIZE self._class_num = config.CLASS_NUM self._image_width = config.IMAGE_WIDTH self._image_hight = config.IMAGE_HIGHT self._index = 0 file = config.TEST_FILE self._data = [] with open(file) as f: for line in f.readlines(): line = line.strip() arr = line.split(',') l = np.zeros(self._class_num, dtype=float) for i in xrange(1, len(arr), 1): index = int(arr[i]) l[index] = 1.0 self._data.append([arr[0], l]) np.random.shuffle(self._data) top[0].reshape(self._batch_size, 3, self._image_hight, self._image_width) top[1].reshape(self._batch_size, self._class_num) def forward(self, bottom, top): imgs_blob = [] labels_blob = [] if (self._index + self._batch_size > len(self._data)): np.random.shuffle(self._data) self._index = 0 while (len(imgs_blob) < self._batch_size): img = cv2.imread(self._data[self._index][0]) label = self._data[self._index][1] if (img is None) or (len(img) < 32) or (len(img[0]) < 32): self._index += 1 continue randint = np.random.randint(2) if randint == 1: img = img[:,::-1,:] imgs_blob.append(img_process.img_to_blob(img, self._image_hight, self._image_width)) labels_blob.append(label) self._index += 1 top[0].data[...] = np.array(imgs_blob) top[1].data[...] = np.array(labels_blob) def backward(self, top, propagate_down, bottom): pass def reshape(self, bottom, top): pass
[ "xiaogao@in66.com" ]
xiaogao@in66.com
9d5940b50bb1c85781629bf130b65cdb741c45e3
6dc72f5c7a1f802a27cbefdd62f1ac05836c5219
/PyDemo/DataAnalysisCode/matplotlibTest.py
8e4a9d085e51d88380970dabe8927a0aa02479f9
[]
no_license
RockJohnson503/MyDemo
9e4e5c7b02ee76d5437fd54c36050655fca145fb
dc1062df01cc53eb9a2a1849709d2f88e8b4488c
refs/heads/master
2022-05-13T22:45:27.051170
2020-04-24T07:32:13
2020-04-24T07:32:13
123,227,439
5
1
null
2022-04-22T21:10:48
2018-02-28T04:07:08
Jupyter Notebook
UTF-8
Python
false
false
2,958
py
# encoding: utf-8 """ File: matplotlibTest.py Author: Rock Johnson """ import numpy as np import matplotlib.pyplot as plt def main(): # Line """ x = np.linspace(-np.pi, np.pi, 256, endpoint=True) # 用numpy生成x轴的线 c, s = np.cos(x), np.sin(x) # 用numpy定义正弦和余弦 plt.figure(1) # 绘制第一个图 plt.plot(x, c, color="blue", linewidth=1.0, linestyle="--", label="COS", alpha=0.5) # 前面的是自变量, 后面的是应变量, 这个是余弦 plt.plot(x, s, color="red", label="SIN") # 这个是正弦 plt.title("COS & SIN") # 给图添加标题 ax = plt.gca() # 轴的编辑器 ax.spines["right"].set_color("none") # 隐藏轴 ax.spines["top"].set_color("none") ax.spines["left"].set_position(("data", 0)) # 将轴移动到数据域的某个点 ax.spines["bottom"].set_position(("data", 0)) ax.xaxis.set_ticks_position("bottom") # 将x轴显示的数据移到x轴的下方 框架默认就是这样的 ax.yaxis.set_ticks_position("left") # 将y轴显示的数据移到y轴的左方 plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi], [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$\pi/2$", r"$\pi$"]) plt.yticks(np.linspace(-1, 1, 5, endpoint=True)) # 设置轴的显示内容 for label in ax.get_xticklabels() + ax.get_yticklabels(): # 设置轴显示内容的样式 label.set_fontsize(12) label.set_bbox(dict(facecolor="white", edgecolor="None", alpha=0.2)) plt.legend(loc="upper left") # 设置图片的说明 plt.grid() # 设置图片的网格线 plt.axis() # 设置图片的显示范围 plt.fill_between(x, np.abs(x) < 0.5, c, c > 0.5, color="green") # 对图片进行填充 t = 1 plt.plot([t, t], [0, np.cos(t)], "y", linewidth="3") # 添加注释线 plt.annotate("cos(1)", xy=(t, np.cos(1)), xycoords="data", xytext=(+10, +13), textcoords="offset points", arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.4")) # 给注释线加描述 plt.show() # 展示图 """ # Scatter fig = plt.figure() fig.add_subplot(3, 3, 1) n = 128 X = np.random.normal(0, 1, n) Y = np.random.normal(0, 1, n) T = np.arctan2(Y, X) # 上色 plt.axes([0.025, 0.025, 0.95, 0.95]) # 设置显示范围 plt.scatter(X, Y, s=75, c=T, alpha=.5) # 画散点 plt.xlim(-1.5, 1.5), plt.xticks([]) # x的范围 plt.ylim(-1.5, 1.5), plt.yticks([]) # y的范围 plt.axis() plt.title("scatter") plt.xlabel("x") plt.ylabel("y") plt.show() def test(): x = np.linspace(-np.pi, np.pi, 256, endpoint=True) y = x/2 plt.figure(1) plt.plot(x, y) ax = plt.gca() ax.spines["top"].set_color("none") ax.spines["right"].set_color("none") ax.spines["left"].set_position(("data", 0)) ax.spines["bottom"].set_position(("data", 0)) plt.show() if __name__ == '__main__': main() pass
[ "836867547@qq.com" ]
836867547@qq.com
187474f9cc7c5845c7a05ff21704d32d32a98c2a
b5e5c37d4221242ec07808e3fb4c8af41d31cc44
/flask_blueprints/colleges_example/migrations/versions/546cf1124ce1_created_blueprints.py
f3a561ae533e0ae15a0d36c3c8a4d3e12562e293
[ "MIT" ]
permissive
yeshwindbz9/flask_crash_codes
1016b3cc1f3eeab474db1b250f903279e34abf4e
d7baf100c3ad3dd57f583fa2e524e737c5b4090a
refs/heads/main
2023-06-28T10:41:55.795560
2021-07-20T13:53:59
2021-07-20T13:53:59
387,804,719
0
0
null
null
null
null
UTF-8
Python
false
false
1,036
py
"""created blueprints Revision ID: 546cf1124ce1 Revises: Create Date: 2021-06-13 22:48:00.089076 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '546cf1124ce1' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('colleges', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Text(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('students', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Text(), nullable=True), sa.Column('clg_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['clg_id'], ['colleges.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('students') op.drop_table('colleges') # ### end Alembic commands ###
[ "64612584+yeshwindbz9@users.noreply.github.com" ]
64612584+yeshwindbz9@users.noreply.github.com
2e7e9f5be7855f4a1ce1d0e1549965cb9c9a4803
348436759194f3645c283dadbf23e55012b63eea
/test_a_voice.py
49c06b86b802e62466adc280d0f692497771a25b
[]
no_license
alexandrali3/User-Identification
4352f8019dee16daee09fcb9b38214e60ae0c4d4
0103e822bb6acc8bfb58c514600804ec82bab119
refs/heads/master
2020-03-20T18:18:26.864607
2018-06-16T13:32:09
2018-06-16T13:32:09
137,581,324
0
0
null
null
null
null
UTF-8
Python
false
false
7,238
py
# coding: utf-8 # In[1]: get_ipython().magic(u'matplotlib inline') # In[2]: import sys import numpy as np import pandas as pd import re as re import matplotlib.pyplot as plt import xgboost as xgb # In[3]: def myPrint(x): print(x.head(15)) print(x.info()) def myPrint2(x): print(x) # In[4]: test_a_voice_df = pd.read_csv('../data/Test-A/test_a_voice_df.csv', header = 0, dtype = {'opp_num':str}) # # Feature 10 # In[45]: def do(x): start_day = int(x['start_time'] % 100000000 / 1000000) start_hour = int(x['start_time'] % 1000000 / 10000) start_min = int(x['start_time'] % 10000 / 100) start_sec = int(x['start_time'] % 100) start = (start_day * 24 * 60 + start_hour * 60 + start_min) * 60 + start_sec end_day = int(x['end_time'] % 100000000 / 1000000) end_hour = int(x['end_time'] % 1000000 / 10000) end_min = int(x['end_time'] % 10000 / 100) end_sec = int(x['end_time'] % 100) end = (end_day * 24 * 60 + end_hour * 60 + end_min) * 60 + end_sec # duration in seconds return end - start + 1 def do2(x): start_day = int(x['start_time'] % 100000000 / 1000000) start_hour = int(x['start_time'] % 1000000 / 10000) start_min = int(x['start_time'] % 10000 / 100) start = start_day * 24 * 60 + start_hour * 60 + start_min end_day = int(x['end_time'] % 100000000 / 1000000) end_hour = int(x['end_time'] % 1000000 / 10000) end_min = int(x['end_time'] % 10000 / 100) end = end_day * 24 * 60 + end_hour * 60 + end_min # duration in minutes return end - start + 1 tmp = test_a_voice_df test_a_voice_df.loc[:, 'dura'] = tmp.apply(do, axis = 1) # In[46]: test_a_1 = test_a_voice_df[test_a_voice_df['in_out'] == 0] test_a_2 = test_a_voice_df[test_a_voice_df['in_out'] == 1] # In[8]: tt = test_a_1['uid'].value_counts().sort_index() # In[9]: dict = tt.to_dict() ans = pd.Series(index = range(5000, 7000), data = dict) # In[10]: ans = ans.fillna(0) ans = ans.astype('int64') # In[11]: ans.to_csv('../data/Test-A/test_a_feature_10.csv', index=True) # # Feature 11 # In[12]: tt = test_a_2['uid'].value_counts().sort_index() # In[13]: dict = tt.to_dict() ans = pd.Series(index = range(5000, 7000), data = dict) # In[14]: ans = ans.fillna(0) ans = ans.astype('int64') # In[15]: ans.to_csv('../data/Test-A/test_a_feature_11.csv', index=True) # # Feature 12 # In[38]: tt = test_a_1.groupby('uid').dura.sum() dict = tt.to_dict() ans = pd.Series(index = range(5000, 7000), data = dict) # In[39]: ans = ans.fillna(0) ans = ans.astype('int64') # In[40]: ans.to_csv('../data/Test-A/test_a_feature_12.csv', index=True) # # Feature 13 # In[41]: tt = test_a_2.groupby('uid').dura.sum() dict = tt.to_dict() ans = pd.Series(index = range(5000, 7000), data = dict) # In[42]: ans = ans.fillna(0) ans = ans.astype('int64') # In[43]: ans.to_csv('../data/Test-A/test_a_feature_13.csv', index=True) # # Feature 14 # In[23]: t1 = test_a_1['uid'].value_counts() t2 = test_a_2['uid'].value_counts() dict = t1.to_dict() tt1 = pd.Series(index = range(5000, 7000), data = dict) tt1 = tt1.fillna(0) dict = t2.to_dict() tt2 = pd.Series(index = range(5000, 7000), data = dict) tt2 = tt2.fillna(0) tt3 = tt1 / (tt1 + tt2) # In[24]: myPrint2(tt3) # In[25]: tt3 = tt3.fillna(0.5) # In[26]: tt3.to_csv('../data/Test-A/test_a_feature_14.csv', index=True) # # Feature 15 # In[27]: group = test_a_1.groupby('uid')['opp_num'] agg = group.aggregate({'opp_num': lambda x: x.nunique()}) # In[29]: agg.rename(columns=lambda x:x.replace('opp_num','opp_cnt'), inplace=True) # In[30]: dict = pd.Series(agg['opp_cnt']).to_dict() tmp = pd.Series(index = range(5000, 7000), data = dict) # In[32]: tmp = tmp.fillna(0) tmp = tmp.astype('int64') # In[33]: tmp.to_csv('../data/Test-A/test_a_feature_15.csv', index=True) # # Feature 16 # In[47]: group = test_a_1.groupby('uid')['dura'] agg = group.mean() # In[50]: dict = agg.to_dict() ans = pd.Series(index = range(5000, 7000), data = dict) # In[51]: ans = ans.fillna(0) ans = ans.astype('int64') # In[53]: ans.to_csv('../data/Test-A/test_a_feature_16.csv', index=True) # # Feature 17 # In[54]: g = test_a_1[test_a_1['dura'] <= 10] # In[55]: ans = g['uid'].value_counts() # In[56]: dict = ans.to_dict() ans2 = pd.Series(index = range(5000, 7000), data = dict) # In[57]: ans2 = ans2.fillna(0) ans2 = ans2.astype('int64') # In[58]: ans2.to_csv('../data/Test-A/test_a_feature_17.csv', index=True) # # Feature 18 # In[59]: g = test_a_1[test_a_1['opp_len'] <= 8] # In[60]: tmp = g['uid'].value_counts() tmp = tmp.sort_index() # In[61]: dict = tmp.to_dict() ans = pd.Series(index = range(5000, 7000), data = dict) # In[62]: ans = ans.fillna(0) ans = ans.astype('int64') # In[63]: ans.to_csv('../data/Test-A/test_a_feature_18.csv', index=True) # # Feature 19 # In[64]: def do(x): return int(x['start_time'] / 1000000) tmp = test_a_voice_df test_a_voice_df.loc[:, 'day'] = tmp.apply(do, axis = 1) # In[65]: test_a_1 = test_a_voice_df[test_a_voice_df['in_out'] == 0] test_a_2 = test_a_voice_df[test_a_voice_df['in_out'] == 1] # In[66]: group = test_a_1.groupby('uid') item_dict = {} for index,g in group: tmp = g['day'].value_counts() item_dict[index] = tmp.std() # In[67]: ans = pd.Series(index = range(5000, 7000), data = item_dict) # In[68]: ans = ans.fillna(0) # In[69]: ans.to_csv('../data/Test-A/test_a_feature_19.csv', index=True) # # Feature 29 to 33 # In[5]: voice_opp_num = test_a_voice_df.groupby(['uid'])['opp_num'].agg({'unique_count': lambda x: len(pd.unique(x)),'count':'count'}).add_prefix('voice_opp_num_') # In[6]: print(voice_opp_num) # # Feature 30 # In[7]: voice_opp_head=test_a_voice_df.groupby(['uid'])['opp_head'].agg({'unique_count': lambda x: len(pd.unique(x))}).add_prefix('voice_opp_head_') # In[8]: print(voice_opp_head) # # Feature 31 # In[9]: voice_opp_len=test_a_voice_df.groupby(['uid','opp_len'])['uid'].count().unstack().add_prefix('voice_opp_len_').fillna(0) # In[10]: voice_opp_len.columns.name = None # In[11]: voice_opp_len = voice_opp_len[['voice_opp_len_5', 'voice_opp_len_8', 'voice_opp_len_11', 'voice_opp_len_12']] # In[12]: print(voice_opp_len) # # Feature 32 # In[13]: voice_call_type = test_a_voice_df.groupby(['uid','call_type'])['uid'].count().unstack().add_prefix('voice_call_type_').fillna(0) # In[14]: voice_call_type.columns.name = None # # Feature 33 # In[15]: voice_in_out = test_a_voice_df.groupby(['uid','in_out'])['uid'].count().unstack().add_prefix('voice_in_out_').fillna(0) # In[16]: voice_in_out.columns.name = None # # Merge Feature 29 to 33 # In[17]: agg = voice_opp_num # In[18]: agg = agg.join(voice_opp_len) # In[19]: agg = agg.join(voice_opp_head) # In[20]: agg = agg.join(voice_call_type) # In[21]: agg = agg.join(voice_in_out) # In[25]: dict = agg.to_dict() agg2 = pd.DataFrame(index = range(5000, 7000), data = dict) # In[26]: agg2 = agg2.fillna(0) agg2 = agg2.astype('int64') # In[27]: agg2.to_csv('../data/Test-A/test_a_feature_29to33.csv', index=True, header=None)
[ "fjcyslyz@gmail.com" ]
fjcyslyz@gmail.com
8bce48d233329ce65bf3f6e60ce59314d8f51fe2
850bf848dbee72062f26f5202ab976bfb385f95c
/code/AutoRec.py
cf1a8c441f3c2abadf99e6a78942466bc4e1cc0d
[ "Apache-2.0" ]
permissive
Kaist-Master/RecSys
b90357af218c1c2c7fc541405907b8ca7d719130
2089d7cceda3a7239587239765d9095a64d4d04a
refs/heads/master
2022-12-04T23:11:40.114211
2020-08-23T03:57:08
2020-08-23T03:57:08
289,611,216
3
0
null
null
null
null
UTF-8
Python
false
false
7,500
py
""" 해당 코드는 pyTorch를 통해서 다음의 [논문](https://akmenon.github.io/papers/autorec/autorec-paper.pdf)을 구현한 코드입니다. """ import pickle import pandas as pd import numpy as np import os, sys, gc from torch.utils.data import Dataset, DataLoader import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as weight_init from torch.autograd import Variable import matplotlib.font_manager as fm fontpath = 'C:/Users/User/Anaconda3/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/NanumBarunGothic.ttf' font = fm.FontProperties(fname=fontpath, size=9).get_name() path = 'C:/Users/User/Documents/RecSys/ml-10m/ml-10M100K/' train = pd.read_csv(path + "r1.train", header=None, names=['userId','movieId','rating','Timestamp']) test = pd.read_csv(path + "r1.test", header=None, names=['userId','movieId','rating','Timestamp']) def preprocessing(df): df['movieId'] = df['userId'].astype(str).apply(lambda x: x.split('::')[1]) df['rating'] = df['userId'].astype(str).apply(lambda x: x.split('::')[2]) df['Timestamp'] = df['userId'].astype(str).apply(lambda x: x.split('::')[3]) df['userId'] = df['userId'].astype(str).apply(lambda x: x.split('::')[0]) del df['Timestamp'] df = df.astype(np.float32) return df train = preprocessing(train) test = preprocessing(test) movie = pd.concat([train, test], axis=0).reset_index(drop=True) user2idx = {} for i, l in enumerate(movie['userId'].unique()): user2idx[l] = i movie2idx = {} for i, l in enumerate(movie['movieId'].unique()): movie2idx[l] = i idx2user = {i: user for user, i in user2idx.items()} idx2movie = {i: item for item, i in movie2idx.items()} n_users, n_items = len(idx2user), len(idx2movie) movie_tr = movie.loc[0:train.shape[0]].reset_index(drop=True) movie_te = movie.loc[train.shape[0]:].reset_index(drop=True) class MovieLenseDataset(Dataset): """ MovieLense dataset.""" # Initialize your data, download, etc. def __init__(self, data, user_based): self.user_based = user_based useridx = data['useridx'] = data['userId'].apply(lambda x: user2idx[x]).values movieidx = data['movieidx'] = data['movieId'].apply(lambda x: movie2idx[x]).values rating = data['rating'].values if self.user_based: i = torch.LongTensor([useridx, movieidx]) v = torch.FloatTensor(rating) self.df = torch.sparse.FloatTensor(i, v, torch.Size([n_users, n_items])).to_dense() else: i = torch.LongTensor([movieidx, useridx]) v = torch.FloatTensor(rating) self.df = torch.sparse.FloatTensor(i, v, torch.Size([n_users, n_items])).to_dense() def __getitem__(self, index): return self.df[index] def __len__(self): return len(self.df) train_loader = DataLoader(MovieLenseDataset(movie_tr, True), batch_size=512, shuffle=True) test_loader = DataLoader(MovieLenseDataset(movie_te, True), batch_size=512, shuffle=True) class AutoEncoder(nn.Module): def __init__(self, num_users, num_movies, is_user_based=True): super().__init__() # 부모 클래스(torch.nn.Module)의 init을 불러옴 self.num_users = num_users self.num_movies = num_movies self.hidden_dim = 500 if is_user_based: # encoder_weight self.encode_w = nn.Linear(self.num_movies, self.hidden_dim, bias=True) self.decode_w = nn.Linear(self.hidden_dim, self.num_movies, bias=True) else: self.encode_w = nn.Linear(self.num_users, self.hidden_dim, bias=True) self.decode_w = nn.Linear(self.hidden_dim, self.num_users, bias=True) torch.nn.init.xavier_uniform_(self.encode_w.weight) torch.nn.init.xavier_uniform_(self.decode_w.weight) self.encoder = nn.Sequential( self.encode_w, nn.Sigmoid() ) self.decoder = nn.Sequential( self.decode_w, nn.Identity() ) def encode(self, x): x = self.encoder(x) return x def decode(self, x): x = self.decoder(x) return x def forward(self, x): return self.decode(self.encode(x)) def MSEloss(inputs, targets): mask = targets != 0 num_ratings = torch.sum(mask.float()) # 해당 주석을 제거하면 값이 0~5사이로 자동적으로 매핑됨 # 단, 실험결과 이렇게 하면 초반의 weight에 대한 학습이 잘 안되는 것 같음 # inputs = torch.clamp(inputs, min=0, max=5) criterion = nn.MSELoss(reduction='sum') return torch.sqrt(criterion(inputs * mask.float(), targets) / num_ratings) dev = torch.cuda.set_device("cuda:0") if torch.cuda.is_available() else torch.device("cpu") model = AutoEncoder(n_users, n_items, True).to(dev) # weight_decay : L2 Regularization # item-based : weight_decay=0.01 , user-based : None optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=0.00001) # learning rate def train(): model.train() train_loss = 0 for idx, train_batch in enumerate(train_loader): train_batch = train_batch.to(dev) optimizer.zero_grad() prediction = model(train_batch) loss = MSEloss(prediction, train_batch) loss.backward() train_loss += loss.item() optimizer.step() return train_loss / (idx+1) def test(): model.eval() test_loss = 0 with torch.no_grad(): for idx, test_batch in enumerate(test_loader): test_batch = test_batch.to(dev) prediction = model(test_batch) loss = MSEloss(prediction, test_batch) test_loss += loss.item() return test_loss / (idx+1) from tqdm.notebook import tqdm as tqdm_notebook nb_epochs = 100 train_losses = [] test_losses = [] for epoch in tqdm_notebook(range(0, nb_epochs)): train_loss = train() test_loss = test() if epoch % 1 == 0: print('Epoch {:4d}/{} Train Loss: {:.6f} Test Loss: {:.6f}'.format(epoch+1, nb_epochs, train_loss, test_loss)) train_losses.append(train_loss) test_losses.append(test_loss) import plotnine from plotnine import * loss_df_tr = pd.DataFrame() loss_df_tr['RMSE'] = train_losses loss_df_tr['Epoch'] = loss_df_tr.index + 1 loss_df_tr['Type'] = 'Train' loss_df_te = loss_df_tr.copy() loss_df_te['RMSE'] = test_losses loss_df_te['Epoch'] = loss_df_te.index + 1 loss_df_te['Type'] = 'Test' loss_df = pd.concat([loss_df_tr, loss_df_te], axis=0) (ggplot(data=loss_df) + geom_line(aes(x='Epoch', y='RMSE', group='Type', color='Type')) + theme_minimal() + ggtitle("AutoRec Loss with PyTorch") + labs(x="Epoch", y="RMSE") + theme(text = element_text(fontproperties=font), axis_text_x = element_text(angle=0, color='black'), axis_line=element_line(color="black"), axis_ticks=element_line(color = "grey"), figure_size=(12,6)) + scale_color_hue(l=0.5) ) # ## 실험결과 # - weight_decay에 따라서 Loss의 수렴하는 정도가 차이남 (작으면 작을 수록 점수상승이 큼) # - 동일한 파라미터여도 초기값이 무엇으로 설정되었냐에 따라서 Local optimal (0.88)을 탈출하냐 못하냐가 결정됨
[ "37744629+choco9966@users.noreply.github.com" ]
37744629+choco9966@users.noreply.github.com
81df218ebdbf7eda2d9096caf07641ec125c20f6
35aa0f20373a21f505d5812caa8d38a5de48fdd0
/drawing_board/wsgi.py
66cdb614e02ae0b114c025f01b055926461410b4
[]
no_license
RUiNtheExtinct/drawing-board
18b49c4f04a224dd34dab9807fc9ee884f01c612
6949d3ef8ee81b83a8d927aba373f6515afdc541
refs/heads/master
2023-03-19T12:11:58.151429
2021-01-19T18:15:51
2021-01-19T18:15:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
""" WSGI config for drawing_board project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'drawing_board.settings') application = get_wsgi_application()
[ "zhanto97@Zhantores-MacBook-Pro.local" ]
zhanto97@Zhantores-MacBook-Pro.local
199858b9ad674d6f94ac538db2d82a0dd171c926
15d1f1bea9c50e756ac01242861659029be92e3e
/Section10/ducks.py
0d36aa30900739430397a917117571d092cc40e0
[]
no_license
cantis/PythonCourse
45173a8f35939f03f2d0f00c66ced168188c74dd
7a86f997f9d99deaa7fd19cc40a495b950b65be3
refs/heads/master
2020-08-17T00:50:29.738311
2020-02-28T22:27:55
2020-02-28T22:27:55
215,582,219
0
0
null
null
null
null
UTF-8
Python
false
false
1,061
py
class Wing(object): def __init__(self, ratio): self.ratio = ratio def fly(self): if self.ratio > 1: print("Weee, this is fun") elif self.ratio == 1: print("This is hard work, but I'm flying") else: print("I think I'll just walk") class Duck(object): def __init__(self): self._wing = Wing(1.8) def walk(self): print("Waddle, waddle, waddle") def swim(self): print("Come on in, the water's lovely") def quack(self): print("Quack quack") def fly(self): self._wing.fly() class Penguin(object): def walk(self): print("Waddle, waddle, I waddle too") def swim(self): print("Come on in, but it's a bit chilly this far South") def quack(self): print("Are you 'ayin' a larf? I'm a penguin!") # def test_duck(duck): # duck.walk() # duck.swim() # duck.quack() if __name__ == '__main__': donald = Duck() donald.fly() # percy = Penguin() # test_duck(percy)
[ "eyoung@winnipeg.ca" ]
eyoung@winnipeg.ca
ed32e4c02cb282f7f450ab5e65bcc76a2e1045a7
6299a4095f6d51cc69e7bf26e1ac696d0b7da765
/io_unicode.py
a43b10d767457706f83cc78bb4cedd28cdb17de8
[]
no_license
xingshuiyueying/NewLearner
592b4eabc6ea3d17bcde2135506ae250f7742e67
c0e406cacd567b10083f6806f9d70ce2ee148d0b
refs/heads/master
2021-07-13T17:05:42.048123
2017-10-19T13:57:56
2017-10-19T13:57:56
107,552,051
0
0
null
2017-10-19T13:57:57
2017-10-19T13:45:05
null
UTF-8
Python
false
false
656
py
# encoding=utf-8 import io # 打开模式可以是阅读模式('r' ) ,写入模式('w' ) 和追加模式('a' ) 。 # 我们还可以选择是通过文本模式('t' ) 还是二进制模式('b' ) 来读取、写入或追加文本。 # 在默认情况下, open() 会将文件视作文本( text) 文件,并以阅读( read) 模式打开它。 f = io.open("abc.txt", "wt", encoding="utf-8") f.write(u"Imagine non-English language here") f.close() text = io.open("abc.txt", encoding="utf-8").read() print(text) print(u'hello world') print(type(u'hello world')) # 以上都是Python2下面的写法,所有字符串前面带u
[ "noreply@github.com" ]
noreply@github.com
d0b6568b123647b509018e6d384314d73e68e422
387ed9a5a7e8427d95a6b18c0901bf24f05c2342
/Charpter1.网络扫描与信息收集/Scapy_ARP请求代码.py
aa15800911ac00d735dc1af3ee453e77e7cdef36
[]
no_license
fat39/Kali_Hacker
efa101ec7407f55457a682c9abb290d8d52d2615
aad0a920cf317645e00c5f4c5e41218380d7930b
refs/heads/master
2020-03-21T11:09:01.832035
2018-06-24T15:11:49
2018-06-24T15:11:49
138,491,806
1
0
null
null
null
null
UTF-8
Python
false
false
1,870
py
#!/usr/bin/python3 # -*- coding=utf-8 -*- import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR)#清除报错 from scapy.all import * from GET_IP_IFCONFIG import get_ip_address_ifconfig #获取本机IP地址 from GET_MAC import get_mac_address #获取本机MAC地址 def arp_request(ip_address, ifname = 'eth0'): #获取本机IP地址 localip = get_ip_address_ifconfig(ifname)['ip_address'] #获取本机MAC地址 localmac = get_mac_address(ifname) try:#发送ARP请求并等待响应 result_raw = srp(Ether(src=localmac, dst='FF:FF:FF:FF:FF:FF')/\ ARP(op=1, \ hwsrc=localmac, hwdst='00:00:00:00:00:00', \ psrc=localip, pdst=ip_address),\ iface = ifname, \ timeout = 1,\ verbose = False) #把响应的数据包对,产生为清单 result_list = result_raw[0].res #[0]第一组响应数据包 #[1]接受到的包,[0]为发送的数据包 #获取ARP头部字段中的['hwsrc']字段,作为返回值返回 return ip_address,result_list[0][1].getlayer(ARP).fields['hwsrc'] except IndexError: return ip_address,None if __name__ == "__main__": from optparse import OptionParser usage = "usage: ./scapy_arp_request ipaddress -i interface" version = "version 1.0" parser = OptionParser(usage=usage,version=version) parser.add_option("-i", "--interface", dest="iface",help="Specify an interface", default='ens160', type="string") (options, args) = parser.parse_args() if arp_request(args[0], options.iface)[1]: print(args[0]+' 的MAC地址为: '+arp_request(args[0], options.iface)[1]) else: print('请确认主机:'+args[0]+' 是否存在')
[ "fat39@163.com" ]
fat39@163.com
afce78ee6775b66c45f63079b9f5005c73737504
694fd7b88754ab8890ad47b9a472c7fedc92fde7
/flask1.py
8b59ec3a8f74c895fc0cd385266e6593893855ef
[]
no_license
ent1k1377/stat_vk_flask
5b15d237d5326acba380b5d43bfe024d89a53da6
9a5206a73d4fe4b3d6636d804fd28a235e5f4324
refs/heads/master
2022-12-18T12:11:40.077885
2020-09-21T17:41:09
2020-09-21T17:41:09
255,080,366
0
0
null
null
null
null
UTF-8
Python
false
false
424
py
from flask import Flask, render_template from main import main, auth_handler app = Flask(__name__) app.config['SECRET_KEY'] = 'yandexlyceum_secret_key' @app.route('/') @app.route('/index') def index(): stat = main() actv = stat[0] ages = stat[1] city = stat[2] return render_template('base.html', actv=actv, ages=ages, city=city) if __name__ == '__main__': app.run(port=8080, host='127.0.0.1')
[ "ent1k1337@yandex.ru" ]
ent1k1337@yandex.ru
60e3220f12616d371c602c53ea446a45cbf5549b
96c3b1d27970d7a852ec6334c36ac2c04b531d22
/old/kasokudo_py2.py
28bfcb5f9537d76253f85386bd8e0f671b257e36
[ "MIT" ]
permissive
chigakucat/Seismograph
a6d43a7d9bfbbf4e03a77222a88a985c1e0043b9
a179c9d7b9c39e03f63ea5faa8b7478f5c678129
refs/heads/master
2023-04-08T12:45:54.462256
2023-03-16T09:18:06
2023-03-16T09:18:06
238,935,847
1
0
MIT
2022-04-18T09:43:53
2020-02-07T13:57:21
Python
UTF-8
Python
false
false
2,018
py
# -*- coding: utf-8 -*- import time import datetime import math import socket import spidev import os import sys # FPS制御 ----- # ターゲットFPS target_fps = 200 start_time = time.time() frame = 0 # SPIセンサ制御 ----- spi = spidev.SpiDev() #spi.open(bus、device) spi.open(0,0) spi.max_speed_hz = 1000*1000 def ReadChannel(channel): adc = spi.xfer2([(0x07 if (channel & 0x04) else 0x06), (channel & 0x03) << 6, 0]) data = ((adc[1] & 0x0f) << 8 ) | adc[2] return data # 加速度データ制御 ----- # A/Dコンバータ値 -> ガル値 係数 ad2gal = 1.13426 # 0.3秒空間数 a_frame = int(target_fps * 0.3) # 地震データ ----- adc_values = [[1] * target_fps, [1] * target_fps, [1] * target_fps] rc_values = [0, 0, 0] a_values = [0] * target_fps * 5 adc_ring_index = 0 a_ring_index = 0 while True: # リングバッファ位置計算 adc_ring_index = (adc_ring_index + 1) % target_fps a_ring_index = (a_ring_index + 1) % (target_fps * 5) # 3軸サンプリング for i in range(3): val = ReadChannel(i) adc_values[i][adc_ring_index] = val # フィルタ適用及び加速度変換 axis_gals = [0, 0, 0] for i in range(3): offset = sum(adc_values[i])/len(adc_values[i]) rc_values[i] = rc_values[i]*0.94+adc_values[i][adc_ring_index]*0.06 axis_gals[i] = (rc_values[i] - offset) * ad2gal if frame % (target_fps / 10) == 0: print(datetime.datetime.now(), "acceleration:" , axis_gals[0], axis_gals[1], axis_gals[2], "frame:", frame) # 次フレームの開始時間を計算 frame += 1 next_frame_time = frame / target_fps # 残時間を計算し、スリープ current_time = time.time() remain_time = next_frame_time - (current_time - start_time) if remain_time > 0: time.sleep(remain_time) # フレーム数は32bit long値の上限あたりでリセットしておく if frame >= 10000: start_time = current_time frame = 1
[ "noreply@github.com" ]
noreply@github.com
a964bd4169bb3261d5073b82773caf0f4bdbcde1
0b65b45d4b529f5505271185705cbedb8d0722cc
/django_base/common.py
0208fabd4ce5f9315428fa6217b96fc4841f040f
[]
no_license
alaalqadi/django_base
f6f2dbdf1f5b5202e2abde16d1f42bb88376d5da
d8b0eb798d0ba8341fd3f4e48144f4ee230513c3
refs/heads/master
2020-12-30T19:10:48.992272
2015-12-16T00:31:19
2015-12-16T00:31:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,118
py
""" Django settings for django_base project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=%2h+%ebz(7*y6)i8eoycf*ej)3-+tps1e8noajd_%9jvqlc^u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] # 3rd party INSTALLED_APPS += [ 'pipeline', 'djangobower', ] # my apps INSTALLED_APPS += [ "main", ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'pipeline.middleware.MinifyHTMLMiddleware', ] ROOT_URLCONF = 'django_base.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_base.wsgi.application' # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', 'djangobower.finders.BowerFinder', ) PIPELINE_CSS = { 'theme': { 'source_filenames': ( 'common.css', 'bootstrap-bower/css/bootstrap-theme.min.css', 'bootstrap-bower/css/bootstrap.min.css', ), 'output_filename': 'css/theme.css', 'extra_context': { 'media': 'screen,projection', }, }, } PIPELINE_JS = { 'theme': { 'source_filenames': ( 'jquery/dist/jquery.min.js', 'bootstrap-bower/js/bootstrap.min.js', ), 'output_filename': 'js/theme.js', } } BOWER_COMPONENTS_ROOT = BASE_DIR + '/components/' BOWER_PATH = '/usr/bin/bower' BOWER_INSTALLED_APPS = ( 'jquery', 'bower-bootstrap', )
[ "a.bazadough@sit-mena.com" ]
a.bazadough@sit-mena.com
6baecec635bf967fa145e7d86f368f87fea7756f
fb6e49665488de0db22e6cde43cc1ada94be3783
/t.py
004a6e8793f8e916b248f552900b3f53ab5e6e2a
[]
no_license
sjffsgafksagfhfggas/tel
d3c02bf57316123754fb00dcd40223162a604f28
a1ced45e56016df93ff0df696d964d4ad9f44770
refs/heads/main
2023-01-11T12:17:05.918112
2020-11-14T16:21:55
2020-11-14T16:21:55
312,600,082
0
0
null
null
null
null
UTF-8
Python
false
false
411
py
import requests import time url = 'https://persian-follower.000webhostapp.com/tel/online.php' s = requests.session() headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'} r = s.get(url, headers=headers) while True: print(r) time.sleep(10) s.get('https://persian-follower.000webhostapp.com/tel/online.php')
[ "noreply@github.com" ]
noreply@github.com
b35dfd51e5226ddc5f657b7ab3840b643ee5244d
b310e5088348af07396a9e65b377d8d80b26ea99
/temperature_conv.py
20c2f33ad3d17b596d71c5435762ec018aef3bd6
[]
no_license
rajeshvermadav/XI_2020
adc14c0829662539ebf376267fc105712beef640
9ba6d0afa7bd8af49bf31ed647840976080e419e
refs/heads/master
2023-01-19T09:52:04.691236
2020-11-23T14:35:18
2020-11-23T14:35:18
287,901,794
0
0
null
null
null
null
UTF-8
Python
false
false
147
py
#Convert Celsius to Fahrenheit cel = float(input("Enter temperature in Celsius:-")) f = (cel*9/5)+32 print("Temperature in Fahrenheit is :-", f)
[ "noreply@github.com" ]
noreply@github.com
1fa8944113bfb629cb7489f5c1d4834c35d30a65
58b05de781d26f436aaeaa44cb8fb31478574883
/emp_project/employees/migrations/0004_auto_20200503_1936.py
6a1300273140cb86d0c68efc5838d6cd4bb6ed49
[]
no_license
levyEstrabillo/employee-todo-app
fdec07cd5f527ffb9e817fb54c376d0aa9893562
25aa2b3ad442b0c0ff8c2f8640f2683b6fdac56c
refs/heads/master
2022-07-01T11:02:50.430042
2020-05-10T02:02:59
2020-05-10T02:02:59
262,693,216
0
0
null
null
null
null
UTF-8
Python
false
false
410
py
# Generated by Django 3.0.2 on 2020-05-03 11:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('employees', '0003_auto_20200503_1935'), ] operations = [ migrations.AlterField( model_name='employeeinfo', name='thumb', field=models.ImageField(blank=True, upload_to='media'), ), ]
[ "levy.estrabillo58@gmail.com" ]
levy.estrabillo58@gmail.com
527591750afea831b3278161d06180013dbcdebb
d995b07b2653884b0254890d80f77e8af9b71041
/mysite/news/apps.py
5e687201cea2cf9f24b10bc2023dfb83770f5a98
[]
no_license
Axl-M/Django_News-Blog
d2a6a449e8be2f61b03dcc6050773cc817913214
d3001567e249e129b6ed8a37d2fce599fa8234df
refs/heads/main
2023-03-30T05:06:03.947738
2021-04-03T04:29:03
2021-04-03T04:29:03
354,167,917
0
0
null
null
null
null
UTF-8
Python
false
false
132
py
from django.apps import AppConfig class NewsConfig(AppConfig): name = 'news' verbose_name = 'Мои новости'
[ "noreply@github.com" ]
noreply@github.com
014a8aab3305226f095b71f76e73bfc13dc1caa5
eb61d62ca1f6f0123e3771105f5dfbbd6115138d
/.history/19-07-21_20210905224104.py
016085b1d34f5ea2a80953238ca45e9068b0410c
[]
no_license
Alopezm5/CORRECTO-2
e0f14bcc3a88c0e222d10e3261e68532008bc42e
223613f1fb04dce3fac9f82f243cb2f22fe100f3
refs/heads/main
2023-07-29T06:52:48.147424
2021-09-12T20:33:27
2021-09-12T20:33:27
388,995,308
0
0
null
null
null
null
UTF-8
Python
false
false
2,222
py
class MENU (): def __init__(self,titulo,opciones=[]): self.titulo = titulo self.opciones = opciones def menu(self): print(self.titulo) for opcion in self.opciones: print(opcion) opc=input("Elije opcion [1 ..... {}]:".formato(len(self.opciones))) return opc menu1=MENU("Menú Principal" , ["1)Calculadora","2)Numeros","3)Listas","4)Cadenas","5)Salir"]) opc=menu1.menu() if opc=="1": menu1=MENU("Menú Calculadora",["1)Suma","2)Resta","3)Multiplicacion" , "4) División" , "5) Salir" ]) opc1=menu1.menu() if opc1 == "1" : print("Opcion Suma") n1=int(input("Ingresar n1: ")) n2=int(input("Ingresar n2: ")) suma=n1+n2 print("{} + {} = {}".format( n1 , n2 , suma )) elif opc1 == "2" : print ( "Opcion Resta" ) n1 = int ( input ( "Ingresar n1:" )) n2 = int ( input ( "Ingresar n2:" )) resta = n1 - n2 print ( "{} - {} = {}".format ( n1 , n2 , resta )) elif opc1 == "3" : print ( "Opcion Multiplicacion" ) n1 = int ( input ( "Ingresar n1:" )) n2 = int ( input ( "Ingresar n2:" )) multiplicacion = n1 * n2 print ( "{} * {} = {}" . formato ( n1 , n2 , multiplicacion )) elif opc1 == "4" : print ( "Opcion Division" ) n1 = int ( input ( "Ingresar n1:" )) n2 = int ( input ( "Ingresar n2:" )) division = n1 / n2 print ( "{} / {} = {}" . formato ( n1 , n2 , division )) elif opc1 == "5" : print ( "Opcion Salir" ) elif opc == "2" : menu2 = MENU ( "Menú Numero" , [ "1) Perfecto" , "2) Primo" , "3) Salir" ]) opc2 = input ( "Elije opcion [1 ..... 3]:" ) elif opc == "3" : print ( "Listas de menú" ) elif opc == "4" : print ( "Menú Cadenas" ) elif opc == "5" : print ( "Menú Salir" ) else: print ( "Opcion no valida" )
[ "85761855+Alopezm5@users.noreply.github.com" ]
85761855+Alopezm5@users.noreply.github.com
0b701c732d9ec6fcdb9862d7c4c3919ff3e5e7c8
761e3ede4c8eb6ecb08f635cb56303e26a6681c7
/resnet.py
2da7db8dc57d107601adcf3c9f3073187691738a
[ "MIT" ]
permissive
zhaobinNF/PSPNet
09be6a329ffad6f352f486c2a7f5d337d7a78e46
8e37762679a9e19fa9ac7adab4b8f5e3bcf1d09d
refs/heads/master
2022-12-06T20:44:51.154156
2020-09-01T11:28:10
2020-09-01T11:28:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
14,715
py
import torch import torch.nn as nn import torch.nn.functional as F import os import urllib.request as urllib from tqdm import tqdm model_urls = { 'resnet50': {'url': "https://download.pytorch.org/models/resnet50-19c8e357.pth", 'id': 'resnet50-19c8e357.pth'}, 'resnet101': {'url': "https://download.pytorch.org/models/resnet101-5d3b4d8f.pth", 'id': 'resnet101-5d3b4d8f.pth'} } # Reference # https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py # model_urls = { # 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', # 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', # 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', # 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', # 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', # 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth', # 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth', # 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth', # 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth', # } class DownloadProgressBar(tqdm): def update_to(self, b=1, bsize=1, tsize=None): if tsize is not None: self.total = tsize self.update(b * bsize - self.n) def download_model(url, id): download_url = './weight' if not os.path.isdir(download_url): os.mkdir(download_url) if not os.path.isfile(os.path.join(download_url, id)): with DownloadProgressBar(unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1]) as t: urllib.urlretrieve(url, filename=os.path.join(download_url, id), reporthook=t.update_to) else: print('Already download') state_dict = torch.load(os.path.join(download_url, id)) return state_dict def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(BasicBlock, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d if groups != 1 or base_width != 64: raise ValueError('BasicBlock only supports groups=1 and base_width=64') if dilation > 1: raise NotImplementedError("Dilation > 1 not supported in BasicBlock") # Both self.conv1 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = norm_layer(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes) self.bn2 = norm_layer(planes) self.downsample = downsample self.stride = stride def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out class Bottleneck(nn.Module): # Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2) # while original implementation places the stride at the first 1x1 convolution(self.conv1) # according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385. # This variant is also known as ResNet V1.5 and improves accuracy according to # https://ngc.nvidia.com/catalog/model-scripts/nvidia:resnet_50_v1_5_for_pytorch. expansion = 4 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(Bottleneck, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d width = int(planes * (base_width / 64.)) * groups # Both self.conv2 and self.downsample layers downsample the input when stride != 1 self.conv1 = conv1x1(inplanes, width) self.bn1 = norm_layer(width) self.conv2 = conv3x3(width, width, stride, groups, dilation) self.bn2 = norm_layer(width) self.conv3 = conv1x1(width, planes * self.expansion) self.bn3 = norm_layer(planes * self.expansion) self.relu = nn.ReLU(inplace=True) self.downsample = downsample self.stride = stride def forward(self, x): identity = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) out = self.relu(out) out = self.conv3(out) out = self.bn3(out) if self.downsample is not None: identity = self.downsample(x) out += identity out = self.relu(out) return out class ResNet(nn.Module): def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None): super(ResNet, self).__init__() if norm_layer is None: norm_layer = nn.BatchNorm2d self._norm_layer = norm_layer self.inplanes = 64 self.dilation = 1 if replace_stride_with_dilation is None: # each element in the tuple indicates if we should replace # the 2x2 stride with a dilated convolution instead replace_stride_with_dilation = [False, False, False] if len(replace_stride_with_dilation) != 3: raise ValueError("replace_stride_with_dilation should be None " "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) self.groups = groups self.base_width = width_per_group self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, bias=False) self.bn1 = norm_layer(self.inplanes) self.relu = nn.ReLU(inplace=True) self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) self.layer1 = self._make_layer(block, 64, layers[0]) self.layer2 = self._make_layer(block, 128, layers[1], stride=2) self.layer3 = self._make_layer(block, 256, layers[2], stride=1, dilation=2) self.layer4 = self._make_layer(block, 512, layers[3], stride=1, dilation=4) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) # Zero-initialize the last BN in each residual branch, # so that the residual branch starts with zeros, and each residual block behaves like an identity. # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 if zero_init_residual: for m in self.modules(): if isinstance(m, Bottleneck): nn.init.constant_(m.bn3.weight, 0) elif isinstance(m, BasicBlock): nn.init.constant_(m.bn2.weight, 0) def _make_layer(self, block, planes, blocks, stride=1, dilation=1): norm_layer = self._norm_layer downsample = None # previous_dilation = self.dilation # if dilate: # self.dilation *= stride # stride = 1 if stride != 1 or self.inplanes != planes * block.expansion: downsample = nn.Sequential( conv1x1(self.inplanes, planes * block.expansion, stride), norm_layer(planes * block.expansion), ) layers = [] layers.append(block(self.inplanes, planes, stride, downsample)) self.inplanes = planes * block.expansion for _ in range(1, blocks): layers.append(block(self.inplanes, planes, groups=self.groups, base_width=self.base_width, dilation=dilation, norm_layer=norm_layer)) return nn.Sequential(*layers) def _forward_impl(self, x): # See note [TorchScript super()] x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.maxpool(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.fc(x) return x def forward(self, x): return self._forward_impl(x) def _resnet(arch, block, layers, pretrained, progress, **kwargs): model = ResNet(block, layers, **kwargs) if pretrained: state_dict = download_model(model_urls[arch]['url'], model_urls[arch]['id']) model.load_state_dict(state_dict) return model def resnet18(pretrained=False, progress=True, **kwargs): r"""ResNet-18 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, **kwargs) def resnet34(pretrained=False, progress=True, **kwargs): r"""ResNet-34 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, **kwargs) def resnet50(pretrained=False, progress=True, **kwargs): r"""ResNet-50 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs) def resnet101(pretrained=False, progress=True, **kwargs): r"""ResNet-101 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs) def resnet152(pretrained=False, progress=True, **kwargs): r"""ResNet-152 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, **kwargs) def resnext50_32x4d(pretrained=False, progress=True, **kwargs): r"""ResNeXt-50 32x4d model from `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ kwargs['groups'] = 32 kwargs['width_per_group'] = 4 return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs) def resnext101_32x8d(pretrained=False, progress=True, **kwargs): r"""ResNeXt-101 32x8d model from `"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ kwargs['groups'] = 32 kwargs['width_per_group'] = 8 return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs) def wide_resnet50_2(pretrained=False, progress=True, **kwargs): r"""Wide ResNet-50-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_ The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 channels, and in Wide ResNet-50-2 has 2048-1024-2048. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ kwargs['width_per_group'] = 64 * 2 return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs) def wide_resnet101_2(pretrained=False, progress=True, **kwargs): r"""Wide ResNet-101-2 model from `"Wide Residual Networks" <https://arxiv.org/pdf/1605.07146.pdf>`_ The model is the same as ResNet except for the bottleneck number of channels which is twice larger in every block. The number of channels in outer 1x1 convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 channels, and in Wide ResNet-50-2 has 2048-1024-2048. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ kwargs['width_per_group'] = 64 * 2 return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3], pretrained, progress, **kwargs)
[ "leaderj1001@gmail.com" ]
leaderj1001@gmail.com
a703462fda9bdaeb385543eac5df408a92a07cc6
0f58400f5e489eb3492e92409ca39a6435ca5dc3
/auth/views.py
3e39ac26aba96cede5bfbc407d8fa3e436d216f6
[]
no_license
vovdl/recipe
e603e3a0f121898c441d2d3ce1a6dc5d1c4c5079
80a8510e33a1a2642dce243a528ad90e80a7675d
refs/heads/master
2020-03-07T22:06:20.049408
2018-04-02T11:33:03
2018-04-02T11:33:03
127,745,007
0
0
null
null
null
null
UTF-8
Python
false
false
2,264
py
import json from time import time import aiohttp_jinja2 from aiohttp import web from aiohttp_session import get_session from auth.models import User def redirect(request, router_name): url = request.app.router[router_name].url() raise web.HTTPFound(url) def set_session(session, user_id, request): session['user'] = str(user_id) session['last_visit'] = time() redirect(request, 'main') def convert_json(message): return json.dumps({'error': message}) class Login(web.View): @aiohttp_jinja2.template('auth/login.html') async def get(self): session = await get_session(self.request) print(session) if session.get('user'): redirect(self.request, 'main') return {'content': 'Please enter login or email'} async def post(self): data = await self.request.post() print(str(data)) user = User(data) result = await user.check_user() if 'id' in result: print('Сессия ' + result['id']) session = await get_session(self.request) print(session) await set_session(session, str(result['id']), self.request) else: return web.Response(content_type='application/json', text=json.dumps(result)) class SignUp(web.View): @aiohttp_jinja2.template('auth/signup.html') async def get(self, **kw): session = await get_session(self.request) if session.get('user'): redirect(self.request, 'main') return {'content': 'Please enter your data'} async def post(self, **kw): data = await self.request.post() print(str(data)) user = User(data) result = await user.create_user() if 'id' in result: session = await get_session(self.request) set_session(session, str(result), self.request) else: return web.Response(content_type='application/json', text=convert_json(result)) class SignOut(web.View): async def get(self, **kw): session = await get_session(self.request) if session.get('user'): del session['user'] redirect(self.request, 'login') else: raise web.HTTPForbidden(body=b'Forbidden')
[ "vovdl18@gmail.com" ]
vovdl18@gmail.com
aa4b51c030f7c0c9e8572f498c6745abb8292658
5323e193bbbe46b6c0904737c595a4c0add0f5fa
/questions3.py
02413c9f19409a37e7af29f26cacdf16aed5227f
[]
no_license
Pidgens/crackingcode
177c7a1b1d66729716237bd71d53170a51f25ee1
99bb08261b975d99c095369795bdc7bf19553e45
refs/heads/master
2020-12-24T07:53:35.678531
2016-08-09T23:04:35
2016-08-09T23:04:35
41,328,682
0
0
null
null
null
null
UTF-8
Python
false
false
3,120
py
#################################################################### #################################################################### #################################################################### import ll t1 = True t2 = False t3 = False def deleteMiddleNodeLinkedList(middle_node): nextData = middle_node.getNext().getData() nextNext = middle_node.getNext.getNext() middle_node.setData(nextData) middle_node.setNext(nextNext) if t1: linkedList = ll.LinkedList() linkedList.insert(1) linkedList.insert(2) linkedList.insert(3) linkedList.insert(4) linkedList.insert(5) print linkedList.head.getNext().getNext().getData() def partitionLinkedListX(head_node , x): beforeStart = None afterStart = None while head_node != None: print 'head_node', head_node.getData() next = head_node.getNext() if head_node.getData() < x: head_node.setNext(beforeStart) beforeStart = head_node else: head_node.setNext(afterStart) afterStart = head_node head_node = next if beforeStart == None: return afterStart head = beforeStart while beforeStart.getNext() != None: beforeStart = beforeStart.getNext() beforeStart.setNext(afterStart) return head if t2: linkedList = ll.LinkedList() linkedList.insert(5) linkedList.insert(4) linkedList.insert(2) linkedList.insert(1) linkedList.insert(3) # print linkedList.head.getData() linkedList = partitionLinkedListX(linkedList.head, 3) print '#:', linkedList.getData() print '1:', linkedList.getNext().getData() print '2:', linkedList.getNext().getNext().getData() print '3:', linkedList.getNext().getNext().getNext().getData() print '3:', linkedList.getNext().getNext().getNext().getNext().getData() def addTwoLinkedList(l1, l2): l1Pointer = l1.head l2Pointer = l2.head sumLL = ll.LinkedList() currentCarry = 0 nextCarry = 0 if l1.size() > l2.size(): # pad 0s while l2.size() < l1.size(): l2.insert(0) if l1.size() < l2.size(): while l2.size() > l1.size(): l1.insert(0) while l1Pointer != None: cur_sum = l1Pointer.getData() + l2Pointer.getData() if cur_sum >= 10: cur_sum = cur_sum % 10 nextCarry = 1 else: nextCarry = 0 sumLL.insert(carry + cur_sum) l1Pointer = l1Pointer.getNext() l2Pointer = l2Pointer.getNext() return sumLL if t3: linkedList = ll.LinkedList() linkedList.insert(1) print 'HEAD1:', linkedList.head.getData() linkedList.insert(3) print 'HEAD2:', linkedList.head.getData() linkedList.insert(7) print 'HEAD3:', linkedList.head.getData() linkedList2 = ll.LinkedList() linkedList2.insert(5) linkedList2.insert(6) linkedList2.insert(4) sum_ll = addTwoLinkedList(linkedList, linkedList2) print sum_ll.head.getData() print sum_ll.head.getNext().getData() print sum_ll.head.getNext().getNext().getData()
[ "dederekchiu@berkeley.edu" ]
dederekchiu@berkeley.edu
3fd8ab1f668b0d8a569b3ba61119bad8f0731db0
31b05ac1d1a0658d41b3a37fa22803032890491c
/pragati/read.py
4daa810f0cd9ba354789056c09b0f9b09f44f449
[]
no_license
pragatimagar/personal
811d0dfe0a0154be090ddaecdf13779f947185be
c2513dde846d64b34691161e18dfbe0b3bf4c007
refs/heads/master
2023-08-20T05:16:02.931435
2021-10-12T06:59:19
2021-10-12T06:59:19
398,735,703
0
0
null
null
null
null
UTF-8
Python
false
false
133
py
f = open('sample.txt') data = f.readline() print(data) data = f.readline() print(data) data = f.readline() print(data) f.close()
[ "pragatimagar28sep@gmail.com" ]
pragatimagar28sep@gmail.com
6821dd97ae86fe803b6cbd0fd537924cbb40832c
67b9cc8dce21e3ebb2654beff15c3564109eb84d
/app/modelviews.py
850a32a31482a62157d0497e167ad7ed01d40b45
[]
no_license
mikekutzma/fyodor
4e8014fb1e192bcd43b013f075e5773970381d8c
5f32160f759e9a0fce96c70e5444f57f6351d27d
refs/heads/master
2023-08-10T14:44:15.716157
2023-05-24T19:57:02
2023-05-24T19:57:02
237,362,877
1
0
null
2023-07-20T13:14:48
2020-01-31T04:54:54
JavaScript
UTF-8
Python
false
false
501
py
from flask_admin import AdminIndexView from flask_admin.contrib.sqla import ModelView from flask_login import current_user class AdminModelView(ModelView): column_exclude_list = ["password_hash", "api_key"] column_editable_list = ["is_approved"] def is_accessible(self): return current_user.is_authenticated and current_user.is_admin class AdminIndexViewLock(AdminIndexView): def is_accessible(self): return current_user.is_authenticated and current_user.is_admin
[ "michaelkutzma@gmail.com" ]
michaelkutzma@gmail.com
f9c0d63812fdae71748924c3aa6603eb056a331e
94a1b2d95f6e36e6892e79c89b306cbb54501839
/code/testcases/advectreact_analytical_MC_PLOT.py
20fbaa49e53a661c07c8d6f4e5be611d66c7be37
[ "MIT" ]
permissive
josephbakarji/learning-pdf
010c00983a64c54e531b31db667e1634125b5c8c
12ec54635322d627089b14802082590a86872f3e
refs/heads/master
2021-07-05T14:42:49.373363
2021-05-25T22:02:04
2021-05-25T22:02:04
239,627,436
0
0
null
null
null
null
UTF-8
Python
false
false
3,002
py
from __init__ import * import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) from data_analysis import Analyze from mc2pdf import MCprocessing from datamanage import DataIO from montecarlo import MonteCarlo from analytical_solutions import AnalyticalSolution, gaussian from mc2pdf import MCprocessing from pdfsolver import PdfGrid from visualization import Visualize from Learning import PDElearn from helper_functions import latexify_varcoef import numpy as np import pdb import time files = [ 'advection_reaction_analytical_635_16_173.txt', 'advection_reaction_analytical_635_709_751.txt', 'advection_reaction_analytical_635_909_800.txt', 'advection_reaction_analytical_635_273_371.txt', 'advection_reaction_analytical_635_856_118.txt', 'advection_reaction_analytical_635_353_126.txt', 'advection_reaction_analytical_635_687_958.txt', 'advection_reaction_analytical_635_874_445.txt', 'advection_reaction_analytical_635_8_582.txt', 'advection_reaction_analytical_635_195_766.txt' ] case = '_'.join(files[0].split('_')[:-3]) print(case) # GET LEARNING DATA output_vec = [] metadata_vec = [] MCcount_vec = [] D = DataIO(case=case, directory=LEARNDIR) D2 = DataIO(case=case, directory=PDFDIR) for i, f in enumerate(files): output, metadata = D.readLearningResults(f) output_vec.append(output) metadata_vec.append(metadata) gridvars, ICparams = D2.loadSolution('_'.join(f.split('_')[:-1])+'.npy', metaonly=True) print(ICparams) MCcount_vec.append(ICparams['MCcount']) A = Analyze() savename = 'advectreact_MC' + "_" + "PLOT" variable = MCcount_vec threshold = 0.05 invert_sign = True cdf = False # A.plotRMSEandCoefs(output_vec, MCcount_vec, , threshold=0.05, invert_sign=True, use_logx=False, set_grid=True, savename=savename) fig, ax = plt.subplots(1, 2, figsize=(13, 5.5)) trainRMSE, testRMSE = A.getTrainTestDependence(output_vec) linestyles = ['solid', 'dashed', 'dashdot', 'dotted'] marker = ['o', 'v', 's', '*']#, '^', '>', '<', 'x', 'D', '1', '.', '2', '3', '4'] styles = [[l, m] for l in linestyles for m in marker] mse = [min(out['alpha_mse_path']) for out in output_vec] ax[0].plot(variable, testRMSE, '.-', linewidth=3, markersize=8) # ax[0].plot(variable, mse, '*-', linewidth=3, markersize=8) ax[0].set_xlabel('$N_{MC}$, Number of Realizations', fontsize=14) ax[0].set_ylabel('RMSE on $\mathcal D_\t{test}$', fontsize=14) # ax[0].legend(['Test Error', 'MSE']) # Coefficients Dependence Multi featarray, relevant_feats = A.getCoefDependence(output_vec, threshold=threshold, invert_sign=invert_sign) for i in range(len(relevant_feats)): ax[1].plot(variable, featarray[:, i], linestyle=styles[i][0], marker=styles[i][1], linewidth=2.5, markersize=7) ax[1].set_xlabel('$N_{MC}$, Number of Realizations', fontsize=14) ax[1].set_ylabel('Coefficients', fontsize=14) leg = ax[1].legend(latexify_varcoef(relevant_feats, cdf=cdf), bbox_to_anchor=(1,1), fontsize=14) leg.get_frame().set_linewidth(0.0) plt.show() fig.savefig(FIGDIR+savename+'.pdf')
[ "josephbakarji@gmail.com" ]
josephbakarji@gmail.com
55a852eeaeb901d55c44ca536f1252719a8088a2
4edf5c9393ed71248026aff9557792b2f1bad05c
/manifold/transformers/smooth_pearson.py
99507b8579adb3c08611026c4bb531f0a503d9e4
[]
no_license
xxasifxx/manifold-rl
5c41ff72ee773d26ce029d08b1dc890205e82b72
366ecea2c74be8982498a1127fda6f8190dbf2f4
refs/heads/master
2020-12-08T22:40:30.694848
2020-01-10T18:33:45
2020-01-10T18:33:45
233,115,183
2
0
null
2020-01-10T19:20:02
2020-01-10T19:20:01
null
UTF-8
Python
false
false
1,800
py
import uuid import creme import creme.stats from manifold.base_types import Transformer class SmoothPearsonTransformer(Transformer): def __init__(self, window=20, **kwargs) -> None: super().__init__() rolling_window = kwargs.get("mean_window", None) if rolling_window is None: rolling_window = window pearson_window = kwargs.get("pearson_window", None) if pearson_window is None: pearson_window = window self.transformed = {} # This is basically a pipeline. We can put pipelines inside of it to self.proceedure = [ {"name": "rolling_mean", "transformation": creme.stats.RollingMean(window_size=rolling_window), "is_xy": False}, {"name": "pearson", "transformation": creme.stats.AutoCorrelation(lag=pearson_window), "is_xy": False} ] self._procedure_check() def process(self, variable, transformation_id:str): transformed_data = self.transformed.get(transformation_id, {"transformers": {}, "index": 0, "history": {}}) self._all_procedures(variable, transformed_data, transformation_id) def _get_final_transformed(self, transformation_id): if len(self.proceedure) == 0: raise AttributeError("You don't have any proceedure steps") transformed = self.transformed.get(f"{transformation_id}", {}) if len(transformed.keys()) == 0: return 0.0 last_step = self.proceedure[-1] last_name = last_step.get("name") last_item = transformed["transformers"].get(last_name) return last_item.get() def step(self, variable, model_id=uuid.uuid4().hex): self.process(variable, model_id) return self._get_final_transformed(model_id)
[ "funguanainc@gmail.com" ]
funguanainc@gmail.com
795506467416cd08d0abe7dcb6647249fe597fa3
b7002e04caa55e2422f537604018361ccb49db37
/lesson4_task3.py
3abbd11b08c3ae60f2d818bda9b0f2f9394ea055
[]
no_license
trumpumpumpum/ITEA_py
a10d0716d60ce7edaa3a842e5d88e3b19d5f3456
d55e70c24f9e99c3ffe0f25a20e4dd42109e4ade
refs/heads/master
2022-08-26T01:17:20.988744
2020-05-26T19:30:43
2020-05-26T19:30:43
259,420,815
0
0
null
null
null
null
UTF-8
Python
false
false
280
py
from collections import Counter my_list = (input('Введите последовательность: ')) def function (x): return x[1] sublist, count = max(Counter(tuple(sorted(x)) for x in my_list).items(), key=function) print('%s - %d' % (list(sublist), count))
[ "noreply@github.com" ]
noreply@github.com
b777223f076ace65e55bd0c622a6919bce5bd167
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/m9bcZKy4niMmsg3JX_24.py
53034914b39b9e5514126b1c339d6d3218688fbc
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
637
py
""" A group of friends have decided to start a secret society. The name will be the first letter of each of their names, sorted in alphabetical order. Create a function that takes in a list of names and returns the name of the secret society. ### Examples society_name(["Adam", "Sarah", "Malcolm"]) ➞ "AMS" society_name(["Harry", "Newt", "Luna", "Cho"]) ➞ "CHLN" society_name(["Phoebe", "Chandler", "Rachel", "Ross", "Monica", "Joey"]) ➞ "CJMPRR" ### Notes The secret society's name should be entirely uppercased. """ def society_name(friends): return ('').join(sorted([x[0] for x in friends]))
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
f971b7cb4264b307272b78014e5745b41ec49a78
fe4247267a21b4d76bbf3ec3ea560453b93b4c88
/testroutes.py
d868b0a86ccaf63e60509e99950b08de3e05616e
[]
no_license
dudmel/Flask
0b5715a3256117f584a3405e2e5240647a837495
f048c2547aff34774e143107a5fd034a8d13e956
refs/heads/master
2021-01-11T18:05:22.871050
2017-01-19T20:02:54
2017-01-19T20:02:54
79,489,626
0
0
null
null
null
null
UTF-8
Python
false
false
7,161
py
""" Routes for the flask application. DEV!! DEV!! DEV!! DEV!! """ from FlaskServer import app from flask import jsonify, request from flask_jwt import JWT, jwt_required, current_identity from Dev import mockedDataRequest import consts as consts from Routes.Alignment import * from Routes.Alignment.alignmnetmockup import * from Routes.Operations import * from Routes.Operations.spectrum import * from Routes.Operations.licenseactivation import * from Routes.Operations.softwareupgrade import * from Routes.Debug import * ########################################## Alignment URLS ############################################ @app.route(consts.ALIGNMNET_MEASURING_URL, methods=['GET', 'POST']) def alignmentroute(): return jsonify(alignmentMockup(request)) # copy this two functions for every get or post @app.route(consts.ALIGNMNET_BEST_POSITION_URL, methods=['GET', 'POST']) def bestpositionroute(): return jsonify(bestpositionMockup(request)) @app.route(consts.ALIGNMNET_POINTER_LOCATION_URL, methods=['GET', 'POST']) def pointerlocationroute(): return jsonify(pointerlocationMockup(request)) @app.route(consts.ALIGNMNET_FINE_ALIGNMNET_URL, methods=['GET']) def fineAligmentRoute(): return jsonify(fineAligmentMockup(request)) @app.route(consts.ALIGNMNET_ACTION_URL + '/<action>', methods=['POST']) def actionRoutAct(action): return jsonify(alignmentActionInvokerMockup(action, request)) @app.route(consts.DEREGISTER_URL, methods=['POST']) def deregister_local_route(): return jsonify(deregisterMockup(request)) # added for simulation @app.route(consts.ALIGNMNET_GET_ALL_BANDS_URL, methods=['GET']) def alignmentGetAllBandsRoute(): return jsonify(getAllBandsMockup(request)) @app.route(consts.ALIGNMNET_SET_BANDS_URL, methods=['POST']) def alignmentSetBandRoute(): return jsonify(setBandMockup(request)) #Alignment Simulator Only @app.route(consts.ALIGNMNET_RESET_TEST_DATA_URL, methods=['POST']) def resetData_route(): return jsonify(resetTestDataMockup(request)) @app.route(consts.ALIGNMNET_GENERATE_ID_URL, methods=['POST']) def generateIdroute(): return jsonify(generateIdMockup(request)) @app.route(consts.ALIGNMNET_INIT_VALUES, methods=['GET']) def initValuesRoute(): return jsonify(getInitialValuesMockup(request)) @app.route(consts.ALIGNMNET_LINK_DATA, methods=['GET']) def linkDataRoute(): return jsonify(getLinkDataMockup(request)) ##################################### Link Evaluation URLS ###################################### # /api/v1/alignment/evaluation/<action> @app.route(consts.ALIGNMNET_LINK_EVAL_URL + '/<action>', methods=['POST']) def getEvaluationResultsRoute(action): return jsonify(startEvaluationMockup(action, request)) @app.route(consts.ALIGNMNET_EVAL_RESULTS_URL, methods=['GET']) def evaluationResults(): return jsonify(getEvaluationResultsMockup(request)) ########################################## Data URLS ############################################ #Monitor @app.route(consts.MONITOR_URL, methods=['GET']) #@jwt_required() def monitor_route(): return jsonify(mockedDataRequest(request, 'monitor')) #System @app.route(consts.SYSTEM_URL, methods=['GET', 'POST']) #@jwt_required() def system_route(): return jsonify(mockedDataRequest(request, 'system')) @app.route(consts.RADIO_URL, methods=['GET', 'POST']) #@jwt_required() def radio_route(): return jsonify(mockedDataRequest(request, 'radio')) @app.route(consts.NETWORK_URL, methods=['GET', 'POST']) #@jwt_required() def network_route(): return jsonify(mockedDataRequest(request, 'network')) @app.route(consts.RECENT_EVENTS_URL) #@jwt_required() def recentevents_route(): return jsonify(mockedDataRequest(request, 'recent-events')) @app.route(consts.ACTIVE_ALARMS_URL, methods=['GET']) #@jwt_required() def activealarmsroute(): return jsonify(mockedDataRequest(request, 'active-alarms')) #Traps Destinations @app.route(consts.TRAPS_DESTINATIONS_URL, methods=['GET', 'POST']) #@jwt_required() def trapsroute(): return jsonify(mockedDataRequest(request, 'traps-destinations')) @app.route(consts.WIFI_URL, methods=['GET', 'POST']) #@jwt_required() def wifiroute(): return jsonify(mockedDataRequest(request, 'wifi')) ########################################## Operations URLS ############################################ @app.route(consts.PING_URL, methods=['POST']) #@jwt_required() def ping_route(): return jsonify(ping(request)) @app.route(consts.TRACE_URL, methods=['POST']) #@jwt_required() def trace_route(): return jsonify(trace(request)) @app.route(consts.RESET_URL, methods=['POST']) #@jwt_required() def reset_route(): return jsonify(odu_reset()) @app.route(consts.RESYNC_URL, methods=['POST']) #@jwt_required() def resync_route(): return jsonify(resync()) @app.route(consts.CHANGE_BAND_URL, methods=['GET', 'POST']) #@jwt_required() def changeband_route(): return jsonify(mockedDataRequest(request, 'change-band')) @app.route(consts.SWU_UPLOAD_URL, methods=['POST']) #@jwt_required() def swuuploadroute(): return jsonify(swu_upload_route(request)) @app.route(consts.SWU_VALIDATE_URL, methods=['GET']) #@jwt_required() def swuvalidateroute(): return jsonify(swu_validate_route(request)) @app.route(consts.SWU_START_URL, methods=['POST']) #@jwt_required() def swustartroute(): return jsonify(swu_start_route(request)) @app.route(consts.SWU_BACKUP_URL, methods=['GET']) #@jwt_required() def swubackuproute(): return swu_start_backup(request) @app.route(consts.SPEED_TEST_URL, methods=['GET','POST']) #@jwt_required() def speedtestroute(): return jsonify(mockedDataRequest(request, 'speedtest')) @app.route('/api/v1/operations/speed-test/stop', methods=['POST']) #@jwt_required() def speedtestroutestop(): return jsonify(mockedDataRequest(request, 'speedtest')) @app.route(consts.SPECTRUM_RANGE_URL, methods=['GET']) #@jwt_required() def spectrumrangeroute(): return jsonify(mockedDataRequest(request, 'spectrum-range')) @app.route(consts.START_SPECTRUM_URL, methods=['POST']) #@jwt_required() def spectrumstartroute(): return jsonify(mockedDataRequest(request, 'spectrum-start')) @app.route(consts.STOP_SPECTRUM_URL, methods=['POST']) #@jwt_required() def spectrumstoproute(): return jsonify(mockedDataRequest(request, 'spectrum-stop')) @app.route(consts.SPECTRUM_TABLE_URL, methods=['GET']) #@jwt_required() def spectrumtableroute(): return jsonify(mockedDataRequest(request, 'spectrum-table')) @app.route(consts.LICENSE_ACTIVATION_URL, methods=['GET', 'POST']) #@jwt_required() def activatelicenseroute(): return jsonify(license_activation(request)) @app.route(consts.DIAGNOSTICS_URL, methods=['GET']) #@jwt_required() def diagnostics(): return get_diagnostics(request) @app.route(consts.CHANGE_LINK_PASSWORD, methods=['POST']) #@jwt_required() def changelinkpasswordroute(): return jsonify(change_link_password(request)) ########################################## Debug URLS ############################################ @app.route(consts.DEBUG_LOG_URL, methods=['GET']) def debuglogroute(): return debug_log_route() @app.route(consts.DEBUG_ATTRIBUTE_URL, methods=['GET', 'POST']) def debugattributeurl(): return jsonify(debug_attribute_route(request))
[ "dudu@misterbit.co.il" ]
dudu@misterbit.co.il
470029f0f4c61c538c098d0ae1782a8c73ebdda8
dc865cfa6d7d0d9d11af1b0ddc2f8a82f148af0f
/main.py
687a0cb2449763c1d21b52dd67b1ac5fb527143a
[ "MIT" ]
permissive
gnovaro/python-audio-transcription
75072b17ebbe3a7cd4f48b823ee25f1cbe69f4b1
328ba6b8ef7d8fa7432399cd8621814696bd302e
refs/heads/main
2023-02-08T07:02:14.318234
2020-12-30T14:41:27
2020-12-30T14:41:27
325,573,102
0
0
null
null
null
null
UTF-8
Python
false
false
1,099
py
# Python audio transcription from audio file import speech_recognition as sr import sys from os import path from pydub import AudioSegment import sphinxbase import pocketsphinx from pprint import pprint # if __name__ == '__main__': try: arg = sys.argv[1] except IndexError: raise SystemExit(f"Usage: {sys.argv[0]} <audio_file>") audio_file = sys.argv[1] sound = AudioSegment.from_mp3(audio_file) sound.export("transcript.wav", format="wav") # transcribe audio file AUDIO_FILE = "transcript.wav" # use the audio file as the audio source r = sr.Recognizer() with sr.AudioFile(AUDIO_FILE) as source: audio = r.record(source) # read the entire audio file # recognize speech using Sphinx try: result = r.recognize_sphinx(audio) pprint(result) #print("Sphinx thinks you said: " + ) except sr.UnknownValueError: print("Sphinx could not understand audio") except sr.RequestError as e: print("Sphinx error; {0}".format(e)) #print("Transcription: " + r.recognize_google(audio))
[ "gnovaro@gmail.com" ]
gnovaro@gmail.com
3d3d447d47cf4de951fd26d005eab160fee57292
2baad3d7ac8df92ac7669bc5226b295f6e572109
/openstack/horizon-mitaka/openstack_dashboard/dashboards/admin/networks/subnets/tests.py
7fc01c9ac5f3a691c3aa99508ff482236d4349f6
[ "Apache-2.0" ]
permissive
naanal/reference
649d61110c0200718de186012466183c35071399
e5401ab6d185f9879da4b7fd20dead4823d662cc
refs/heads/master
2020-04-12T07:33:59.989760
2016-12-21T12:26:30
2016-12-21T12:26:30
57,004,495
0
0
null
null
null
null
UTF-8
Python
false
false
13,953
py
# Copyright 2012 NEC Corporation # Copyright 2015 Cisco Systems, 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. from django.core.urlresolvers import reverse from django import http from mox3.mox import IsA # noqa from horizon.workflows import views from openstack_dashboard import api from openstack_dashboard.dashboards.project.networks import tests from openstack_dashboard.test import helpers as test DETAIL_URL = 'horizon:admin:networks:subnets:detail' NETWORKS_INDEX_URL = reverse('horizon:admin:networks:index') NETWORKS_DETAIL_URL = 'horizon:admin:networks:detail' class NetworkSubnetTests(test.BaseAdminViewTests): @test.create_stubs({api.neutron: ('network_get', 'subnet_get',)}) def test_subnet_detail(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .MultipleTimes().AndReturn(network) api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) self.mox.ReplayAll() url = reverse(DETAIL_URL, args=[subnet.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'horizon/common/_detail.html') self.assertEqual(res.context['subnet'].id, subnet.id) @test.create_stubs({api.neutron: ('subnet_get',)}) def test_subnet_detail_exception(self): subnet = self.subnets.first() api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() url = reverse(DETAIL_URL, args=[subnet.id]) res = self.client.get(url) redir_url = NETWORKS_INDEX_URL self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get',)}) def test_subnet_create_get(self): network = self.networks.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) self.mox.ReplayAll() url = reverse('horizon:admin:networks:addsubnet', args=[network.id]) res = self.client.get(url) self.assertTemplateUsed(res, views.WorkflowView.template_name) @test.create_stubs({api.neutron: ('network_get', 'subnet_create',)}) def test_subnet_create_post(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.subnet_create(IsA(http.HttpRequest), network_id=network.id, name=subnet.name, cidr=subnet.cidr, ip_version=subnet.ip_version, gateway_ip=subnet.gateway_ip, enable_dhcp=subnet.enable_dhcp, allocation_pools=subnet.allocation_pools, tenant_id=subnet.tenant_id)\ .AndReturn(subnet) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse(NETWORKS_DETAIL_URL, args=[subnet.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'subnet_create',)}) def test_subnet_create_post_network_exception(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) # admin DetailView is shared with userpanel one, so # redirection URL on error is userpanel index. redir_url = reverse('horizon:project:networks:index') self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'subnet_create',)}) def test_subnet_create_post_subnet_exception(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.subnet_create(IsA(http.HttpRequest), network_id=network.id, name=subnet.name, cidr=subnet.cidr, ip_version=subnet.ip_version, gateway_ip=subnet.gateway_ip, enable_dhcp=subnet.enable_dhcp, tenant_id=subnet.tenant_id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) redir_url = reverse(NETWORKS_DETAIL_URL, args=[subnet.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get',)}) def test_subnet_create_post_cidr_inconsistent(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) self.mox.ReplayAll() # dummy IPv6 address cidr = '2001:0DB8:0:CD30:123:4567:89AB:CDEF/60' form_data = tests.form_data_subnet( subnet, cidr=cidr, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) expected_msg = 'Network Address and IP version are inconsistent.' self.assertContains(res, expected_msg) @test.create_stubs({api.neutron: ('network_get',)}) def test_subnet_create_post_gw_inconsistent(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) self.mox.ReplayAll() # dummy IPv6 address gateway_ip = '2001:0DB8:0:CD30:123:4567:89AB:CDEF' form_data = tests.form_data_subnet(subnet, gateway_ip=gateway_ip, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) self.assertContains(res, 'Gateway IP and IP version are inconsistent.') @test.create_stubs({api.neutron: ('subnet_update', 'subnet_get',)}) def test_subnet_update_post(self): subnet = self.subnets.first() api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) api.neutron.subnet_update(IsA(http.HttpRequest), subnet.id, name=subnet.name, enable_dhcp=subnet.enable_dhcp, dns_nameservers=[], host_routes=[])\ .AndReturn(subnet) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet, allocation_pools=[]) url = reverse('horizon:admin:networks:editsubnet', args=[subnet.network_id, subnet.id]) res = self.client.post(url, form_data) redir_url = reverse(NETWORKS_DETAIL_URL, args=[subnet.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('subnet_update', 'subnet_get',)}) def test_subnet_update_post_gw_inconsistent(self): subnet = self.subnets.first() api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) self.mox.ReplayAll() # dummy IPv6 address gateway_ip = '2001:0DB8:0:CD30:123:4567:89AB:CDEF' form_data = tests.form_data_subnet(subnet, gateway_ip=gateway_ip, allocation_pools=[]) url = reverse('horizon:admin:networks:editsubnet', args=[subnet.network_id, subnet.id]) res = self.client.post(url, form_data) self.assertContains(res, 'Gateway IP and IP version are inconsistent.') @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete(self): self._test_subnet_delete() @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete_with_mac_learning(self): self._test_subnet_delete(mac_learning=True) def _test_subnet_delete(self, mac_learning=False): subnet = self.subnets.first() network_id = subnet.network_id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.subnet_delete(IsA(http.HttpRequest), subnet.id) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'subnets__delete__%s' % subnet.id} url = reverse(NETWORKS_DETAIL_URL, args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete_exception(self): self._test_subnet_delete_exception() @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete_exception_with_mac_learning(self): self._test_subnet_delete_exception(mac_learning=True) def _test_subnet_delete_exception(self, mac_learning=False): subnet = self.subnets.first() network_id = subnet.network_id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.subnet_delete(IsA(http.HttpRequest), subnet.id)\ .AndRaise(self.exceptions.neutron) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'subnets__delete__%s' % subnet.id} url = reverse(NETWORKS_DETAIL_URL, args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url)
[ "rajagopalx@gmail.com" ]
rajagopalx@gmail.com
88d084a5e639c06765a2703e2fe746e1bdda29b8
5fa1b6503dde1e46f56245496d263e60a96884f7
/products/migrations/0008_auto_20200120_0634.py
91af1015a2795d0e416c9870fd247c0248b72766
[]
no_license
AlexeyGarmash/test-api
ab2100d69399c49df82a75ca134cbc28f8c15b01
6feea95baff0aa9c7956edd244767b27cd52f8b5
refs/heads/master
2022-12-10T02:31:49.567737
2020-01-21T17:10:20
2020-01-21T17:10:20
235,076,658
0
0
null
2022-12-08T03:28:43
2020-01-20T10:34:09
JavaScript
UTF-8
Python
false
false
494
py
# Generated by Django 3.0.2 on 2020-01-20 04:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0007_comment_photo'), ] operations = [ migrations.RemoveField( model_name='comment', name='photo', ), migrations.AddField( model_name='product', name='photo', field=models.ImageField(null=True, upload_to=''), ), ]
[ "i.republic2014@gmail.com" ]
i.republic2014@gmail.com
24d57aa224c97de21b2deb7be132ea3fdbf88ba2
1f1704af13eececeec48cd5300910386f1849639
/src/partial_testing.py
211c61a72d01aee52d6f7a49e1840cf468563ed1
[]
no_license
michaelmathen/Kernel_Paper
40787fc8add1574365ec4ad30d45011f77b2e630
9cf513e0a69a04a0df336e62a695accce5c1b0dd
refs/heads/master
2020-05-25T17:36:51.873810
2019-06-20T21:12:03
2019-06-20T21:12:03
187,912,240
0
0
null
null
null
null
UTF-8
Python
false
false
13,940
py
import csv import numpy as np import time import pyscan import random import matplotlib.pyplot as plt import math from scipy.special import erfinv import Mapping def sqr_dist(pt, center): return (pt[0] - center[0]) ** 2 + (pt[1] - center[1]) ** 2 def kernel(pt, center, bandwidth): return math.exp(- sqr_dist(pt, center) / bandwidth ** 2) """ A number of different distance measurements that can be useful for comparing the similarity of the anomalies. """ def Kl_divergence(pts, bandwidth, planted, found): divergence = 0 p_total = 0 q_total = 0 for pt in pts: P_x = kernel(pt, planted, bandwidth) Q_x = kernel(pt, found, bandwidth) p_total += P_x q_total += Q_x for pt in pts: try: P_x = kernel(pt, planted, bandwidth) / p_total Q_x = kernel(pt, found, bandwidth) / q_total if P_x > np.finfo(float).eps and Q_x > np.finfo(float).eps: divergence += P_x * math.log( P_x / Q_x) except ZeroDivisionError: continue return divergence def l2_dist(pts, bandwidth, planted, found): dist_sqr = 0 for pt in pts: P_x = kernel(pt, planted, bandwidth) Q_x = kernel(pt, found, bandwidth) dist_sqr += (P_x - Q_x) ** 2 return math.sqrt(dist_sqr) def angular_dist(pts, bandwidth, planted, found): inner_prod = 0 p_sum = 0 q_sum = 0 for pt in pts: P_x = kernel(pt, planted, bandwidth) Q_x = kernel(pt, found, bandwidth) inner_prod += P_x * Q_x p_sum += P_x * P_x q_sum += Q_x * Q_x if q_sum == 0 or p_sum == 0: return 0.0 return inner_prod / (math.sqrt(p_sum) * math.sqrt(q_sum)) def extended_jc(pts, bandwidth, planted, found): inner_prod = 0 p_sum = 0 q_sum = 0 for pt in pts: P_x = kernel(pt, planted, bandwidth) Q_x = kernel(pt, found, bandwidth) inner_prod += P_x * Q_x p_sum += P_x * P_x q_sum += Q_x * Q_x return inner_prod / (p_sum + q_sum - inner_prod) def run_power_test(actual_mx, disc, red, blue, n, s, annuli, count, two_level_sample): r_frac = len(red) b_frac = len(blue) power_count = 0 for _ in range(count): pts = red + blue random.shuffle(pts) new_red = pts[:r_frac] new_blue = pts[b_frac:] m_sample = pyscan.my_sample(new_red, s) b_sample = pyscan.my_sample(new_blue, s) if two_level_sample: net_set1 = pyscan.my_sample(m_sample, n) net_set2 = pyscan.my_sample(b_sample, n) else: net_set1 = m_sample net_set2 = b_sample n = s net_set = net_set1 + net_set2 m_sample = pyscan.to_weighted(m_sample) b_sample = pyscan.to_weighted(b_sample) reg, mx = pyscan.max_annuli_scale(net_set, m_sample, b_sample, annuli, disc) if mx > actual_mx: power_count += 1 return power_count / count def testing_partial_framework( pts, output_file, l_s, h_s, count, r=.04, p=0.8, q=.5, annuli_eps=.1, two_level_sample = True, algorithm="annuli", statistic="k", power_test=None, max_time=None, seed =None, planted_reg=None): if seed is not None: random.seed(a=seed) else: seed = random.randint(0, 10000000) random.seed(a=seed) #seed = 9704595 if planted_reg is None: red, blue, bandwidth, center_pt = pyscan.plant_kernel_disk_region(pts, r, p, q) else: red, blue, bandwidth, center_pt = planted_reg bernoulli_sample = [(pt, 1) for pt in red] + [(pt, 0) for pt in blue] print(bandwidth, center_pt) actual_mx = pyscan.disc_bernoulli_kern(red, blue, p, q, bandwidth, center_pt) try: with open(output_file, "r") as fh: exists = True except FileNotFoundError: exists = False with open(output_file, 'a+') as f: writer = None for i in np.logspace(l_s, h_s, count): eps = i n = 1 / eps s = 1 / (2 * eps * eps) n = int(round(n) + .1) s = int(round(s) + .1) start_time = time.time() if statistic == "bs": baseline_sample = pyscan.my_sample(bernoulli_sample, s) m_sample = [pt for (pt, id) in baseline_sample if id] b_sample = [pt for (pt, _) in baseline_sample] print(len(m_sample)) print(len(baseline_sample)) print("here") else: m_sample = pyscan.my_sample(red, s) b_sample = pyscan.my_sample(blue, s) if two_level_sample: net_set1 = pyscan.my_sample(m_sample, n) net_set2 = pyscan.my_sample(b_sample, n) else: net_set1 = m_sample net_set2 = b_sample n = s net_set = net_set1 + net_set2 m_sample = pyscan.to_weighted(m_sample) b_sample = pyscan.to_weighted(b_sample) # kern = pyscan.gaussian_kernel(bandwidth) # disc = pyscan.Bernoulli_K(kern) r_g = bandwidth * math.sqrt(math.e) * eps * 5 disk_r = bandwidth * math.sqrt(math.log(1 / eps)) if algorithm == "kernel": reg, mx = pyscan.max_kernel_slow(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel2": reg, mx = pyscan.max_kernel_slow2(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel_adaptive": reg, mx = pyscan.max_kernel_adaptive(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel_prune": disk_r = bandwidth * math.sqrt(math.log((len(m_sample) + len(b_sample)) / eps)) reg, mx = pyscan.max_kernel_prune_far(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel_fast": reg, mx = pyscan.max_kernel(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "combinatorial" or "satscan" in algorithm: if statistic == "k": disc_f = pyscan.RKULLDORF elif statistic == "b": disc_f = pyscan.bernoulli(0) elif statistic == "bs": disc_f = pyscan.rbernoulli(eps * .0001) #disc_f = pyscan.bernoulli(len(red), len(blue), eps / 2) elif statistic == "d": disc_f = pyscan.DISC if algorithm == "combinatorial": reg, mx = pyscan.max_disk(net_set, m_sample, b_sample, disc_f) elif algorithm == "satscan_grid": reg, mx = pyscan.satscan_grid(m_sample, b_sample, r_g, disk_r, disc_f) elif algorithm == "satscan_points": reg, mx = pyscan.satscan_points(m_sample, b_sample, disc_f) end_time = time.time() print("Finished this run.") print(reg, mx) (p_m, q_m, mx) = pyscan.measure_kernel(reg.get_origin(), pyscan.to_weighted(red), pyscan.to_weighted(blue), bandwidth) if power_test is not None: power = run_power_test(mx, disc, red, blue, n, s, annuli, power_test, two_level_sample) else: power = None # r_g = bandwidth * math.sqrt(math.e) * eps * 5 # disk_r = bandwidth * math.sqrt(math.log((len(m_sample) + len(b_sample)) / eps)) # centers = pyscan.kernel_centers(m_sample, b_sample, r_g, disk_r, bandwidth) # # fig, ax = plt.subplots(figsize=(20,20)) # # bx = Mapping.get_bx(pts) # #ax, _ = Mapping.map_trajectories([], [], bx) # pyscan.plot_points(ax, m_sample, "r") # pyscan.plot_points(ax, b_sample, "b") # #pyscan.plot_points(ax, net_set, "k") # #pyscan.plot_kernel(ax, pts, center_pt, bandwidth, res=50) # #pyscan.plot_points(ax, centers, "k") # print(reg.get_origin()) # pyscan.plot_kernel(ax, pts, reg.get_origin(), bandwidth, res=50) # plt.axis('off') # plt.show() #kl_val = Kl_divergence(pts, bandwidth, center_pt, reg.get_origin()) kl_val = 0 print("Finished kl div") l2 = l2_dist(pts, bandwidth, center_pt, reg.get_origin()) print("Finished l2") angle = 0#angular_dist(pts, bandwidth, center_pt, reg.get_origin()) print("Finished Angle") ejc = extended_jc(pts, bandwidth, center_pt, reg.get_origin()) print("Finished EJC") row = {"disc": "bernoulli", "n": n, "s": s, "r": r, "q": q, "p":p, "p_m": p_m, "q_m": q_m, "time": end_time - start_time, "m_disc_approx": mx, "m_disc": actual_mx, "center_distance": reg.get_origin().dist(center_pt), "kl_div": kl_val, "l2_dist": l2, "angular_dist": angle, "jc": ejc, "power": power, "bandwidth": bandwidth, "seed": seed} if writer is None: writer = csv.DictWriter(f, fieldnames=list(row.keys())) if not exists: writer.writeheader() writer.writerow(row) print("Run time {}".format(time.time() - start_time)) print(row) f.flush() if max_time is not None and end_time - start_time > max_time: return def testing_bandwidth_framework( pts, output_file, l_s, h_s, count, r=.04, p=0.8, q=.5, eps=.02, annuli_eps=.1, two_level_sample = True, algorithm="annuli", statistic="k", power_test=None, max_time=None, seed =None): if seed is not None: random.seed(a=seed) else: seed = random.randint(0, 10000000) random.seed(a=seed) #seed = 9704595 red, blue, bandwidth_orig, center_pt = pyscan.plant_kernel_disk_region(pts, r, p, q) actual_mx = pyscan.disc_bernoulli_kern(red, blue, p, q, bandwidth_orig, center_pt) try: with open(output_file, "r") as fh: exists = True except FileNotFoundError: exists = False with open(output_file, 'a+') as f: writer = None for i in np.logspace(l_s, h_s, count): n = 1 / eps s = 1 / (2 * eps * eps) n = int(round(n) + .1) s = int(round(s) + .1) print(i) bandwidth = bandwidth_orig * i start_time = time.time() m_sample = pyscan.my_sample(red, s) b_sample = pyscan.my_sample(blue, s) if two_level_sample: net_set1 = pyscan.my_sample(m_sample, n) net_set2 = pyscan.my_sample(b_sample, n) else: net_set1 = m_sample net_set2 = b_sample n = s net_set = net_set1 + net_set2 m_sample = pyscan.to_weighted(m_sample) b_sample = pyscan.to_weighted(b_sample) # kern = pyscan.gaussian_kernel(bandwidth) # disc = pyscan.Bernoulli_K(kern) r_g = bandwidth * math.sqrt(math.e) * eps * 5 disk_r = bandwidth * math.sqrt(math.log(1 / eps)) if algorithm == "kernel": reg, mx = pyscan.max_kernel_slow(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel2": reg, mx = pyscan.max_kernel_slow2(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel_adaptive": reg, mx = pyscan.max_kernel_adaptive(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel_prune": disk_r = bandwidth * math.sqrt(math.log((len(m_sample) + len(b_sample)) / eps)) reg, mx = pyscan.max_kernel_prune_far(m_sample, b_sample, r_g, disk_r, bandwidth) elif algorithm == "kernel_fast": reg, mx = pyscan.max_kernel(m_sample, b_sample, r_g, disk_r, bandwidth) end_time = time.time() print(reg, mx) (p_m, q_m, mx) = pyscan.measure_kernel(reg.get_origin(), pyscan.to_weighted(red), pyscan.to_weighted(blue), bandwidth_orig) row = {"disc": "bernoulli", "n": n, "s": s, "r": r, "q": q, "p":p, "p_m": p_m, "q_m": q_m, "time": end_time - start_time, "m_disc_approx": mx, "m_disc": actual_mx, "center_distance": reg.get_origin().dist(center_pt), "kl_div": Kl_divergence(pts, bandwidth_orig, center_pt, reg.get_origin()), "l2_dist": l2_dist(pts, bandwidth_orig, center_pt, reg.get_origin()), "angular_dist": angular_dist(pts, bandwidth_orig, center_pt, reg.get_origin()), "jc": extended_jc(pts, bandwidth_orig, center_pt, reg.get_origin()), "power": None, "bandwidth": bandwidth_orig, "seed": seed, "scale": i} if writer is None: writer = csv.DictWriter(f, fieldnames=list(row.keys())) if not exists: writer.writeheader() writer.writerow(row) print(row) f.flush() if max_time is not None and end_time - start_time > max_time: return
[ "michaelmathen@gmail.com" ]
michaelmathen@gmail.com
eecca24a0adcd29352d7af9f0f13143148db787d
bcc2eadf72d0c2a38e595f973ad4840ac038bd53
/Valid Palindrome.py
f674e38ffc21634991493803e1287fdb53981cfe
[]
no_license
jke-zq/myleetcode.py
5841cec144884bcef9f0adadbb10dbe4ed34963f
e0f032f34f7fa8fa4f6e5af65c60b3fe581fdc23
refs/heads/master
2020-04-03T23:24:39.657299
2016-09-18T14:35:25
2016-09-18T14:35:25
49,498,500
4
0
null
null
null
null
UTF-8
Python
false
false
523
py
class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() == s[right].lower(): left, right = left + 1, right - 1 else: return False return True
[ "jke0zq@gmail.com" ]
jke0zq@gmail.com
3e49bd42d62f972de0165d6b58cb355f27bb58d7
decce6355fc5573056e1464e0d860d5393bd0bd9
/archive/scraper.py
c7877e871a8b5e1c5d07066501fa1ed235b0cb46
[]
no_license
coolstoryjoe/used_cars
e64f4f952432b61677bea6d85b249700c8caaa94
fe9476ae68ac272f1703775b48730bc41b98384a
refs/heads/master
2023-02-26T00:06:47.520692
2021-01-31T18:32:55
2021-01-31T18:32:55
334,579,782
0
0
null
null
null
null
UTF-8
Python
false
false
2,167
py
from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq import pandas as pd import matplotlib.pyplot as plt from sqlalchemy import create_engine from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from webdriver_manager.chrome import ChromeDriverManager def parse(url): uClient = uReq(url) url_soup = soup(uClient.read(), "html.parser") uClient.close() return(url_soup) def pull_url(url): chrome_driver_path = '/Users/josepholeynik/Coding/Python/used_cars/chromedriver' chrome_options = Options() chrome_options.add_argument('--headless') user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36' chrome_options.add_argument('user-agent={0}'.format(user_agent)) webdriverC = webdriver.Chrome(executable_path = chrome_driver_path, options = chrome_options) #webdriverC = webdriver.Chrome(ChromeDriverManager().install())#, options = chrome_options) with webdriverC as driver: #wait = WebDriverWait(driver, 20)#.until(EC.presence_of_element_located((By.CLASS_NAME, "first-price"))) #element = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'first-price'))) wait = WebDriverWait(driver, 30) driver.implicitly_wait(10) driver.get(url) wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME,'first-price'))) #results = driver.find_element_by_class_name('first-price').text quotesoup = soup(driver.page_source, features="lxml") driver.close() #redsoup = (quotesoup.find('span',{'class':'first-price'}).text) return(quotesoup) # AutoTrader.com AUTOTRADE = 'https://www.autotrader.com/cars-for-sale/all-cars?zip=90401&makeCodeList=TOYOTA&modelCodeList=TACOMA' print(pull_url(AUTOTRADE)) # CarsDirect.com # Hemmings.com # Autolist.com # CarGurus.com # AutoTempest.com # KBB.com (Kelley Blue Book) # Cars & Bids
[ "josepholeynik@Josephs-MacBook-Pro.local" ]
josepholeynik@Josephs-MacBook-Pro.local
d42bb7243da4d8b4e2ecee6adc37f84734b86402
0c0b5a384ab533f809fcf8f20cd0d4d6f410db44
/sublime-text-3/Backup/20160824124035/LaTeXTools/latex_cite_completions.py
e7314e46f5396793957a2bc72c92c4844822f549
[]
no_license
jordlynn/.files
1a4708289b40480585ab485775026924935f1ec2
a371e19160a3fecb35b4446d3f3ab6e31609ba6e
refs/heads/master
2021-06-11T07:59:49.753728
2017-02-14T10:08:37
2017-02-14T10:08:37
50,607,631
0
0
null
null
null
null
UTF-8
Python
false
false
20,559
py
''' This module implements the cite-completion behaviour, largely by relying on implementations registered with latextools_plugin and configured using the `bibliograph_plugins` configuration key. At present, there is one supported method on custom plugins. `get_entries`: This method should take a sequence of bib_files and return a sequence of Mapping-like objects where the key corresponds to a Bib(La)TeX key and returns the matching value. We provide default fallbacks for any of the quick panel formatting options that might not be automatically mapped to a field, e.g., `author_short`, etc. or to deal with missing data, e.g. entries that have no `journal` but use the `journaltitle` field. Plugins can override this behaviour, however, by explicitly setting a value for whatever key they like. ''' # ST2/ST3 compat from __future__ import print_function import sublime if sublime.version() < '3000': # we are on ST2 and Python 2.X _ST3 = False import getTeXRoot from kpsewhich import kpsewhich from latextools_utils.is_tex_file import is_tex_file, get_tex_extensions from latextools_utils import bibformat, get_setting from latextools_utils.internal_types import FillAllHelper import latextools_plugin # reraise implementation from 6 exec("""def reraise(tp, value, tb=None): raise tp, value, tb """) strbase = basestring else: _ST3 = True from . import getTeXRoot from .kpsewhich import kpsewhich from .latex_fill_all import FillAllHelper from .latextools_utils.is_tex_file import is_tex_file, get_tex_extensions from .latextools_utils import bibformat, get_setting from . import latextools_plugin # reraise implementation from 6 def reraise(tp, value, tb=None): if value is None: value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value strbase = str import os import sys import re import codecs from string import Formatter import collections import traceback class NoBibFilesError(Exception): pass class BibParsingError(Exception): def __init__(self, filename=""): self.filename = filename class BibPluginError(Exception): pass OLD_STYLE_CITE_REGEX = re.compile(r"([^_]*_)?\*?([a-z]*?)etic\\") # I apoligise profusely for this regex # forward version with explanation: # \\ # (?: # (?# # first branch matches \foreigntextquote, # \hypentextquote, \foreignblockquote, \hyphenblockquote, # \hybridblockquote and starred versions # syntax is: # \foreigntextquote{lang}[key][punct]{text} # ) # (?:foreign|hyphen|hybrid(?=block))(?:text|block)quote\*? # \{[^}]*\}\[(?:(?:[^[\],]*,)*)?| # (?# # second branch matches \textquote, \blockquote and # starred versions # syntax is: # \textquote[key]{text} # ) # (?:text|block)quote\*?\[(?:(?:[^[\],]*,)*)?| # (?# # third branch matches \foreigntextcquote, # \hyphentextcquote, \foreignblockcquote, \hypenblockcquote, # \hybridblockcquote and starred versions # syntax is: # \foreigntextcquote{lang}[prenote][postnote]{key}{text} # ) # (?:foreign|hyphen|hybrid(?=block))(?:text|block)cquote\*? # \{[^}]*\}(?:\[[^\]]*\]){0,2}\{(?:(?:[^{},]*,)*)?| # (?# # fourth branch matches \textcquote, \blockcquote and # starred versions # syntax is: # \textcquote[prenote][postnote]{key}{text} # ) # (?:text|block)cquote\*?(?:\[[^\]]*\]){0,2}\{(?:(?:[^{},]*,)*)?| # (?# # fifth branch matches \volcite and friends # syntax is: # \volcite[prenote]{volume}[page]{key} # ) # (?:p|P|f|ft|s|S|t|T|a|A)?volcite # (?:\[[^\]]*\])?\{[^}]*\}(?:\[[^\]]*\])?\{(?:(?:[^{},]*,)*)?| # (?# # sixth branch matches \volcites and friends # syntax is: # \volcites(multiprenote)(multipostnote)[prenote]{volume}[page]{key} # ...[prenote]{volume}[page]{key} # ) # (?:p|P|f|ft|s|S|t|T|a|A)?volcites # (?:\([^)]*\)){0,2} # (?:(?:\[[^\]]*\])?\{[^}]*\} # (?:\[[^\]]*\])?\{(?:(?:[^{},]*,)*)?(?:\}(?=.*?\{))?){1,}| # (?# # seventh branch matches \cites and friends, excluding \volcite # syntax is: # \cites(multiprenote)(multipostnote)[prenote][postnote]{key} # ...[prenote][postnote]{key} # ) # (?:(?!(?:p|P|f|ft|s|S|t|T|a|A)?volcites) # (?:[A-Z]?[a-z]*c)|C)ites(?!style) # (?:\([^)]*\)){0,2} # (?:(?:\[[^\]]*\]){0,2}\{(?:(?:[^{},]*,)*)?(?:\}(?=.*?\{))?){1,}| # (?# # eighth branch matches most everything else, excluding \volcite, # \mcite, \citereset and \citestyle # syntax is: # \cite[<prenote>][<postnote>]{key} # ) # (?:(?!(?:p|P|f|ft|s|S|t|T|a|A)?volcite|mcite) # (?:[A-Z]?[a-z]*c)|C)ite(?!reset\*?|style)([a-zX*]*?) # ([.*?]){0,2}(?:\[[^\]]*\]){0,2}\{(?:(?:[^{},]*,)*)?| # (?# # ninth branch matches apacite commands # syntax is: # \citeA<prenote>[postnote]{key} # ) # (?:mask)?(?:full|short)cite # (?:(?:author|year)(?:NP)?|NP|A)? # (?:<[^>]*>)?(?:\[[^\]]*\])?\{(?:(?:[^{},]*,)*)?)$ NEW_STYLE_CITE_REGEX = re.compile( r"""(?: (?:(?P<prefix1>[^\[\],]*)(?:,[^\[\],]*)*\[\}[^\{]*\{ \*?etouq(?:kcolb|txet)(?:ngierof|nehpyh|(?<=kcolb)dirbyh))| (?:(?P<prefix2>[^\[\],]*)(?:,[^\[\],]*)*\[\*?etouq(?:kcolb|txet))| (?:(?P<prefix3>[^{},]*)(?:,[^{},]*)*\{(?:\][^\[]*\[){0,2}\}[^\{]*\{ \*?etouqc(?:kcolb|txet)(?:ngierof|nehpyh|(?<=kcolb)dirbyh))| (?:(?P<prefix4>[^{},]*)(?:,[^{},]*)*\{(?:\][^\[]*\[){0,2} \*?etouqc(?:kcolb|txet))| (?:(?P<prefix5>[^{},]*)(?:,[^{},]*)*\{(?:\][^\[]*\[)?\}[^\{}]*\{(?:\][^\[]*\[)? eticlov(?:p|P|f|ft|s|S|t|T|a|A)?)| (?:(?P<prefix6>[^{},]*)(?:,[^{},]*)*\{(?:\][^\[]*\[)?\}[^\{}]*\{(?:\][^\[]*\[)? (?:\}[^\{}]*\{(?:\][^\[]*\[)?\}[^\{}]*\{(?:\][^\[]*\[)?)* (?:\)[^(]*\(){0,2} seticlov(?:p|P|f|ft|s|S|t|T|a|A)?)| (?:(?P<prefix7>[^{},]*)(?:,[^{},]*)*\{(?:\][^\[]*\[){0,2} (?:\}[^\}]*\{(?:\][^\[]*\[){0,2})* (?:[\.\*\?]){0,2}(?:\)[^(]*\(){0,2} seti(?:C|c(?!lov)[a-z]*[A-Z]?))| (?:(?P<prefix8>[^{},]*)(?:,[^{},]*)*\{(?:\][^\[]*\[){0,2} (?:[\.\*\?]){0,2}(?!\*?teser|elyts)(?P<fancy_cite>[a-z\*]*?) eti(?:C|c(?!lov|m\\)[a-z]*[A-Z]?))| (?:(?P<prefix9>[^{},]*)(?:,[^{},]*)*\{(?:\][^\[]*\[)? (?:>[^<]*<)?(?:(?:PN)?(?:raey|rohtua)|PN|A)?etic (?:lluf|trohs)?(?:ksam)?) )\\""", re.X) def match(rex, str): m = rex.match(str) if m: return m.group(0) else: return None # recursively search all linked tex files to find all # included bibliography tags in the document and extract # the absolute filepaths of the bib files def find_bib_files(rootdir, src, bibfiles): if not is_tex_file(src): src_tex_file = None for ext in get_tex_extensions(): src_tex_file = ''.join((src, ext)) if os.path.exists(os.path.join(rootdir, src_tex_file)): src = src_tex_file break if src != src_tex_file: print("Could not find file {0}".format(src)) return file_path = os.path.normpath(os.path.join(rootdir,src)) print("Searching file: " + repr(file_path)) # See latex_ref_completion.py for why the following is wrong: #dir_name = os.path.dirname(file_path) # read src file and extract all bibliography tags try: src_file = codecs.open(file_path, "r", 'UTF-8') except IOError: sublime.status_message("LaTeXTools WARNING: cannot open included file " + file_path) print ("WARNING! I can't find it! Check your \\include's and \\input's.") return src_content = re.sub("%.*","",src_file.read()) src_file.close() m = re.search(r"\\usepackage\[(.*?)\]\{inputenc\}", src_content) if m: f = None try: f = codecs.open(file_path, "r", m.group(1)) src_content = re.sub("%.*", "", f.read()) except: pass finally: if f and not f.closed: f.close() # While these commands only allow a single resource as their argument... resources = re.findall(r'\\addbibresource(?:\[[^\]]+\])?\{([^\}]+\.bib)\}', src_content) resources += re.findall(r'\\addglobalbib(?:\[[^\]]+\])?\{([^\}]+\.bib)\}', src_content) resources += re.findall(r'\\addsectionbib(?:\[[^\]]+\])?\{([^\}]+\.bib)\}', src_content) # ... these can have a comma-separated list of resources as their argument. multi_resources = re.findall(r'\\begin\{refsection\}\[([^\]]+)\]', src_content) multi_resources += re.findall(r'\\bibliography\{([^\}]+)\}', src_content) multi_resources += re.findall(r'\\nobibliography\{([^\}]+)\}', src_content) for multi_resource in multi_resources: for res in multi_resource.split(','): res = res.strip() if res[-4:].lower() != '.bib': res = res + '.bib' resources.append(res) # extract absolute filepath for each bib file for res in resources: # We join with rootdir, the dir of the master file candidate_file = os.path.normpath(os.path.join(rootdir, res)) # if the file doesn't exist, search the default tex paths if not os.path.exists(candidate_file): candidate_file = kpsewhich(res, 'mlbib') if candidate_file is not None and os.path.exists(candidate_file): bibfiles.append(candidate_file) # search through input tex files recursively for f in re.findall(r'\\(?:input|include|subfile)\{[^\}]+\}',src_content): input_f = re.search(r'\{([^\}]+)', f).group(1) find_bib_files(rootdir, input_f, bibfiles) def run_plugin_command(command, *args, **kwargs): ''' This function is intended to run a command against a user-configurable list of bibliography plugins set using the `bibliography` setting. Parameters: `command`: a string representing the command to invoke, which should generally be the name of a function to be called on the plugin class. `*args`: the args to pass to the function `**kwargs`: the keyword args to pass to the function Additionally, the following keyword parameters can be specified to control how this function works: `stop_on_first`: if True (default), no more attempts will be made to run the command after the first plugin that returns a non-None result `expect_result`: if True (default), a BibPluginError will be raised if no plugin returns a non-None result Example: run_plugin_command('get_entries', *bib_files) This will attempt to invoke the `get_entries` method of any configured plugin, passing in the discovered bib_files, and returning the result. The general assumption of this function is that we only care about the first valid result returned from a plugin and that plugins that should not handle a request will either not implement the method or implement a version of the method which raises a NotImplementedError if that plugin should not handle the current situation. ''' stop_on_first = kwargs.pop('stop_on_first', True) expect_result = kwargs.pop('expect_result', True) def _run_command(plugin_name): plugin = None try: plugin = latextools_plugin.get_plugin(plugin_name) except latextools_plugin.NoSuchPluginException: pass if not plugin: error_message = 'Could not find bibliography plugin named {0}. Please ensure your LaTeXTools.sublime-settings is configured correctly.'.format( plugin_name) print(error_message) raise BibPluginError(error_message) # instantiate plugin try: plugin = plugin() except: error_message = 'Could not instantiate {0}. {0} must have a no-args __init__ method'.format( type(plugin).__name__, ) print(error_message) raise BibPluginError(error_message) try: result = getattr(plugin, command)(*args, **kwargs) except TypeError as e: if "'{0}()'".format(command) in str(e): error_message = '{1} is not properly implemented by {0}.'.format( type(plugin).__name__, command ) print(error_message) raise BibPluginError(error_message) else: reraise(*sys.exc_info()) except AttributeError as e: if "'{0}'".format(command) in str(e): error_message = '{0} does not implement `{1}`'.format( type(plugin).__name__, command ) print(error_message) raise BibPluginError(error_message) else: reraise(*sys.exc_info()) except NotImplementedError: return None return result plugins = get_setting('bibliography', ['traditional']) if not plugins: print('bibliography setting is blank. Loading traditional plugin.') plugins = 'traditional' result = None if isinstance(plugins, strbase): if not plugins.endswith('_bibliography'): plugins = '{0}_bibliography'.format(plugins) result = _run_command(plugins) else: for plugin_name in plugins: if not plugin_name.endswith('_bibliography'): plugin_name = '{0}_bibliography'.format(plugin_name) try: result = _run_command(plugin_name) except BibPluginError: continue if stop_on_first and result is not None: break if expect_result and result is None: raise BibPluginError("Could not find a plugin to handle '{0}'. See the console for more details".format(command)) return result def get_cite_completions(view): root = getTeXRoot.get_tex_root(view) if root is None: # This is an unnamed, unsaved file # FIXME: should probably search the buffer instead of giving up raise NoBibFilesError() print(u"TEX root: " + repr(root)) bib_files = [] find_bib_files(os.path.dirname(root), root, bib_files) # remove duplicate bib files bib_files = list(set(bib_files)) print("Bib files found: ") print(repr(bib_files)) if not bib_files: # sublime.error_message("No bib files found!") # here we can! raise NoBibFilesError() bib_files = ([x.strip() for x in bib_files]) completions = run_plugin_command('get_entries', *bib_files) return completions # Based on html_completions.py # see also latex_ref_completions.py # # It expands citations; activated by # cite<tab> # citep<tab> and friends # # Furthermore, you can "pre-filter" the completions: e.g. use # # cite_sec # # to select all citation keywords starting with "sec". # # There is only one problem: if you have a keyword "sec:intro", for instance, # doing "cite_intro:" will find it correctly, but when you insert it, this will be done # right after the ":", so the "cite_intro:" won't go away. The problem is that ":" is a # word boundary. Then again, TextMate has similar limitations :-) # # There is also another problem: * is also a word boundary :-( So, use e.g. citeX if # what you want is \cite*{...}; the plugin handles the substitution class CiteFillAllHelper(FillAllHelper): def get_auto_completions(self, view, prefix, line): # Reverse, to simulate having the regex # match backwards (cool trick jps btw!) line = line[::-1] # Check the first location looks like a cite_, but backward old_style = OLD_STYLE_CITE_REGEX.match(line) # Do not match on plain "cite[a-zX*]*?" when autocompleting, # in case the user is typing something else if old_style and not prefix: return [] try: completions = get_cite_completions(view) except NoBibFilesError: print("No bib files found!") sublime.status_message("No bib files found!") return [] except BibParsingError as e: message = "Error occurred parsing {0}. {1}.".format( e.filename, e.message ) print(message) traceback.print_exc() sublime.status_message(message) return [] if prefix: lower_prefix = prefix.lower() completions = [ c for c in completions if _is_prefix(lower_prefix, c) ] if len(completions) == 0: return [] cite_autocomplete_format = get_setting( 'cite_autocomplete_format', '{keyword}: {title}' ) def formatted_entry(entry): try: return entry['<autocomplete_formatted>'] except: return bibformat.format_entry( cite_autocomplete_format, entry ) completions = [ ( formatted_entry(c), c['keyword'] ) for c in completions ] if old_style: return completions, '{' else: return completions def get_completions(self, view, prefix, line): try: completions = get_cite_completions(view) except NoBibFilesError: sublime.error_message("No bib files found!") return except BibParsingError as e: traceback.print_exc() sublime.error_message( "Error occurred parsing {0}. {1}.".format( e.filename, e.message ) ) return if prefix: lower_prefix = prefix.lower() completions = [ c for c in completions if _is_prefix(lower_prefix, c) ] completions_length = len(completions) if completions_length == 0: return elif completions_length == 1: return [completions[0]['keyword']] cite_panel_format = get_setting( 'cite_panel_format', ["{title} ({keyword})", "{author}"] ) def formatted_entry(entry): try: return entry["<panel_formatted>"] except: return [ bibformat.format_entry(s, entry) for s in cite_panel_format ] formatted_completions = [] result_completions = [] for completion in completions: formatted_completions.append(formatted_entry(completion)) result_completions.append(completion['keyword']) return formatted_completions, result_completions def matches_line(self, line): return bool( OLD_STYLE_CITE_REGEX.match(line) or NEW_STYLE_CITE_REGEX.match(line) ) def matches_fancy_prefix(self, line): return bool(OLD_STYLE_CITE_REGEX.match(line)) def is_enabled(self): return get_setting('cite_auto_trigger', True) def _is_prefix(lower_prefix, entry): try: return lower_prefix in entry["<prefix_match>"] except: return lower_prefix in bibformat.create_prefix_match_str(entry) def plugin_loaded(): # load plugins from the bibliography_plugins dir of LaTeXTools if it exists # this allows us to have pre-packaged plugins that won't require any user # setup os_path = os.path latextools_plugin.add_plugin_path( os_path.join(os_path.dirname(__file__), 'bibliography_plugins')) # ensure plugin_loaded() called on ST2 if not _ST3: plugin_loaded()
[ "snake.river52@gmail.com" ]
snake.river52@gmail.com
a3680abdf8ea1f58cb021e30012ae67da1030aa1
c53c08efa1118f0083da981029c0b6e4f44d2cab
/fileshare/admin.py
2ea155603ecc9de84a22a56694bd77356ae025f8
[]
no_license
refik/uppsala
f448acc1fed9215baaa256b91bd8d914e1741c97
3e7f37ccc0014baa54551005fcfec0048b8be302
refs/heads/master
2020-12-24T16:42:50.689115
2010-05-15T18:59:25
2010-05-15T18:59:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
118
py
from uppsala.fileshare.models import UploadedFile from django.contrib import admin admin.site.register(UploadedFile)
[ "gro.tiiy@yiit.org" ]
gro.tiiy@yiit.org
18822a247320d7bea2a9c353a0d312e2991fcffb
0f684f1f5271bd18475113a46c0d7c1232a3da5a
/apps/users/views.py
7eb719adb4c0d73a937698f828eb26b67dc2132f
[]
no_license
aaronmyatt/talespace-backend
20eb648422eef326c1b622e9a1b675fefa6a004f
c229ea3d5554a80e0b5d193921b2a6f8dea58f17
refs/heads/master
2020-07-12T09:31:44.441170
2017-04-07T01:31:50
2017-04-07T01:31:50
73,912,315
1
0
null
2017-04-11T13:17:32
2016-11-16T11:11:42
Python
UTF-8
Python
false
false
955
py
from rest_auth.views import UserDetailsView from rest_framework.viewsets import ModelViewSet from .models import UserDetails, UserSkills from .serializers import UserSkillsSerializer class CustomUserDetailsView(UserDetailsView): def get_object(self): user = self.request.user return UserDetails.objects.get(user=user) def update(self, request, *args, **kwargs): return super().update(request, partial=True) class UserSkillsView(ModelViewSet): ''' Gets the users skills TODO: limit single object lookup to the users skills only! ''' queryset = UserSkills.objects.all() serializer_class = UserSkillsSerializer def get_queryset(self): return UserDetails.objects.get(user=self.request.user).userskills_set def perform_create(self, serializer): user = self.request.user user_details = UserDetails.objects.get(user=user) serializer.save(user=user_details)
[ "aaronmyatt@gmail.com" ]
aaronmyatt@gmail.com
ff5805ad92b2c3b4b50586b984b637a7c56cd144
76addcb531eea2f3c6715e2e6f8750c4dc274cfc
/jushacore/_jushacore.py
68e0e73865e98b2b865ae1a32e9bf7ae36e98330
[]
no_license
luxiaolei/JushaMS
1171f0bcbce89b56e63daddf2485ca99db36006f
4262910f57793dc66da3aa997ed921d24af759db
refs/heads/master
2021-05-01T10:45:47.892952
2016-04-29T11:06:25
2016-04-29T11:06:25
57,284,360
1
1
null
null
null
null
UTF-8
Python
false
false
15,573
py
# -*- coding: utf-8 -*- ''' This file is part of the Python jushacore package, an open source tool for exploration, analysis and visualization of data. Copyright 2011–2015 by the authors: Daniel Müllner, http://danifold.net Aravindakshan Babu, anounceofpractice@hotmail.com Python jushacore is distributed under the GPLv3 license. See the project home page http://danifold.net/jushacore for more information. ------------------------------------------------------------------------------- Implementation of the jushacore algorithm with the following characteristics: - for a multi-dimensional filter function - memory-efficient for subsets of M{R^n}, or for general metric spaces (Memory efficiency for Euclidean data can still be improved, with an implementation of hierarchical clustering which accepts Euclidean data instead of a distance matrix.) ''' from __future__ import print_function import numpy as np from scipy.spatial.distance import pdist from multiprocessing import cpu_count from threading import Thread import sys if sys.hexversion < 0x03000000: from Queue import Queue range = xrange else: from queue import Queue try: from fastcluster import linkage except ImportError: sys.stderr.write('jushacore warning: Could not load the module ' '“fastcluster”.\nThe module “scipy.cluster.hierarchy“ is ' 'used instead, but it will be slower.\n') from scipy.cluster.hierarchy import linkage from jushacore.jusha_output import jusha_output, fcluster from time import time __all__ = ['jushacore', 'single_linkage', 'complete_linkage', 'average_linkage', 'weighted_linkage', 'centroid_linkage', 'median_linkage', 'ward_linkage', 'n_obs', 'crop', 'mask_data'] class single_linkage: ''' Helper class. Wraps a call to single linkage clustering and provides a readable description. ''' def __call__(self, X): return linkage(X, method='single') def __str__(self): return 'Single linkage clustering' class complete_linkage: ''' Helper class. Wraps a call to complete linkage clustering and provides a readable description. ''' def __call__(self, X): return linkage(X, method='complete') def __str__(self): return 'Complete linkage clustering' class average_linkage: ''' Helper class. Wraps a call to average linkage clustering and provides a readable description. ''' def __call__(self, X): return linkage(X, method='average') def __str__(self): return 'Average linkage clustering' class weighted_linkage: ''' Helper class. Wraps a call to weighted linkage clustering and provides a readable description. ''' def __call__(self, X): return linkage(X, method='weighted') def __str__(self): return 'Weighted linkage clustering' class centroid_linkage: ''' Helper class. Wraps a call to centroid linkage clustering and provides a readable description. ''' def __call__(self, X): return linkage(X, method='centroid') def __str__(self): return 'Centroid linkage clustering' class median_linkage: ''' Helper class. Wraps a call to median linkage clustering and provides a readable description. ''' def __call__(self, X): return linkage(X, method='median') def __str__(self): return 'Median linkage clustering' class ward_linkage: ''' Helper class. Wraps a call to Ward linkage clustering and provides a readable description. ''' def __call__(self, X): return linkage(X, method='ward') def __str__(self): return 'Ward linkage clustering' cluster_default = single_linkage() def Mapper_step(q, pcd, N, point_labels, filt, cover, cluster, cutoff, M, metricpar, verbose): if verbose: print ('Start jushacore thread.') while True: level = q.get() if level is None: # Sentinel: end the thread break # Select the points in this filter range idx = cover.data_index(level) num_points = idx.size # Handle special cases. # 0 points in the filter interval: just skip the loop iteration. if num_points == 0: if verbose: print('Warning! Filter level {0} is empty.'.\ format(level.index)) num_clust = 0 Z = None R = None # 1 point => 1 cluster elif num_points == 1: if verbose: print('Warning! Filter level {0} has only one point.'.\ format(level.index)) num_clust = 1 points_clusters = np.zeros(1,dtype=int) # We label clusters starting with 0. Z = np.empty((0,4)) R = 0. # 2 or more points: general case else: if verbose: print('Filter level {0} has {1} points.'.\ format(level.index, num_points)) if pcd.ndim==1: part_data = compressed_submatrix(pcd,idx) else: part_data = pdist(pcd[idx,:], **metricpar) # diameter R = part_data.max() Z = cluster(part_data) if Z[-1,2]>R: print('Warning: last clustering distance is bigger than the ' 'diameter of the filter slice ({0}>{1}).'.\ format(Z[-1,2], R)) R = Z[-1,2] if cutoff: # heights in the clustering tree heights = Z[:,2] # determine a cutoff value # To do: Improve this! num_clust = cutoff(heights, R) # actual clustering, after the cutoff value has been determined points_clusters = fcluster(Z, num_clust) # My fcluster starts labelling clusters at 0! #assert num_clust == points_clusters.max() assert np.all(np.unique(points_clusters)==\ np.arange(num_clust)) if cutoff: # # Determine the nodes of the output graph # # Each cluster in the partial clustering gives a node for cl in range(num_clust): points = idx[ points_clusters == cl ] # This gives us the # indices of the clusters points in the d matrix. # The color is determined by the first filter component! attribute = np.median(filt[points,0]) # Color the nodes by their median filter value # # Normally, the data points are labeled 0,1,... # Allow relabeling of the data point, whatever this is good # for. # To do: ask Aravind. if point_labels is not None: points = point_labels[ points ] M.add_node( level.index, points, attribute ) else: # save data for the scale graph algorithm M.scale_graph_data.append(dataidx=idx, dendrogram=Z, diameter=R, levelindex=level.index) def jushacore(pcd, filt, cover, cutoff, mask=None, cluster=cluster_default, point_labels=None, metricpar={}, simple=False, filter_info=None, verbose=True): ''' jushacore algorithm :param pcd: input data, point cloud in :math:`R^n`, or compressed distance matrix for *N* points :type pcd: ``numpy.ndarray((N,n), dtype=float)`` or ``numpy.ndarray((N*(N-1)/2), dtype=float)`` :param filt: filter function with *comp* components :type filt: ``numpy.ndarray((N, comp), dtype=float)`` or ``numpy.ndarray(N, dtype=float)`` :param cover: Class for the cover of the filter range. See :ref:`section:cover`. :type cover: iterator :param cutoff: Cutoff function for the partial clustering tree. See :ref:`section:cluster_cutoff`. :type cutoff: function or ``None`` :param mask: (Mainly for the GUI) A mask to choose a subset of the input points :type mask: Anything that can be used for `indexing of NumPy arrays <http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html>`_, e.g. a Boolean array of size *N*. :param cluster: Clustering function. :type cluster: See :ref:`section:clustering_function` :param point_labels: Labels for the input points (optional). If this is None, the points are labeled 0,1,...,N−1. :type point_labels: ``numpy.ndarray(N)`` :param metricpar: If the input data is in vector form, these are the parameters that are given to the ``scipy.spatial.distance.pdist`` function. If the input data is a compressed distance matrix, this argument is ignored. :type metricpar: dict :param simple: (to be documented by example) If ``True``, then intersections are only considered for adjacent cover patches in the 1-dimensional variant. In particular, the output simplicial complex is a graph without higher-dimensional simplices. :type simple: bool :param filter_info: (For the GUI) Filter info to be stored in the output :type filter_info: :param verbose: Print status message? :type verbose: bool :return: jushacore output data structure :rtype: ``jusha_output`` instance ''' # input checks assert isinstance(pcd, np.ndarray) assert pcd.dtype == np.float if pcd.ndim==1: N = n_obs(pcd) print('Number of observations: {0}.'.format(N)) if not np.all(pcd>=0): raise ValueError('jushacore needs nonnegative dissimilarity values.') else: assert pcd.ndim == 2 [N, n] = pcd.shape assert isinstance(filt, np.ndarray) assert filt.dtype == np.float if filt.ndim == 1: filt = filt[:,np.newaxis] assert filt.ndim == 2 assert np.alen(filt) == N if point_labels is not None: assert isinstance(point_labels, np.ndarray) assert point_labels.size == N # Initialize variables M = jusha_output(point_labels=point_labels) #xl_add, fixed core dump error, when wrapped cores = cpu_count() #cores = 1 if verbose: print('Number of CPU cores present: {0}'.format(cores)) work_queue = Queue() threads = [Thread(target=Mapper_step, args=(work_queue, pcd, N, point_labels, filt, cover, cluster, cutoff, M, metricpar, verbose)) for i in range(cores)] for t in threads: t.start() if verbose: for i in range(filt.shape[1]): print('jushacore: Filter range in dimension {0}: [{1:0.2f}, ' '{2:0.2f}]'.format(i, np.min(filt[:,i]), np.max(filt[:,i]))) print('jushacore: Cover: {0}'.format(cover)) print('jushacore: Clustering: {0}'.format(cluster)) print('jushacore: Cutoff: {0}'.format(cutoff)) # jushacore main loop patches = cover(filt, mask) if not cutoff: M.reserve_scale_graph(len(patches)) for level in patches: if verbose: print("Level: " + str(level.index)) M.add_level(level.index, level.range_min, level.range_max) work_queue.put(level) for i in range(cores): # Sentinels; tell the thread to stop work_queue.put(None) for t in threads: t.join() assert work_queue.empty(), ('Work qeue is not empty. Probably there was ' 'an error in one of the parallel jushacore ' 'threads.') if cutoff: # When all nodes have been added, make the data structure consistent # since we didn't keep track of the nodes in each level. M.add_nodes_to_levelsets() M.complex_from_nodes(cover=cover, verbose=verbose, simple=simple) # Add info filt_mask = filt if mask is None else filt[mask] if filter_info is not None: M.add_info(filter_info=filter_info) M.add_info(filter_min=np.min(filt_mask[:,0]), filter_max=np.max(filt_mask[:,0])) M.add_info(filter_min_array=np.min(filt_mask, axis=0), filter_max_array=np.max(filt_mask, axis=0)) M.add_info(cover = cover.info) M.add_info(cutoff = str(cutoff)) M.add_info(cluster = str(cluster)) return M def n_obs(dm): ''' Determine the number of observations from a compressed distance matrix. @param dm: compressed distance matrix @type dm: numpy.ndarray(N*(N-1)/2, dtype=float) @return: M{N}, the number of observations @rtype: nonnegative integer ''' k = np.alen(dm) if k==0: return 1 else: N = int(np.ceil(np.sqrt(k * 2))) assert k == N*(N-1)//2 return N #def compressed_idx(N,r,c): # ''' # The linear index of the distance from point M{r} to point M{c>r} in # a compressed distance matrix with M{N} data points. # ''' # assert r<c # return (2*N-3-r)*r/2-1+c def mask_data(data, mask, labels=None): if mask is None or np.all(mask): return data, None else: if labels is None: newlabels = np.flatnonzero(mask) else: newlabels = labels[mask] if data.ndim==1: return compressed_submatrix(data, np.flatnonzero(mask)), newlabels else: return data[mask], newlabels def compressed_submatrix(dm, idx): ''' Extract from a compressed distance matrix the corresponding matrix for a subset of points without bringing the matrix into square form first. The indices in the list C{idx} must be in increasing order. @param dm: compressed distance matrix @type dm: numpy.ndarray(N*(N-1)/2, dtype=float) @param idx: indices of the subset @type idx: numpy.ndarray(n, dtype=int) @param N: the number of observation in C{dm} (optional) @type N: integer @return: compressed distance matrix @rtype: numpy.ndarray(n*(n-1)/2, dtype=float) ''' N = n_obs(dm) n = np.alen(idx) res = np.empty(n*(n-1)//2,dtype=dm.dtype) # Shorter Python code, does the same thing. # Which variant is faster? # #for i,c in enumerate(combinations(idx,2)): # res[i] = dm[compressed_idx(N,*c)] for r in range(n-1): s = (2*n-1-r)*r//2 t = idx[r] i = idx[r+1:] + (2*N-3-t)*t//2-1 res[s:s+n-1-r] = dm[i] return res def crop(f, a, b): from scipy.stats import scoreatpercentile s1 = scoreatpercentile(f, a) s2 = scoreatpercentile(f, 100-b) assert s1<=s2 return np.logical_and(f>=s1, f<=s2) if __name__=='__main__': '''Test equvalence of the Python and the C++ implementation''' import cmappertools import numpy as np for i in range(10000): N = np.random.random_integers(1000) n = np.random.random_integers(N) dm = np.random.rand(N*(N-1)//2) idx = np.unique(np.random.randint(N,size=n)) r = compressed_submatrix(dm,idx) s = cmappertools.compressed_submatrix(dm,idx) if np.any(r!=s): raise AssertionError print("Iteration {0}: OK.".format(i)) else: '''Load the C++ routines, if available.''' try: from cmappertools import compressed_submatrix except ImportError: sys.stderr.write("The 'cmappertools' module could not be imported.\n") del sys
[ "26442779@qq.com" ]
26442779@qq.com
e2c46e9c3c12ed70166afee419a09e346f651ad9
09df89395816834ddf77de620f959c22e74d8c00
/Bit Manipulation/Single Number.py
382f244e2e89ffbe38dd4070043ad097ea451177
[]
no_license
gdh756462786/Leetcode_by_python
c853c4e3de255a8b4016c59944a0d40213a539a7
6387543a2a23c30aef1d5d37db54ca72cfb19270
refs/heads/master
2020-06-22T11:53:24.758506
2018-12-28T03:03:31
2018-12-28T03:03:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
760
py
# coding: utf-8 ''' Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ''' class Solution(object): ''' 对数组元素执行异或运算,最终结果即为所求。 由于异或运算的性质,两个相同数字的异或等于0,而任意数字与0的亦或都等于它本身。 另外,异或运算满足交换律。 ''' def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ ans = 0 for num in nums: ans ^= num return ans solution = Solution() print solution.singleNumber([2,2,5,3,3])
[ "pengshuang92@163.com" ]
pengshuang92@163.com
2a9dd4046fdba27ca3f4b55180f1d9043b3eb125
e585a3c695d5b06f47b36c4e54af44756e50916b
/manage.py
1151335c8f2a3bdb7c606e1268b14a3179c2edd9
[]
no_license
anishchapagain/djangoPoll
d756b7aedc5cdf05508b3b9eaa3e7d8f66ce9d55
1510f2f8e4eb1746c2beb8873a653f6bb9ac639a
refs/heads/master
2021-01-20T00:33:30.322392
2019-08-19T15:36:15
2019-08-19T15:36:15
89,148,848
2
0
null
null
null
null
UTF-8
Python
false
false
803
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mypoll.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
[ "anishchapagain" ]
anishchapagain
a1d751994efc5489e5445b3a868a6d761bfe842f
56169cb87066ca6ae3c8c86086cb5240df82e523
/accounts/migrations/0001_initial.py
05c2946e3efc3a5043e820260fb6f170a4c19fa8
[]
no_license
s-bekk/greatkart-django-proj
7a9d34a55a5e2bb899ef045cc82519be164f9f54
9d5861cbce5f5330c84d395ffb0f61cc0b1da007
refs/heads/main
2023-07-12T02:06:19.500976
2021-08-16T22:09:56
2021-08-16T22:09:56
391,713,108
0
0
null
null
null
null
UTF-8
Python
false
false
1,355
py
# Generated by Django 3.2.3 on 2021-07-18 17:21 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Account', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('username', models.CharField(max_length=50, unique=True)), ('email', models.EmailField(max_length=100, unique=True)), ('phone_number', models.CharField(max_length=50)), ('date_joined', models.DateTimeField(auto_now_add=True)), ('last_login', models.DateTimeField(auto_now_add=True)), ('is_admin', models.BooleanField(default=False)), ('is_staff', models.BooleanField(default=False)), ('is_active', models.BooleanField(default=False)), ('is_superadmin', models.BooleanField(default=False)), ], options={ 'abstract': False, }, ), ]
[ "sb6187@nyu.edu" ]
sb6187@nyu.edu
930bdd6c664af3339a2e4cd163054d717ef73e87
8600ea155f279e5a8dfe5a1926038511f6b6a7ea
/hr_timesheet_invoice/report/account_analytic_profit.py
600535ee02795acbe0674bc506d0626bbe7cc93d
[]
no_license
MarkNorgate/addons-EAD
c2fff89ab16fce3ba19fbe433ee5863705a6f4e5
840f28642b5d328e4b86839c413e5164622295a5
refs/heads/master
2020-04-23T22:11:00.164438
2015-07-22T12:24:53
2015-07-22T12:24:53
39,501,011
0
0
null
null
null
null
UTF-8
Python
false
false
5,780
py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # $Id$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from report import report_sxw import pooler class account_analytic_profit(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(account_analytic_profit, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'lines': self._lines, 'user_ids': self._user_ids, 'journal_ids': self._journal_ids, 'line': self._line, }) def _user_ids(self, lines): user_obj=pooler.get_pool(self.cr.dbname).get('res.users') ids=list(set([b.user_id.id for b in lines])) res=user_obj.browse(self.cr, self.uid, ids) return res def _journal_ids(self, form, user_id): line_obj=pooler.get_pool(self.cr.dbname).get('account.analytic.line') journal_obj=pooler.get_pool(self.cr.dbname).get('account.analytic.journal') line_ids=line_obj.search(self.cr, self.uid, [ ('date', '>=', form['date_from']), ('date', '<=', form['date_to']), ('journal_id', 'in', form['journal_ids'][0][2]), ('user_id', '=', user_id), ]) ids=list(set([b.journal_id.id for b in line_obj.browse(self.cr, self.uid, line_ids)])) res=journal_obj.browse(self.cr, self.uid, ids) return res def _line(self, form, journal_ids, user_ids): pool=pooler.get_pool(self.cr.dbname) line_obj=pool.get('account.analytic.line') product_obj=pool.get('product.product') price_obj=pool.get('product.pricelist') ids=line_obj.search(self.cr, self.uid, [ ('date', '>=', form['date_from']), ('date', '<=', form['date_to']), ('journal_id', 'in', journal_ids), ('user_id', 'in', user_ids), ]) res={} for line in line_obj.browse(self.cr, self.uid, ids): if line.account_id.pricelist_id: if line.account_id.to_invoice: if line.to_invoice: id=line.to_invoice.id name=line.to_invoice.name discount=line.to_invoice.factor else: name="/" discount=1.0 id = -1 else: name="Fixed" discount=0.0 id=0 pl=line.account_id.pricelist_id.id price=price_obj.price_get(self.cr, self.uid, [pl], line.product_id.id, line.unit_amount or 1.0, line.account_id.partner_id.id)[pl] else: name="/" discount=1.0 id = -1 price=0.0 if id not in res: res[id]={'name': name, 'amount': 0, 'cost':0, 'unit_amount':0,'amount_th':0} xxx = round(price * line.unit_amount * (1-(discount or 0.0)), 2) res[id]['amount_th']+=xxx if line.invoice_id: self.cr.execute('select id from account_analytic_line where invoice_id=%s', (line.invoice_id.id,)) tot = 0 for lid in self.cr.fetchall(): lid2 = line_obj.browse(self.cr, self.uid, lid[0]) pl=lid2.account_id.pricelist_id.id price=price_obj.price_get(self.cr, self.uid, [pl], lid2.product_id.id, lid2.unit_amount or 1.0, lid2.account_id.partner_id.id)[pl] tot += price * lid2.unit_amount * (1-(discount or 0.0)) if tot: procent = line.invoice_id.amount_untaxed / tot res[id]['amount'] += xxx * procent else: res[id]['amount'] += xxx else: res[id]['amount'] += xxx res[id]['cost']+=line.amount res[id]['unit_amount']+=line.unit_amount for id in res: res[id]['profit']=res[id]['amount']+res[id]['cost'] res[id]['eff']='%d' % (-res[id]['amount'] / res[id]['cost'] * 100,) return res.values() def _lines(self, form): line_obj=pooler.get_pool(self.cr.dbname).get('account.analytic.line') ids=line_obj.search(self.cr, self.uid, [ ('date', '>=', form['date_from']), ('date', '<=', form['date_to']), ('journal_id', 'in', form['journal_ids'][0][2]), ('user_id', 'in', form['employee_ids'][0][2]), ]) res=line_obj.browse(self.cr, self.uid, ids) return res report_sxw.report_sxw('report.account.analytic.profit', 'account.analytic.line', 'addons/hr_timesheet_invoice/report/account_analytic_profit.rml', parser=account_analytic_profit) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
[ "mark.norgate@affinity-digital.com" ]
mark.norgate@affinity-digital.com
5b40a924ba782f0ff2c051bc0ed22e9b2c4c3bdd
5a5a3d428454885cb0798e6574d714141bbfb8d7
/boolean_app/api.py
1edc8a136364eb019e5df06aad3a73ecdcea0a5d
[]
no_license
jariberi/boolean
5c226bf1935eed32931b02bb9e376c8146e66055
5149a8cb1ff0a18ff0752750565001a817948ef3
refs/heads/master
2021-01-21T04:39:15.587478
2017-08-08T18:46:59
2017-08-08T18:46:59
32,043,913
0
0
null
null
null
null
UTF-8
Python
false
false
33,615
py
from boolean_app.models import Articulo, Venta, Recibo, Detalle_cobro, Proveedor,\ Valores, Compra, Dinero, OrdenPago, ChequeTercero, Cliente, ChequePropio from django.db.models import Q from StringIO import StringIO from django.http.response import HttpResponse import json from datetime import date from django.core.urlresolvers import reverse_lazy from decimal import Decimal from pdb import set_trace from boolean.settings import RAZON_SOCIAL_EMPRESA import datetime import re def _getattr_foreingkey(obj, attr): pt = attr.count('.') if pt == 0:#No hay clave foranea re = getattr(obj, attr) if isinstance(re, date): return re.strftime("%d/%m/%Y") if isinstance(re, Decimal): return "%.2f" %re else: return re else: nobj = getattr(obj, attr[:attr.find('.')]) nattr = attr[attr.find('.')+1:] return _getattr_foreingkey(nobj,nattr) def get_cantidad_tiempo(detalle): #set_trace() if detalle.tipo_articulo=="AA": if detalle.articulo and detalle.articulo.unidad_medida=="HS": mins = int(round((detalle.cantidad-int(detalle.cantidad))*60)) return "%s:%s" %(int(detalle.cantidad),mins) else: return "%.2f" %detalle.cantidad else: return "%.2f" %detalle.cantidad def get_cantidad_tiempo_ac(ac): if not ac.pers: if ac.articulo.unidad_medida=="HS": mins = int(round((ac.cantidad-int(ac.cantidad))*60)) return "%s:%s" %(int(ac.cantidad),mins) else: return "%.2f" %ac.cantidad else: return "%.2f" %ac.cantidad def filtering(get, dataset, data_struct, global_search): """ :param get: Diccionario GET del request de la vista, para buscar los parametros :param dataset: Dataset con la info, normalmente objects.all() :param data_struct: Dictionario con la estructura de la tabla {0:'columna_a',1:'columna_b'} :param global_search: En que columna debe buscar el termino global :return: Dataset filtrado segun los parametros """ # Extraccion de las busquedas indivuales individual_searchs_i = {} for item in get: match = re.match(r'columns\[(\d+)\]\[search\]\[value\]', item) if match and get[item]: individual_searchs_i[int(match.group(1))] = int(get[item]) # Filtrado de los datos search = get['search[value]'] queries_g = [] for item in global_search: queries_g.append(Q(**{item + '__icontains': search})) print queries_g qs = reduce(lambda x, y: x | y, queries_g) queries_i = [] for k, v in individual_searchs_i.iteritems(): if v == 'false': queries_i.append(Q(**{data_struct[k]: False})) if v == 'true': queries_i.append(Q(**{data_struct[k]: True})) else: queries_i.append(Q(**{data_struct[k] + '__icontains': v})) if individual_searchs_i: qi = reduce(lambda x, y: x & y, queries_i) qs = qs | qi return dataset.filter(qs) def ordering(get, dataset, data_struct): individual_orders = {} for item in get: match_dir = re.match(r'order\[(\d+)\]\[dir\]', item) match_col = re.match(r'order\[(\d+)\]\[column\]', item) if match_dir or match_col and get[item]: if match_dir: i = int(match_dir.group(1)) if i not in individual_orders: individual_orders[i] = ['', ''] individual_orders[i][0] = get[item] if match_col: i = int(match_col.group(1)) if i not in individual_orders: individual_orders[i] = ['', ''] individual_orders[i][1] = get[item] dirs = {'asc': '', 'desc': '-'} ordering = [] for k, order in individual_orders.iteritems(): ordering.append(dirs[order[0]] + data_struct[int(order[1])]) ordering = tuple(ordering) return dataset.order_by(*ordering) def make_data(dataset, list_display, url_modif=None, url_suspen=None, url_hab=None, detalle=None): """ :param dataset: Dataset con la info, normalmente objects.all() :param list_display: :return: Datos en Array """ data = [] for obj in dataset: row = map(lambda field: _getattr_foreingkey(obj, field), list_display) if url_modif: row.append('<a href="%s"><i class="material-icons">mode_edit</i></a>' % reverse(url_modif, args=[obj.pk])) if url_suspen and url_hab: if obj.suspendido: row.append('<a href="%s"><i class="material-icons">keyboard_arrow_up</i></a>' % reverse(url_hab, args=[obj.pk])) else: row.append('<a href="%s"><i class="material-icons">keyboard_arrow_down</i></a>' % reverse(url_suspen, args=[ obj.pk])) if detalle: real_detail = {} for field in re.findall(r'%\((\w+\(*\)*)\)s', detalle): real_detail[field] = getattr(obj, field[:-2])() if field.endswith("()") else getattr(obj, field) deta = detalle % real_detail row.insert(0, deta) data.append(row) return data def format_det_venta(detalles_venta): html = """<table> <thead> <tr> <td>Cantidad</td> <td>Articulo</td> <td>P. Unitario</td ><td>P. Total</td> </tr> </thead> <tbody>""" for det in detalles_venta: print "Detalle venta" print det.id html = html + "<tr><td>"+get_cantidad_tiempo(det)+"</td>" if det.articulo and det.tipo_articulo == "AA": html = html + "<td>"+det.articulo.codigo+" "+det.articulo.codigo_fabrica+" "+det.articulo.denominacion+"</td>" elif det.tipo_articulo == "AP": html = html + "<td>"+det.articulo_personalizado+"</td>" elif det.tipo_articulo == "AC": html = html + "<td><table><tbody>" acs = det.detallearticulocompuesto_set.all() for ac in acs: html = html + "<tr><td>"+get_cantidad_tiempo_ac(ac)+"</td>" if ac.articulo: html = html + "<td>"+ac.articulo.denominacion+"</td>" elif ac.articulo_personalizado: html = html + "<td>"+ac.articulo_personalizado+"</td>" html = html + "<td>"+"%.2f" %ac.precio_unitario+"</td>" html = html + "<td>"+"%.2f" %ac.total_con_descuento_factura_e_item+"</td>" html = html + "</tr>" html = html + "</tbody></table></td>" html = html + "<td>"+"%.2f" %det.precio_unitario+"</td>" html = html + "<td>"+"%.2f" %det.total_con_descuento_factura+"</td>" html = html + "</tr>" html = html + "</tbody></table>" return html def articulo_datatables_view(request): objects = Articulo.objects.all() desde = request.GET['desde'] es_b = True if 'es_b' in request.GET else False print es_b if desde == 'seleccionArticulo': list_display = ['pk','codigo', 'codigo_fabrica','denominacion','rubro.nombre','precio_venta'] #list_filter = ['codigo', 'codigo_fabrica','denominacion'] elif desde == 'mainArticulos': list_display = ['codigo', 'codigo_fabrica','denominacion','linea.nombre','rubro.nombre','ultima_actualizacion_precio'] list_filter = ['codigo', 'codigo_fabrica','denominacion','linea__nombre','rubro__nombre'] # Cuenta total de articulos: recordsTotal = objects.count() #Filtrado de los articulos search = request.GET['search[value]'] if desde == 'seleccionArticulo': queries = [] qcodigo = Q(**{'codigo__icontains' : search}) queries.append(qcodigo) qcodigo_fabrica = Q(**{'codigo_fabrica__icontains' : search}) queries.append(qcodigo_fabrica) qdenocontains = Q(**{'denominacion__icontains' : search}) queries.append(qdenocontains) deno = "" if search: for pa in search.replace(" "," ").split(" "): if pa and pa is not " ": deno = deno + "+"+pa+" " #set_trace() print deno qdenominacion = Q(**{'denominacion__search' : deno}) queries.append(qdenominacion) #queries = [Q(**{f+'__contains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) objects = objects.filter(qs) elif desde == 'mainArticulos': queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) objects = objects.filter(qs) #Ordenado #order = dict( enumerate(list_display) ) #dirs = {'asc': '', 'desc': '-'} #ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])] #objects = objects.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = objects.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) objects = objects[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in objects: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) if es_b: row[5]= obj.precio_venta_iva_inc if desde == 'mainArticulos': ops = '<a href="%s">EDITAR</a> -- <a href="%s">BORRAR</a>' %(reverse_lazy('editarArticulo',args=[obj.pk]),reverse_lazy('borrarArticulo',args=[obj.pk])) row.append(ops) data.append(row) #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def comp_datatables_view(request): comprobantes = Venta.objects.all().order_by('fecha','tipo','numero') print len(comprobantes) list_display = ['fecha', 'tipo','pto_vta_num_full','cliente.razon_social','neto','iva21','total','aprobado'] list_filter = ['cliente__razon_social'] # Cuenta total de articulos: recordsTotal = comprobantes.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) comprobantes = comprobantes.filter(qs) #Ordenado #order = dict( enumerate(list_display) ) #dirs = {'asc': '', 'desc': '-'} #ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])] #objects = objects.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = comprobantes.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) comprobantes = comprobantes[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in comprobantes: print obj.id row=map(lambda field: _getattr_foreingkey(obj, field), list_display) detalles_venta_html = format_det_venta(obj.detalle_venta_set.all()) row.insert(0,detalles_venta_html) if row[-1]: row[-1]="Aprobado" else: row[-1]="Borrador" row[3]="N/A" ops = '<a class="imprimirComprobante" href="%s">IMPRIMIR</a>' %(reverse_lazy('imprimirComprobante',args=[obj.pk])) if obj.aprobado else "" row.append(ops) #Es un table (<table>..........</table> data.append(row) #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def cobros_datatables_view(request): cobros = Recibo.objects.all() #Campos directos, personalizacion mas adelante list_display = ['fecha', 'numero_full','cliente.razon_social','total_str'] list_filter = ['numero', 'cliente__razon_social'] data_struct = {0: 'fecha', 1: 'numero', 2: 'cliente__razon_social'} # Cuenta total de articulos: recordsTotal = cobros.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) cobros = cobros.filter(qs) #Ordenado cobros = ordering(request.GET, cobros, data_struct) #order = dict( enumerate(list_display) ) #dirs = {'asc': '', 'desc': '-'} #ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])] #objects = objects.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = cobros.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) cobros = cobros[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in cobros: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) detalle_pago = Detalle_cobro.objects.filter(recibo=obj) det = "" for detalle in detalle_pago: det = det + "%s<br>" %detalle.venta row.insert(3, det) ops = '<a class="imprimirRecibo" href="%s">IMPRIMIR</a>' %(reverse_lazy('imprimirRecibo',args=[obj.pk])) row.append(ops) data.append(row) #set_trace() #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def get_comprobantes_de_cliente(request,cliente): cliente = Cliente.objects.get(id=cliente) comprs = Venta.objects.filter(cliente=cliente,pagado=False) data = [] for com in comprs: obj = {"id":com.id,"comprobante":"%s" %com} data.append(obj) s = StringIO() json.dump(data,s) s.seek(0) return HttpResponse(s.read()) def get_datos_defecto_cheque(request,cliente): cliente = Cliente.objects.get(id=cliente) defe={'razon_social':cliente.razon_social,'cuit':cliente.cuit,'paguese_a':RAZON_SOCIAL_EMPRESA,'fecha':datetime.date.today().strftime("%d/%m/%Y")} s = StringIO() json.dump(defe,s) s.seek(0) return HttpResponse(s.read()) def get_credito_valores(request,cliente): cliente = Cliente.objects.get(id=cliente) for rec in cliente.recibo_set.all(): for valor in rec.dinero_set.all(): try: if valor.pendiente_para_recibo > 0.009: #obj = {'num_cheque':valor.chequetercero.numero, 'pendiente':'%.2f' %valor.chequetercero.pendiente_para_recibo} obj = {'pendiente':'%.2f' %valor.pendiente_para_recibo} s = StringIO() json.dump(obj,s) s.seek(0) return HttpResponse(s.read()) except Dinero.DoesNotExist: continue return HttpResponse() def get_credito_valores_op(request,proveedor): proveedor = Proveedor.objects.get(id=proveedor) for op in proveedor.ordenpago_set.all(): for valor in op.dinero_set.all(): try: #if valor.chequetercero.pendiente_para_orden_pago > 0.009: if valor.pendiente_para_orden_pago > 0.009: print valor.pendiente_para_orden_pago obj = {'pendiente':'%.2f' %valor.pendiente_para_orden_pago} s = StringIO() json.dump(obj,s) s.seek(0) return HttpResponse(s.read()) except Dinero.DoesNotExist: continue return HttpResponse() def cliente_datatables_view(request): clientes = Cliente.objects.all() list_display = ['razon_social', 'telefono'] list_filter = ['razon_social'] # Cuenta total de articulos: recordsTotal = clientes.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) clientes = clientes.filter(qs) #Ordenado #order = dict( enumerate(list_display) ) #dirs = {'asc': '', 'desc': '-'} #ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])] #objects = objects.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = clientes.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) clientes = clientes[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in clientes: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) direccion = obj.direccion+' - '+obj.localidad+' ('+obj.get_provincia_display()+')' row.insert(1,direccion) #ops = '<a href="%s" class="btn btn-primary" role="button">EDITAR</a> <a href="%s" class="btn btn-danger" role="button">BORRAR</a>'\ # %(reverse_lazy('editarCliente',args=[obj.pk]),reverse_lazy('borrarCliente',args=[obj.pk])) ops = '''<div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Acciones <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="%s">Editar</a></li> <li><a href="%s">Suspender</a></li> </ul> </div>'''\ %(reverse_lazy('editarCliente',args=[obj.pk]),reverse_lazy('borrarCliente',args=[obj.pk])) detalle='''<u>CUIT</u>: <strong>%s</strong><br> <u>Informacion fiscal</u>: Condicion IVA: %s - IIBB: %s<br> <u>Direccion</u>: %s, %s (%s) -- CP: %s<br> <u>Contacto</u>: TE: %s FAX: %s<br> </u>Informacion extra</u>:<br> %s'''\ % (obj.cuit, obj.get_cond_iva_display(), obj.codigo_ingresos_brutos, obj.direccion,\ obj.localidad, obj.provincia, obj.codigo_postal, obj.telefono,\ obj.fax, obj.notas) row.insert(0, detalle) row.append(ops) data.append(row) #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def proveedores_datatables_view(request): proveedores = Proveedor.objects.all() list_display = ['razon_social', 'telefono']#Para direccion uso varios campos, definido abajo list_filter = ['razon_social'] # Cuenta total de articulos: recordsTotal = proveedores.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) proveedores = proveedores.filter(qs) #Ordenado #order = dict( enumerate(list_display) ) #dirs = {'asc': '', 'desc': '-'} #ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])] #objects = objects.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = proveedores.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) proveedores = proveedores[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in proveedores: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) direccion = obj.direccion+' - '+obj.localidad+' ('+obj.provincia+')' row.insert(1,direccion) ops = '''<div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Acciones <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li><a href="%s">Editar</a></li> <li><a href="%s">Suspender</a></li> </ul> </div>'''\ %(reverse_lazy('editarProveedor',args=[obj.pk]),reverse_lazy('borrarProveedor',args=[obj.pk])) detalle='''<u>CUIT</u>: <strong>%s</strong><br> <u>Informacion fiscal</u>: Condicion IVA: %s - IIBB: %s<br> <u>Direccion</u>: %s, %s (%s) -- CP: %s<br> <u>Contacto</u>: TE: %s FAX: %s EMAIL:%s<br> </u>Informacion extra</u>:<br> %s'''\ % (obj.cuit, obj.condicion_iva, obj.codigo_ingresos_brutos, obj.direccion,\ obj.localidad, obj.provincia, obj.codigo_postal, obj.telefono,\ obj.fax, obj.email, obj.notas) row.insert(0, detalle) row.append(ops) data.append(row) #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def cheques_datatables_view(request): tipo=request.GET['tipo'] if tipo=='cartera': cols={1:'fecha',2:'numero',3:'cobro',4:'titular',5:'monto'} cheques = ChequeTercero.objects.all().filter(en_cartera=True) list_display = ['fecha','numero', 'cobro','titular','monto'] list_filter = ['numero'] elif tipo=='completo': cols={1:'fecha',2:'numero',3:'cobro',4:'titular',5:'monto'} cheques = ChequeTercero.objects.all() list_display = ['fecha','numero', 'cobro','titular','monto'] list_filter = ['numero'] # Cuenta total de articulos: recordsTotal = cheques.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) cheques = cheques.filter(qs) #Ordenado #order = dict( enumerate(list_display) ) dirs = {'asc': '', 'desc': '-'} ordering = dirs[request.GET['order[0][dir]']] + cols[int(request.GET['order[0][column]'])] cheques = cheques.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = cheques.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) cheques = cheques[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in cheques: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) if tipo=='completo': estado = 'En cartera' if obj.en_cartera else 'Entregado' row.append(estado) attr_disabled='' #attr_disabled='' if obj.en_cartera else 'disabled' #class_disabled='' class_disabled='' if obj.en_cartera else ' class="disabled"' ops = '''<div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Acciones <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> <li%s><a class="btn_quitar_de_cartera" data-id="%s" %s href="#">Quitar de cartera</a></li> </ul> </div>''' %(class_disabled,obj.id,attr_disabled) row.append(ops) detalle='''<u>CUIT</u>: <strong>%s</strong><br> <u>Banco</u>: %s<br> <u>Entregado por</u>: %s (%s)<br> <u>Paguese a</u>: %s<br> <u>Domiclio de pago</u>: %s<br> <u>Observaciones</u>: %s<br>'''\ % ( obj.cuit_titular, obj.banco.nombre, obj.recibo.cliente, obj.recibo.numero_full, obj.paguese_a,\ obj.domicilio_de_pago, obj.observaciones if obj.observaciones else "N/A") row.insert(0, detalle) if tipo =='cartera': row.append(obj.id) data.append(row) #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def cheques_propios_datatables_view(request): cols={1:'fecha',2:'numero',3:'cobro',4:'monto'} cheques = ChequePropio.objects.all() list_display = ['fecha','numero', 'cobro','monto'] list_filter = ['numero'] # Cuenta total de articulos: recordsTotal = cheques.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) cheques = cheques.filter(qs) #Ordenado #order = dict( enumerate(list_display) ) dirs = {'asc': '', 'desc': '-'} ordering = dirs[request.GET['order[0][dir]']] + cols[int(request.GET['order[0][column]'])] cheques = cheques.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = cheques.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) cheques = cheques[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in cheques: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) detalle='''<u>Paguese a</u>: %s<br> <u>Orden Pago</u>: %s<br>'''\ % ( obj.paguese_a, obj.orden_pago) row.insert(0, detalle) data.append(row) #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def comp_compras_datatables_view(request): cols = {0:'fecha',1:'tipo',2:'identificador',3:'proveedor__razon_social',4:'neto',\ 5:'iva',6:'total',7:'estado'} comprobantes = Compra.objects.all() print (request.GET) for k,v in request.GET.iteritems(): print "Key: %s - Value: %s" %(k,v) list_display = ['fecha', 'tipo','identificador','proveedor.razon_social','neto','iva','total','estado'] list_filter = ['proveedor__razon_social', 'numero'] # Cuenta total de articulos: recordsTotal = comprobantes.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) comprobantes = comprobantes.filter(qs) #Ordenado #order = dict( enumerate(list_display) ) dirs = {'asc': '', 'desc': '-'} ordering = dirs[request.GET['order[0][dir]']] + cols[int(request.GET['order[0][column]'])] comprobantes=comprobantes.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = comprobantes.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) comprobantes = comprobantes[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in comprobantes: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) print row #detalles_venta_html = format_det_venta(obj.detalle_venta_set.all()) #row.insert(0,detalles_venta_html) #ops = '<a class="imprimirComprobante" href="%s">IMPRIMIR</a>' %(reverse_lazy('imprimirComprobante',args=[obj.pk])) if obj.aprobado else "" #row.append(ops) #Es un table (<table>..........</table> data.append(row) #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def cheque_quitar_de_cartera(request):#Mandar id y observaciones en POST print "LALALALALALALALA" if request.POST: id_cheque = request.POST['id_cheque'] observaciones = request.POST['observaciones'] cheque = ChequeTercero.objects.get(id=id_cheque) cheque.observaciones = observaciones cheque.en_cartera=False cheque.save() #obj = {'id':recibo.id} #s = StringIO() #json.dump(obj,s) #s.seek(0) return HttpResponse() def pagos_datatables_view(request): pagos = OrdenPago.objects.all() #Campos directos, personalizacion mas adelante list_display = ['fecha', 'numero_full','proveedor.razon_social','total_str'] list_filter = ['numero', 'proveedor__razon_social'] data_struct = {0: 'fecha', 1: 'numero', 2: 'proveedor__razon_social'} # Cuenta total de articulos: recordsTotal = pagos.count() #Filtrado de los articulos search = request.GET['search[value]'] queries = [Q(**{f+'__icontains' : search}) for f in list_filter] qs = reduce(lambda x, y: x|y, queries) pagos = pagos.filter(qs) #Ordenado pagos = ordering(request.GET, pagos, data_struct) #order = dict( enumerate(list_display) ) #dirs = {'asc': '', 'desc': '-'} #ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])] #objects = objects.order_by(ordering) # Conteo de articulos despues dle filtrado recordsFiltered = pagos.count() # finally, slice according to length sent by dataTables: start = int(request.GET['start']) length = int(request.GET['length']) pagos = pagos[ start : (start+length)] # extract information #data = [map(lambda field: _getattr_foreingkey(obj, field), list_display) for obj in objects] data = [] for obj in pagos: row=map(lambda field: _getattr_foreingkey(obj, field), list_display) det = "" for detalle in obj.detalle_pago_set.all(): det = det + "%s<br>" %detalle.compra row.insert(3, det) val = "" for valor in obj.dinero_set.all(): val = val + "%s<br>" %valor row.insert(4, val) ops = '<a class="imprimirOrdenPago" href="%s">IMPRIMIR</a>' %(reverse_lazy('imprimirOrdenPago',args=[obj.pk])) row.append(ops) data.append(row) #set_trace() #define response response = { 'data': data, 'recordsTotal': recordsTotal, 'recordsFiltered': recordsFiltered, 'draw': request.GET['draw'] } #serialize to json s = StringIO() json.dump(response, s) s.seek(0) return HttpResponse(s.read()) def validar_comprobante_compra(request): numero = request.GET['numero'] punto_venta = request.GET['punto_venta'] tipo = request.GET['tipo_comprobante'] proveedor = request.GET['proveedor'] try: com = Compra.objects.get(numero=numero, punto_venta=punto_venta, tipo=tipo, proveedor__id=proveedor) print com if com: existe = True else: existe = False except Compra.DoesNotExist: existe = False print "Existe: %s" %existe obj = {'existe': existe} s = StringIO() json.dump(obj, s) s.seek(0) return HttpResponse(s.read())
[ "jariberi@gmail.com" ]
jariberi@gmail.com
e7b1234dabcd20980a3ecafe45c7a90b8b2eb887
5d9b8f8c8d5d3d5619aa4a4315f15f3595120e8a
/lcs/agents/yacs/__init__.py
84f29ef38ed5c526be58faf5d67e17cf667526f8
[ "MIT" ]
permissive
ParrotPrediction/pyalcs
e752d87cec4c9a7ea59099e9162a22edf2c5e751
9811bc5cde935e04e0fd87fb5930bd1b9170e73a
refs/heads/master
2023-06-10T01:36:20.465974
2022-04-11T12:14:02
2022-04-11T12:14:02
78,022,708
11
17
MIT
2023-05-31T17:09:37
2017-01-04T14:28:53
Python
UTF-8
Python
false
false
38
py
from .yacs import Configuration, YACS
[ "noreply@github.com" ]
noreply@github.com
cdb0f62c22ca6450cb047066dfa91fdc6c7c1520
769c05bab5d656eaa060af78f2974422970c7a86
/salary_simulation_API/models/pessoas/pessoa_juridica.py
4db9170b7adfd2c4c0a6dfffd9360479bdd6825b
[]
no_license
IanniMuliterno/salary-simulation-API
e201cc0f690797a541629054f8bfb9f0a3228dc7
ffb5a93db8d15a9b0dab4ab832aaf8225939eae5
refs/heads/master
2023-01-22T07:11:32.102657
2020-11-16T09:15:53
2020-11-16T09:15:53
null
0
0
null
null
null
null
UTF-8
Python
false
false
203
py
from salary_simulation_API.models.pessoas.pessoa import Pessoa class Pessoa_Juridica(Pessoa): def __init__(self, nome, cnpj, qtd_dependentes): super().__init__(nome, cnpj, qtd_dependentes)
[ "diogotnascimento94@gmail.com" ]
diogotnascimento94@gmail.com
d71225a5971b289a663790b22a26fbfd50314c32
5857ce4d4579381ce03938f32e96f482f0b59485
/session6/exp_1/exp_1_2.py
69c102057ecac35e66cfd6d9307715b6f1461852
[]
no_license
Burntt/Python_for_Data_Science
3ae9eeb10a94a194c0e7436613929aad1a1dbd56
5ef040a23953bf48a6654cb9c6f9ebf6f1dc99ce
refs/heads/master
2023-04-23T03:26:40.412523
2021-05-05T19:25:48
2021-05-05T19:25:48
312,195,854
0
0
null
null
null
null
UTF-8
Python
false
false
564
py
from sklearn import preprocessing from sklearn import linear_model from exp_1.exp_1_1 import feature_transformation, train, predict, classifier, fit_classifier from exp_1 import exp_1_1 def init_classifier(): # global classifier exp_1_1.classifier = linear_model.LogisticRegression( penalty = 'l1', random_state = 2022 ) print('Exp_1_2 classifier initialized') def predict_proba(self, test_df): transformed_features = self.feature_transformation(test_df) return self.fit_classifier.predict_proba(transformed_features)
[ "allesaangort@gmail.com" ]
allesaangort@gmail.com
8df5cec16f173c8706a8a401d7180c003d9c5c7b
ebbb5fd79e8ea187de2e4deafd340b15a361020e
/src/flask_multi_view/extensions/sqlachemy.py
6cfb2184545f14c9be838f9d9757333590c8a2e4
[ "MIT" ]
permissive
wooyek/glosuj-w-lomiankach
0b90f7062d821234b4f8f9b940d46fd437a7edbd
0bc957d3a3d05127ea16d07c112a6a3705dcdc88
refs/heads/master
2021-01-22T17:22:06.416701
2014-10-21T11:02:50
2014-10-21T11:02:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
14,637
py
# coding=utf-8 # Copyright 2013 Janusz Skonieczny import json import logging from flask import request, render_template, make_response from .. import form_next, ViewSetupError from ..actions import BaseActionView from ..forms import DefaultDeleteForm from werkzeug.exceptions import NotFound from werkzeug.utils import redirect from flask_babel import gettext as _ def get_or_404(model, primary_key, next_url=None): rv = model.query.get(primary_key) if rv: return rv if next_url: return redirect(next_url) msg = _(u"Nie znaleziono obiektu „{}” dla klucza {}") raise NotFound(msg.format(model.__name__, str(primary_key))) class BaseModelView(BaseActionView): model = None query = None page_size = 20 rules = {} def _load_obj(self, *args, **kwargs): """ Load instance based on key/id in view arguments """ id = kwargs.get('id') return get_or_404(self.model, id) def _get_query(self, parent=None, order=None, *args, **kwargs): """ Get the list of items for this view. This must be an interable, and may be a queryset (in which qs-specific behavior will be enabled). """ if self.query: return self.query if not self.model: raise ViewSetupError(u"'%s' must define or 'query' or 'model'".format(self.__class__.__name__)) self.query = self.model.query order = request.args.get('order', order) if order: if order.startswith("-"): self.query = self.query.order_by(getattr(self.model, order[1:]).desc()) else: self.query = self.query.order_by(getattr(self.model, order[1:])) return self.query, order def _get_list_context(self, query, order=None, *args, **kwargs): """ Get the context for this view. """ page_size = int(request.args.get('page_size', self.page_size)) if not page_size: # ignore paging setup if there is no page_size set return {'list': query} # offset is purely informational and ignored when during page fetching offset = request.args.get('offset') offset = int(offset) + page_size if offset else 0 cursor = request.args.get('cursor') if cursor: raise Exception("Cursors are not supported") # cursor = Cursor(urlsafe=cursor) # seq, cursor, more = query.fetch_page(self.page_size, start_cursor=cursor) else: seq = query.offset(offset).limit(page_size).all() more = True # TODO: 19.11.13 wooyek this needs improvemnts ;) if cursor: cursor = cursor.urlsafe() context = { 'list': seq, 'paginator': {'cursor': cursor, 'more': more, 'offset': offset, 'order': order}, } return context @classmethod def get_rules(cls, action, view, default=None): """ Add a dictionary fallback for rules declaration. """ view_rules = super(BaseModelView, cls).get_rules(action, view, default=None) return view_rules or cls.rules.get(action, default) class ModelView(BaseModelView): """CRUD actions auto generated for a given model. Gives meth:`list`, meth:`create_get`, meth:`create_put`, meth:`detail`, meth:`update_get`, meth:`update_post`, meth:`delete_get` and meth:`delete_post methods`. Subclass has to declare setup options and call :meth:`register_routes`:: class MyView(ModelView): model = MyModel MyView.register(app) """ templates = {} templates_xhr = {} forms = {} # This controller creates a fallback rule declaration method for easy rules override # in subclasses without the need to re-declare action method rules = { "list": [("", {})], # will generate a /Model/ url without trailing 'list' "detail": [("<int:id>/", {})], # key based detail, modify this "create": [(None, {"methods": ['GET', 'POST']})], # create "update": [("<int:id>/update", {"methods": ['GET', 'POST']})], "delete": [("<int:id>/delete", {"methods": ['GET', 'POST']})], } def __init__(self): super(ModelView, self).__init__() # need to copy mutable class fields to instance to avoid type wide changes self.templates = self.templates.copy() self.templates_xhr = self.templates_xhr.copy() self.forms = self.forms.copy() self.obj = None def list(self, *args, **kwargs): """ Renders a list page with pagination support based on :class:`google.appengine.ext.ndb.query.Cursor`. :return: Responce object """ query, order = self._get_query(*args, **kwargs) context = self._get_list_context(query, order) response = self._render("list", **context) if "paginator" in context: headers = { 'X-Cursor': context['paginator']['cursor'], 'X-Offset': context['paginator']['offset'], } response.headers.extend(headers) return response def detail(self, *args, **kwargs): """Renders a signdle object detail page :return: Responce object """ self.obj = self._load_obj(*args, **kwargs) context = self._get_detail_context(object=self.obj) response = self._render("detail", **context) # # TODO: 19.11.13 wooyek this is silly, tiw ill not work with all models from SQLAlchemy # http://stackoverflow.com/questions/6745189/how-do-i-get-the-name-of-an-sqlalchemy-objects-primary-key # headers = { # 'X-PrimaryKey': self.obj.id, # # 'X-Key': self.obj.key.urlsafe(), # } # response.headers.extend(headers) return response @form_next def create(self, *args, **kwargs): form = self._get_form("create", *args, **kwargs) next_url = request.args.get("next_url") if not form.validate_on_submit(): # not valid show the form again return self._render("create", form=form, next_url=next_url) # create object and redirect to next_url or read_get # self.obj = self.model() # form.populate_obj(self.obj) # self.obj.put() self.obj = form.save() return redirect(self._get_create_next()) @form_next def update(self, *args, **kwargs): self.obj = self._load_obj(*args, **kwargs) form = self._get_form("update", obj=self.obj, *args, **kwargs) next_url = request.args.get("next_url") or self.url('detail', key=self.obj.key) if not form.validate_on_submit(): # not valid show the form again return self._render("update", form=form, object=self.obj, next_url=next_url) # update object and redirect to next_url or read_get # form.populate_obj(self.obj) # self.obj.put() form.save() return redirect(next_url) @form_next def delete(self, *args, **kwargs): try: self.obj = self._load_obj(*args, **kwargs) except NotFound: return redirect(self.url('list')) form = self._get_form("delete", obj=self.obj, default=DefaultDeleteForm, *args, **kwargs) if not form.validate_on_submit(): next_url = request.args.get("next_url") or self.url('detail', key=self.obj.key.urlsafe()) # not valid show the form again return self._render("delete", form=form, object=self.obj, next_url=next_url) # delete object and redirect to next_url or read_get self.obj.key.delete() next_url = request.args.get("next_url") if next_url and next_url.endswith(self.url('detail', key=self.obj.key)): next_url = None return redirect(next_url or self.url('list')) def _get_form(self, action, obj=None, default=None, parent=None, *args, **kwargs): """ Creates an instance of form for a given action """ form_class = self._get_form_class(action, default=default, *args, **kwargs) # query parameters can be used as initial data for the form form_initial_data = kwargs.pop("form_initial_data", None) or request.args # passing only an initial data as kwargs # flaskext.wft.form.Form is auto loading it's form_data from the request return form_class(obj=obj, model=self.model, parent=parent, **form_initial_data) def _get_create_next(self): return request.args.get("next_url") or self.url("list") def _get_template(self, view): """ Return a template name or a template itself """ if request.is_xhr: template = self.templates_xhr.get(view) or self.templates.get(view) else: template = self.templates.get(view) kind = self.controller_name() if view == 'list' and template is None: # special list template select for XHR requests if request.is_xhr: return "{}/rows.html".format(kind) return "{}/list.html".format(kind) if template is None and view in ['create', 'update']: # special create/update fallback return "{}/form.html".format(kind) # default template is named after view and places in folder named after model kind return "{}/{}.html".format(kind, view) def _render(self, view, **kwargs): """ Renders a template and returs a Responcse instance """ # assert context is not None, "RenderMixin needs context data other than None" template_name = self._get_template(view) assert template_name body = render_template(template_name, view=self, **kwargs) return make_response(body) def _get_detail_context(self, **kwargs): return kwargs def _get_form_class(self, action, default=None, *args, **kwargs): """ Gets form_class from forms dictionary or finds a default form for a model based on model kind. """ form_class = self.forms.get(action) if form_class: return form_class elif default: return default # forms_module = self.model.__module__.split('.', -1)[0] + ".forms" forms_module = self.__module__.rsplit('.', 1)[0] + ".forms" form_class = self.controller_name() + "Form" logging.debug("form_class: %s" % form_class) import sys try: __import__(forms_module) form_class = getattr(sys.modules[forms_module], form_class) self.forms[action] = form_class return form_class except ImportError as ex: logging.warn(ex, exc_info=True) msg = "{0} could not import a default forms module '{1}'. Provide a form class or put '{2}' it in the default forms module." msg = msg.format(self.__class__.__name__, forms_module, form_class) raise ViewSetupError(msg) except AttributeError as ex: logging.warn(ex, exc_info=True) msg = "{0} could not find a default form '{2}' in '{1}' module. Provide a form class or implement a default one." msg = msg.format(self.__class__.__name__, forms_module, form_class) raise ViewSetupError(msg) class ModelRPC(BaseModelView): json_encoder = None # This controller creates a fallback rule declaration method for easy rules override # in subclasses without the need to re-declare action method rules = { "rpc": [("<int:id>/rpc", {"methods": ["GET", "PUT", "DELETE"]})], "search": [("search", {"methods": ["GET"]})], } def rpc(self, **kwargs): meth = getattr(self, "_" + request.method.lower(), None) # if the request method is HEAD and we don't have a handler for it # retry with GET if meth is None and request.method == 'HEAD': meth = getattr(self, '_get', None) assert meth is not None, 'Unimplemented method %r' % request.method return meth(**kwargs) def _get(self, id): obj = self._load_obj(id=id) rv = json.dumps(obj, indent=2, cls=self.json_encoder) return make_response(rv, 200, {'Content-Type': "application/json; charset=utf-8"}) def _put(self, id): obj = self._load_obj(id=id) obj.update(**request.json) obj.put() data = { "success": True, } rv = json.dumps(data, cls=self.json_encoder) return make_response(rv, 200, {'Content-Type': "application/json; charset=utf-8"}) def _delete(self, key): ndb.transaction(key.delete) data = { "success": True, } rv = json.dumps(data, cls=self.json_encoder) return make_response(rv, 200, {'Content-Type': "application/json; charset=utf-8"}) def search(self, *args, **kwargs): query, order = self._get_query(*args, **kwargs) search = request.args.get('search') query_field = request.args.get('query_field') field = getattr(self.model, query_field) query = query.filter(field.startswith(search)) data = self._get_list_context(query) data['list'] = [{"id": o.id, "cn": o.cn} for o in data['list']] rv = json.dumps(data, indent=2, cls=self.json_encoder) return make_response(rv, 200, {'Content-Type': "application/json; charset=utf-8"}) class ChildModelView(ModelView): parent_model = None @classmethod def get_url_prefix(cls, action=None): """ Prefixes url with parent key """ if action in ("list", "create"): return "/{}/<key:parent>/{}".format(cls.parent_model.__name__, cls.controller_name()) return super(ChildModelView, cls).get_url_prefix(action) def url(self, action, **kwargs): if action in ("list", "create"): parent = self.key or getattr(self, "parent", None) kwargs['parent'] = parent return super(ChildModelView, self).url(action, **kwargs)
[ "js@bravelabs.pl" ]
js@bravelabs.pl
c682dbe0c08b2b8188a1f15f8be584ff2944f575
0810b308b09e6680b5df2b5f412494d07d02f181
/1905/month01/code/day11/demo01.py
6df18b52956cef2cc3a75f7c6d67874f3607f4cf
[]
no_license
952033053/python3
d323ecff1bcd208fc81b74e2ab7e0eb9ce31d514
29c8fb7f3ca90e18cce1f9a62a27415aac946c46
refs/heads/master
2020-06-21T18:19:55.610435
2019-07-18T02:57:31
2019-07-18T02:57:31
197,524,517
0
0
null
null
null
null
UTF-8
Python
false
false
1,210
py
class Wife: def __init__(self, name, age, weight): self.name = name # 本质:障眼法(实际将变量名改为:_类名__age) # self.__age = age self.set_age(age) # self.__weight = weight self.set_weight(weight) # 提供公开的读写方法 def get_age(self): return self.__age def set_age(self, value): if 21 <= value <= 31: self.__age = value else: pass # 提供公开的读写方法 def get_weight(self): return self.__weight def set_weight(self, value): if 40 <= value <= 60: self.__weight = value else: pass w01 = Wife("铁锤公主", 20, 20) # 重新创建了新实例变量(没有改变类中定义的__age) # w01.__age = 107  w01._Wife__age = 20 # (修改了类中定义的私有变量) print(w01.__dict__)# python内置变量,存储对象的实例变量. w01 = Wife("铁锤公主", 30, 50) w01.set_age(25) w01.set_weight(55) print(w01.get_age()) print(w01.get_weight()) # 练习:定义敌人类(姓名,攻击力10 -- 50,血量100 -- 200) # 创建一个敌人对象,可以修改数据,读取数据。
[ "lvze@tedu.cn" ]
lvze@tedu.cn
3e5c8a02435756870b66ed8e37cefa1637efcfc2
85180a2385e0b336ab0ebc2159627a992b4b99ea
/personal_portfolio_project/blog/urls.py
8cd9037a72c7c570932044e80eaa39eaf40160dd
[ "MIT" ]
permissive
HuyNguyen260398/Django-Portfolio
d939157006902e2f9e5010ef43edd2035eddf2ba
6edfe98f0296a76e7b0b783c79df7565555bb9e9
refs/heads/master
2022-10-06T16:29:45.443896
2020-06-07T14:52:47
2020-06-07T14:52:47
269,487,297
0
0
null
null
null
null
UTF-8
Python
false
false
204
py
from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.all_blogs, name='all_blogs'), path('<int:blog_id>/', views.blog_detail, name='blog_detail'), ]
[ "huynguyen260398@gmail.com" ]
huynguyen260398@gmail.com
bc22e398eb6df31cbeb29c3afa9753fce3ee2209
d5552053db67872b4c914931208a76f3a4dc190d
/app/auth/forms.py
6083cf97bcac4e50a3e9a320b2d1027756104366
[ "MIT" ]
permissive
LonglyCode/flask-blog
24e5df9ae904d67e825077f4c6ed513d63f88bc6
b7f36e8798c61aa1669ede59452f3ca446f5b9ce
refs/heads/master
2021-01-12T13:28:52.947100
2017-04-09T12:08:05
2017-04-09T12:08:05
69,955,539
2
0
null
null
null
null
UTF-8
Python
false
false
3,140
py
from flask_wtf import Form from wtforms import (BooleanField, PasswordField, StringField, SubmitField, ValidationError) from wtforms.validators import Email, EqualTo, Length, Regexp, Required from ..models import User class LoginForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) password = PasswordField('Password', validators=[Required()]) remember_me = BooleanField('Keep me logged in') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) username = StringField('Username', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) password = PasswordField('Password', validators=[ Required(), EqualTo('password2', message='Passwords must match.')]) password2 = PasswordField('Confirm password', validators=[Required()]) submit = SubmitField('Register') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Username already in use.') class ChangePasswordForm(Form): old_password = PasswordField('Old password', validators=[Required()]) password = PasswordField('New password', validators=[ Required(), EqualTo('password2', message='Passwords must match')]) password2 = PasswordField('Confirm new password', validators=[Required()]) submit = SubmitField('Update Password') class PasswordResetRequestForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) submit = SubmitField('Reset Password') class PasswordResetForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) password = PasswordField('New Password', validators=[ Required(), EqualTo('password2', message='Passwords must match')]) password2 = PasswordField('Confirm password', validators=[Required()]) submit = SubmitField('Reset Password') def validate_email(self, field): if User.query.filter_by(email=field.data).first() is None: raise ValidationError('Unknown email address.') class ChangeEmailForm(Form): email = StringField('New Email', validators=[Required(), Length(1, 64), Email()]) password = PasswordField('Password', validators=[Required()]) submit = SubmitField('Update Email Address') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.')
[ "emoxun8215@gmail.com" ]
emoxun8215@gmail.com
5022aed0c12a9d2b6cc6445c59f653eb34a351a5
3e89e83b5d6d603b08328a24af3ebed04fbffe70
/apps/storybase/models/base.py
35124d23be4ad87e75f439e3704cf96d832b68f9
[]
no_license
jwirfs-brock/atlas
cd955dc81750c415030f89bd4f71478717c68b61
ceee382c206b483d21c0cfdb99603bf647de18df
refs/heads/master
2021-01-21T00:04:54.837863
2012-09-21T16:03:44
2012-09-21T16:03:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,975
py
"""Abstract base classes for common Model functionality""" from datetime import datetime from django.db import models class LicensedModel(models.Model): """Abstract base class for models with a license""" # Class "constants" DEFAULT_LICENSE = 'CC BY-NC-SA' LICENSES = ( ('CC BY-NC-SA', u'Attribution-NonCommercial-ShareAlike Creative Commons'), ('CC BY-NC', u'Attribution-NonCommercial Creative Commons'), ('CC BY-NC-ND', u'Attribution-NonCommercial-NoDerivs Creative Commons'), ('CC BY', u'Attribution Creative Commons'), ('CC BY-SA', u'Attribution-ShareAlike Creative Commons'), ('CC BY-ND', u'Attribution-NoDerivs Creative Commons'), ('none', u'None (All rights reserved)') ) # Fields license = models.CharField(max_length=25, choices=LICENSES, default=DEFAULT_LICENSE) class Meta: """Model metadata options""" abstract = True def get_license_name(self, code): """Convert a license's code to its full name Arguments: code -- String representing the first element of a tuple in LICENSES. This is what is stored in the database for a LicensedModel. """ licenses = dict(self.LICENSES) return licenses[code] def license_name(self): """ Convert the license code to a more human-readable version """ return self.get_license_name(self.license) class PublishedModel(models.Model): """Abstract base class for models with publication information""" # Class-level "constants" STATUS = ( (u'draft', u'draft'), (u'published', u'published'), ) DEFAULT_STATUS = u'draft' # Fields status = models.CharField(max_length=10, choices=STATUS, default=DEFAULT_STATUS) published = models.DateTimeField(blank=True, null=True) class Meta: """Model metadata options""" abstract = True # Signal handlers def set_date_on_published(sender, instance, **kwargs): """Set the published date of a story on status change For models inheriting from PublishedModel. Should be connected to the pre_save signal. """ try: old_instance = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: # Object is new, so field won't have changed. # Just check status. if instance.status == 'published': instance.published = datetime.now() else: if (instance.status == 'published' and old_instance.status != 'published'): instance.published = datetime.now() class TimestampedModel(models.Model): """ Abstract base class that provides created and last edited fields """ created = models.DateTimeField(auto_now_add=True) last_edited = models.DateTimeField(auto_now=True) class Meta: """Model metadata options""" abstract = True
[ "geoff@terrorware.com" ]
geoff@terrorware.com
5305a63f29462426d834113f01d8cae548e68af0
96513b17edbc399aad3a788c08b1338c0acdaa44
/manage.py
0035c98fbfd42bce9e0c6dfe18d103ff627680c7
[]
no_license
lostarray/BaiduMusic
bd6b5e2931cbc2beececf70c1bc5c6c066ee3c54
a5005c29833cc8b41ca462dd14b4877632cf5e1d
refs/heads/master
2021-01-01T18:41:47.278945
2013-09-07T14:38:33
2013-09-07T14:38:33
12,340,507
1
0
null
null
null
null
UTF-8
Python
false
false
253
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "baidumusic.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "dev@lostarray.com" ]
dev@lostarray.com
f1ece8a87e4704cc91b73d8644f880bf5fdb87f6
726a328641d1d22c061233847b9b869476a0708d
/users/models.py
e27865c503925206fa44b511f51430c3c65c1da5
[]
no_license
dennix2014/bandersnatch
081af3420ae0b5823fca931c39c670f310ca434e
1b0322e0aa0f5af6e05a0a216592d1242ffa55fb
refs/heads/master
2020-08-01T05:07:34.606924
2019-09-25T21:06:07
2019-09-25T21:06:07
210,865,999
0
0
null
null
null
null
UTF-8
Python
false
false
1,924
py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, first_name=first_name, last_name=last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, first_name, last_name, **extra_fields): user=self._create_user(email, password, first_name, last_name, True, True, **extra_fields) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def get_user(): return User.objects.get(id=2)
[ "denisu29@gmail.com" ]
denisu29@gmail.com
904dd720156582a9d32aad1b748857d40ea41d53
b2aea92629c72fcc8333b5638711336636cc4ca4
/website/__init__.py
1e1fba60009aa596d22e4558e0e73af874badadc
[ "MIT" ]
permissive
prathits012/songData
ed0e0959af7f7456661f51ead220aab72c3bb4af
8f42cacc55f5a62d22e968619d134f5771781f64
refs/heads/main
2023-02-19T15:33:56.947217
2021-01-16T06:45:20
2021-01-16T06:45:20
324,482,675
0
1
null
2021-01-05T04:11:18
2020-12-26T04:43:00
Python
UTF-8
Python
false
false
1,036
py
"""WEBSITE package initializer.""" import flask # app is a single object used by all the code modules in this package app = flask.Flask(__name__) # pylint: disable=invalid-name # Read settings from config module (website/config.py) app.config.from_object("website.config") # Overlay settings read from a Python file whose path is set in the environment # variable INSTA485_SETTINGS. Setting this environment variable is optional. # Docs: http://flask.pocoo.org/docs/latest/config/ # # EXAMPLE: # $ export WEBSITE_SETTINGS=secret_key_config.py app.config.from_envvar("WEBSITE_SETTINGS", silent=True) # Tell our app about views and model. This is dangerously close to a # circular import, which is naughty, but Flask was designed that way. # (Reference http://flask.pocoo.org/docs/patterns/packages/) We're # going to tell pylint and pycodestyle to ignore this coding style violation. import website.api # noqa: E402 pylint: disable=wrong-import-position import website.views # noqa: E402 pylint: disable=wrong-import-position
[ "sharjani@umich.edu" ]
sharjani@umich.edu
0538ced83301e51cdbcd5ac5065bade2f2a5a2ec
ff79c73d6c4d9f53099880a9ce5f614685268601
/fuzzers/machxo3/007-plc2_cemux/fuzzer.py
65f503f3f4fdb86a1af598aa909b74984e85f1ad
[ "ISC", "MIT" ]
permissive
YosysHQ/prjtrellis
79f88b5a398c67730601813330f77826902b7664
e830a28077e1a789d32e75841312120ae624c8d6
refs/heads/master
2023-08-06T17:00:57.091823
2023-07-03T15:20:30
2023-07-03T15:20:30
123,840,862
152
33
NOASSERTION
2023-09-08T23:34:29
2018-03-04T23:57:10
Python
UTF-8
Python
false
false
952
py
from fuzzconfig import FuzzConfig import nonrouting import fuzzloops import nets import pytrellis import re cfg = FuzzConfig(job="PLC2REG", family="MachXO3", device="LCMXO3LF-1300E", ncl="empty.ncl", tiles=["R10C11:PLC"]) def main(): pytrellis.load_database("../../../database") cfg.setup() empty_bitfile = cfg.build_design(cfg.ncl, {}) cfg.ncl = "cemux.ncl" def per_slice(slicen): def get_substs(cemux): if cemux == "INV": cemux = "CE:::CE=#INV" if cemux == "0": cemux = "1:::1=0" return dict(slice=slicen, cemux=cemux) nonrouting.fuzz_enum_setting(cfg, "SLICE{}.CEMUX".format(slicen), ["0", "1", "CE", "INV"], lambda x: get_substs(cemux=x), empty_bitfile, False) fuzzloops.parallel_foreach(["A", "B", "C", "D"], per_slice) if __name__ == "__main__": main()
[ "mmicko@gmail.com" ]
mmicko@gmail.com
a23a7e33c1782c9ee33febac97d8c7f5bf25be3c
c9a57c4d9692883287c8c761e097bc9203340428
/예제.py
dab0378b03387f291c0d133bbb9a372b98e78eb8
[]
no_license
KANG-YEONWOOK/ppythonn
ce3f58bf1f332742466c9a90196ab5947e622373
ca6366d09cfbcff0b8b2f7580581dd32ff59fe67
refs/heads/master
2023-03-01T19:35:50.831326
2021-02-14T10:15:41
2021-02-14T10:15:41
338,767,104
0
0
null
null
null
null
UTF-8
Python
false
false
461
py
a = ("홍길동", "고길동", "김길동", "이길동") b = [[1,2,3,0,1],[2,3,4,0,1],[1,2,4,0,1],[3,3,4,0,1]] for i in range(0, len(a)) : for j in range(0, len(b)-1) : b[i][3] = b[i][3] + b[i][j] for i in range(0, len(b)) : for j in range(i+1, len(b)): if b[i][3] < b[j][3] : b[i][4] += 1 elif b[i][3] > b[j][3] : b[j][4] += 1 else : b[i][4] += 1 b[j][4] += 1 print(b)
[ "wook1833@gmail.com" ]
wook1833@gmail.com
68525d7c28155593970297ce734a3defb5f52017
6c725248ae880e52e2fb9f1cd007eb50cdffa272
/paper/generate_heatmaps.py
9ca3a97abffb9bcfffc00732acefda4953b51c82
[ "MIT" ]
permissive
mymuli/memory-wrap
921850ace41de347e700346391f5d4df7a065b99
b26ca3b2567bd5cd6e114957cd799153f620ac7b
refs/heads/master
2023-06-30T17:07:18.231782
2021-08-04T13:26:59
2021-08-04T13:26:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,331
py
import torch # type: ignore import numpy as np import absl.flags import absl.app import os import datasets import aux import matplotlib.pyplot as plt # type: ignore from matplotlib import figure # type: ignore import captum.attr # type: ignore # user flags absl.flags.DEFINE_string("path_model", None, "Path of the trained model") absl.flags.DEFINE_string("dir_dataset", 'datasets/', "dir path where datasets are stored") absl.flags.mark_flag_as_required("path_model") FLAGS = absl.flags.FLAGS def visualize_image_mult_attr( attr, original_image, method, sign, titles = None, fig_size = (4, 6), use_pyplot = True ): r""" Modified version of visualize_image_mult_attr of Captum library. Visualizes attribution using multiple visualization methods displayed in a 1 x k grid, where k is the number of desired visualizations. Args: attr (numpy.array): Numpy array corresponding to attributions to be visualized. Shape must be in the form (H, W, C), with channels as last dimension. Shape must also match that of the original image if provided. original_image (numpy.array, optional): Numpy array corresponding to original image. Shape must be in the form (H, W, C), with channels as the last dimension. Image can be provided either with values in range 0-1 or 0-255. This is a necessary argument for any visualization method which utilizes the original image. methods (list of strings): List of strings of length k, defining method for each visualization. Each method must be a valid string argument for method to visualize_image_attr. signs (list of strings): List of strings of length k, defining signs for each visualization. Each sign must be a valid string argument for sign to visualize_image_attr. titles (list of strings, optional): List of strings of length k, providing a title string for each plot. If None is provided, no titles are added to subplots. Default: None fig_size (tuple, optional): Size of figure created. Default: (8, 6) use_pyplot (boolean, optional): If true, uses pyplot to create and show figure and displays the figure after creating. If False, uses Matplotlib object oriented API and simply returns a figure object without showing. Default: True. **kwargs (Any, optional): Any additional arguments which will be passed to every individual visualization. Such arguments include `show_colorbar`, `alpha_overlay`, `cmap`, etc. Returns: 2-element tuple of **figure**, **axis**: - **figure** (*matplotlib.pyplot.figure*): Figure object on which visualization is created. If plt_fig_axis argument is given, this is the same figure provided. - **axis** (*matplotlib.pyplot.axis*): Axis object on which visualization is created. If plt_fig_axis argument is given, this is the same axis provided. Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> ig = IntegratedGradients(net) >>> # Computes integrated gradients for class 3 for a given image . >>> attribution, delta = ig.attribute(orig_image, target=3) >>> # Displays original image and heat map visualization of >>> # computed attributions side by side. >>> _ = visualize_mutliple_image_attr(attribution, orig_image, >>> ["original_image", "heat_map"], ["all", "positive"]) """ if titles is not None: assert len(attr) == len(titles), ( "If titles list is given, length must " "match that of methods list." ) if use_pyplot: plt_fig = plt.figure(figsize=fig_size) else: plt_fig = figure.Figure(figsize=fig_size) el_4cols = int(len(attr)/len(original_image)) plt_axis = plt_fig.subplots(len(original_image), el_4cols) # When visualizing one if len(attr) == 1: plt_axis = [plt_axis] for i in range(len(attr)): row = int(i/(len(attr)/len(original_image))) image = original_image[row] column = int(i%el_4cols) if attr[i] is None: meth = "original_image" captum.attr.visualization.visualize_image_attr( attr[i], original_image=image, method=meth, sign=sign, plt_fig_axis=(plt_fig, plt_axis[row][column]), use_pyplot=False, title=titles[i] if titles else None, ) else: meth = method captum.attr.visualization.visualize_image_attr( attr[i], original_image=image, method=meth, sign=sign, plt_fig_axis=(plt_fig, plt_axis[row][column]), show_colorbar=True, use_pyplot=False, alpha_overlay=0.4, cmap='plasma', outlier_perc=20, title=titles[i] if titles else None, ) plt_axis[row][column].set_box_aspect(1) plt_fig.tight_layout() if use_pyplot: plt.show() return plt_fig, plt_axis def run(path:str,dataset_dir:str): """ Function to generate heatmaps for testing images using a given model. Args: path (str): model path dataset_dir (str): dir where datasets are stored """ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("Device:{}".format(device)) batch_size_test=1 # load model checkpoint = torch.load(path) modality = checkpoint['modality'] if modality not in ['memory','encoder_memory']: raise ValueError(f'Model\'s modality (model type) must be one of [\'memory\',\'encoder_memory\'], not {modality}.') dataset_name = checkpoint['dataset_name'] model = aux.get_model( checkpoint['model_name'],checkpoint['num_classes'],model_type= modality) model.load_state_dict(checkpoint['model_state_dict']) model = model.to(device) model.eval() # load data train_examples = checkpoint['train_examples'] if dataset_name == 'CIFAR10' or dataset_name == 'CINIC10': name_classes= ['airplane','automobile', 'bird', 'cat','deer','dog', 'frog' ,'horse','ship','truck'] else: name_classes = range(checkpoint['num_classes']) load_dataset = getattr(datasets, 'get_'+dataset_name) undo_normalization = getattr(datasets, 'undo_normalization_'+dataset_name) _, _, test_loader, mem_loader = load_dataset(dataset_dir,batch_size_train=50, batch_size_test=batch_size_test,batch_size_memory=100,size_train=train_examples) memory_iter = iter(mem_loader) def get_image(image, revert_norm=True): if revert_norm: im = undo_normalization(image) else: im = image im = im.squeeze().cpu().detach().numpy() transformed_im = np.transpose(im, (1, 2, 0)) return transformed_im #saving stuff dir_save = "images/saliency/"+dataset_name+"/"+modality+"/" + checkpoint['model_name'] + "/" if not os.path.isdir(dir_save): os.makedirs(dir_save) # run heatmap saliency = captum.attr.IntegratedGradients(model) show_grad = "positive" type_viz = "blended_heat_map" for batch_idx, (images, _) in enumerate(test_loader): try: memory, _ = next(memory_iter) except StopIteration: memory_iter = iter(mem_loader) memory, _ = next(memory_iter) try: aux_memory, _ = next(memory_iter) except StopIteration: memory_iter = iter(mem_loader) aux_memory, _ = next(memory_iter) images = images.to(device) memory = memory.to(device) aux_memory = aux_memory.to(device) #compute output outputs,rw = model(images,memory,return_weights=True) _, predictions = torch.max(outputs, 1) # compute memory outputs memory_outputs = model(memory,aux_memory) _, memory_predictions = torch.max(memory_outputs, 1) mem_val,memory_sorted_index = torch.sort(rw,descending=True) # build baselines for heatmap baseline_input = torch.ones_like(images[0].unsqueeze(0)) images.requires_grad = True for ind in range(len(images)): model.zero_grad() input_selected = images[ind].unsqueeze(0) # M_c u M_e : set of sample with a positive impact on prediction m_ec = memory_sorted_index[ind][mem_val[ind]>0] pred_mec = memory_predictions[m_ec] mc = memory_sorted_index[ind][(pred_mec != predictions[ind]).nonzero(as_tuple=True)].tolist() me = memory_sorted_index[ind][(pred_mec == predictions[ind]).nonzero(as_tuple=True)].tolist() #get images current_image = get_image(images[ind]) if mc: top_counter_index = mc[0] counter_image = get_image(memory[top_counter_index]) if me: top_example_index = me[0] example_memory_image = get_image(memory[top_example_index]) # get reduced memory reduced_mem = memory[m_ec] baseline_memory = torch.ones_like(reduced_mem) reduced_mem.requires_grad = True # compute gradients (grad_im,grad_mem) = saliency.attribute((input_selected,reduced_mem), baselines=(baseline_input,baseline_memory), target=predictions[ind].item(), internal_batch_size=2, n_steps=40 ) grad_input = get_image(grad_im,False) if mc: # get counterfactual with the highest weight top_counter_index_grad = (pred_mec != predictions[ind]).nonzero(as_tuple=True)[0][0] grad_counter = get_image(grad_mem[top_counter_index_grad],False) if me: # get explanation by example with the highest weight top_example_index_grad = (pred_mec == predictions[ind]).nonzero(as_tuple=True)[0][0] grad_example = get_image(grad_mem[top_example_index_grad],False) # visualize if mc and me: # case where there are counterfactuals and explanation by examples in memory fig,_ = visualize_image_mult_attr([None,grad_input,None,grad_example,None,grad_counter],[current_image,example_memory_image,counter_image],type_viz,show_grad,['Input\nPredict:{}'.format(name_classes[predictions[ind]]),'Saliency','Example\nw:{:.2f}'.format(rw[ind][top_example_index]),'Saliency', 'Counterfactual\nw:{:.2f}'.format(rw[ind][top_counter_index]),'Saliency'],use_pyplot=False) elif mc: # cases where there are only counterfactuals in memory fig,_ = visualize_image_mult_attr([None,grad_input,None,grad_counter],[current_image,counter_image],type_viz,show_grad,['Input\nPredict:{}'.format(name_classes[predictions[ind]]),'Saliency', 'Counterfactual\nw:{:.2f}'.format(rw[ind][top_counter_index]),'Saliency'],use_pyplot=False) elif me: # cases where there are only explanations by expamples in memory fig,_ = visualize_image_mult_attr([None,grad_input,None,grad_example],[current_image,example_memory_image],type_viz,show_grad,['Input\nPredict:{}'.format(name_classes[predictions[ind]]),'Saliency','Example\nw:{:.2f}'.format(rw[ind][top_example_index]),'Saliency'],use_pyplot=False) fig.savefig(dir_save+str(batch_idx*batch_size_test+ind)+".png") plt.close() print('{}/{}'.format(batch_idx,len(test_loader)),end='\r') def main(args): run(FLAGS.path_model,FLAGS.dir_dataset) if __name__ == '__main__': absl.app.run(main)
[ "noreply@github.com" ]
noreply@github.com
db752e445c89dce58b999281d862e5596a6a40a7
f64b3d29310b4284f4e56151aeb481e9c1d20fc0
/src/training.py
77392fcfb6a21ae10205e0c08435436f6f3f470f
[ "BSD-2-Clause" ]
permissive
jcboyd/roi-gan
da13e73484571f39ba15f2bd15b8cd1753a22806
663b8847b62e701b03767a65efc1a3ee27cceabd
refs/heads/master
2021-01-14T02:37:11.054536
2020-09-14T15:21:20
2020-09-14T15:21:20
242,568,902
1
0
null
null
null
null
UTF-8
Python
false
false
3,022
py
import torch from torch.nn import MSELoss, L1Loss def train_on_batch_discriminator(discriminator, imgs, optimiser, device): images, labels, fake_labels = imgs batch_size = images.shape[0] h, w = images.shape[2:4] disc_patch = (1, h // 2 ** 2, w // 2 ** 2) input_images = torch.cat([images, images], axis=0) input_labels = torch.cat([labels, fake_labels], axis=0) # INFER BATCH_SIZE AND DISC_PATCH FROM INPUTS! valid = torch.ones((batch_size,) + disc_patch) fake = torch.zeros((batch_size,) + disc_patch) targets = torch.cat([valid, fake], axis=0).to(device) outputs = discriminator(input_images, input_labels) # clear previous gradients optimiser.zero_grad() # forward pass d_loss = MSELoss()(outputs, targets) # calculate gradients d_loss.backward() # descent step optimiser.step() return d_loss def train_on_batch_roi_gan(roi_gan, data, optimiser, device): images, labels, fake_labels, bboxes = data batch_size = images.shape[0] num_roi = bboxes.shape[0] input_images = torch.cat([images, images], axis=0) input_labels = torch.cat([labels, fake_labels], axis=0) input_bboxes = torch.cat([bboxes, bboxes], axis=0) input_bboxes[num_roi:, 0] += batch_size # increment image id input_bboxes[:, 1:] = input_bboxes[:, 1:] / 2 # correct for pooling valid = torch.ones((num_roi, 1)) fake = torch.zeros((num_roi, 1)) targets = torch.cat([valid, fake], axis=0).to(device) # clear previous gradients optimiser.zero_grad() # forward pass validity = roi_gan(input_images, input_labels, input_bboxes) # calculate loss d_loss = MSELoss()(validity, targets) # backpropagate d_loss.backward() # descent step optimiser.step() return d_loss def train_on_batch_combined(models, data, optimiser, lamdbas, device): # clear previous gradients optimiser.zero_grad() generator, discriminator, roi_gan = models images, labels, bboxes = data batch_size = images.shape[0] h, w = images.shape[2:4] disc_patch = (1, h // 2 ** 2, w // 2 ** 2) bboxes[:, 1:] = bboxes[:, 1:] / 2 # correct for pooling fake_labels = generator(images) # Discriminators determines validity of translated images num_roi = bboxes.shape[0] valid_roi = torch.ones((num_roi, 1)).to(device) validity_roi = roi_gan(images, fake_labels, bboxes) # Discriminators determines validity of translated images valid_patch = torch.ones((batch_size,) + disc_patch).to(device) validity_patch = discriminator(images, fake_labels) # Best results with (0.2, 1, 5) lambda_dis, lambda_roi, lambda_gen = lamdbas g_loss = lambda_dis * MSELoss()(validity_patch, valid_patch) + \ lambda_roi * MSELoss()(validity_roi, valid_roi) + \ lambda_gen * L1Loss()(labels, fake_labels) # calculate gradients g_loss.backward() # descent step optimiser.step() return g_loss
[ "joseph.boyd@curie.fr" ]
joseph.boyd@curie.fr
7b02734b673f07ee117030f9239e9637a5e104a6
99b30366e96963839ad61d49d1eeaa5782d8780f
/api/liberouterapi/modules/jobs/JobManager.py
ce7883a73f285bbfe0884fed55b7e2d815697b9c
[]
no_license
petrstehlik/examon-web
bd114171aaa055565bd9c23151764f26c9aa538f
75d42b93bf8dc8b429e969d6679448ce4ba6219f
refs/heads/master
2021-01-20T21:23:29.949813
2017-08-30T10:39:30
2017-08-30T10:39:30
101,760,427
1
2
null
2017-08-29T13:02:48
2017-08-29T12:48:59
Python
UTF-8
Python
false
false
8,605
py
""" PBS Job Manager class This class manages all incoming messages regarding the PBS job info Author: Petr Stehlik <xstehl14@stud.fit.vutbr.cz> @ 2017/07 """ import paho.mqtt.client as mqtt import logging, json, copy import time class JobManager(): # Callback function on what to do with the message before storing it in database on_receive = None # Database dictionary # Records are organized by the job ID and received message db = dict() db_fail = dict() finished = dict() def __init__(self, mqtt_broker, mqtt_port, mqtt_topics): """ drop_job_arrays The PBS hook sends job arrays where job ID is in format xxxxxxx[xxxx].io01 """ self.log = logging.getLogger(__name__) self.broker = mqtt_broker self.port = mqtt_port self.topics = [(str(topic), 0) for topic in mqtt_topics] self.db = dict() self.db_fail = dict() self.client = mqtt.Client() # Register methods for connection and message receiving self.client.on_connect = self.on_connect self.client.on_message = self.on_message self.on_receive = self.default_on_receive self.on_end = self.default_on_end self.on_fail = self.default_on_fail self.client.connect(mqtt_broker, self.port, 60) self.client.loop_start() def on_connect(self, client, userdata, flags, rc): """ Subscribe to all topics """ result, mid = client.subscribe(self.topics) if result == mqtt.MQTT_ERR_SUCCESS: self.log.info("Successfully subscribed to all topics") else: self.log.error("Failed to subscribe to topics") def on_message(self, client, userdata, msg): """ Take action on received messages Currently parsed actions: jobs_runjob jobs_exc_begin jobs_exc_end """ self.log.info("Received message '%s': %s " % (msg.topic, msg.payload)) topic = str(msg.topic).split('/') try: payload = json.loads(str(msg.payload).replace("'", '"')) except Exception as e: self.log.error("Failed to load JSON payload. Reason: %s" % str(e)) return jobid = str(payload['job_id']) # Process runjob event if topic[-1] == "jobs_runjob": self.process_runjob(jobid, payload) return # Process exc_begin event # This event requires the runjob event to be already present in the DB elif topic[-1] == "jobs_exc_begin": if jobid in self.db: self.process_exc_begin(jobid, payload) else: self.log.warn("Job '%s' - missing runjob event" % jobid) self.process_exc_begin_fail(jobid, payload) # Process end event of job exec elif topic[-1] == "jobs_exc_end": if jobid in self.db and \ "exc_begin" in self.db[jobid] and \ len(self.db[jobid]["exc_begin"]) == len(payload["vnode_list"]): self.process_exc_end(jobid, payload) else: self.log.warn("Job '%s' - missing exc_begin or runjob event" % jobid) self.process_exc_end_fail(jobid, payload) # We received unknown message else: self.log.warn("Received unknown topic '%s'" % msg.topic) return self.check_timeout() def process_runjob(self, jobid, payload): """ Process runjob message Example payload: { project":"_pbs_project_default", "vnode_list":["node215"], "job_id":"2901535.io01", "ngpus":0, "qtime":1502446511, "req_mem":"8192", "node_list":["None"], "job_name":"STDIN", "queue":"shared", "req_cpus":1, "nmics":0, "req_time":1800, "variable_list ":{ "PBS_O_SYSTEM":"Linux", "PBS_O_SHELL":"/bin/bash" }, "job_owner":"pstehlik", "backup_qtime":"2017-08-11 12:15:35", "mpiprocs":1, "Qlist":"cincomp", "account_name":"PHD_Summer17_1", "ctime":1502446511 } Notes: qtime - UNIX timestamp backup_qtime - ISO timestamp ctime - UNIX timestamp """ if jobid in self.db: # The job is already there self.db[jobid]["runjob"].append(payload) else: self.db[jobid] = { "runjob" : [payload] } self.on_receive(jobid) def process_exc_begin(self, jobid, payload): """ Example payload: "org/cineca/cluster/galileo/jobs_exc_begin":{ "vnode_list":["node064"], "job_id":"2901321.io01", "job_cores":[0,1], "start_time":"2017-08-11 11:19:09", "node_list":[ "node064" ], "node_id":"node064", "job_owner":"pstehlik", "job_name":"STDIN" } """ if "exc_begin" in self.db[jobid]: self.db[jobid]["exc_begin"].append(payload) else: self.db[jobid]["exc_begin"] = [payload] self.on_receive(jobid) def process_exc_end(self, jobid, payload): """ { "vnode_list":["node063"], "cpupercent":0, "job_id":"2901306.io01", "job_cores":[0,1], "used_vmem":"3", "cputime":0, "used_mem":"3", "node_id":"node063", "end_time":"2017-08-11 11:11:31", "node_list":["node063"], "job_owner":"pstehlik", "job_name":"STDIN", "real_walltime":41 } """ if "exc_end" in self.db[jobid]: self.db[jobid]["exc_end"].append(payload) else: self.db[jobid]["exc_end"] = [payload] # Check if all "exc_end" messages are in the DB # if everything is in place we can trigger the on_end method and remove it from active self.on_receive(jobid) if len(self.db[jobid]["exc_end"]) == len(self.db[jobid]["exc_end"][0]["vnode_list"]): self.on_end(jobid) # All is done, remove the job from DB self.log.info("Removing job %s from DB" % jobid) # DEVEL only to see finished jobs self.finished[jobid] = copy.deepcopy(self.db[jobid]) del self.db[jobid] def process_exc_begin_fail(self, jobid, payload): if jobid not in self.db_fail: self.db_fail[jobid] = dict() # In case there is a previous correct event in the DB move it to failed if jobid in self.db: self.db_fail[jobid] = copy.deepcopy(self.db[jobid]) del self.db[jobid] if "exc_begin" in self.db_fail[jobid]: self.db_fail[jobid]["exc_begin"].append(payload) else: self.db_fail[jobid]["exc_begin"] = [payload] self.on_fail(jobid) def process_exc_end_fail(self, jobid, payload): if not jobid in self.db_fail: self.db_fail[jobid] = dict() # In case there is a previous correct event in the DB move it to failed if jobid in self.db: self.db_fail[jobid] = copy.deepcopy(self.db[jobid]) del self.db[jobid] if "exc_end" in self.db_fail[jobid]: self.db_fail[jobid]["exc_end"].append(payload) else: self.db_fail[jobid]["exc_end"] = [payload] self.on_fail(jobid) def check_timeout(self): """Check timeout in all active records The timeout time is taken as ctime + req_time and compared to current unix timestamp If current timestamp is smaller, the job is moved to failed db """ for jobid in self.db.copy(): timeout = self.db[jobid]['runjob'][0]['ctime'] + self.db[jobid]['runjob'][0]['req_time'] now = int(time.time()) if timeout < now: self.db_fail[jobid] = copy.deepcopy(self.db[jobid]) del self.db[jobid] self.log.info("TIMEOUT: Moving job %s to fail DB" % jobid) self.on_fail(jobid) def default_on_receive(self, jobid): pass def default_on_end(self, jobid): pass def default_on_fail(self, jobid): pass
[ "xstehl14@stud.fit.vutbr.cz" ]
xstehl14@stud.fit.vutbr.cz
94de5cb261739463d38134ab19e54dd476e3672b
ba9117112b9a7926519cc0dcd5eb5856f08ca10f
/django-for-beginners/pages_project/pages_project/urls.py
5faf08f59b52759a4a70cb98f3cfbdd60c98fa0d
[]
no_license
vertinskiy-oleg/learning
b3aafaf7f7f4774691f3d5133a5cfcfd24ed41d5
d61975ed8ff6b87dc268519b80a98e102ccfaa05
refs/heads/master
2020-07-07T12:08:15.784115
2020-05-11T08:56:16
2020-05-11T08:56:16
203,342,675
0
0
null
2020-05-05T20:21:30
2019-08-20T09:21:35
Python
UTF-8
Python
false
false
822
py
"""pages_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')) ]
[ "decruel89@gmail.com" ]
decruel89@gmail.com
e149e5a6365c00732f7a4af4d55d89261f54742e
a0494d363be4b8deba66b99a4782e85917692169
/season.py
8a9af92660cdf2618397e06a6d1ba63936939ec6
[]
no_license
anliely/Python
5f0db606381b200f7094a10c98bcd4c7cf6a55c6
27350fc602ad44157e329df4a70c6c981796c0c6
refs/heads/master
2020-03-27T12:33:31.921696
2018-11-27T09:37:58
2018-11-27T09:37:58
146,553,642
0
0
null
null
null
null
UTF-8
Python
false
false
1,715
py
import requests from bs4 import BeautifulSoup def get_weather(city_id): url = "http://www.weather.com.cn/weather/{}.shtml".format(city_id) headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} response = requests.get(url, headers=headers) response.encoding = 'utf-8' html = response.text soup = BeautifulSoup(html, 'lxml') dates = soup.find_all('h1') date_time = [] # 存放七天内的日期 for i in dates: date = str(i)[7:9] date_time.append(date) date_time = date_time[:][:7] msg = soup.find_all('p', class_="wea") description = [] # 存放天气的描述信息 for i in msg: desc = i.string description.append(desc) msg2 = soup.find_all('p', class_="tem") max_tem = [] # 存放当天的最高气温 min_tem = [] # 存放当天的最低气温 for i in msg2: s = i.find_all('span') for x in s: max_tem.append(x.string) z = i.find_all('i') for y in z: min_tem.append(y.string) wins = [] # 用于存储风向 win_power = [] # 用于存储风力 msg3 = soup.find_all('p', class_='win') for i in msg3: for x in i.find_all('span'): wins.append(x.get('title')) for y in i.find_all('i'): win_power.append(y.string) num = 0 for i in wins[:]: if num % 2 == 1: wins.remove(i) num += 1 weather = [] a = 0 for _ in range(7): msg = tuple((date_time[a],description[a],min_tem[a],max_tem[a],wins[a],win_power[a])) weather.append(msg) return weather
[ "noreply@github.com" ]
noreply@github.com
213c596a45abec1b5e81f530fba91b5f6cc9caaa
d24081eb0903ad71acf31dd35afc93152a07abb7
/musician_server/musician_server/urls.py
28636a83198890ba0a566b42dfc4dde2ffc4fd0a
[]
no_license
jordondoug2019/react-CRUD-musicians
25995bb973db8831eba33e6cdab5d943563c23da
c64ff8e23161507ff1261cbbb0d1f60f6835c919
refs/heads/master
2023-01-21T04:26:46.519512
2019-11-06T15:16:50
2019-11-06T15:16:50
219,938,006
0
0
null
2023-01-05T00:40:36
2019-11-06T07:35:05
JavaScript
UTF-8
Python
false
false
810
py
"""musician_server URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('musician_app.urls')), path('admin/', admin.site.urls), ]
[ "jdouglas2015@gmail.com" ]
jdouglas2015@gmail.com
6cf4bd1d3c45c16ef34b1e3634aecb269328e5c2
74df9ce87872f43ff6836563cd8019eb9b95f5b0
/20_catchment_attributes/src/tests/test_upstream_agg.py
e4fed6c9e9b273d4bbced707d80ad68b192d54f7
[]
no_license
USGS-R/delaware-model-prep
017f0d9f727d5d5b4449cd69758c4b32f12860ed
45e1ffeee7d6ea4a95e374e16cbc1196bf703f41
refs/heads/main
2023-06-08T19:38:46.764070
2023-06-01T23:56:42
2023-06-01T23:56:42
202,405,091
2
14
null
2023-04-07T23:28:32
2019-08-14T18:31:12
R
UTF-8
Python
false
false
1,966
py
import os from catch_attr import relate_attr_to_segments from aggregate_upstream import aggregate_upstream_attr def test_agg_to_seg(): attr_w_id_file = 'tests/sample_combined_cats_w_ids_02.feather' random_segs = [3356, 2768, 2317, 1714, 1646] temp_outfile = 'temp_out' seg_attr = relate_attr_to_segments(attr_w_id_file, temp_outfile) seg_attr.set_index('seg_id_nat', inplace=True) os.remove(temp_outfile) var = 'soil_moist_max' assert round(seg_attr.loc[3356, var], 2) == 5.26 assert round(seg_attr.loc[2768, var], 2) == 3.71 assert round(seg_attr.loc[2317, var], 2) == 2.93 assert round(seg_attr.loc[1714, var], 2) == 2.92 assert round(seg_attr.loc[1646, var], 2) == 3.91 var = 'hru_area' assert round(seg_attr.loc[3356, var]) == 17874 assert round(seg_attr.loc[2768, var]) == 39272 assert round(seg_attr.loc[2317, var]) == 3448 assert round(seg_attr.loc[1714, var]) == 25884 assert round(seg_attr.loc[1646, var]) == 26228 var = 'dprst_area' assert round(seg_attr.loc[3356, var]) == 0 assert round(seg_attr.loc[2768, var]) == 339 assert round(seg_attr.loc[2317, var]) == 3 assert round(seg_attr.loc[1714, var], 1) == 2.5 assert round(seg_attr.loc[1646, var]) == 1357 def test_agg_upstream(): test_segs = [2013, 1647, 2277] attr_file = 'tests/sample_seg_attr_drb.feather' link_file = 'tests/sample_high_obs_upstream_sites.csv' temp_outfile = 'temp_out' agg_up = aggregate_upstream_attr(attr_file, link_file, temp_outfile) agg_up.set_index('seg_id_nat', inplace=True) os.remove(temp_outfile) var = 'hru_area' assert round(agg_up.loc[2013, var]) == 33026 assert round(agg_up.loc[1647, var]) == 129409 assert round(agg_up.loc[2277, var]) == 28549 var = 'covden_sum' assert round(agg_up.loc[2013, var], 2) == .30 assert round(agg_up.loc[1647, var], 2) == .78 assert round(agg_up.loc[2277, var], 2) == .60
[ "jsadler@usgs.gov" ]
jsadler@usgs.gov
34796e03ad42278148564162c60c8e9b9f5fc4b8
56c3cefe1da4731175ee73d90ca2629d79bfe696
/egs/ptb_chime4test/local/run_trf_nce_cnn.py
3e8eeb368c4f54c64b8acffe0aafefdd38e84a84
[]
no_license
wbengine/TRF-NN-Tensorflow
022a187c80c80293553958c17a267c7eaf81213f
e225829c36043293d092cf8ed620d6dce0abc8f0
refs/heads/master
2022-04-16T10:20:46.999159
2020-03-05T04:56:20
2020-03-05T04:56:20
114,067,559
5
1
null
null
null
null
UTF-8
Python
false
false
3,475
py
import tensorflow as tf import os import sys import time import numpy as np import task from model import wblib as wb from model import reader from model import trfbase from model import trfnce from model import lstmlm import run_lstmlm # [data] data = reader.Data().load_raw_data([task.train, task.valid, task.test], add_beg_token='</s>', add_end_token='</s>') # data.cut_train_to_length(50) def create_name(config, q_config): s = str(config) if q_config is not None: s += '_with_' + run_lstmlm.create_name(q_config) # s += '_op%d' % config.noise_operation_num # s += '_lstm' # s += '_logz{}'.format(int(config.init_zeta[0])) return s def main(_): config = trfnce.Config(data) config.structure_type = 'cnn' config.embedding_dim = 200 config.cnn_filters = [(i, 100) for i in range(1, 11)] config.cnn_width = 3 config.cnn_layers = 3 config.cnn_hidden = 200 config.rnn_hidden_layers = 2 config.rnn_hidden_size = 200 config.rnn_predict = True config.batch_size = 10 config.noise_factor = 10 config.noise_sampler = 'lstm:lstm/lstm_e200_h200x2/model.ckpt' config.init_weight = 0.1 config.optimize_method = ['adam', 'adam'] config.lr_param = trfbase.LearningRateEpochDelay(0.001) config.lr_zeta = trfbase.LearningRateEpochDelay(0.01) config.max_epoch = 100 # config.dropout = 0.75 # config.init_zeta = config.get_initial_logz(20) config.update_zeta = True config.write_dbg = False config.print() # q_config = run_lstmlm.small_config(data) q_config = None name = create_name(config, q_config) logdir = 'trf_nce/' + name wb.mkdir(logdir, is_recreate=True) sys.stdout = wb.std_log(os.path.join(logdir, 'trf.log')) print(logdir) data.write_vocab(logdir + '/vocab.txt') data.write_data(data.datas[1], logdir + '/valid.id') data.write_data(data.datas[2], logdir + '/test.id') # wb.rmdir(logdirs) with tf.Graph().as_default(): if q_config is None: m = trfnce.TRF(config, data, logdir=logdir, device='/gpu:0') else: m = trfnce.TRF(config, data, logdir=logdir, device='/gpu:0', q_model=lstmlm.LM(q_config, device='/gpu:0') ) # s1 = trfnce.NoiseSamplerNgram(config, data, 2) # s2 = trfnce.NoiseSamplerLSTMEval(config, data, config.noise_sampler.split(':')[-1]) sv = tf.train.Supervisor(logdir=os.path.join(logdir, 'logs'), global_step=m.train_net.global_step) sv.summary_writer.add_graph(tf.get_default_graph()) # write the graph to logs session_config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=False) session_config.gpu_options.allow_growth = True with sv.managed_session(config=session_config) as session: with session.as_default(): if m.q_model is not None: print('load lstmlm for q model') m.q_model.restore(session, './lstm/' + run_lstmlm.create_name(q_config) + '/model.ckpt') m.train(sv, session, print_per_epoch=0.1, operation=task.Ops(m), ) if __name__ == '__main__': tf.app.run(main=main)
[ "wb.th08@gmail.com" ]
wb.th08@gmail.com
c5e0b845eec88fe50d7ed7cfda31c0af3417e7a8
e645ebf3b5177eb0ebedb7f239bd6e1b40bf1b07
/ups/minuit2.cfg
53e4d870fb2d8ee6bb0e4e0ceb063982e4b81138
[]
no_license
lsst-dm/bp
e095cdb7412124fef39bdd8428fce70bbf0f462a
31c0b65866d06a09575a53d0dd558320e6994a06
refs/heads/main
2023-07-22T11:32:48.479329
2023-07-10T00:30:32
2023-07-10T00:30:32
37,212,636
0
0
null
null
null
null
UTF-8
Python
false
false
2,936
cfg
# -*- python -*- """ Dependencies and configuration for minuit2 """ import os.path import eups def _get_root(): """Return the root directory of the package.""" return eups.productDir("minuit2") dependencies = { # Names of packages required to build against this package. "required": [], # Names of packages optionally setup when building against this package. "optional": [], # Names of packages required to build this package, but not required to build against it. "buildRequired": [], # Names of packages optionally setup when building this package, but not used in building against it. "buildOptional": [], } def setup(conf, products, build=False): """ Update an SCons environment to make use of the package. Arguments: conf ------ An SCons Configure context. The SCons Environment conf.env should be updated by the setup function. products -- A dictionary consisting of all dependencies and the return values of calls to their setup() functions, or None if the dependency was optional and was not found. build ----- If True, this is the product currently being built, and products in "buildRequired" and "buildOptional" dependencies will also be present in the products dict. """ conf.env.PrependUnique(**paths) if not build: conf.env.AppendUnique(**doxygen) for target in libs: if target not in conf.env.libs: conf.env.libs[target] = lib[target].copy() else: for lib in libs[target]: if lib not in conf.env.libs[target]: conf.env.libs[target].append(lib) return {"paths": paths, "doxygen": doxygen, "libs": libs, "extra": {}} ################################################################################################### # Variables for default implementation of setup() below; if the user provides # a custom implementation of setup(), everything below is unnecessary. # Packages to be added to the environment. paths = { # Sequence of paths to add to the include path. "CPPPATH": [os.path.join(_get_root(), "include")], # Sequence of paths to add to the linker path. "LIBPATH": [os.path.join(_get_root(), "lib")], } doxygen = { # Sequence of Doxygen tag files produced by this product. "DOXYGEN_TAGFILES": [], # Sequence of Doxygen configuration files to include in dependent products. "DOXYGEN_INCLUDES": [], } # Libraries provided by the package, not including standard library prefixes or suffixes. # Additional custom targets besides the standard "main", "python", and "test" targets may # be provided as well. libs = { # Normal libraries. "main": ["Minuit2"], # Libraries only linked with C++-coded Python modules. "python": [], # Libraries only linked with C++-coded unit tests. "test": [], }
[ "jbosch@git.lsstcorp.org" ]
jbosch@git.lsstcorp.org
d5b92e89495e020133c29af5b45314200c8b6a13
cb329f0f6b19d3b799faca722ed625f8df5eef28
/no_necesarios/islas.py
6017277124794fe1f93885062a763378f35fabae
[]
no_license
AlfilAlex/pdfrename
46668f728d2e6c29782a6fe20d531208717dae91
117c2ce7d459edd885a1f92976afcb9ce63d9a43
refs/heads/master
2023-05-21T20:45:46.515265
2021-06-06T22:28:54
2021-06-06T22:28:54
332,865,620
0
0
null
null
null
null
UTF-8
Python
false
false
2,593
py
#%% import pandas as pd class islas: def __init__(self, pajaros, nodos, nombre): self.pajaros = pajaros self.nodos = nodos self.nombre = nombre def pajaros_isla(self): return self.pajaros def nodos_isla(self): return self.nodos def nombre_isla(self): return self.nombre def pajaros_emigracion(self, cantidad): self.pajaros = self.pajaros - cantidad def pajaros_migracion(self, cantidad): self.pajaros = self.pajaros + cantidad def pajaros_emigracion(self, cantidad): self.pajaros = self.pajaros - cantidad #%% isla_A = islas(1100, {'A-B': 0.001, 'A-C': 0.01, 'A-F': 0.01}, 'A') isla_B = islas(100, {'B-C': 0.01, 'B-A': 0.06}, 'B') isla_C = islas(100, {'C-A': 0.001, 'C-B': 0.01, 'C-E': 0.01}, 'C') isla_D = islas(200, {'D-A': 0.01, 'D-A': 0.04}, 'D') isla_E = islas(100, {'E-A': 0.001, 'E-F': 0.01, 'E-D': 0.021}, 'E') isla_F = islas(100, {'F-D': 0.01, 'F-B': 0.01, 'F-C': 0.01}, 'F') lista_islas = [isla_A, isla_B, isla_C, isla_D, isla_E, isla_F] dic_islas = {} for isla in lista_islas: dic_islas[isla.nombre_isla()] = [] for i in range(10000): for isla in lista_islas: nodo = isla.nodos_isla() #Generamos una lista con las islas complementarias a 'isla' nombres = [nombre for nombre in lista_islas if nombre != isla] for nombre in nombres: nodo = isla.nombre_isla() + '-' + nombre.nombre_isla() try: cantidad = isla.nodos_isla()[nodo]* isla.pajaros_isla() except: continue isla.pajaros_emigracion(cantidad) nombre.pajaros_migracion(cantidad) if isla == isla_A: dic_islas[isla.nombre_isla()].append(isla.pajaros_isla()) #print(isla.pajaros_isla()) if isla == isla_B: dic_islas[isla.nombre_isla()].append(isla.pajaros_isla()) #print(isla.pajaros_isla()) if isla == isla_C: dic_islas[isla.nombre_isla()].append(isla.pajaros_isla()) #print(isla.pajaros_isla()) if isla == isla_D: dic_islas[isla.nombre_isla()].append(isla.pajaros_isla()) #print(isla.pajaros_isla()) if isla == isla_E: dic_islas[isla.nombre_isla()].append(isla.pajaros_isla()) #print(isla.pajaros_isla()) if isla == isla_F: dic_islas[isla.nombre_isla()].append(isla.pajaros_isla()) #print(isla.pajaros_isla()) df = pd.DataFrame(dic_islas) df.plot() print(df) # %%
[ "cabimax@outlook.com" ]
cabimax@outlook.com
e66abe47562b3982f3bf9d1c381c53dcbbaa823b
2530418e9788d1e1e191534f044b8313fbe6b5be
/Insta/models.py
fb7a8a93cbe7da52a89ce1e660c134f2bb219e22
[]
no_license
Huayuehu/django-instagram-proj
7134bdf494a7c6fc2ffc501cc68322ea1be8b7d2
c0e371547f4e5c418a5d772a3d59f74cf25b90a8
refs/heads/master
2022-12-15T02:25:04.355882
2020-09-04T06:54:56
2020-09-04T06:54:56
292,764,352
0
0
null
null
null
null
UTF-8
Python
false
false
4,840
py
from django.db import models from django.contrib.auth.models import AbstractUser from imagekit.models import ProcessedImageField # Django中常见的第三方的显示图片的库 from django.urls import reverse # 用于处理url常见的函数 # # Create your models here. # # Define a model for picture post class InstaUser(AbstractUser): # 自定义的user model继承了django自带的AbstractUser的属性,同时可以自己添加customized fields profile_pic = ProcessedImageField( upload_to='static/images/profiles', # 指定图片上传后的存储地址 format='JPEG', options={'quality':100}, blank=True, # 图片可以是空或者不存在 null=True, ) def get_connections(self): # 获得所有我在follow的人 connections = UserConnection.objects.filter(creator=self) return connections def get_followers(self): # 获得所有follow我的人 followers = UserConnection.objects.filter(followed=self) return followers def is_followed_by(self, user): followers = UserConnection.objects.filter(followed=self) # 先拿到所有在follow我的人 return followers.filter(creator=user).exists() # 在那里面查找,在follow我的人里面是否有当前的user def get_absolute_url(self): return reverse('user_detail', args=[str(self.id)]) def __str__(self): return self.username class UserConnection(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey( InstaUser, on_delete=models.CASCADE, related_name="friendship_creator_set") # 本人去follow别人,user.friendship_creator_set返回的是我正在follow的所有人 followed = models.ForeignKey( InstaUser, on_delete=models.CASCADE, related_name="friend_set") # 返回follow我的所有人 def __str__(self): return self.creator.username + ' follows ' + self.followed.username class Post(models.Model): author = models.ForeignKey( # a foreign key indicate a Many-To-One relationship InstaUser, # foreign key is InstaUser blank=True, null=True, on_delete=models.CASCADE, # delete this author will delete all his posts related_name='my_posts', # we can use author.my_posts to get all posts belong to this user ) title = models.TextField(blank=True, null=True) # title的类型是Django自带的TextField,括号中的参数表示title为空或者完全没有title也可以post出去 image = ProcessedImageField( upload_to='static/images/posts', # 指定图片上传后的存储地址 format='JPEG', options={'quality':100}, blank=True, # 图片可以是空或者不存在 null=True, ) posted_on = models.DateTimeField( auto_now_add=True, editable=False, ) def __str__(self): return self.title def get_absolute_url(self): # 当有人保存了一个post对象,会自动跳转到get_absolute_url这个函数里返回的地方 return reverse('post_detail', args=[str(self.id)]) # reverse用于找到某个页面对应的url,在这里是跳转到刚刚保存的那个post对应的detail信息的网页,detail这个网页需要传id这个参数,所有后面传进去 def get_like_count(self): return self.likes.count() # 返回所有作用于这个post.likes的数量 def get_comment_count(self): return self.comments.count() class Like(models.Model): # Like是一个关系型model,连接了Post和InstaUser这两个model post = models.ForeignKey( Post, on_delete=models.CASCADE, # 定义了这样一个操作:如果post被删除,那整个like关系应该被删除 related_name='likes') # 用某个post.likes可以返回所有给这篇post点过赞的users user = models.ForeignKey( InstaUser, on_delete=models.CASCADE, # 定义了这样一个操作:如果post被删除,那整个like关系应该被删除 related_name='likes') # 用某个user.likes可以返回所有给这个user点过赞的所有posts class Meta: unique_together = ("post", "user") # 一个user只能给一个特定的post点一次赞 def __str__(self): return 'Like: ' + self.user.username + ' likes ' + self.post.title class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments',) user = models.ForeignKey( InstaUser, on_delete=models.CASCADE, related_name='comments') comment = models.CharField(max_length=100) posted_on = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return self.comment
[ "huayuehu@usc.edu" ]
huayuehu@usc.edu
e6f6045cc2fb7e9d2b61ded3d712cc41bf1bd78b
c6e5d5ff2ee796fd42d7895edd86a49144998067
/platform/core-scheduler/polyaxon/polyconf/wsgi.py
752f03d7945e907b86cc6786cbdc1116ab7a7e94
[ "Apache-2.0" ]
permissive
zeyaddeeb/polyaxon
f4481059f93d8b70fb3d41840a244cd9aaa871e0
1f2b236f3ef36cf2aec4ad9ec78520dcc9ef4ee5
refs/heads/master
2023-01-19T05:15:34.334784
2020-11-27T17:08:35
2020-11-27T17:08:35
297,410,504
0
0
Apache-2.0
2020-09-21T17:20:27
2020-09-21T17:20:26
null
UTF-8
Python
false
false
995
py
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, 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. """ WSGI config for search project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "polyconf.settings") application = get_wsgi_application()
[ "mouradmourafiq@gmail.com" ]
mouradmourafiq@gmail.com
6973e7ab73a7308979ed796297693210c4ebf6a6
950bae8d6a6a5506960f2e5c527f8f22e70e5d10
/material/curso_em_video/ex046.py
1337928b9eed58565b8ecdf4a0df65657790ec4f
[ "MIT" ]
permissive
sergiodealencar/courses
766f3933c9de439ee30f688d2113f7a97f57f13e
c9d86b27b0185cc82624b01ed76653dbc12554a3
refs/heads/main
2023-02-25T22:17:05.934354
2021-02-04T01:31:06
2021-02-04T01:31:06
313,715,483
0
0
null
null
null
null
UTF-8
Python
false
false
96
py
from time import sleep for c in range(10, -1, -1): print(c) sleep(1) print('\nBOOOM!!!')
[ "55211077+sergiodealencar@users.noreply.github.com" ]
55211077+sergiodealencar@users.noreply.github.com
15ad9fc31a64afdb97a2b6c515ba068674988d2d
8ad1853764e19a1b01be01299f611fd07d367f8a
/for_submit/advocate1.py
49b7309c014714a729c1fec5e5c71422ed63f4d9
[]
no_license
SummerVibeQi/Kaggle-Quora-Insincere-Questions-Classification-1
110ee986db6922fcfea6cab5670e9df7b0d39f72
99375a00bc5d11e46e9761772ad7bd71c2da52d0
refs/heads/master
2021-04-09T00:45:07.532500
2019-02-04T15:09:33
2019-02-04T15:09:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
59,631
py
# import time # from sklearn.externals import joblib # import random # import pandas as pd # import numpy as np # import gc # import re # import torch # from tqdm import tqdm_notebook, tnrange # from tqdm.auto import tqdm # # tqdm.pandas(desc='Progress') # from collections import Counter # # import torch.nn as nn # import torch.optim as optim # import torch.nn.functional as F # from torch.utils.data import Dataset, DataLoader # from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence # from torch.autograd import Variable # from sklearn.metrics import f1_score # import os # # from keras.preprocessing.text import Tokenizer # from keras.preprocessing.sequence import pad_sequences # # # cross validation and metrics # from sklearn.model_selection import StratifiedKFold # from sklearn.metrics import f1_score # from torch.optim.optimizer import Optimizer # # # embed_size = 300 # how big is each word vector # max_features = 120000 # how many unique words to use (i.e num rows in embedding vector) # maxlen = 70 # max number of words in a question to use # batch_size = 512 # how many samples to process at once # n_epochs = 3 # how many times to iterate over all samples # n_splits = 4 # Number of K-fold Splits # # SEED = 1029 # # # def seed_everything(seed=1029): # random.seed(seed) # os.environ['PYTHONHASHSEED'] = str(seed) # np.random.seed(seed) # torch.manual_seed(seed) # torch.cuda.manual_seed(seed) # torch.backends.cudnn.deterministic = True # # # seed_everything() # # # ## FUNCTIONS TAKEN FROM https://www.kaggle.com/gmhost/gru-capsule # # def load_glove(word_index): # EMBEDDING_FILE = './input/embeddings/glove.840B.300d/glove.840B.300d.txt' # # def get_coefs(word, *arr): # return word, np.asarray(arr, dtype='float32')[:300] # # embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding='utf-8', errors='ignore')) # # all_embs = np.stack(embeddings_index.values()) # emb_mean, emb_std = -0.005838499, 0.48782197 # embed_size = all_embs.shape[1] # # # word_index = tokenizer.word_index # nb_words = min(max_features, len(word_index)) # # Why random embedding for OOV? what if use mean? # embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) # # embedding_matrix = np.random.normal(emb_mean, 0, (nb_words, embed_size)) # std 0 # for word, i in word_index.items(): # if i >= max_features: continue # embedding_vector = embeddings_index.get(word) # if embedding_vector is not None: embedding_matrix[i] = embedding_vector # # return embedding_matrix # # # def load_fasttext(word_index): # EMBEDDING_FILE = './input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' # # def get_coefs(word, *arr): # return word, np.asarray(arr, dtype='float32') # # embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE) if len(o) > 100) # # all_embs = np.stack(embeddings_index.values()) # emb_mean, emb_std = all_embs.mean(), all_embs.std() # embed_size = all_embs.shape[1] # # # word_index = tokenizer.word_index # nb_words = min(max_features, len(word_index)) # embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) # # embedding_matrix = np.random.normal(emb_mean, 0, (nb_words, embed_size)) # for word, i in word_index.items(): # if i >= max_features: continue # embedding_vector = embeddings_index.get(word) # if embedding_vector is not None: embedding_matrix[i] = embedding_vector # # return embedding_matrix # # # def load_para(word_index): # EMBEDDING_FILE = './input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' # # def get_coefs(word, *arr): # return word, np.asarray(arr, dtype='float32') # # embeddings_index = dict( # get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore') if len(o) > 100) # # all_embs = np.stack(embeddings_index.values()) # emb_mean, emb_std = -0.0053247833, 0.49346462 # embed_size = all_embs.shape[1] # # # word_index = tokenizer.word_index # nb_words = min(max_features, len(word_index)) # embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) # # embedding_matrix = np.random.normal(emb_mean, 0, (nb_words, embed_size)) # for word, i in word_index.items(): # if i >= max_features: continue # embedding_vector = embeddings_index.get(word) # if embedding_vector is not None: embedding_matrix[i] = embedding_vector # # return embedding_matrix # # # df_train = pd.read_csv("./input/train.csv") # df_test = pd.read_csv("./input/test.csv") # joblib.dump(df_train, 'df_train.pkl', compress=3) # joblib.dump(df_test, 'df_test.pkl', compress=3) # # df = pd.concat([df_train, df_test], sort=True) # # # def build_vocab(texts): # sentences = texts.apply(lambda x: x.split()).values # vocab = {} # for sentence in sentences: # for word in sentence: # try: # vocab[word] += 1 # except KeyError: # vocab[word] = 1 # return vocab # # # vocab = build_vocab(df['question_text']) # # # def build_vocab(texts): # sentences = texts.apply(lambda x: x.split()).values # vocab = {} # for sentence in sentences: # for word in sentence: # try: # vocab[word] += 1 # except KeyError: # vocab[word] = 1 # return vocab # # # def known_contractions(embed): # known = [] # for contract in contraction_mapping: # if contract in embed: # known.append(contract) # return known # # # def clean_contractions(text, mapping): # specials = ["’", "‘", "´", "`"] # for s in specials: # text = text.replace(s, "'") # text = ' '.join([mapping[t] if t in mapping else t for t in text.split(" ")]) # return text # # # def correct_spelling(x, dic): # for word in dic.keys(): # x = x.replace(word, dic[word]) # return x # # # def unknown_punct(embed, punct): # unknown = '' # for p in punct: # if p not in embed: # unknown += p # unknown += ' ' # return unknown # # # def clean_numbers(x): # x = re.sub('[0-9]{5,}', '#####', x) # x = re.sub('[0-9]{4}', '####', x) # x = re.sub('[0-9]{3}', '###', x) # x = re.sub('[0-9]{2}', '##', x) # return x # # # def clean_special_chars(text, punct, mapping): # for p in mapping: # text = text.replace(p, mapping[p]) # # for p in punct: # text = text.replace(p, ' {} '.format(p)) # # specials = {'\u200b': ' ', '…': ' ... ', '\ufeff': '', 'करना': '', # 'है': ''} # Other special characters that I have to deal with in last # for s in specials: # text = text.replace(s, specials[s]) # # return text # # # def add_lower(embedding, vocab): # count = 0 # for word in vocab: # if word in embedding and word.lower() not in embedding: # embedding[word.lower()] = embedding[word] # count += 1 # print("Added {} words to embedding".format(count)) # # # puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '#', '*', # '+', '\\', '•', '~', '@', '£', # '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', # '½', 'à', '…', # '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', # '▓', '—', '‹', '─', # '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', # 'Ã', '⋅', '‘', '∞', # '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', # '≤', '‡', '√', ] # # # def clean_text(x): # x = str(x) # for punct in puncts: # x = x.replace(punct, ' {} '.format(punct)) # return x # # # def clean_numbers(x): # x = re.sub('[0-9]{5,}', '#####', x) # x = re.sub('[0-9]{4}', '####', x) # x = re.sub('[0-9]{3}', '###', x) # x = re.sub('[0-9]{2}', '##', x) # return x # # # mispell_dict = {"ain't": "is not", "aren't": "are not", "can't": "cannot", "'cause": "because", # "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", # "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would", # "he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", # "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", # "I'll've": "I will have", "I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", # "i'll": "i will", "i'll've": "i will have", "i'm": "i am", "i've": "i have", "isn't": "is not", # "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have", # "it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have", # "mightn't": "might not", "mightn't've": "might not have", "must've": "must have", "mustn't": "must not", # "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have", # "o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", # "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", # "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", # "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", # "so've": "so have", "so's": "so as", "this's": "this is", "that'd": "that would", # "that'd've": "that would have", "that's": "that is", "there'd": "there would", # "there'd've": "there would have", "there's": "there is", "here's": "here is", "they'd": "they would", # "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", # "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", # "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", # "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", # "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", # "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", # "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", # "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", # "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", # "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would", # "y'all'd've": "you all would have", "y'all're": "you all are", "y'all've": "you all have", # "you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", # "you're": "you are", "you've": "you have", 'colour': 'color', 'centre': 'center', # 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', # 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', # 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', # 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', # 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', # 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', # "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', # 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', # 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', # 'demonitization': 'demonetization', 'demonetisation': 'demonetization'} # # # def _get_mispell(mispell_dict): # mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys())) # return mispell_dict, mispell_re # # # mispellings, mispellings_re = _get_mispell(mispell_dict) # # # def replace_typical_misspell(text): # def replace(match): # return mispellings[match.group(0)] # # return mispellings_re.sub(replace, text) # # # from sklearn.preprocessing import StandardScaler # # # def add_features(df): # df['question_text'] = df['question_text'].progress_apply(lambda x: str(x)) # df['total_length'] = df['question_text'].progress_apply(len) # df['capitals'] = df['question_text'].progress_apply(lambda comment: sum(1 for c in comment if c.isupper())) # df['caps_vs_length'] = df.progress_apply(lambda row: float(row['capitals']) / float(row['total_length']), # axis=1) # df['num_words'] = df.question_text.str.count('\S+') # df['num_unique_words'] = df['question_text'].progress_apply(lambda comment: len(set(w for w in comment.split()))) # df['words_vs_unique'] = df['num_unique_words'] / df['num_words'] # # return df # # # def load_and_prec(): # train_df = pd.read_csv("./input/train.csv") # test_df = pd.read_csv("./input/test.csv") # print("Train shape : ", train_df.shape) # print("Test shape : ", test_df.shape) # # # lower # train_df["question_text"] = train_df["question_text"].apply(lambda x: x.lower()) # test_df["question_text"] = test_df["question_text"].apply(lambda x: x.lower()) # # # Clean the text # train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_text(x)) # test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_text(x)) # # # Clean numbers # train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_numbers(x)) # test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_numbers(x)) # # joblib.dump(train_df, 'pre_df_train.pkl', compress=3) # joblib.dump(test_df, 'pre_df_test.pkl', compress=3) # # # Clean speelings # # train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x)) # # test_df["question_text"] = test_df["question_text"].apply(lambda x: replace_typical_misspell(x)) # # ## fill up the missing values # train_X = train_df["question_text"].fillna("_##_").values # test_X = test_df["question_text"].fillna("_##_").values # # ###################### Add Features ############################### # # https://github.com/wongchunghang/toxic-comment-challenge-lstm/blob/master/toxic_comment_9872_model.ipynb # train = add_features(train_df) # test = add_features(test_df) # # features = train[['caps_vs_length', 'words_vs_unique']].fillna(0) # test_features = test[['caps_vs_length', 'words_vs_unique']].fillna(0) # # ss = StandardScaler() # ss.fit(np.vstack((features, test_features))) # features = ss.transform(features) # test_features = ss.transform(test_features) # ########################################################################### # # ## Tokenize the sentences # tokenizer = Tokenizer(num_words=max_features) # tokenizer.fit_on_texts(list(train_X)) # train_X = tokenizer.texts_to_sequences(train_X) # test_X = tokenizer.texts_to_sequences(test_X) # # ## Pad the sentences # train_X = pad_sequences(train_X, maxlen=maxlen) # test_X = pad_sequences(test_X, maxlen=maxlen) # # ## Get the target values # train_y = train_df['target'].values # # # # Splitting to training and a final test set # # train_X, x_test_f, train_y, y_test_f = train_test_split(list(zip(train_X,features)), train_y, test_size=0.2, random_state=SEED) # # train_X, features = zip(*train_X) # # x_test_f, features_t = zip(*x_test_f) # # # shuffling the data # # np.random.seed(SEED) # # trn_idx = np.random.permutation(len(train_X)) # # # train_X = train_X[trn_idx] # # train_y = train_y[trn_idx] # # features = features[trn_idx] # # return train_X, test_X, train_y, features, test_features, tokenizer.word_index # # # # return train_X, test_X, train_y, x_test_f,y_test_f,features, test_features, features_t, tokenizer.word_index # # return train_X, test_X, train_y, tokenizer.word_index # # x_train, x_test, y_train, features, test_features, word_index = load_and_prec() # # # missing entries in the embedding are set using np.random.normal so we have to seed here too # seed_everything() # # glove_embeddings = load_glove(word_index) # paragram_embeddings = load_para(word_index) # # fasttext_embeddings = load_fasttext(word_index) # # # embedding_matrix = np.mean([glove_embeddings, paragram_embeddings, fasttext_embeddings], axis=0) # embedding_matrix = np.mean([glove_embeddings, paragram_embeddings], axis=0) # joblib.dump(embedding_matrix, 'embedding_matrix.pkl', compress=3) # del glove_embeddings, paragram_embeddings # gc.collect() # # # # embedding_matrix = joblib.load('embedding_matrix.pkl') # # # code inspired from: https://github.com/anandsaha/pytorch.cyclic.learning.rate/blob/master/cls.py # class CyclicLR(object): # def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3, # step_size=2000, mode='triangular', gamma=1., # scale_fn=None, scale_mode='cycle', last_batch_iteration=-1): # # if not isinstance(optimizer, Optimizer): # raise TypeError('{} is not an Optimizer'.format( # type(optimizer).__name__)) # self.optimizer = optimizer # # if isinstance(base_lr, list) or isinstance(base_lr, tuple): # if len(base_lr) != len(optimizer.param_groups): # raise ValueError("expected {} base_lr, got {}".format( # len(optimizer.param_groups), len(base_lr))) # self.base_lrs = list(base_lr) # else: # self.base_lrs = [base_lr] * len(optimizer.param_groups) # # if isinstance(max_lr, list) or isinstance(max_lr, tuple): # if len(max_lr) != len(optimizer.param_groups): # raise ValueError("expected {} max_lr, got {}".format( # len(optimizer.param_groups), len(max_lr))) # self.max_lrs = list(max_lr) # else: # self.max_lrs = [max_lr] * len(optimizer.param_groups) # # self.step_size = step_size # # if mode not in ['triangular', 'triangular2', 'exp_range'] \ # and scale_fn is None: # raise ValueError('mode is invalid and scale_fn is None') # # self.mode = mode # self.gamma = gamma # # if scale_fn is None: # if self.mode == 'triangular': # self.scale_fn = self._triangular_scale_fn # self.scale_mode = 'cycle' # elif self.mode == 'triangular2': # self.scale_fn = self._triangular2_scale_fn # self.scale_mode = 'cycle' # elif self.mode == 'exp_range': # self.scale_fn = self._exp_range_scale_fn # self.scale_mode = 'iterations' # else: # self.scale_fn = scale_fn # self.scale_mode = scale_mode # # self.batch_step(last_batch_iteration + 1) # self.last_batch_iteration = last_batch_iteration # # def batch_step(self, batch_iteration=None): # if batch_iteration is None: # batch_iteration = self.last_batch_iteration + 1 # self.last_batch_iteration = batch_iteration # for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): # param_group['lr'] = lr # # def _triangular_scale_fn(self, x): # return 1. # # def _triangular2_scale_fn(self, x): # return 1 / (2. ** (x - 1)) # # def _exp_range_scale_fn(self, x): # return self.gamma ** (x) # # def get_lr(self): # step_size = float(self.step_size) # cycle = np.floor(1 + self.last_batch_iteration / (2 * step_size)) # x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1) # # lrs = [] # param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs) # for param_group, base_lr, max_lr in param_lrs: # base_height = (max_lr - base_lr) * np.maximum(0, (1 - x)) # if self.scale_mode == 'cycle': # lr = base_lr + base_height * self.scale_fn(cycle) # else: # lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration) # lrs.append(lr) # return lrs # # # def bestThresshold(y_train, train_preds): # tmp = [0, 0, 0] # idx, cur, max # delta = 0 # for tmp[0] in tqdm(np.arange(0.1, 0.501, 0.01)): # tmp[1] = f1_score(y_train, np.array(train_preds) > tmp[0]) # if tmp[1] > tmp[2]: # delta = tmp[0] # tmp[2] = tmp[1] # print('best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, tmp[2])) # return delta # # # splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED).split(x_train, y_train)) # # import torch as t # import torch.nn as nn # import torch.nn.functional as F # # embedding_dim = 300 # embedding_path = '../save/embedding_matrix.npy' # or False, not use pre-trained-matrix # use_pretrained_embedding = True # # hidden_size = 60 # gru_len = hidden_size # # Routings = 4 # 5 # Num_capsule = 5 # Dim_capsule = 5 # 16 # dropout_p = 0.25 # rate_drop_dense = 0.28 # LR = 0.001 # T_epsilon = 1e-7 # num_classes = 30 # # # class Embed_Layer(nn.Module): # def __init__(self, embedding_matrix=None, vocab_size=None, embedding_dim=300): # super(Embed_Layer, self).__init__() # self.encoder = nn.Embedding(vocab_size + 1, embedding_dim) # if use_pretrained_embedding: # # self.encoder.weight.data.copy_(t.from_numpy(np.load(embedding_path))) # 方法一,加载np.save的npy文件 # self.encoder.weight.data.copy_(t.from_numpy(embedding_matrix)) # 方法二 # # def forward(self, x, dropout_p=0.25): # return nn.Dropout(p=dropout_p)(self.encoder(x)) # # # class GRU_Layer(nn.Module): # def __init__(self): # super(GRU_Layer, self).__init__() # self.gru = nn.GRU(input_size=300, # hidden_size=gru_len, # bidirectional=True) # ''' # 自己修改GRU里面的激活函数及加dropout和recurrent_dropout # 如果要使用,把rnn_revised import进来,但好像是使用cpu跑的,比较慢 # ''' # # # if you uncomment /*from rnn_revised import * */, uncomment following code aswell # # self.gru = RNNHardSigmoid('GRU', input_size=300, # # hidden_size=gru_len, # # bidirectional=True) # # # 这步很关键,需要像keras一样用glorot_uniform和orthogonal_uniform初始化参数 # def init_weights(self): # ih = (param.data for name, param in self.named_parameters() if 'weight_ih' in name) # hh = (param.data for name, param in self.named_parameters() if 'weight_hh' in name) # b = (param.data for name, param in self.named_parameters() if 'bias' in name) # for k in ih: # nn.init.xavier_uniform_(k) # for k in hh: # nn.init.orthogonal_(k) # for k in b: # nn.init.constant_(k, 0) # # def forward(self, x): # return self.gru(x) # # # # core caps_layer with squash func # class Caps_Layer(nn.Module): # def __init__(self, input_dim_capsule=gru_len * 2, num_capsule=Num_capsule, dim_capsule=Dim_capsule, \ # routings=Routings, kernel_size=(9, 1), share_weights=True, # activation='default', **kwargs): # super(Caps_Layer, self).__init__(**kwargs) # # self.num_capsule = num_capsule # self.dim_capsule = dim_capsule # self.routings = routings # self.kernel_size = kernel_size # 暂时没用到 # self.share_weights = share_weights # if activation == 'default': # self.activation = self.squash # else: # self.activation = nn.ReLU(inplace=True) # # if self.share_weights: # self.W = nn.Parameter( # nn.init.xavier_normal_(t.empty(1, input_dim_capsule, self.num_capsule * self.dim_capsule))) # else: # self.W = nn.Parameter( # t.randn(BATCH_SIZE, input_dim_capsule, self.num_capsule * self.dim_capsule)) # 64即batch_size # # def forward(self, x): # # if self.share_weights: # u_hat_vecs = t.matmul(x, self.W) # else: # print('add later') # # batch_size = x.size(0) # input_num_capsule = x.size(1) # u_hat_vecs = u_hat_vecs.view((batch_size, input_num_capsule, # self.num_capsule, self.dim_capsule)) # u_hat_vecs = u_hat_vecs.permute(0, 2, 1, 3) # 转成(batch_size,num_capsule,input_num_capsule,dim_capsule) # b = t.zeros_like(u_hat_vecs[:, :, :, 0]) # (batch_size,num_capsule,input_num_capsule) # # for i in range(self.routings): # b = b.permute(0, 2, 1) # c = F.softmax(b, dim=2) # c = c.permute(0, 2, 1) # b = b.permute(0, 2, 1) # outputs = self.activation(t.einsum('bij,bijk->bik', (c, u_hat_vecs))) # batch matrix multiplication # # outputs shape (batch_size, num_capsule, dim_capsule) # if i < self.routings - 1: # b = t.einsum('bik,bijk->bij', (outputs, u_hat_vecs)) # batch matrix multiplication # return outputs # (batch_size, num_capsule, dim_capsule) # # # text version of squash, slight different from original one # def squash(self, x, axis=-1): # s_squared_norm = (x ** 2).sum(axis, keepdim=True) # scale = t.sqrt(s_squared_norm + T_epsilon) # return x / scale # # # class Capsule_Main(nn.Module): # def __init__(self, embedding_matrix=None, vocab_size=None): # super(Capsule_Main, self).__init__() # self.embed_layer = Embed_Layer(embedding_matrix, vocab_size) # self.gru_layer = GRU_Layer() # # 【重要】初始化GRU权重操作,这一步非常关键,acc上升到0.98,如果用默认的uniform初始化则acc一直在0.5左右 # self.gru_layer.init_weights() # self.caps_layer = Caps_Layer() # self.dense_layer = Dense_Layer() # # def forward(self, content): # content1 = self.embed_layer(content) # content2, _ = self.gru_layer( # content1) # 这个输出是个tuple,一个output(seq_len, batch_size, num_directions * hidden_size),一个hn # content3 = self.caps_layer(content2) # output = self.dense_layer(content3) # return output # # # class Attention(nn.Module): # def __init__(self, feature_dim, step_dim, bias=True, **kwargs): # super(Attention, self).__init__(**kwargs) # # self.supports_masking = True # # self.bias = bias # self.feature_dim = feature_dim # self.step_dim = step_dim # self.features_dim = 0 # # weight = torch.zeros(feature_dim, 1) # nn.init.xavier_uniform_(weight) # self.weight = nn.Parameter(weight) # # if bias: # self.b = nn.Parameter(torch.zeros(step_dim)) # # def forward(self, x, mask=None): # feature_dim = self.feature_dim # step_dim = self.step_dim # # eij = torch.mm( # x.contiguous().view(-1, feature_dim), # self.weight # ).view(-1, step_dim) # # if self.bias: # eij = eij + self.b # # eij = torch.tanh(eij) # a = torch.exp(eij) # # if mask is not None: # a = a * mask # # a = a / torch.sum(a, 1, keepdim=True) + 1e-10 # # weighted_input = x * torch.unsqueeze(a, -1) # return torch.sum(weighted_input, 1) # # # class NeuralNet(nn.Module): # def __init__(self): # super(NeuralNet, self).__init__() # # fc_layer = 16 # fc_layer1 = 16 # # self.embedding = nn.Embedding(max_features, embed_size) # self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) # self.embedding.weight.requires_grad = False # # self.embedding_dropout = nn.Dropout2d(0.1) # self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True) # self.gru = nn.GRU(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) # # self.lstm2 = nn.LSTM(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) # # self.lstm_attention = Attention(hidden_size * 2, maxlen) # self.gru_attention = Attention(hidden_size * 2, maxlen) # self.bn = nn.BatchNorm1d(16, momentum=0.5) # self.linear = nn.Linear(hidden_size * 8 + 3, fc_layer1) # 643:80 - 483:60 - 323:40 # self.relu = nn.ReLU() # self.dropout = nn.Dropout(0.1) # self.fc = nn.Linear(fc_layer ** 2, fc_layer) # self.out = nn.Linear(fc_layer, 1) # self.lincaps = nn.Linear(Num_capsule * Dim_capsule, 1) # self.caps_layer = Caps_Layer() # # def forward(self, x): # # Capsule(num_capsule=10, dim_capsule=10, routings=4, share_weights=True)(x) # # h_embedding = self.embedding(x[0]) # h_embedding = torch.squeeze( # self.embedding_dropout(torch.unsqueeze(h_embedding, 0))) # # h_lstm, _ = self.lstm(h_embedding) # h_gru, _ = self.gru(h_lstm) # # ##Capsule Layer # content3 = self.caps_layer(h_gru) # content3 = self.dropout(content3) # batch_size = content3.size(0) # content3 = content3.view(batch_size, -1) # content3 = self.relu(self.lincaps(content3)) # # ##Attention Layer # h_lstm_atten = self.lstm_attention(h_lstm) # h_gru_atten = self.gru_attention(h_gru) # # # global average pooling # avg_pool = torch.mean(h_gru, 1) # # global max pooling # max_pool, _ = torch.max(h_gru, 1) # # f = torch.tensor(x[1], dtype=torch.float).cuda() # # # [512,160] # conc = torch.cat((h_lstm_atten, h_gru_atten, content3, avg_pool, max_pool, f), 1) # conc = self.relu(self.linear(conc)) # conc = self.bn(conc) # conc = self.dropout(conc) # # out = self.out(conc) # # return out # # # class MyDataset(Dataset): # def __init__(self, dataset): # self.dataset = dataset # # def __getitem__(self, index): # data, target = self.dataset[index] # # return data, target, index # # def __len__(self): # return len(self.dataset) # # # def sigmoid(x): # return 1 / (1 + np.exp(-x)) # # # # matrix for the out-of-fold predictions # train_preds = np.zeros((len(x_train))) # # matrix for the predictions on the test set # # test_preds = np.zeros((len(df_test))) # test_preds = np.zeros((len(df_test), len(splits))) # # always call this before training for deterministic results # seed_everything() # # # x_test_cuda_f = torch.tensor(x_test_f, dtype=torch.long).cuda() # # test_f = torch.utils.data.TensorDataset(x_test_cuda_f) # # test_loader_f = torch.utils.data.DataLoader(test_f, batch_size=batch_size, shuffle=False) # # x_test_cuda = torch.tensor(x_test, dtype=torch.long).cuda() # test = torch.utils.data.TensorDataset(x_test_cuda) # test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False) # # avg_losses_f = [] # avg_val_losses_f = [] # # for j, (train_idx, valid_idx) in enumerate(splits): # x_train = np.array(x_train) # y_train = np.array(y_train) # features = np.array(features) # # x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.long).cuda() # y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32).cuda() # # kfold_X_features = features[train_idx.astype(int)] # kfold_X_valid_features = features[valid_idx.astype(int)] # x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.long).cuda() # y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32).cuda() # # # model = BiLSTM(lstm_layer=2,hidden_dim=40,dropout=DROPOUT).cuda() # model = NeuralNet() # # # make sure everything in the model is running on the GPU # model.cuda() # # # define binary cross entropy loss # # note that the model returns logit to take advantage of the log-sum-exp trick # # for numerical stability in the loss # loss_fn = torch.nn.BCEWithLogitsLoss(reduction='sum') # # step_size = 300 # base_lr, max_lr = 0.001, 0.003 # optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), # lr=max_lr) # # ################################################################################################ # scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr, # step_size=step_size, mode='exp_range', # gamma=0.99994) # ############################################################################################### # # train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold) # valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold) # # train = MyDataset(train) # valid = MyDataset(valid) # # ##No need to shuffle the data again here. Shuffling happens when splitting for kfolds. # train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) # # valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) # # print('Fold {}'.format(j+1)) # for epoch in range(n_epochs): # # set train mode of the model. This enables operations which are only applied during training like dropout # start_time = time.time() # model.train() # # avg_loss = 0. # for i, (x_batch, y_batch, index) in enumerate(train_loader): # # Forward pass: compute predicted y by passing x to the model. # ################################################################################################ # f = kfold_X_features[index] # y_pred = model([x_batch, f]) # ################################################################################################ # # ################################################################################################ # # if scheduler: # scheduler.batch_step() # ################################################################################################ # # # Compute and print loss. # loss = loss_fn(y_pred, y_batch) # # # Before the backward pass, use the optimizer object to zero all of the # # gradients for the Tensors it will update (which are the learnable weights # # of the model) # optimizer.zero_grad() # # # Backward pass: compute gradient of the loss with respect to model parameters # loss.backward() # # # Calling the step function on an Optimizer makes an update to its parameters # optimizer.step() # avg_loss += loss.item() / len(train_loader) # # # set evaluation mode of the model. This disabled operations which are only applied during training like dropout # model.eval() # # # predict all the samples in y_val_fold batch per batch # valid_preds_fold = np.zeros((x_val_fold.size(0))) # test_preds_fold = np.zeros((len(df_test))) # # avg_val_loss = 0. # for i, (x_batch, y_batch, index) in enumerate(valid_loader): # f = kfold_X_valid_features[index] # y_pred = model([x_batch, f]).detach() # # avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) # valid_preds_fold[i * batch_size:(i + 1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] # # elapsed_time = time.time() - start_time # print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t time={:.2f}s'.format( # epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time)) # avg_losses_f.append(avg_loss) # avg_val_losses_f.append(avg_val_loss) # # predict all samples in the test set batch per batch # for i, (x_batch,) in enumerate(test_loader): # f = test_features[i * batch_size:(i + 1) * batch_size] # y_pred = model([x_batch, f]).detach() # # test_preds_fold[i * batch_size:(i + 1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] # # train_preds[valid_idx] = valid_preds_fold # # test_preds += test_preds_fold / len(splits) # test_preds[:, j] = test_preds_fold # print('All \t loss={:.4f} \t val_loss={:.4f} \t '.format(np.average(avg_losses_f), np.average(avg_val_losses_f))) # joblib.dump(train_preds, 'valid_pred_bilstm.pkl', compress=3) # joblib.dump(test_preds, 'test_pred_bilstm.pkl', compress=3) # # delta = bestThresshold(y_train[valid_idx.astype(int)], valid_preds_fold) # # del df, df_test, df_train, features, kfold_X_features, kfold_X_valid_features, mispellings_re, test_features # del test_preds, test_preds_fold, train_idx, train_preds, valid_idx, valid_preds_fold, vocab, word_index, x_test, x_train, y_train # gc.collect() # import os # # import numpy as np # import pandas as pd # from sklearn.externals import joblib # # import time # # pd.set_option('max_colwidth', 400) # # from keras.preprocessing.text import Tokenizer # from keras.preprocessing.sequence import pad_sequences # # import torch # import torch.nn as nn # import torch.optim as optim # import torch.nn.functional as F # from torch.utils.data import Dataset, DataLoader # from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence # from torch.autograd import Variable # import torch.utils.data # import random # import warnings # # warnings.filterwarnings("ignore", message="F-score is ill-defined and being set to 0.0 due to no predicted samples.") # import re # # n_epochs = 3 # embed_size = 300 # # INPUT_PATH = './input' # # train = pd.read_csv(os.path.join(INPUT_PATH, "train.csv")) # test = pd.read_csv(os.path.join(INPUT_PATH, "test.csv")) # sub = pd.read_csv(os.path.join(INPUT_PATH, 'sample_submission.csv')) # # puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '#', '*', # '+', '\\', '•', '~', '@', '£', # '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', # '½', 'à', '…', # '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', # '▓', '—', '‹', '─', # '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', # 'Ã', '⋅', '‘', '∞', # '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', # '≤', '‡', '√', ] # # # def clean_text(x): # x = str(x) # for punct in puncts: # x = x.replace(punct, ' {} '.format(punct)) # return x # # # def clean_numbers(x): # x = re.sub('[0-9]{5,}', '#####', x) # x = re.sub('[0-9]{4}', '####', x) # x = re.sub('[0-9]{3}', '###', x) # x = re.sub('[0-9]{2}', '##', x) # return x # # # mispell_dict = {"aren't": "are not", # "can't": "cannot", # "couldn't": "could not", # "didn't": "did not", # "doesn't": "does not", # "don't": "do not", # "hadn't": "had not", # "hasn't": "has not", # "haven't": "have not", # "he'd": "he would", # "he'll": "he will", # "he's": "he is", # "i'd": "I would", # "i'd": "I had", # "i'll": "I will", # "i'm": "I am", # "isn't": "is not", # "it's": "it is", # "it'll": "it will", # "i've": "I have", # "let's": "let us", # "mightn't": "might not", # "mustn't": "must not", # "shan't": "shall not", # "she'd": "she would", # "she'll": "she will", # "she's": "she is", # "shouldn't": "should not", # "that's": "that is", # "there's": "there is", # "they'd": "they would", # "they'll": "they will", # "they're": "they are", # "they've": "they have", # "we'd": "we would", # "we're": "we are", # "weren't": "were not", # "we've": "we have", # "what'll": "what will", # "what're": "what are", # "what's": "what is", # "what've": "what have", # "where's": "where is", # "who'd": "who would", # "who'll": "who will", # "who're": "who are", # "who's": "who is", # "who've": "who have", # "won't": "will not", # "wouldn't": "would not", # "you'd": "you would", # "you'll": "you will", # "you're": "you are", # "you've": "you have", # "'re": " are", # "wasn't": "was not", # "we'll": " will", # "didn't": "did not", # "tryin'": "trying"} # # # def _get_mispell(mispell_dict): # mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys())) # return mispell_dict, mispell_re # # # mispellings, mispellings_re = _get_mispell(mispell_dict) # # # def replace_typical_misspell(text): # def replace(match): # return mispellings[match.group(0)] # # return mispellings_re.sub(replace, text) # # # # Clean the text # train["question_text"] = train["question_text"].apply(lambda x: clean_text(x.lower())) # test["question_text"] = test["question_text"].apply(lambda x: clean_text(x.lower())) # # # Clean numbers # train["question_text"] = train["question_text"].apply(lambda x: clean_numbers(x)) # test["question_text"] = test["question_text"].apply(lambda x: clean_numbers(x)) # # # train = joblib.load('df_train.pkl') # # test = joblib.load('df_test.pkl') # # Clean speelings # train["question_text"] = train["question_text"].apply(lambda x: replace_typical_misspell(x)) # test["question_text"] = test["question_text"].apply(lambda x: replace_typical_misspell(x)) # # joblib.dump(train, 'pre2_df_train.pkl', compress=3) # joblib.dump(test, 'pre2_df_test.pkl', compress=3) # # max_features = 120000 # tk = Tokenizer(lower=True, filters='', num_words=max_features) # full_text = list(train['question_text'].values) + list(test['question_text'].values) # tk.fit_on_texts(full_text) # # train_tokenized = tk.texts_to_sequences(train['question_text'].fillna('missing')) # test_tokenized = tk.texts_to_sequences(test['question_text'].fillna('missing')) # # max_len = 72 # maxlen = 72 # X_train = pad_sequences(train_tokenized, maxlen=max_len) # X_test = pad_sequences(test_tokenized, maxlen=max_len) # # y_train = train['target'].values # # # def sigmoid(x): # return 1 / (1 + np.exp(-x)) # # # ######## # embed_size = 300 # embedding_path = os.path.join(INPUT_PATH, "embeddings/glove.840B.300d/glove.840B.300d.txt") # def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') # embedding_index = dict(get_coefs(*o.split(" ")) for o in open(embedding_path, encoding='utf-8', errors='ignore')) # # all_embs = np.stack(embedding_index.values()) # #emb_mean,emb_std = all_embs.mean(), all_embs.std() # emb_mean,emb_std = -0.005838499, 0.48782197 # word_index = tk.word_index # nb_words = min(max_features, len(word_index)) # embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words + 1, embed_size)) # for word, i in word_index.items(): # if i >= max_features: continue # embedding_vector = embedding_index.get(word) # if embedding_vector is not None: embedding_matrix[i] = embedding_vector # # embedding_path = os.path.join(INPUT_PATH, "embeddings/paragram_300_sl999/paragram_300_sl999.txt") # def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') # embedding_index = dict(get_coefs(*o.split(" ")) for o in open(embedding_path, encoding='utf-8', errors='ignore') if len(o)>100) # # all_embs = np.stack(embedding_index.values()) # # emb_mean,emb_std = all_embs.mean(), all_embs.std() # emb_mean,emb_std = -0.0053247833, 0.49346462 # embedding_matrix1 = np.random.normal(emb_mean, emb_std, (nb_words + 1, embed_size)) # for word, i in word_index.items(): # if i >= max_features: continue # embedding_vector = embedding_index.get(word) # if embedding_vector is not None: embedding_matrix1[i] = embedding_vector # # embedding_matrix = np.mean([embedding_matrix, embedding_matrix1], axis=0) # del embedding_matrix1 # # # embedding_matrixはbilstmのものを使い回す # # ######## # # # embedding_matrix = joblib.load('embedding_matrix.pkl') # # # class Attention(nn.Module): # def __init__(self, feature_dim, step_dim, bias=True, **kwargs): # super(Attention, self).__init__(**kwargs) # # self.supports_masking = True # # self.bias = bias # self.feature_dim = feature_dim # self.step_dim = step_dim # self.features_dim = 0 # # weight = torch.zeros(feature_dim, 1) # nn.init.xavier_uniform_(weight) # self.weight = nn.Parameter(weight) # # if bias: # self.b = nn.Parameter(torch.zeros(step_dim)) # # def forward(self, x, mask=None): # feature_dim = self.feature_dim # step_dim = self.step_dim # # eij = torch.mm( # x.contiguous().view(-1, feature_dim), # self.weight # ).view(-1, step_dim) # # if self.bias: # eij = eij + self.b # # eij = torch.tanh(eij) # a = torch.exp(eij) # # if mask is not None: # a = a * mask # # a = a / torch.sum(a, 1, keepdim=True) + 1e-10 # # weighted_input = x * torch.unsqueeze(a, -1) # return torch.sum(weighted_input, 1) # # # class NeuralNet(nn.Module): # def __init__(self): # super(NeuralNet, self).__init__() # # hidden_size = 128 # # self.embedding = nn.Embedding(max_features, embed_size) # self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) # self.embedding.weight.requires_grad = False # # self.embedding_dropout = nn.Dropout2d(0.1) # self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True) # self.gru = nn.GRU(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) # # self.lstm_attention = Attention(hidden_size * 2, maxlen) # self.gru_attention = Attention(hidden_size * 2, maxlen) # # self.linear = nn.Linear(1024, 16) # self.relu = nn.ReLU() # self.dropout = nn.Dropout(0.1) # self.out = nn.Linear(16, 1) # # def forward(self, x): # h_embedding = self.embedding(x) # h_embedding = torch.squeeze(self.embedding_dropout(torch.unsqueeze(h_embedding, 0))) # # h_lstm, _ = self.lstm(h_embedding) # h_gru, _ = self.gru(h_lstm) # # h_lstm_atten = self.lstm_attention(h_lstm) # h_gru_atten = self.gru_attention(h_gru) # # avg_pool = torch.mean(h_gru, 1) # max_pool, _ = torch.max(h_gru, 1) # # conc = torch.cat((h_lstm_atten, h_gru_atten, avg_pool, max_pool), 1) # conc = self.relu(self.linear(conc)) # conc = self.dropout(conc) # out = self.out(conc) # # return out # # # x_test_cuda = torch.tensor(X_test, dtype=torch.long).cuda() # test = torch.utils.data.TensorDataset(x_test_cuda) # batch_size = 512 # test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False) # # # def train_model(model, x_train, y_train, x_val, y_val, validate=True): # optimizer = torch.optim.Adam(model.parameters()) # # # scheduler = CosineAnnealingLR(optimizer, T_max=5) # # scheduler = StepLR(optimizer, step_size=3, gamma=0.1) # # train = torch.utils.data.TensorDataset(x_train, y_train) # valid = torch.utils.data.TensorDataset(x_val, y_val) # # train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) # valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) # # loss_fn = torch.nn.BCEWithLogitsLoss(reduction='mean').cuda() # best_score = -np.inf # # for epoch in range(n_epochs): # start_time = time.time() # model.train() # avg_loss = 0. # # for x_batch, y_batch in tqdm(train_loader, disable=True): # y_pred = model(x_batch) # # loss = loss_fn(y_pred, y_batch) # # optimizer.zero_grad() # # loss.backward() # # optimizer.step() # avg_loss += loss.item() / len(train_loader) # # model.eval() # # valid_preds = np.zeros((x_val_fold.size(0))) # # if validate: # avg_val_loss = 0. # for i, (x_batch, y_batch) in enumerate(valid_loader): # y_pred = model(x_batch).detach() # # avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) # valid_preds[i * batch_size:(i + 1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] # search_result = threshold_search(y_val.cpu().numpy(), valid_preds) # # val_f1, val_threshold = search_result['f1'], search_result['threshold'] # elapsed_time = time.time() - start_time # print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t val_f1={:.4f} best_t={:.2f} \t time={:.2f}s'.format( # epoch + 1, n_epochs, avg_loss, avg_val_loss, val_f1, val_threshold, elapsed_time)) # else: # elapsed_time = time.time() - start_time # print('Epoch {}/{} \t loss={:.4f} \t time={:.2f}s'.format( # epoch + 1, n_epochs, avg_loss, elapsed_time)) # # valid_preds = np.zeros((x_val_fold.size(0))) # # avg_val_loss = 0. # for i, (x_batch, y_batch) in enumerate(valid_loader): # y_pred = model(x_batch).detach() # # avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) # valid_preds[i * batch_size:(i + 1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] # # print('Validation loss: ', avg_val_loss) # # test_preds = np.zeros((len(test_loader.dataset))) # # for i, (x_batch,) in enumerate(test_loader): # y_pred = model(x_batch).detach() # # test_preds[i * batch_size:(i + 1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] # # scheduler.step() # # return valid_preds, test_preds # , test_preds_local # # # seed = 1029 # # # def threshold_search(y_true, y_proba): # best_threshold = 0 # best_score = 0 # for threshold in tqdm([i * 0.01 for i in range(100)], disable=True): # score = f1_score(y_true=y_true, y_pred=y_proba > threshold) # if score > best_score: # best_threshold = threshold # best_score = score # search_result = {'threshold': best_threshold, 'f1': best_score} # return search_result # # # def seed_everything(seed=1234): # random.seed(seed) # os.environ['PYTHONHASHSEED'] = str(seed) # np.random.seed(seed) # torch.manual_seed(seed) # torch.cuda.manual_seed(seed) # torch.backends.cudnn.deterministic = True # # # seed_everything() # # train_preds = np.zeros(len(train)) # from tqdm import tqdm # from sklearn.metrics import f1_score # # splits = list(StratifiedKFold(n_splits=4, shuffle=True, random_state=10).split(X_train, y_train)) # test_preds = np.zeros((len(test), len(splits))) # for i, (train_idx, valid_idx) in enumerate(splits): # x_train_fold = torch.tensor(X_train[train_idx], dtype=torch.long).cuda() # y_train_fold = torch.tensor(y_train[train_idx, np.newaxis], dtype=torch.float32).cuda() # x_val_fold = torch.tensor(X_train[valid_idx], dtype=torch.long).cuda() # y_val_fold = torch.tensor(y_train[valid_idx, np.newaxis], dtype=torch.float32).cuda() # # train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold) # valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold) # # train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) # valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) # # print('Fold {}'.format(i+1)) # # seed_everything(seed + i) # model = NeuralNet() # model.cuda() # # valid_preds_fold, test_preds_fold = train_model(model, # x_train_fold, # y_train_fold, # x_val_fold, # y_val_fold, validate=True) # # train_preds[valid_idx] = valid_preds_fold # test_preds[:, i] = test_preds_fold # # # test_preds_local[:, i] = test_preds_local_fold # joblib.dump(train_preds, 'valid_pred_pytorch.pkl', compress=3) # joblib.dump(test_preds, 'test_pred_pytorch.pkl', compress=3) # # ## 以下は後で消す # search_result = threshold_search(y_train[valid_idx.astype(int)], valid_preds_fold) # print(search_result) # # sub['prediction'] = test_preds.mean(1) > search_result['threshold'] # # sub.to_csv("submission.csv", index=False) # # # del df, df_test, df_train, embedding_matrix, features, mispellings_re, test_features # # del test_preds, train_idx, train_preds, valid_idx, vocab, word_index, x_test, x_train # # del y_train # # gc.collect() import os import pandas as pd import numpy as np from sklearn.externals import joblib from sklearn.linear_model import Lasso from sklearn.metrics import f1_score INPUT_PATH = './input' def bestThresshold(y_train, train_preds): tmp = [0, 0, 0] # idx, cur, max delta = 0 for tmp[0] in np.arange(0.01, 0.501, 0.01): tmp[1] = f1_score(y_train, np.array(train_preds) > tmp[0]) if tmp[1] > tmp[2]: delta = tmp[0] tmp[2] = tmp[1] return delta, tmp[2] def merge_predictions(X_tr, y_tr, X_te=None, est=None, verbose=True): if est is None: est = Lasso(alpha=0.0001, precompute=True, max_iter=1000, positive=True, random_state=9999, selection='random') est.fit(X_tr, y_tr) # if hasattr(est, 'intercept_') and verbose: return (est.predict(X_tr), est.predict(X_te) if X_te is not None else None) va_preds = [] te_preds = [] te_preds0 = [] te_preds1 = [] te_preds2 = [] te_preds3 = [] va_preds.append(joblib.load("valid_pred_bilstm.pkl")[:, np.newaxis]) va_preds.append(joblib.load("valid_pred_pytorch.pkl")[:, np.newaxis]) te_preds.append(joblib.load("test_pred_bilstm.pkl").mean(1)[:, np.newaxis]) te_preds.append(joblib.load("test_pred_pytorch.pkl").mean(1)[:, np.newaxis]) # te_preds0.append(joblib.load("test_pred_bilstm.pkl")[:,0][:, np.newaxis]) # te_preds0.append(joblib.load("test_pred_pytorch.pkl")[:,0][:, np.newaxis]) # te_preds1.append(joblib.load("test_pred_bilstm.pkl")[:,1][:, np.newaxis]) # te_preds1.append(joblib.load("test_pred_pytorch.pkl")[:,1][:, np.newaxis]) # te_preds2.append(joblib.load("test_pred_bilstm.pkl")[:,2][:, np.newaxis]) # te_preds2.append(joblib.load("test_pred_pytorch.pkl")[:,2][:, np.newaxis]) # te_preds3.append(joblib.load("test_pred_bilstm.pkl")[:,3][:, np.newaxis]) # te_preds3.append(joblib.load("test_pred_pytorch.pkl")[:,3][:, np.newaxis]) # print(te_preds0[0].shape) # print(te_preds0[1].shape) va_preds = np.hstack(va_preds) te_preds = np.hstack(te_preds) # te_preds0 = np.hstack(te_preds0) # te_preds1 = np.hstack(te_preds1) # te_preds2 = np.hstack(te_preds2) # te_preds3 = np.hstack(te_preds3) y_va = joblib.load("df_train.pkl").target.values[:, np.newaxis] print(va_preds.shape) print(te_preds.shape) va_preds_merged, te_preds_merged = merge_predictions(X_tr=va_preds, y_tr=y_va, X_te=te_preds) delta, f_score = bestThresshold(y_va, va_preds_merged) # print('[Model mean] best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, f_score)) # va_preds_merged, te_preds_merged1 = merge_predictions(X_tr=va_preds, y_tr=y_va, X_te=te_preds1) # delta, f_score = bestThresshold(y_va, va_preds_merged) # print('[Model mean] best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, f_score)) # va_preds_merged, te_preds_merged2 = merge_predictions(X_tr=va_preds, y_tr=y_va, X_te=te_preds2) # delta, f_score = bestThresshold(y_va, va_preds_merged) # print('[Model mean] best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, f_score)) # va_preds_merged, te_preds_merged3 = merge_predictions(X_tr=va_preds, y_tr=y_va, X_te=te_preds3) # delta, f_score = bestThresshold(y_va, va_preds_merged) print('[Model mean] best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, f_score)) # te_preds_merged = (te_preds_merged0 + te_preds_merged1 + te_preds_merged2 + te_preds_merged3)/ 4 df_test = pd.read_csv(os.path.join(INPUT_PATH, "test.csv")) submission = df_test[['qid']].copy() submission['prediction'] = (te_preds_merged > delta).astype(int) submission.to_csv('submission.csv', index=False) # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in
[ "a14z7ym@aiit.ac.jp" ]
a14z7ym@aiit.ac.jp
98ac30fd2bd0aa5285eea162827c1942b83d46d7
dee6fd2475bebfba6c12c861b5b3e6c60aad0b96
/music/migrations/0001_initial.py
de1e503bdb714abd5eac041ff7032969d444438e
[]
no_license
kevin-roark/adhoc-x2
4c67f66a62deb0b4e18c2ce202eda429b08d2cce
944fda23eaa6ed6f0ded70a08af7912b715c7825
refs/heads/master
2021-06-04T09:19:17.683899
2017-10-23T16:03:44
2017-10-23T16:03:44
16,844,748
0
0
null
null
null
null
UTF-8
Python
false
false
4,512
py
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Artist' db.create_table('music_artist', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('name', self.gf('django.db.models.fields.CharField')(max_length=255)), )) db.send_create_signal('music', ['Artist']) # Adding model 'MusicEmbed' db.create_table('music_musicembed', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('artist', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['music.Artist'])), ('title', self.gf('django.db.models.fields.CharField')(max_length=255)), )) db.send_create_signal('music', ['MusicEmbed']) # Adding model 'Song' db.create_table('music_song', ( ('musicembed_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['music.MusicEmbed'], unique=True, primary_key=True)), ('song', self.gf('django.db.models.fields.files.FileField')(max_length=100)), ('track_number', self.gf('django.db.models.fields.IntegerField')(null=True, blank=True)), ('streamable', self.gf('django.db.models.fields.BooleanField')(default=False)), ('downloadable', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_signal('music', ['Song']) # Adding model 'Release' db.create_table('music_release', ( ('musicembed_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['music.MusicEmbed'], unique=True, primary_key=True)), )) db.send_create_signal('music', ['Release']) # Adding M2M table for field songs on 'Release' db.create_table('music_release_songs', ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), ('release', models.ForeignKey(orm['music.release'], null=False)), ('song', models.ForeignKey(orm['music.song'], null=False)) )) db.create_unique('music_release_songs', ['release_id', 'song_id']) def backwards(self, orm): # Deleting model 'Artist' db.delete_table('music_artist') # Deleting model 'MusicEmbed' db.delete_table('music_musicembed') # Deleting model 'Song' db.delete_table('music_song') # Deleting model 'Release' db.delete_table('music_release') # Removing M2M table for field songs on 'Release' db.delete_table('music_release_songs') models = { 'music.artist': { 'Meta': {'object_name': 'Artist'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'music.musicembed': { 'Meta': {'object_name': 'MusicEmbed'}, 'artist': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['music.Artist']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'music.release': { 'Meta': {'object_name': 'Release', '_ormbases': ['music.MusicEmbed']}, 'musicembed_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['music.MusicEmbed']", 'unique': 'True', 'primary_key': 'True'}), 'songs': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['music.Song']", 'symmetrical': 'False'}) }, 'music.song': { 'Meta': {'object_name': 'Song', '_ormbases': ['music.MusicEmbed']}, 'downloadable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'musicembed_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['music.MusicEmbed']", 'unique': 'True', 'primary_key': 'True'}), 'song': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}), 'streamable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'track_number': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}) } } complete_apps = ['music']
[ "gupta.udbhav@gmail.com" ]
gupta.udbhav@gmail.com
c752f809883f4437516c5a4abb09f34955fe40e2
fd2981b5b2bb37587c90c51b03d353630d58ffb4
/Orientada Objeto/lista_exercicios3.py
531cc2d57a1eb9e94dc5afa7a718d0b4f370466e
[]
no_license
vitosoliveira/Python
00363a55a78356149310cf86a20dbf7b7c84c278
4ae1ed6e9dca9b5e38bbf9a422022761056f95bb
refs/heads/master
2022-07-28T12:15:44.383056
2020-05-20T20:45:43
2020-05-20T20:45:43
247,159,094
0
0
null
null
null
null
UTF-8
Python
false
false
479
py
class Pessoa(): __telefone = "" def __init__(self,nome,endereco): self.__nome = nome self.__endereco = endereco def get_nome(self): return self.__nome def get_end(self): return self.__endereco def get_tel(self): return self.__telefone def set_nome (self,nome): self.__nome = nome def set_end (self, endereco): self.__endereco = endereco def set_tel (self,tel): self.__telefone = tel
[ "vitor.soliveira@aluno.faculdadeimpacta.com.br" ]
vitor.soliveira@aluno.faculdadeimpacta.com.br
cad49a464e253ae9342c164c950fd6c0ec78bdcf
d5a32e532fe231c16e52149604f0db34c5f4d2f9
/binarysearch.io/sum_of_the_deepest_node.py
a7848ee9b46081b4f3607498a2a3079159af306e
[ "MIT" ]
permissive
mishrakeshav/Competitive-Programming
93705f63337639e8464c1d50f3394434b7422f15
00c1bd272646754ca4c260d57989304c8e323838
refs/heads/master
2023-07-06T07:32:23.042324
2023-06-29T15:27:24
2023-06-29T15:27:24
216,195,590
3
3
MIT
2020-10-03T07:55:18
2019-10-19T11:27:53
Python
UTF-8
Python
false
false
1,288
py
# class Tree: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def solve(self, root): # Write your code here nodeLevel = {} def deepest(root,level=0): if root is None: return else: if level not in nodeLevel: nodeLevel[level] = [] nodeLevel[level].append(root.val) deepest(root.left,level+1) deepest(root.right, level+1) deepest(root,0) return sum(nodeLevel[max(nodeLevel)]) class Solution: def solve(self, root): waiting = [root] while(waiting): newWaiting = [] possAns = 0 for node in waiting: possAns += node.val if node.left: newWaiting.append(node.left) if node.right: newWaiting.append(node.right) if not newWaiting: return possAns else: waiting = newWaiting
[ "mishrakeshav@users.noreply.github.com" ]
mishrakeshav@users.noreply.github.com
09705c6a4dfd5febaf20aa02490ba12bb957faad
b95ea9ec7a46a9c008e66eba4d96665dc7fab4df
/caspr/models/utils.py
99101475f7b862315a2d9de3588f17a7e7218a72
[ "MIT" ]
permissive
davrempe/caspr
05b3bff46dfa6caf4b46652451a5d3c86a0ecadb
b8360dab9b1bd9087b10e7568a2a4c6cc63f009a
refs/heads/main
2023-04-02T16:47:14.746292
2023-03-30T20:39:48
2023-03-30T20:39:48
306,191,089
76
6
null
null
null
null
UTF-8
Python
false
false
894
py
# # Adapted from https://github.com/stevenygd/PointFlow # from math import log, pi import torch import numpy as np def standard_normal_logprob(z): log_z = -0.5 * log(2 * pi) return log_z - z.pow(2) / 2 # Taken from https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/15 def truncated_normal(tensor, mean=0, std=1, trunc_std=2): size = tensor.shape tmp = tensor.new_empty(size + (4,)).normal_() valid = (tmp < trunc_std) & (tmp > -trunc_std) ind = valid.max(-1, keepdim=True)[1] tensor.data.copy_(tmp.gather(-1, ind).squeeze(-1)) tensor.data.mul_(std).add_(mean) return tensor def sample_gaussian(size, truncate_std=None, device=None): y = torch.randn(*size).float() y = y if device is None else y.to(device) if truncate_std is not None: truncated_normal(y, mean=0, std=1, trunc_std=truncate_std) return y
[ "davrempe@gmail.com" ]
davrempe@gmail.com
ee736b75cbe69fbf7495f8be1a6d931650aa9a87
cdafe4cf77b7be4e7395e9518bec65c3debc46ac
/client/menu/__init__.py
c3fbcd0d1799ee926fe6949b0e72b04b30023f7c
[ "MIT" ]
permissive
rrsilaya/spaceteam
e87e5cc9a92c14cc8ed175171e282f07827d66c5
eca853d82f14d1d5f5f892977dfb35d20da40d0b
refs/heads/master
2020-04-03T11:27:08.118968
2018-12-12T05:06:53
2018-12-12T05:06:53
155,222,034
0
0
null
null
null
null
UTF-8
Python
false
false
262
py
from menu.main import Main from menu.lobby import Lobby from menu.connect import Connect from menu.username import Username from menu.welcome import Welcome from menu.connecting import Connecting from menu.getip import GetIp from menu.howtoplay import HowToPlay
[ "rrsilaya@gmail.com" ]
rrsilaya@gmail.com
5d2e5134e1095e1fd5b25e03a0582d9165899207
f0e048b2398b42a3c3ec42925ab75f754cd8d214
/configs/RAChallenge/s2anet_r101_fpn_1x_ms_ra.py
a06a8e7cd56271360518b99aafbdbfc70973c468
[]
no_license
myknowntime/RIDet
c56535f52ccf76e41bd181faf2bceb2f0e8fbd57
96bee9a7089a267855d494fbf9d2f2f78064c54e
refs/heads/master
2023-08-14T23:46:32.849835
2021-10-06T14:29:31
2021-10-06T14:29:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,958
py
# fp16 settings # fp16 = dict(loss_scale=512.) # model settings model = dict( type='S2ANetDetector', pretrained='torchvision://resnet101', backbone=dict( type='ResNet', depth=101, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, style='pytorch'), neck=dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs=True, num_outs=5), rbox_head=dict( type='S2ANetHead', num_classes=6, in_channels=256, feat_channels=256, stacked_convs=2, align_conv_type='AlignConv',#[AlignConv,DCN,GA_DCN] align_conv_size=3, with_orconv=True, anchor_ratios=[1.0], anchor_strides=[8, 16, 32, 64, 128], anchor_scales=[4], target_means=[.0, .0, .0, .0, .0], target_stds=[1.0, 1.0, 1.0, 1.0, 1.0], loss_fam_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=5.0), # loss权重修改 从1到5 loss_fam_bbox=dict( type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0), loss_odm_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=5.0), # loss权重修改 从1到5 loss_odm_bbox=dict( type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0))) # training and testing settings train_cfg = dict( fam_cfg=dict( anchor_target_type='hbb_obb_rbox_overlap', assigner=dict( type='MaxIoUAssignerRbox', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False), odm_cfg=dict( anchor_target_type='obb_obb_rbox_overlap', anchor_inside_type='center', assigner=dict( type='MaxIoUAssignerRbox', pos_iou_thr=0.5, neg_iou_thr=0.4, min_pos_iou=0, ignore_iof_thr=-1), allowed_border=-1, pos_weight=-1, debug=False)) test_cfg = dict( nms_pre=2000, min_bbox_size=0, score_thr=0.15, nms=dict(type='nms_rotated', iou_thr=0.1), max_per_img=2000) img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True), dict(type='RotatedResize', img_scale=(1024, 1024), keep_ratio=True), # dict(type='RotatedResize', img_scale=(1024, 1024), keep_ratio=True), dict(type='RotatedRandomFlip', flip_ratio=0), # dict(type='RandomRotate', rate=0.5, angles=[30, 60, 90, 120, 150], auto_bound=False), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1024, 1024), flip=False, transforms=[ dict(type='RotatedResize', img_scale=(1024, 1024), keep_ratio=True), # dict(type='RotatedRandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='Pad', size_divisor=32), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ]) ] # dataset settings dataset_type = 'RAChallengeDataset' data_root = 'data/RAChallenge/stage1/train/' # train无augmentation warmup_data_root = 'data/RAChallenge/warmup/' # warmup数据无augmentation test_root = 'data/RAChallenge/stage1/' stage2_test_root = 'data/RAChallenge/stage2/' all_data_root = 'data/RAChallenge/stage1/all_data_augment/' # train_aug + warmup_aug data = dict( imgs_per_gpu=2, workers_per_gpu=2, # train no aug train=dict( type=dataset_type, ann_file=all_data_root + 'train.json', img_prefix=all_data_root + 'images/', pipeline=train_pipeline), # # train with aug # train=dict( # type=dataset_type, # ann_file=aug_data_root + 'train.json', # img_prefix=aug_data_root + 'images/', # pipeline=train_pipeline), val=dict( type=dataset_type, ann_file=data_root + 'trainval_split/trainval.json', img_prefix=data_root + 'trainval_split/images/', pipeline=test_pipeline), # submission test=dict( type=dataset_type, ann_file=stage2_test_root + 'test.json', img_prefix=stage2_test_root + 'test2/', pipeline=test_pipeline) # # evalloss_fam_cls: 1.0105, # test=dict( # type=dataset_type, # ann_file=warmup_data_root + 'train.json', # img_prefix=warmup_data_root + 'images/', # pipeline=test_pipeline) ) # optimizer # optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0001) optimizer = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.00005) optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2)) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[6, 10]) # step=[8, 16, 20]) # step=[12, 24, 36, 48]) checkpoint_config = dict(interval=2) # yapf:disable log_config = dict( interval=20, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook') ]) # yapf:enable # runtime settings total_epochs = 12 dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = 'work_dirs/s2anet_r101_fpn_1024_ms_ra/' load_from = 'work_dirs/s2anet_r101_fpn_1024_ms_ra/70_10-15.pth' # load_from = None resume_from = None workflow = [('train', 1)]
[ "mq_chaser@126.com" ]
mq_chaser@126.com
a8d6d37a709547b86f9836a1d6b38849d9760e04
e0eddd9133560e1598f49feda94fd67eb121df1e
/GoEatApp.py
497524792ef3b7c6adc1e44a7943bbb6c10740e7
[]
no_license
gun0317/GoEat
c39126573a24bf48460445fe3fef111d06378df7
d045642fb1a726e5815c2c5ef6a0f89b4582065e
refs/heads/master
2020-09-09T08:25:45.025911
2019-03-08T07:36:07
2019-03-08T07:36:07
221,399,126
1
0
null
2019-11-13T07:32:46
2019-11-13T07:32:45
null
UTF-8
Python
false
false
3,456
py
import numpy as np import pickle import pandas as pd import GoEat from GoEatWebCrawler import GoEatWebCrawler from collections import Counter from konlpy.tag import Hannanum from konlpy.tag import Kkma from konlpy.utils import concordance, pprint import scipy import sklearn import konlpy import re import pymysql db = pymysql.connect(host = 'DESKTOP-PD3BJSG',port=3306,user='mysql',password ='mysql93',db='goeat',charset = 'utf8') cursor = db.cursor() sql ="SELECT table_name FROM information_schema.tables where table_schema='goeat'" cursor.execute(sql) table = cursor.fetchall() table_names = [] for name in table: table_names.append(name[0]) for table_name in table_names: table_select = "SELECT * FROM " + table_name col_show = col = "SHOW COLUMNS FROM " + table_name cursor.execute(table_select) data = cursor.fetchall() cursor.execute(col_show) columns = cursor.fetchall() col_name = [] for column in columns: col_name.append(column[0].replace('\ufeff','')) vars()[table_name +'_df'] = pd.DataFrame(list(data),columns = col_name) vars()[table_name +'_df'].index = vars()[table_name +'_df'].index + 1 #smooth_user_preference interactions_full_df = interactions_df \ .groupby(['userIndex', 'foodIndex'])['eventStrength'].mean() \ .apply(GoEat.smooth_user_preference).reset_index() #get tfidf tfidf_df = tfidf_df.drop('foodIndex',axis=1) tfidf_feature_names = tfidf_df.columns tfidf_matrix = scipy.sparse.csr_matrix(tfidf_df) #build user profiles user_profiles = {} for key, value in list(zip(user_profiles_df.loc[:,'userIndex'].values, user_profiles_df.loc[:,user_profiles_df.columns != 'userIndex'].values)): user_profiles[key] = value.reshape(1, -1) #get new user info print('음식 추천을 시작합니다!', rec_start_time) user_index = int(input('userIndex를 입력해주세요 : ')) new_user = GoEat.cold_start_question(user_index,food_df,15) interactions_df = interactions_df.append(new_user,ignore_index=True) interactions_full_df = interactions_df \ .groupby(['userIndex', 'foodIndex'])['eventStrength'].mean() \ .apply(GoEat.smooth_user_preference).reset_index() ##Content-based filtering## #build user profile #builder.get_interacted_indexed_df(interactions_full_df,food_df) #user_profiles[user_index] = builder.build_users_profile(user_index) builder= GoEat.user_profiles_builder() builder.get_interacted_indexed_df(interactions_full_df,food_df) user_profiles = builder.build_users_profiles(interactions_df,food_df,tfidf_matrix) #builder.get_interacted_indexed_df(interactions_full_df,food_df) #content-based model building cb_model = GoEat.CBRecommender(food_df,user_profiles,tfidf_matrix) ##Collaborative model building## #build users X items SVD cf_preds_df = GoEat.users_items_svd(interactions_full_df, nfactors = 5) #collaborative model building cf_model = GoEat.CFRecommender(cf_preds_df, food_df) #Hybrid Model buliding hybrid_model = GoEat.HybridRecommender(cb_model,cf_model,food_df,method='harmonic') rec_foods = hybrid_model.recommend_items(user_index,topn=3,items_to_ignore=new_user.foodIndex.tolist(),verbose=True) print('\n') print('당신께 추천드리는 음식은!!!\n') print('1번 째! ' + rec_foods.loc[0,'foodName']) print('2번 째! ' + rec_foods.loc[1,'foodName']) print('3번 째! ' + rec_foods.loc[2,'foodName']) # #interaction_df
[ "35717288+taenyun93@users.noreply.github.com" ]
35717288+taenyun93@users.noreply.github.com
87c6b732826010a09b36dc58caec09f610519427
8d946e49d0e9c5e038b6dd5fdfc11c72f64470f9
/instagram/urls.py
f97803739aafc2feba7d773b1e1fc52f1f78a5e7
[ "MIT" ]
permissive
gabyxbinnaeah/TwinterApp
bfc955fdf529b5ecce89f62ab6bd4f8ecf9e461e
a0f68527a3e01cd47e49f9a17988ec5095422695
refs/heads/master
2023-06-16T01:07:43.531740
2021-07-14T08:37:50
2021-07-14T08:37:50
384,447,340
0
0
null
null
null
null
UTF-8
Python
false
false
1,314
py
"""instagram URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.urls import path,include from django.contrib.auth import views from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django_registration.backends.one_step.views import RegistrationView urlpatterns = [ path('admin/', admin.site.urls), path('', include('chat.urls')), path('accounts/', include('django_registration.backends.one_step.urls')), path('accounts/', include('django.contrib.auth.urls')), path('accounts/register/',RegistrationView.as_view(success_url='/'),name='django_registration_register'), ]
[ "gabyxbinnaeh4@gmail.com" ]
gabyxbinnaeh4@gmail.com
730866580b73659ddb97537f635907379b8b456e
7b36bf1b3f298412c5cf6cda8a654aec3408966e
/test/verifywithizhaoyue.py
152a3d8695f50624bb6a0fb5a48958944bd11233
[]
no_license
machine-w/vguangserver
9b4621f25d11e8f552a22882d13db7c4892df6a8
6dc44832bbad274aa4467befa35ba8f627874682
refs/heads/master
2022-04-24T05:32:58.764328
2020-04-28T13:47:50
2020-04-28T13:47:50
258,980,970
0
0
null
null
null
null
UTF-8
Python
false
false
495
py
import sys sys.path.append("..") from .resultinterface import OperResult class ToList(OperResult): def __init__(self,SimpleRate,**extendInfor): super().__init__(SimpleRate,**extendInfor) self.dataList =[] def read(self): print(self.dataList) def write(self,step,stepTime,curTime,dataType,data): self.dataList.append(data.numpy()) def clear(self): pass if __name__ == "__main__": r = ToList(100) print(isinstance(r, OperResult))
[ "steve2008.ma@gmail.com" ]
steve2008.ma@gmail.com
6d1a989bb6d0863e4392b6b5982cb9a5e2b1b642
9d0195aa83cc594a8c61f334b90375961e62d4fe
/JTTest/SL7/CMSSW_10_2_15/src/dataRunA/nano993.py
6a4a6c9844658758121f01dd960432ed50dbceed
[]
no_license
rsk146/CMS
4e49592fc64f6438051544c5de18598db36ed985
5f8dab8c59ae556598b9747b52b88205fffc4dbe
refs/heads/master
2022-12-01T03:57:12.126113
2020-08-04T03:29:27
2020-08-04T03:29:27
284,863,383
0
0
null
null
null
null
UTF-8
Python
false
false
4,292
py
# Auto generated configuration file # using: # Revision: 1.19 # Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v # with command line options: nanoAOD_jetToolbox_cff -s NANO --data --eventcontent NANOAOD --datatier NANOAOD --no_exec --conditions 102X_dataRun2_Sep2018Rereco_v1 --era Run2_2018,run2_nanoAOD_102Xv1 --customise_commands=process.add_(cms.Service('InitRootHandlers', EnableIMT = cms.untracked.bool(False))) --customise JMEAnalysis/JetToolbox/nanoAOD_jetToolbox_cff.nanoJTB_customizeMC --filein /users/h2/rsk146/JTTest/SL7/CMSSW_10_6_12/src/ttbarCutTest/dataReprocessing/0004A5E9-9F18-6B42-B31D-4206406CE423.root --fileout file:jetToolbox_nano_datatest.root import FWCore.ParameterSet.Config as cms from Configuration.StandardSequences.Eras import eras process = cms.Process('NANO',eras.Run2_2018,eras.run2_nanoAOD_102Xv1) # import of standard configurations process.load('Configuration.StandardSequences.Services_cff') process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Configuration.EventContent.EventContent_cff') process.load('Configuration.StandardSequences.GeometryRecoDB_cff') process.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff') process.load('PhysicsTools.NanoAOD.nano_cff') process.load('Configuration.StandardSequences.EndOfProcess_cff') process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) # Input source process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:root://cms-xrd-global.cern.ch//store/data/Run2018A/EGamma/MINIAOD/17Sep2018-v2/120000/61C328F6-6BDC-FB4F-A3E2-4BF07EBED5FA.root'), secondaryFileNames = cms.untracked.vstring() ) process.options = cms.untracked.PSet( ) # Production Info process.configurationMetadata = cms.untracked.PSet( annotation = cms.untracked.string('nanoAOD_jetToolbox_cff nevts:1'), name = cms.untracked.string('Applications'), version = cms.untracked.string('$Revision: 1.19 $') ) # Output definition process.NANOAODoutput = cms.OutputModule("NanoAODOutputModule", compressionAlgorithm = cms.untracked.string('LZMA'), compressionLevel = cms.untracked.int32(9), dataset = cms.untracked.PSet( dataTier = cms.untracked.string('NANOAOD'), filterName = cms.untracked.string('') ), fileName = cms.untracked.string('file:jetToolbox_nano_datatest993.root'), outputCommands = process.NANOAODEventContent.outputCommands ) # Additional output definition # Other statements from Configuration.AlCa.GlobalTag import GlobalTag process.GlobalTag = GlobalTag(process.GlobalTag, '102X_dataRun2_Sep2018Rereco_v1', '') # Path and EndPath definitions process.nanoAOD_step = cms.Path(process.nanoSequence) process.endjob_step = cms.EndPath(process.endOfProcess) process.NANOAODoutput_step = cms.EndPath(process.NANOAODoutput) # Schedule definition process.schedule = cms.Schedule(process.nanoAOD_step,process.endjob_step,process.NANOAODoutput_step) from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask associatePatAlgosToolsTask(process) # customisation of the process. # Automatic addition of the customisation function from PhysicsTools.NanoAOD.nano_cff from PhysicsTools.NanoAOD.nano_cff import nanoAOD_customizeData #call to customisation function nanoAOD_customizeData imported from PhysicsTools.NanoAOD.nano_cff process = nanoAOD_customizeData(process) # Automatic addition of the customisation function from JMEAnalysis.JetToolbox.nanoAOD_jetToolbox_cff from JMEAnalysis.JetToolbox.nanoAOD_jetToolbox_cff import nanoJTB_customizeMC #call to customisation function nanoJTB_customizeMC imported from JMEAnalysis.JetToolbox.nanoAOD_jetToolbox_cff process = nanoJTB_customizeMC(process) # End of customisation functions # Customisation from command line process.add_(cms.Service('InitRootHandlers', EnableIMT = cms.untracked.bool(False))) # Add early deletion of temporary data products to reduce peak memory need from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete process = customiseEarlyDelete(process) # End adding early deletion
[ "rsk146@scarletmail.rutgers.edu" ]
rsk146@scarletmail.rutgers.edu
cefa36b71fd4da6c8b37f32c155e0eb34813882b
0296bc69a0d9608ed826ad7a719395f019df098f
/Tools/semantic_check.py
7bbe1e264b5436b25ade1ce79adfe0c38466b046
[]
no_license
jcn16/Blender_HDRmap_render
c0486a77e04c5b41a6f75f123dbdb3d10c682367
50e6cdb79fef83081de9830e7105dd425a235a9e
refs/heads/main
2023-07-19T22:22:53.622052
2021-08-20T06:29:10
2021-08-20T06:29:10
377,757,283
2
0
null
null
null
null
UTF-8
Python
false
false
559
py
import os from tqdm import tqdm ''' check if semantic_mask is complete ''' root='/media/jcn/新加卷/JCN/JCN_test_datset/Train_512' child_dirs=os.listdir(root) child_dirs.sort() pbar=tqdm(total=len(child_dirs)) for model in child_dirs: pbar.update(1) sub_dirs=os.listdir(os.path.join(root,model)) sub_dirs.remove('prt') sub_dirs.remove('GEO') sub_dirs.sort() for dir in sub_dirs: src=os.path.join(root,model,dir,'semantic_mask.png') if os.path.exists(src): continue else: print(src)
[ "591599635@qq.com" ]
591599635@qq.com
3187f7441f3e10f1fb6b9e456dee754204018c84
76ac66b96091e60d5521ab7db69a086d620fefce
/unidad5/ejercicio.py
b96bb987cc8096f1d55284105ca07623bf2d0a29
[]
no_license
Jesus121299/EJERCICIOS_INDIVIDUALES
aa88980cb3aa43c2dbef1624d70f2150c833171c
b663d3d331b7d455b9d13240c7d5bde5022e7791
refs/heads/master
2020-09-21T08:37:12.151621
2019-11-28T23:24:14
2019-11-28T23:24:14
224,743,548
0
0
null
null
null
null
UTF-8
Python
false
false
1,415
py
# -*- codig: utf-8 -*- import re patch = "ejerciciounidad5.txt" try: archivo=open(patch,'r') except: print("el archivo no se pudo ejecutar") quit() texto="" for linea in archivo: texto += linea #Ejercicio 1 variables= r'([A-Za-z-_]+\s*[=|;])' resultvar = re.findall(variables,texto) print("\n Las variables que estan declaradas son:\n", resultvar) #Ejercicio 2 entero = r'[+,-]?[0-9]+' decimal = r'[[0-9]*[.]]?[0-9]+' resultente = re.findall(entero,texto) resultdeci = re.findall(decimal,texto) print("\n Los numeros enteros del archivo son:\n", resultente) print("\nLos numeros decimales del archivo son:\n", resultdeci) #Ejercicio 3 aritmetica = r'[A-Za-z|0-9]+[+*/%-]+[A-Za-z|0-9|]' aritmeticaresul = re.findall(aritmetica, texto) print("Los operadores aritmeticos del archivo son: \n", aritmeticaresul) #Ejercicio 4 relacional = r'[A-Za-z|0-9]+\s*[|<|>|!=|<=|>=]+\s*[A-Za-z|0-9]+' relacionalresul = re.findall(relacional, texto) print("\n Los operadores relacionales identificados son: \n", relacionalresul) #Ejercicio 5 reservadas = r'\b(false|def|if|raise|none|del|import|return|true|elif|int|try|and|else|is|while|as|except|lambda|with|assert|finally|nonlocal|yield|break|for|not|class|from|or|continue|global|pass\s)+|\s[:]+' resultadoreser = re.findall(reservadas, texto) print("\n LAS PALABRAS RESERVADAS SON: ", resultadoreser) print ("")
[ "noreply@github.com" ]
noreply@github.com
831bf874cf91a60dd3b751441f81891df7c7e738
6d21a0366cd7eaf9be4cda90d3db999e7f0ebcf6
/detection/yolo/data/ayudajf.py
9071217f81ec0248ce019ac36ede09d143950953
[]
no_license
juanfra16/PizzaRecognition
b8299c9c5e60f0fe9b9bc81c48f4bc908c18fd33
2613dbcf502c92cfdbf40014b80279a8adb00bf4
refs/heads/master
2022-11-22T10:36:57.672332
2020-07-20T06:27:21
2020-07-20T06:27:21
280,964,869
0
0
null
2020-07-19T22:56:50
2020-07-19T22:56:49
null
UTF-8
Python
false
false
172
py
import sys archivo1, nuevo = sys.argv[1:3] with open(archivo1) as file: datos = file.read().replace("../","") with open(nuevo, "w") as file: file.write(datos)
[ "jfrojas5@uc.cl" ]
jfrojas5@uc.cl
afd31b55843500b8234e4d0c37c5e4063cf5bb46
6ff2e7e5a1db3643fde55fa1368ecc1ec747a2e6
/lib/adbUtils.py
e2a8aa4e0fbe9a2df1d01589968ac4736325c848
[ "MIT" ]
permissive
thanksdanny/Auto_Analysis
4985b41f2ba56cd1a7e930ff5d0107a88caa4311
284d116b6397cb77c72c2c45a0bffa2a8f62e384
refs/heads/master
2021-01-20T07:32:07.181213
2017-03-08T02:12:46
2017-03-08T02:12:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
32,326
py
# -*- coding: utf-8 -*- __author__ = 'joko' """ @author:joko @time: 16/11/8 下午2:52 """ import platform import subprocess import re from time import sleep import time import os import random PATH = lambda p: os.path.abspath(p) # 判断系统类型,windows使用findstr,linux使用grep system = platform.system() if system is "Windows": find_util = "findstr" else: find_util = "grep" # 判断是否设置环境变量ANDROID_HOME if "ANDROID_HOME" in os.environ: if system == "Windows": command = os.path.join( os.environ["ANDROID_HOME"], "platform-tools", "adb.exe") else: command = os.path.join( os.environ["ANDROID_HOME"], "platform-tools", "adb") else: raise EnvironmentError( "Adb not found in $ANDROID_HOME path: %s." % os.environ["ANDROID_HOME"]) class ADB(object): """ 单个设备,可不传入参数device_id """ def __init__(self, device_id=""): if device_id == "": self.device_id = "" else: self.device_id = "-s %s" % device_id def adb(self, args): cmd = "%s %s %s" % (command, self.device_id, str(args)) return subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def shell(self, args): cmd = "%s %s shell %s" % (command, self.device_id, str(args),) return subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def get_device_state(self): """ 获取设备状态: offline | bootloader | device """ return self.adb("get-state").stdout.read().strip() def get_device_id(self): """ 获取设备id号,return serialNo """ return self.adb("get-serialno").stdout.read().strip() def get_android_version(self): """ 获取设备中的Android版本号,如4.2.2 """ return self.shell( "getprop ro.build.version.release").stdout.read().strip() def get_sdk_version(self): """ 获取设备SDK版本号 """ return self.shell("getprop ro.build.version.sdk").stdout.read().strip() def get_device_model(self): """ 获取设备型号 """ return self.shell("getprop ro.product.model").stdout.read().strip() def get_pid(self, package_name): """ 获取进程pid args: - packageName -: 应用包名 usage: getPid("com.android.settings") """ if system is "Windows": pidinfo = self.shell( "ps | findstr %s$" % package_name).stdout.read() else: pidinfo = self.shell( "ps | %s -w %s" % (find_util, package_name)).stdout.read() if pidinfo == '': return "the process doesn't exist." pattern = re.compile(r"\d+") result = pidinfo.split(" ") result.remove(result[0]) return pattern.findall(" ".join(result))[0] def kill_process(self, pid): """ 杀死应用进程 args: - pid -: 进程pid值 usage: killProcess(154) 注:杀死系统应用进程需要root权限 """ if self.shell("kill %s" % str(pid)).stdout.read().split(": ")[-1] == "": return "kill success" else: return self.shell("kill %s" % str(pid)).stdout.read().split(": ")[-1] def quit_app(self, package_name): """ 退出app,类似于kill掉进程 usage: quitApp("com.android.settings") """ self.shell("am force-stop %s" % package_name) # def get_focused_package_and_activity(self): # """ # 获取当前应用界面的包名和Activity,返回的字符串格式为:packageName/activityName # """ # pattern = re.compile(r"[a-zA-Z0-9.]+/.[a-zA-Z0-9.]+") # out = self.shell( # "dumpsys window w | %s \/ | %s name=" % # (find_util, find_util)).stdout.read().strip() # # return pattern.findall(out)[0] def get_focused_package_and_activity(self): """ 获取当前应用界面的包名和Activity,返回的字符串格式为:packageName/activityName """ out = self.shell( "dumpsys activity activities | %s mFocusedActivity" % find_util).stdout.read().strip().split(' ')[3] return out def get_current_package_name(self): """ 获取当前运行的应用的包名 """ return self.get_focused_package_and_activity().split("/")[0] def get_current_activity(self): """ 获取当前运行应用的activity """ return self.get_focused_package_and_activity().split("/")[-1] def get_battery_level(self): """ 获取电池电量 """ level = self.shell("dumpsys battery | %s level" % find_util).stdout.read().split(": ")[-1] return int(level) def get_backstage_services(self, page_name): """ :return: 指定应用后台运行的services """ services_list = [] for line in self.shell( 'dumpsys activity services %s' % page_name).stdout.readlines(): if line.strip().startswith('intent'): service_name = line.strip().split('=')[-1].split('}')[0] if service_name not in services_list: services_list.append(service_name) return services_list def get_current_backstage_services(self): """ :return: 当前应用后台运行的services """ package = self.get_current_package_name() return self.get_backstage_services(package) def get_battery_status(self): """ 获取电池充电状态 BATTERY_STATUS_UNKNOWN:未知状态 BATTERY_STATUS_CHARGING: 充电状态 BATTERY_STATUS_DISCHARGING: 放电状态 BATTERY_STATUS_NOT_CHARGING:未充电 BATTERY_STATUS_FULL: 充电已满 """ status_dict = {1: "BATTERY_STATUS_UNKNOWN", 2: "BATTERY_STATUS_CHARGING", 3: "BATTERY_STATUS_DISCHARGING", 4: "BATTERY_STATUS_NOT_CHARGING", 5: "BATTERY_STATUS_FULL"} status = self.shell("dumpsys battery | %s status" % find_util).stdout.read().split(": ")[-1] return status_dict[int(status)] def get_battery_temp(self): """ 获取电池温度 """ temp = self.shell("dumpsys battery | %s temperature" % find_util).stdout.read().split(": ")[-1] return int(temp) / 10.0 def get_screen_resolution(self): """ 获取设备屏幕分辨率,return (width, high) """ pattern = re.compile(r"\d+") out = self.shell( "dumpsys display | %s PhysicalDisplayInfo" % find_util).stdout.read() display = pattern.findall(out) return int(display[0]), int(display[1]) def reboot(self): """ 重启设备 """ self.adb("reboot") def fast_boot(self): """ 进入fastboot模式 """ self.adb("reboot bootloader") def get_system_app_list(self): """ 获取设备中安装的系统应用包名列表 """ sysApp = [] for packages in self.shell("pm list packages -s").stdout.readlines(): sysApp.append(packages.split(":")[-1].splitlines()[0]) return sysApp def get_third_app_list(self): """ 获取设备中安装的第三方应用包名列表 """ thirdApp = [] for packages in self.shell("pm list packages -3").stdout.readlines(): thirdApp.append(packages.split(":")[-1].splitlines()[0]) return thirdApp def get_matching_app_list(self, keyword): """ 模糊查询与keyword匹配的应用包名列表 usage: getMatchingAppList("qq") """ matApp = [] for packages in self.shell( "pm list packages %s" % keyword).stdout.readlines(): matApp.append(packages.split(":")[-1].splitlines()[0]) return matApp def get_app_start_total_time(self, component): """ 获取启动应用所花时间 usage: getAppStartTotalTime("com.android.settings/.Settings") """ time = self.shell("am start -W %s | %s TotalTime" % (component, find_util)).stdout.read().split(": ")[-1] return int(time) def install_app(self, app_file): """ 安装app,app名字不能含中文字符 args: - appFile -: app路径 usage: install("/Users/joko/Downloads/1.apk") INSTALL_FAILED_ALREADY_EXISTS 应用已经存在,或卸载了但没卸载干净 adb install 时使用 -r 参数,或者先 adb uninstall <packagename> 再安装 INSTALL_FAILED_INVALID_APK 无效的 APK 文件 INSTALL_FAILED_INVALID_URI 无效的 APK 文件名 确保 APK 文件名里无中文 INSTALL_FAILED_INSUFFICIENT_STORAGE 空间不足 清理空间 INSTALL_FAILED_DUPLICATE_PACKAGE 已经存在同名程序 INSTALL_FAILED_NO_SHARED_USER 请求的共享用户不存在 INSTALL_FAILED_UPDATE_INCOMPATIBLE 以前安装过同名应用,但卸载时数据没有移除 先 adb uninstall <packagename> 再安装 INSTALL_FAILED_SHARED_USER_INCOMPATIBLE 请求的共享用户存在但签名不一致 INSTALL_FAILED_MISSING_SHARED_LIBRARY 安装包使用了设备上不可用的共享库 INSTALL_FAILED_REPLACE_COULDNT_DELETE 替换时无法删除 INSTALL_FAILED_DEXOPT dex 优化验证失败或空间不足 INSTALL_FAILED_OLDER_SDK 设备系统版本低于应用要求 INSTALL_FAILED_CONFLICTING_PROVIDER 设备里已经存在与应用里同名的 content provider INSTALL_FAILED_NEWER_SDK 设备系统版本高于应用要求 INSTALL_FAILED_TEST_ONLY 应用是 test-only 的,但安装时没有指定 -t 参数 INSTALL_FAILED_CPU_ABI_INCOMPATIBLE 包含不兼容设备 CPU 应用程序二进制接口的 native code INSTALL_FAILED_MISSING_FEATURE 应用使用了设备不可用的功能 INSTALL_FAILED_CONTAINER_ERROR sdcard 访问失败 确认 sdcard 可用,或者安装到内置存储 INSTALL_FAILED_INVALID_INSTALL_LOCATION 不能安装到指定位置 切换安装位置,添加或删除 -s 参数 INSTALL_FAILED_MEDIA_UNAVAILABLE 安装位置不可用 一般为 sdcard,确认 sdcard 可用或安装到内置存储 INSTALL_FAILED_VERIFICATION_TIMEOUT 验证安装包超时 INSTALL_FAILED_VERIFICATION_FAILURE 验证安装包失败 INSTALL_FAILED_PACKAGE_CHANGED 应用与调用程序期望的不一致 INSTALL_FAILED_UID_CHANGED 以前安装过该应用,与本次分配的 UID 不一致 清除以前安装过的残留文件 INSTALL_FAILED_VERSION_DOWNGRADE 已经安装了该应用更高版本 使用 -d 参数 INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE 已安装 target SDK 支持运行时权限的同名应用,要安装的版本不支持运行时权限 INSTALL_PARSE_FAILED_NOT_APK 指定路径不是文件,或不是以 .apk 结尾 INSTALL_PARSE_FAILED_BAD_MANIFEST 无法解析的 AndroidManifest.xml 文件 INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION 解析器遇到异常 INSTALL_PARSE_FAILED_NO_CERTIFICATES 安装包没有签名 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES 已安装该应用,且签名与 APK 文件不一致 先卸载设备上的该应用,再安装 INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING 解析 APK 文件时遇到 CertificateEncodingException INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME manifest 文件里没有或者使用了无效的包名 INSTALL_PARSE_FAILED_BAD_SHARED_USER_ID manifest 文件里指定了无效的共享用户 ID INSTALL_PARSE_FAILED_MANIFEST_MALFORMED 解析 manifest 文件时遇到结构性错误 INSTALL_PARSE_FAILED_MANIFEST_EMPTY 在 manifest 文件里找不到找可操作标签(instrumentation 或 application) INSTALL_FAILED_INTERNAL_ERROR 因系统问题安装失败 INSTALL_FAILED_USER_RESTRICTED 用户被限制安装应用 INSTALL_FAILED_DUPLICATE_PERMISSION 应用尝试定义一个已经存在的权限名称 INSTALL_FAILED_NO_MATCHING_ABIS 应用包含设备的应用程序二进制接口不支持的 native code INSTALL_CANCELED_BY_USER 应用安装需要在设备上确认,但未操作设备或点了取消 在设备上同意安装 INSTALL_FAILED_ACWF_INCOMPATIBLE 应用程序与设备不兼容 does not contain AndroidManifest.xml 无效的 APK 文件 is not a valid zip file 无效的 APK 文件 Offline 设备未连接成功 先将设备与 adb 连接成功 unauthorized 设备未授权允许调试 error: device not found 没有连接成功的设备 先将设备与 adb 连接成功 protocol failure 设备已断开连接 先将设备与 adb 连接成功 Unknown option: -s Android 2.2 以下不支持安装到 sdcard 不使用 -s 参数 No space left on devicerm 空间不足 清理空间 Permission denied ... sdcard ... sdcard 不可用 """ # for line in self.adb("install -r %s" % app_file).stdout.readlines(): # if 'Failure' in line: # print line.strip() return self.adb("install -r %s" % app_file) def is_install(self, packageName): """ 判断应用是否安装,已安装返回True,否则返回False usage: isInstall("com.example.apidemo") """ if self.get_matching_app_list(packageName): return True else: return False def remove_app(self, packageName): """ 卸载应用 args: - packageName -:应用包名,非apk名 """ return self.adb("uninstall %s" % packageName) def clear_app_data(self, packageName): """ 清除应用用户数据 usage: clearAppData("com.android.contacts") """ if "Success" in self.shell( "pm clear %s" % packageName).stdout.read().splitlines(): return "clear user data success " else: return "make sure package exist" def reset_current_app(self): """ 重置当前应用 """ packageName = self.get_current_package_name() component = self.get_focused_package_and_activity() self.clear_app_data(packageName) self.start_activity(component) def get_app_install_path(self, path_name): """ 获取第三方应用安装地址 :return: """ t = self.shell("pm path %s" % path_name).stdout.readlines() return ''.join(t).strip().split(':')[1] def pull_install_app(self, save_path): """ 获取当前Android设备第三方应用包,并且pull到本地 :param save_path: 存放路径 :return: """ for app_package_name in self.get_third_app_list(): install_app_path = self.get_app_install_path(app_package_name) self.pull(install_app_path, save_path + '/' + app_package_name + '.apk') def start_activity(self, component): """ 启动一个Activity usage: startActivity(component = "com.android.settinrs/.Settings") """ self.shell("am start -n %s" % component) def start_web_page(self, url): """ 使用系统默认浏览器打开一个网页 usage: startWebpage("http://www.baidu.com") """ self.shell("am start -a android.intent.action.VIEW -d %s" % url) def call_phone(self, number): """ 启动拨号器拨打电话 usage: callPhone(10086) """ self.shell( "am start -a android.intent.action.CALL -d tel:%s" % str(number)) def send_key_event(self, keycode): """ 发送一个按键事件 args: - keycode -: http://developer.android.com/reference/android/view/KeyEvent.html usage: sendKeyEvent(keycode.HOME) """ self.shell("input keyevent %s" % str(keycode)) sleep(0.5) def long_press_key(self, keycode): """ 发送一个按键长按事件,Android 4.4以上 usage: longPressKey(keycode.HOME) """ self.shell("input keyevent --longpress %s" % str(keycode)) sleep(0.5) def touch(self, e=None, x=None, y=None): """ 触摸事件 usage: touch(e), touch(x=0.5,y=0.5) """ width, high = self.get_screen_resolution() if (e is not None): x = e[0] y = e[1] if (0 < x < 1): x = x * width if (0 < y < 1): y = y * high self.shell("input tap %s %s" % (str(x), str(y))) sleep(0.5) def get_focused_package_xml(self, save_path): file_name = random.randint(10, 99) self.shell( 'uiautomator dump /data/local/tmp/{}.xml'.format(file_name)).communicate() self.adb('pull /data/local/tmp/{}.xml {}'.format(file_name, save_path)).communicate() def touch_by_element(self, element): """ 点击元素 usage: touchByElement(Element().findElementByName(u"计算器")) """ self.shell("input tap %s %s" % (str(element[0]), str(element[1]))) sleep(0.5) def touch_by_ratio(self, ratioWidth, ratioHigh): """ 通过比例发送触摸事件 args: - ratioWidth -:width占比, 0<ratioWidth<1 - ratioHigh -: high占比, 0<ratioHigh<1 usage: touchByRatio(0.5, 0.5) 点击屏幕中心位置 """ self.shell("input tap %s %s" % (str(ratioWidth * self.get_screen_resolution[0]), str(ratioHigh * self.get_screen_resolution[1]))) sleep(0.5) def swipe_by_coord(self, start_x, start_y, end_x, end_y, duration=" "): """ 滑动事件,Android 4.4以上可选duration(ms) usage: swipe(800, 500, 200, 500) """ self.shell( "input swipe %s %s %s %s %s" % (str(start_x), str(start_y), str(end_x), str(end_y), str(duration))) sleep(0.5) def swipe( self, e1=None, e2=None, start_x=None, start_y=None, end_x=None, end_y=None, duration=" "): """ 滑动事件,Android 4.4以上可选duration(ms) usage: swipe(e1, e2) swipe(e1, end_x=200, end_y=500) swipe(start_x=0.5, start_y=0.5, e2) """ width, high = self.get_screen_resolution() if (e1 is not None): start_x = e1[0] start_y = e1[1] if (e2 is not None): end_x = e2[0] end_y = e2[1] if (0 < start_x < 1): start_x = start_x * width if (0 < start_y < 1): start_y = start_y * high if (0 < end_x < 1): end_x = end_x * width if (0 < end_y < 1): end_y = end_y * high self.shell( "input swipe %s %s %s %s %s" % (str(start_x), str(start_y), str(end_x), str(end_y), str(duration))) sleep(0.5) def swipe_by_ratio( self, start_ratioWidth, start_ratioHigh, end_ratioWidth, end_ratioHigh, duration=" "): """ 通过比例发送滑动事件,Android 4.4以上可选duration(ms) usage: swipeByRatio(0.9, 0.5, 0.1, 0.5) 左滑 """ x_point, y_point = self.get_screen_resolution() self.shell("input swipe %s %s %s %s %s" % (str(start_ratioWidth * x_point), str(start_ratioHigh * y_point), str(end_ratioWidth * x_point), str(end_ratioHigh * y_point), str(duration))) sleep(0.5) def swipe_to_left(self): """ 左滑屏幕 """ self.swipe_by_ratio(0.8, 0.5, 0.2, 0.5) def swipe_to_right(self): """ 右滑屏幕 """ self.swipe_by_ratio(0.2, 0.5, 0.8, 0.5) def swipe_to_up(self): """ 上滑屏幕 """ self.swipe_by_ratio(0.5, 0.8, 0.5, 0.2) def swipe_to_down(self): """ 下滑屏幕 """ self.swipe_by_ratio(0.5, 0.2, 0.5, 0.8) def long_press(self, e=None, x=None, y=None): """ 长按屏幕的某个坐标位置, Android 4.4 usage: longPress(e) longPress(x=0.5, y=0.5) """ self.swipe( e1=e, e2=e, start_x=x, start_y=y, end_x=x, end_y=y, duration=2000) def long_press_element(self, e): """ 长按元素, Android 4.4 """ self.shell( "input swipe %s %s %s %s %s" % (str( e[0]), str( e[1]), str( e[0]), str( e[1]), str(2000))) sleep(0.5) def long_press_by_ratio(self, ratio_width, ratio_high): """ 通过比例长按屏幕某个位置, Android.4.4 usage: longPressByRatio(0.5, 0.5) 长按屏幕中心位置 """ self.swipe_by_ratio( ratio_width, ratio_high, ratio_width, ratio_high, duration=2000) def send_text(self, string): """ 发送一段文本,只能包含英文字符和空格,多个空格视为一个空格 usage: sendText("i am unique") """ text = str(string).split(" ") out = [] for i in text: if i != "": out.append(i) length = len(out) for i in xrange(length): self.shell("input text %s" % out[i]) # if i != length - 1: # self.sendKeyEvent(keycode.SPACE) sleep(0.5) def screen_shot(self, appPath): """ 获取当前设备的截图,导出到指定目录 """ self.shell("/system/bin/screencap -p /sdcard/temp.png") time.sleep(3) self.adb("pull /sdcard/temp.png %s" % appPath) def version_name(self): """ 查询当前屏幕应用版本 """ for package in self.shell( 'dumpsys package %s' % self.get_current_package_name()).stdout.readlines(): if 'versionName' in package: return package.split('=', 2)[1].strip() def specifies_app_version_name(self, package): """ 获取指定应用的versionName :param package:应用包名 :return: 包名,versionName """ for package in self.shell( 'dumpsys package %s' % package).stdout.readlines(): if 'versionName' in package: return package.split('=', 2)[1].strip() def version_code(self): """ 查询当前屏幕应用versionCode """ for package in self.shell( 'dumpsys package %s' % self.get_current_package_name()).stdout.readlines(): if 'versionCode' in package: return package.split('=', 2)[1].split(' ', 2)[0] def first_install_time(self): """ 查询当前屏幕应用安装时间 """ for package in self.shell( 'dumpsys package %s' % self.get_current_package_name()).stdout.readlines(): if 'firstInstallTime' in package: return package.split('=', 2)[1].strip() def last_update_time(self): """ 查询当前屏幕应用安装更新时间 """ for package in self.shell( 'dumpsys package %s' % self.get_current_package_name()).stdout.readlines(): if 'lastUpdateTime' in package: return package.split('=', 2)[1].strip() def wifi_name(self): """ 查询连接wifi名称 """ for package in self.shell('dumpsys wifi').stdout.readlines(): if package.startswith('mWifiInfo'): wifi_name = re.findall(r'SSID:([^"]+), BSSID', package) if not wifi_name: return None else: return wifi_name[0].strip() def get_network_state(self): """ 设备是否连上互联网 :return: """ if 'unknown' in self.shell('ping -w 1 www.baidu.com').stdout.readlines()[0]: return False else: return True def get_cpu(self, package_name): """ 获取当前cpu百分比 """ p = self.shell( 'top -n 1 -d 0.5 | %s %s' % (find_util, package_name)) while True: r = p.stdout.readline().strip().decode('utf-8') if r.endswith(package_name): lst = [cpu for cpu in r.split(' ') if cpu] return int(lst[2].split('%', 1)[0]) def __mem_pss(self, package_name): """ 获取当前应用内存 """ p = self.shell( 'top -n 1 -d 0.5 | %s %s' % (find_util, package_name)) while True: r = p.stdout.readline().strip().decode('utf-8') if r.endswith(package_name): lst = [mem for mem in r.split(' ') if mem] return int(lst[6].split('K')[0]) def __mem_mem_total(self): p = self.shell('cat proc/meminfo') while True: r = p.stdout.readline().strip().decode('utf-8') if r and 'MemTotal' in r: lst = [MemTotal for MemTotal in r.split(' ') if MemTotal] return int(lst[1]) def get_mem(self, package_name): """ 获取当前内存百分比 """ try: return int( self.__mem_pss(package_name) / float( self.__mem_mem_total()) * 100) except: return None def fill_disk(self): """ 填满手机磁盘,需root """ self.shell('dd if=/dev/zero of=/mnt/sdcard/bigfile') def del_fill_disk(self): """ 删除填满磁盘的大文件 """ self.shell('rm -r /mnt/sdcard/bigfile') def backup_apk(self, package_name, path): """ 备份应用与数据 - all 备份所有 -f 指定路径 -system|-nosystem -shared 备份sd卡 """ self.adb( 'backup -apk %s -f %s/mybackup.ab' % (package_name, path)) def restore_apk(self, path): """ 恢复应用与数据 - all 备份所有 -f 指定路径 -system|-nosystem """ self.adb('restore %s' % path) def c_logcat(self): """ :return: 清理缓存中的log """ return self.adb('logcat -c') def logcat(self, log_path): return self.adb('logcat -v time > %s&' % (log_path)) def get_cpu_version(self): """ 获取cpu基带版本 :return: arm64-v8a """ t = self.shell( "getprop ro.product.cpu.abi | tr -d '\r'").stdout.readlines() return ''.join(t).strip() def pull(self, remote_file, local_file): """ :param remote_file: 拉取文件地址 :param local_file: 存放文件地址 :return: """ return self.adb('pull %s %s' % (remote_file, local_file)) def rm(self, remote_file): """ :param remote_file: 删除文件地址 :return: """ return self.shell(remote_file) def rm_minicap_jpg(self, remote_file): """ :param remote_file: 删除minicap图片缓存 :return: """ self.rm('rm -r /data/local/tmp/%s.jpg' % (remote_file)) def get_disk(self): """ 获取手机磁盘信息 :return: Used:用户占用,Free:剩余空间 """ for s in self.shell('df').stdout.readlines(): if '/mnt/shell/emulated' in s or '/storage/sdcard0' in s: lst = [] for i in s.split(' '): if i: lst.append(i) return 'Used:%s,Free:%s' % (lst[2], lst[3]) def get_dmesg(self): """ :return:内核日志 """ t = self.shell("dmesg").stdout.readlines() return ''.join(t).strip() def get_device_name(self): """ :return: 设备名 :SM-G9006W """ t = self.shell("getprop ro.product.model").stdout.readlines() return ''.join(t).strip() def get_battery(self): """ :return:全部电量相关信息 """ t = self.shell("dumpsys battery").stdout.readlines() return ''.join(t).strip() def get_wm_density(self): """ 屏幕密度 :return:Physical density: 480 """ t = self.shell("wm density").stdout.readlines() return ''.join(t).strip() def get_window_displays(self): """ :return:显示屏参数 """ t = self.shell("dumpsys window displays").stdout.readlines() return ''.join(t).strip() def get_mac_address(self): """ :return:mac地址 """ t = self.shell("cat /sys/class/net/wlan0/address").stdout.readlines() return ''.join(t).strip() def get_cpu_info_all(self): """ :return:cpu全部信息 """ t = self.shell("cat /proc/cpuinfo").stdout.readlines() return ''.join(t).strip() def get_cpu_mem_all(self): """ :return:内存全部信息 """ t = self.shell("cat /proc/meminfo").stdout.readlines() return ''.join(t).strip() def get_sys_all(self): """ :return:设备全部信息 """ t = self.shell("cat /system/build.prop").stdout.readlines() return ''.join(t).strip() def get_ps(self): """ :return:设备全部进程信息 """ t = self.shell("ps").stdout.readlines() return ''.join(t).strip() def get_cpu_mem_info(self): """ :return:当前设备cpu与内存全部信息 """ t = self.shell("top -n 1 -d 0.5").stdout.readlines() return ''.join(t).strip() def get_phone_ime(self): """ :return:获取设备已安装的输入法包名 """ ime_list = [ime.strip() for ime in self.shell("ime list -s").stdout.readlines()] return ime_list def set_phone_ime(self, arg): """ :return: 更改手机输入法 """ self.shell("ime set %s" % arg) if __name__ == "__main__": A = ADB() print A.get_focused_package_and_activity()
[ "joko@joko.local" ]
joko@joko.local
ce9c54594a00ae100c7357c987125ca30237ad11
0b1036624fb01e6e80b60911e902d43893d5556c
/Point_sources/two_point_sources.py
bb7caef2f209958a0d165230556b389be5e1e4b1
[]
no_license
InstitutdAcoustiqueGraduateSchool/CalendrierAvant2021
f39b93a3c140463fce4c168985ed71b343a1de1a
56cafe3d02149ff752e10eb4b7171e6969cfa95a
refs/heads/main
2023-01-23T23:52:05.538082
2020-12-04T14:17:12
2020-12-04T14:17:12
318,491,805
0
0
null
null
null
null
UTF-8
Python
false
false
2,960
py
import numpy as np from numpy import sqrt, exp import matplotlib.pyplot as plt from matplotlib import animation # import myfig plt.rc('lines', linewidth=2) plt.rc('font', size=14) plt.rc('axes', linewidth=1.5, labelsize=14) plt.rc('legend', fontsize=14) class Monopole(): def __init__(self, coords, Q, phase=0): """monopole fonction Args: coords (tuple): position m Q (float): debit volumique m^3/s phase (float, optional): rad. Defaults to 0. """ self.x, self.y = coords # m self.Q = Q # m^3/s self.phase = phase # rad def func(self, freq, x, y, c, rho, t): r = sqrt((x - self.x)**2+(y - self.y)**2) k = 2*np.pi*freq/c omega = 2*np.pi*freq mono = 1j*rho*omega*self.Q / \ (4*np.pi) * exp(1j*(omega*t - k*r + self.phase))/r return mono name_gif = 'two_sources.gif' # Grid parameters N = 200 xmin, xmax = -5, 5 # m ymin, ymax = -5, 5 # m x, y = np.linspace(xmin, xmax, N), np.linspace(ymin, ymax, N) X, Y = np.meshgrid(x, y) # Phisical parameters c = 343 # m/s freq = 250 # Hz rho = 1.225 # kg/m3 d = 2.5 # distance between sources m Q = 1e-2 # debit m^3/s position_1 = (0, d/2) position_2 = (0, -d/2) # case 1 pressure_phi = np.zeros(X.shape) source_1_1 = Monopole(position_1, Q) source_2_1 = Monopole(position_2, Q) pressure_phi = source_1_1.func( freq, X, Y, c, rho, t=0) + source_2_1.func(freq, X, Y, c, rho, t=0) # case 2 pressure_outphi = np.zeros(X.shape) source_1_2 = Monopole(position_1, Q) source_2_2 = Monopole(position_2, -Q) pressure_outphi = source_1_2.func( freq, X, Y, c, rho, t=0) + source_2_2.func(freq, X, Y, c, rho, t=0) # Animation clim = (-2, 2) # color lim fig, (ax, ax2) = plt.subplots(1, 2, figsize=(10, 5)) case1 = ax.imshow(np.real(pressure_phi), vmin=clim[0], vmax=clim[1], origin='lower', aspect='equal', extent=[xmin, xmax, ymin, ymax]) case2 = ax2.imshow(np.real(pressure_outphi), vmin=clim[0], vmax=clim[1], origin='lower', aspect='equal', extent=[xmin, xmax, ymin, ymax]) ax.set_xlabel('$x~(m)$') ax2.set_xlabel('$x~(m)$') ax.set_ylabel('$y~(m)$') ax2.set_ylabel('$y~(m)$') fig.suptitle('Pression rayonnée par deux points sources') ax.set_title('1') ax2.set_title('2') # fig.tight_layout() # plt.close() def init(): case1.set_array(np.real(pressure_phi)) case2.set_array(np.real(pressure_outphi)) return (case1, case2) def animate(i): case1.set_array( np.array(np.real(pressure_phi*np.exp(1j*(i/24)*2*np.pi)))) case2.set_array( np.array(np.real(pressure_outphi*np.exp(1j*(i/24)*2*np.pi)))) return (case1, case2,) my = animation.FuncAnimation(fig, animate, init_func=init, frames=24, interval=30, blit=False, repeat=True) plt.show() # my.save(name_gif, writer='imagemagick', fps=24, dpi=150)# saving as gif, need to install imagemagick
[ "nicolas.pajusco@gmail.com" ]
nicolas.pajusco@gmail.com
038f08193105dd2adb3c942429af7abf567fd8e4
f63835e383b07bda24b9ec7ed40bd4247a332823
/client_code/Old/zzzTicketNewDetailsContent/__init__.py
3b11e292b1404767387b1486a79895bf38d9d1d5
[]
no_license
rhosyn/Customer-Support
bdf199d4ebc4c5b6506ad23ccbc28cba75df06a5
967b241cd920db43124826a5b006a22974e95111
refs/heads/master
2020-12-06T20:37:34.886170
2020-01-08T12:04:52
2020-01-08T12:04:52
232,547,246
0
0
null
null
null
null
UTF-8
Python
false
false
584
py
from ._anvil_designer import zzzTicketNewDetailsContentTemplate from anvil import * import anvil.facebook.auth import anvil.google.auth, anvil.google.drive from anvil.google.drive import app_files import anvil.users import anvil.tables as tables import anvil.tables.query as q from anvil.tables import app_tables import anvil.server class zzzTicketNewDetailsContent(zzzTicketNewDetailsContentTemplate): def __init__(self, **properties): # Set Form properties and Data Bindings. self.init_components(**properties) # Any code you write here will run when the form opens.
[ "bridget@anvil.works" ]
bridget@anvil.works
f061946cae59ba198cc5cbd450bcdb35f93ca5d8
739712a0a65460b75aa0ab4fdc73cf01cd023a0e
/functions/get_forecast_weather.py
be1cd985b7cdda8ab9fb4eb4423fb0ae3a380ecc
[]
no_license
newini/wasshi-bot
fc082d226ad181285d9ab5837588bec34c8f37d0
2883e9ec69b6ab1be0e23898286b654058ed2ea0
refs/heads/master
2023-01-11T10:40:25.464130
2023-01-03T02:10:15
2023-01-03T02:10:15
191,912,126
0
0
null
null
null
null
UTF-8
Python
false
false
2,357
py
#!/usr/bin/env python3 # coding:UTF-8 from configs.production import * # Timezone timezone = 9 JST = datetime.timezone(datetime.timedelta(hours=timezone), "JST") # Use Open Weather Map API def getForecastWeather(city_jp): if city_jp == "": shutil.copyfile("assets/images/city_not_found.jpg", "tmp/city_not_found.jpg") return ( "https://wasshi-bot.herokuapp.com/send_from_tmp?filename=city_not_found.jpg" ) translator = Translator() city_en = translator.translate(city_jp).text url = owm_forcast_url.format(city=city_en, key=OWM_KEY) response = requests.get(url) data = response.json() # If city not found in OWM if "cod" in data and data["cod"] == "404": shutil.copyfile( "assets/images/city_not_found_owm.jpg", "tmp/city_not_found_owm.jpg" ) return "https://wasshi-bot.herokuapp.com/send_from_tmp?filename=city_not_found_owm.jpg" # Time timezone = data["city"]["timezone"] # shift second cnt = 0 x = [] y = [] text = [] for forcast_list in data["list"]: # if forcast_list["weather"][0]["main"].lower() == "clear": # text.append(u'\U00002600') # elif forcast_list["weather"][0]["main"].lower() == "clouds": # text.append(u'\U00002601') # elif forcast_list["weather"][0]["main"].lower() == "rain": # text.append(u'\U0001f327') # else: # text.append(forcast_list["weather"][0]["main"]) text.append(forcast_list["weather"][0]["main"]) x.append(datetime.datetime.fromtimestamp(forcast_list["dt"] + timezone)) y.append(forcast_list["main"]["temp"]) cnt += 1 if cnt > 7 * forcast_day: break # Add city and contry into text text[0] = city_en + "<br>" + data["city"]["country"] + "<br>" + text[0] # Plot graph in tmp directory wasshi_url = "https://wasshi-bot.herokuapp.com/" page_name = "plot_graph" params = {"city": city_en, "x": x, "y": y, "text": text} plot_response = requests.get(url=wasshi_url + page_name, params=params) page_name = "send_from_tmp" image_url = ( wasshi_url + page_name + "?filename=" + city_en + ".jpeg&" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") ) return image_url
[ "eunchong.kim@cern.ch" ]
eunchong.kim@cern.ch
b9c37c09364456c17e447fe1b6fd2676b5eef8a1
7ea9786bae7a490365440be59c042f166c584577
/ElastiSearch - Tutorias/sources/connection.py
1db2f22675a0a9deaa171da27ec2690ee9818a83
[]
no_license
gutohuida/AiProjects
c1283faf04e2af1fe9749d0dd1deef6857ae55d7
93bebe632d6506b8d4c01c459e4db1c0f19f6b35
refs/heads/master
2023-06-10T00:52:54.019089
2019-11-27T20:06:32
2019-11-27T20:06:32
214,003,201
0
0
null
null
null
null
UTF-8
Python
false
false
1,520
py
# import flask dependencies from flask import Flask, request, make_response, jsonify from elasticDB import ElasticDB import json #Read config with open('./config.json') as file: config = json.load(file) #Start ElasticDB es = ElasticDB(config["connection"]) # initialize the flask app app = Flask(__name__) # default route @app.route('/') def index(): return 'Hello World!' @app.route('/scrap') def insert(): #Get json from the body req = request.get_json(force=True) #Get variables, the information needed, from json path = req['path'] subject = req['subject'] index = req['index'] extract_type = req['extract_type'] #Scrap the documments into Elastic es.scrap(path,subject,index,extract_type) return 'ok' @app.route('/searchQuery') def searchQuery(): #Get json from the body req = request.get_json(force=True) #Get variables, the information needed, from json index = req['index'] query = req['query'] #Search in the index res = es.search_query(index,query) return jsonify(res['hits']['hits']) @app.route('/search') def search(): #Get json from the body req = request.get_json(force=True) #Get variables, the information needed, from json indexes = req['indexes'] key_words = req['keywords'] arqnames = req['arqnames'] #Search in the index res = es.search(arqnames,indexes,key_words) return jsonify(res['hits']['hits']) # run the app if __name__ == '__main__': app.run(debug=True)
[ "GUSTAVO.SAN@uninter.com" ]
GUSTAVO.SAN@uninter.com
78505e3632d0a004438b00fe97edb270d6d3e5c9
ca49fa7d54ea538751cc3338c4066d1cb9781322
/FP_350_image3_wealthgap.py
141bf76f30d0f474f56b8caa0e709f6b2e6ff8ec
[]
no_license
jtrax22/final_project_350
fc1d669e05b1558079b35747d6031faa3cc18384
86e0185aab67c15c53d1997ceae8c8ae7f66cea8
refs/heads/main
2023-04-05T20:40:24.521676
2021-05-05T22:33:48
2021-05-05T22:33:48
361,915,467
0
0
null
null
null
null
UTF-8
Python
false
false
1,713
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 26 21:25:24 2021 @author: jamestraxler """ from bs4 import BeautifulSoup as bs import requests import matplotlib.pyplot as plt import pandas as pd #from matplotlib import style #import statsmodels.api as sm import numpy as np #from matplotlib import style #from scipy import stats #from sklearn.metrics import r2_score #import json #from pandas.io.json import json_normalize #import matplotlib.pyplot as plt #import math from matplotlib.pyplot import figure url = 'https://en.wikipedia.org/wiki/Wealth_inequality_in_the_United_States' res = requests.get(url) soup = bs(res.text, "html.parser") wiki = pd.read_html(requests.get(url).text) wealth = wiki[1] hnw = wealth['Household Net Worth'].to_list() top1 = wealth['Top 1%'].to_list() names = wealth q4 = wealth.iloc[0] q4 = [(p) for p in q4] q4 = q4[1:][:-1] #Quarter 4 integer_map = map(float, q4) q4 = list(map(float, q4)) q2 = wealth.iloc[1] q2 = [(p) for p in q2] q2 = q2[1:][:-1] #Quarter 2 integer_map = map(float, q2) q2 = list(map(float, q2)) names = [(col) for col in names.columns] names = names[1:][:-1] #print(names[0]) #graph figure(num=None, figsize=(16, 6)) font = {'family' : 'Times New Roman', 'weight' : 'bold', 'size' : 15} plt.rc('font', **font) plt.subplot(1, 2, 1) plt.bar(names,q4, color='navy') plt.yticks(np.arange(0, 50, 5)) plt.xlabel('2016 Wealth status') plt.ylabel('($ Trillions)') plt.title("Household Networth") plt.subplot(1, 2, 2) plt.bar(names,q2, color = 'navy') plt.yticks(np.arange(0, 50, 5)) plt.xlabel('2020 Wealth status') plt.ylabel('($ Trillions)') plt.title("Household Networth") plt.show()
[ "noreply@github.com" ]
noreply@github.com
29637ca1f514b6d45d39390e8c368590681c9c78
c3d97602991058def90746b90fa0e50e5215bc7f
/src/data/samplers.py
ca892fe776a88e73d6759dbe32ebd3e28c6779c4
[]
no_license
thanhtungbs00/ReID
0ac75609fefe404ea76032f4267aa0862807ed31
f0750e96eeba998146c77e6ddda1bf0d07cd683c
refs/heads/master
2021-05-24T09:52:17.738976
2020-04-05T00:14:04
2020-04-05T00:14:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,221
py
import torch import torchvision import random from src.data.datasets import ImageDataset class RandomBalanceBatchSampler(torch.utils.data.Sampler): def __init__(self, datasource: ImageDataset, classes_count=1, samples_per_class_count=1, iters_count=1): self.datasource = datasource self.classes_count = classes_count if self.classes_count > self.datasource.classes_count(): raise IndexError( "There are only " + str(self.datasource.classes_count()) + " classes in the dataset, cannot get " + str(self.classes_count) + " classes") self.samples_per_class_count = samples_per_class_count self.iters_count = iters_count def __len__(self): return self.iters_count def __iter__(self): for _ in range(self.iters_count): class_idxs = self.datasource.get_random_class_idxs( self.classes_count) batch = [] for classid in class_idxs: for _ in range(self.samples_per_class_count): idx = random.randint( 0, self.datasource.samples_count(classid)-1) batch.append((classid, idx)) yield batch
[ "hoangvan10it@gmail.com" ]
hoangvan10it@gmail.com
dcb59987c7a46a585c8c0bd5a323f824c579fb2d
9ed3294af5edc900f2acf248f67ca73327844e67
/TwoPointer.py/sortByColors.py
a265b3d1b130455d15bf162cc3aa560a1e875c2a
[]
no_license
sandeepkumar09/InterviewBit
f173531cee03cce7c9249c0e5b24999120179c4a
079705554659480ea7b3abbb96b6cfb606d4dff9
refs/heads/master
2020-04-11T06:18:53.542839
2018-12-13T03:29:28
2018-12-13T03:29:28
150,111,071
0
0
null
null
null
null
UTF-8
Python
false
false
427
py
class Solution: # @param A : list of integers # @return A after the sort def sortColors(self, A): for i in range(len(A)): if A[i] == 0 and i != 0: A[i:i+1] = [] A.insert(0, 0) elif A[i] == 2 and i != len(A)-1: A[i:i+1] = [] A.append(2) else: pass return A sol = Solution() a = [0,1,2] a[0:1] = [] a.insert(0,0) print(a) print(sol.sortColors([1,0,2,1]))
[ "sandeep.090896@gmail.com" ]
sandeep.090896@gmail.com
f2f183e30e51a8a92dd3ac4df1a0dfd0ad292f0d
351f39a29e38467f8137e9c90114293236ff4af9
/venv/Scripts/easy_install-3.6-script.py
49a23509e17f1497eb43e0fd530920d3b8e24411
[]
no_license
MasonWhite000/AlienInvasion
e6dc3a810b520d4347aacf0159ae9f05bdae5e3a
76a01d4e3f15abea6466752f8395ca6db1179c77
refs/heads/master
2020-03-16T22:23:54.694508
2018-05-29T12:44:09
2018-05-29T12:44:09
133,037,619
0
0
null
null
null
null
UTF-8
Python
false
false
467
py
#!C:\Users\mcwhit02\PycharmProjects\AlienInvasion\venv\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==28.8.0','console_scripts','easy_install-3.6' __requires__ = 'setuptools==28.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==28.8.0', 'console_scripts', 'easy_install-3.6')() )
[ "mason.white@stu.jefferson.kyschools.us" ]
mason.white@stu.jefferson.kyschools.us
9e9a78685cf9219df7db2543b3cb31fc4e86d42d
4524c4940d7fa830c23e4dc8e1144d5eec74365b
/ex15.py
75842d887ad14a1f8b08026f86360c2596f8855c
[]
no_license
AmyShackles/LearnPython3TheHardWay
ef493209a181f62bfa45ff3ec456ae0fd2c3e8a9
4e175d58dfe8c7295ebfbee3947e944b35e52f8c
refs/heads/master
2020-03-23T03:49:53.052976
2018-07-27T21:14:30
2018-07-27T21:14:30
141,051,327
0
0
null
null
null
null
UTF-8
Python
false
false
742
py
from sys import argv # assigns arg[0] to the variable script and argv[1] to the variable filename script, filename = argv # assigns the function for opening the file to the variable txt txt = open(filename) # prints the string 'Here is your {value of variable filename}' print(f"Here's your file {filename}:") # prints the output of invoking read on open(filename) print(txt.read()) # prints the string 'Type the filename again:' print("Type the filename again:") # asks the user for input (the filename) file_again = input("> ") # takes the user input and calls the function open on it and assigns it to the variable txt_again txt_again = open(file_again) # prints the output of invoking read on open(file_again) print(txt_again.read())
[ "amyshackles@gmail.com" ]
amyshackles@gmail.com
dd426cece91ace7c75c2382cf46a7a7d67142c58
8de6a35a7b5a227346f6434cde00903f3f711aa6
/tests/datasource/data_connector/test_inferred_asset_s3_data_connector.py
7085406d78e9db3d415b11de8f0680c4a33acb25
[ "Apache-2.0" ]
permissive
sfrancavilla/great_expectations
f893225a5a5fef127e2ad8c2255e70fc4ef5d8cb
e7c981589196ca4650bb4177c9a0a3d4570cf79c
refs/heads/develop
2023-03-26T19:22:29.727114
2021-03-15T16:50:59
2021-03-15T16:50:59
348,127,049
0
0
Apache-2.0
2021-03-15T21:25:24
2021-03-15T21:25:22
null
UTF-8
Python
false
false
33,328
py
from contextlib import ExitStack as does_not_raise from typing import List import boto3 import pandas as pd import pytest from moto import mock_s3 from ruamel.yaml import YAML import great_expectations.exceptions.exceptions as ge_exceptions from great_expectations.core.batch import ( BatchDefinition, BatchRequest, PartitionDefinition, ) from great_expectations.data_context.util import instantiate_class_from_config from great_expectations.datasource.data_connector import InferredAssetS3DataConnector from great_expectations.datasource.data_connector.inferred_asset_s3_data_connector import ( INVALID_S3_CHARS, _check_valid_s3_path, ) yaml = YAML() @mock_s3 def test_basic_instantiation(): region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "path/A-100.csv", "path/A-101.csv", "directory/B-1.csv", "directory/B-2.csv", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) my_data_connector: InferredAssetS3DataConnector = InferredAssetS3DataConnector( name="my_data_connector", datasource_name="FAKE_DATASOURCE_NAME", default_regex={ "pattern": r"(.+)/(.+)-(\d+)\.csv", "group_names": ["data_asset_name", "letter", "number"], }, bucket=bucket, prefix="", ) # noinspection PyProtectedMember my_data_connector._refresh_data_references_cache() assert my_data_connector.get_data_reference_list_count() == 4 assert my_data_connector.get_unmatched_data_references() == [] # Illegal execution environment name with pytest.raises(ValueError): print( my_data_connector.get_batch_definition_list_from_batch_request( batch_request=BatchRequest( datasource_name="something", data_connector_name="my_data_connector", data_asset_name="something", ) ) ) @mock_s3 def test_simple_regex_example_with_implicit_data_asset_names_self_check(): region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "A-100.csv", "A-101.csv", "B-1.csv", "B-2.csv", "CCC.csv", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) my_data_connector: InferredAssetS3DataConnector = InferredAssetS3DataConnector( name="my_data_connector", datasource_name="FAKE_DATASOURCE_NAME", default_regex={ "pattern": r"(.+)-(\d+)\.csv", "group_names": [ "data_asset_name", "number", ], }, bucket=bucket, prefix="", ) # noinspection PyProtectedMember my_data_connector._refresh_data_references_cache() self_check_report_object = my_data_connector.self_check() assert self_check_report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 2, "example_data_asset_names": ["A", "B"], "data_assets": { "A": { "example_data_references": ["A-100.csv", "A-101.csv"], "batch_definition_count": 2, }, "B": { "example_data_references": ["B-1.csv", "B-2.csv"], "batch_definition_count": 2, }, }, "example_unmatched_data_references": ["CCC.csv"], "unmatched_data_reference_count": 1, "example_data_reference": {}, } @mock_s3 def test_complex_regex_example_with_implicit_data_asset_names(): region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "2020/01/alpha-1001.csv", "2020/01/beta-1002.csv", "2020/02/alpha-1003.csv", "2020/02/beta-1004.csv", "2020/03/alpha-1005.csv", "2020/03/beta-1006.csv", "2020/04/beta-1007.csv", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) my_data_connector: InferredAssetS3DataConnector = InferredAssetS3DataConnector( name="my_data_connector", datasource_name="FAKE_DATASOURCE_NAME", default_regex={ "pattern": r"(\d{4})/(\d{2})/(.+)-\d+\.csv", "group_names": ["year_dir", "month_dir", "data_asset_name"], }, bucket=bucket, prefix="", ) # noinspection PyProtectedMember my_data_connector._refresh_data_references_cache() # Test for an unknown execution environment with pytest.raises(ValueError): # noinspection PyUnusedLocal batch_definition_list: List[ BatchDefinition ] = my_data_connector.get_batch_definition_list_from_batch_request( batch_request=BatchRequest( datasource_name="non_existent_datasource", data_connector_name="my_data_connector", data_asset_name="my_data_asset", ) ) # Test for an unknown data_connector with pytest.raises(ValueError): # noinspection PyUnusedLocal batch_definition_list: List[ BatchDefinition ] = my_data_connector.get_batch_definition_list_from_batch_request( batch_request=BatchRequest( datasource_name="FAKE_DATASOURCE_NAME", data_connector_name="non_existent_data_connector", data_asset_name="my_data_asset", ) ) assert ( len( my_data_connector.get_batch_definition_list_from_batch_request( batch_request=BatchRequest( datasource_name="FAKE_DATASOURCE_NAME", data_connector_name="my_data_connector", data_asset_name="alpha", ) ) ) == 3 ) assert ( len( my_data_connector.get_batch_definition_list_from_batch_request( batch_request=BatchRequest( datasource_name="FAKE_DATASOURCE_NAME", data_connector_name="my_data_connector", data_asset_name="beta", ) ) ) == 4 ) assert my_data_connector.get_batch_definition_list_from_batch_request( batch_request=BatchRequest( datasource_name="FAKE_DATASOURCE_NAME", data_connector_name="my_data_connector", data_asset_name="alpha", partition_request={ "batch_identifiers": { "year_dir": "2020", "month_dir": "03", } }, ) ) == [ BatchDefinition( datasource_name="FAKE_DATASOURCE_NAME", data_connector_name="my_data_connector", data_asset_name="alpha", partition_definition=PartitionDefinition( year_dir="2020", month_dir="03", ), ) ] @mock_s3 def test_self_check(): region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "A-100.csv", "A-101.csv", "B-1.csv", "B-2.csv", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) my_data_connector: InferredAssetS3DataConnector = InferredAssetS3DataConnector( name="my_data_connector", datasource_name="FAKE_DATASOURCE_NAME", default_regex={ "pattern": r"(.+)-(\d+)\.csv", "group_names": ["data_asset_name", "number"], }, bucket=bucket, prefix="", ) # noinspection PyProtectedMember my_data_connector._refresh_data_references_cache() self_check_report_object = my_data_connector.self_check() assert self_check_report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 2, "example_data_asset_names": ["A", "B"], "data_assets": { "A": { "example_data_references": ["A-100.csv", "A-101.csv"], "batch_definition_count": 2, }, "B": { "example_data_references": ["B-1.csv", "B-2.csv"], "batch_definition_count": 2, }, }, "example_unmatched_data_references": [], "unmatched_data_reference_count": 0, "example_data_reference": {}, } @mock_s3 def test_test_yaml_config(empty_data_context): context = empty_data_context region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "2020/01/alpha-1001.csv", "2020/01/beta-1002.csv", "2020/02/alpha-1003.csv", "2020/02/beta-1004.csv", "2020/03/alpha-1005.csv", "2020/03/beta-1006.csv", "2020/04/beta-1007.csv", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) report_object = context.test_yaml_config( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: FAKE_DATASOURCE name: TEST_DATA_CONNECTOR bucket: {bucket} prefix: "" default_regex: pattern: (\\d{{4}})/(\\d{{2}})/(.*)-.*\\.csv group_names: - year_dir - month_dir - data_asset_name """, return_mode="report_object", ) assert report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 2, "example_data_asset_names": ["alpha", "beta"], "data_assets": { "alpha": { "example_data_references": [ "2020/01/alpha-*.csv", "2020/02/alpha-*.csv", "2020/03/alpha-*.csv", ], "batch_definition_count": 3, }, "beta": { "example_data_references": [ "2020/01/beta-*.csv", "2020/02/beta-*.csv", "2020/03/beta-*.csv", ], "batch_definition_count": 4, }, }, "example_unmatched_data_references": [], "unmatched_data_reference_count": 0, "example_data_reference": {}, } @mock_s3 def test_yaml_config_excluding_non_regex_matching_files(empty_data_context): context = empty_data_context region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "2020/01/alpha-1001.csv", "2020/01/beta-1002.csv", "2020/02/alpha-1003.csv", "2020/02/beta-1004.csv", "2020/03/alpha-1005.csv", "2020/03/beta-1006.csv", "2020/04/beta-1007.csv", "gamma-202001.csv", "gamma-202002.csv", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) report_object = context.test_yaml_config( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: FAKE_DATASOURCE name: TEST_DATA_CONNECTOR bucket: {bucket} prefix: "" default_regex: pattern: (\\d{{4}})/(\\d{{2}})/(.*)-.*\\.csv group_names: - year_dir - month_dir - data_asset_name """, return_mode="report_object", ) assert report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 2, "example_data_asset_names": ["alpha", "beta"], "data_assets": { "alpha": { "example_data_references": [ "2020/01/alpha-*.csv", "2020/02/alpha-*.csv", "2020/03/alpha-*.csv", ], "batch_definition_count": 3, }, "beta": { "example_data_references": [ "2020/01/beta-*.csv", "2020/02/beta-*.csv", "2020/03/beta-*.csv", ], "batch_definition_count": 4, }, }, "example_unmatched_data_references": ["gamma-202001.csv", "gamma-202002.csv"], "unmatched_data_reference_count": 2, "example_data_reference": {}, } @mock_s3 def test_nested_directory_data_asset_name_in_folder(empty_data_context): context = empty_data_context region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "A/A-1.csv", "A/A-2.csv", "A/A-3.csv", "B/B-1.csv", "B/B-2.csv", "B/B-3.csv", "C/C-1.csv", "C/C-2.csv", "C/C-3.csv", "D/D-1.csv", "D/D-2.csv", "D/D-3.csv", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) report_object = context.test_yaml_config( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: FAKE_DATASOURCE name: TEST_DATA_CONNECTOR bucket: {bucket} prefix: "" default_regex: group_names: - data_asset_name - letter - number pattern: (\\w{{1}})\\/(\\w{{1}})-(\\d{{1}})\\.csv """, return_mode="report_object", ) assert report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 4, "example_data_asset_names": ["A", "B", "C"], "data_assets": { "A": { "batch_definition_count": 3, "example_data_references": ["A/A-1.csv", "A/A-2.csv", "A/A-3.csv"], }, "B": { "batch_definition_count": 3, "example_data_references": ["B/B-1.csv", "B/B-2.csv", "B/B-3.csv"], }, "C": { "batch_definition_count": 3, "example_data_references": ["C/C-1.csv", "C/C-2.csv", "C/C-3.csv"], }, }, "unmatched_data_reference_count": 0, "example_unmatched_data_references": [], "example_data_reference": {}, } @mock_s3 def test_redundant_information_in_naming_convention_random_hash(empty_data_context): context = empty_data_context region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "2021/01/01/log_file-2f1e94b40f310274b485e72050daf591.txt.gz", "2021/01/02/log_file-7f5d35d4f90bce5bf1fad680daac48a2.txt.gz", "2021/01/03/log_file-99d5ed1123f877c714bbe9a2cfdffc4b.txt.gz", "2021/01/04/log_file-885d40a5661bbbea053b2405face042f.txt.gz", "2021/01/05/log_file-d8e478f817b608729cfc8fb750ebfc84.txt.gz", "2021/01/06/log_file-b1ca8d1079c00fd4e210f7ef31549162.txt.gz", "2021/01/07/log_file-d34b4818c52e74b7827504920af19a5c.txt.gz", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) report_object = context.test_yaml_config( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: FAKE_DATASOURCE name: TEST_DATA_CONNECTOR bucket: {bucket} prefix: "" default_regex: group_names: - year - month - day - data_asset_name pattern: (\\d{{4}})/(\\d{{2}})/(\\d{{2}})/(log_file)-.*\\.txt\\.gz """, return_mode="report_object", ) assert report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 1, "example_data_asset_names": ["log_file"], "data_assets": { "log_file": { "batch_definition_count": 7, "example_data_references": [ "2021/01/01/log_file-*.txt.gz", "2021/01/02/log_file-*.txt.gz", "2021/01/03/log_file-*.txt.gz", ], } }, "unmatched_data_reference_count": 0, "example_unmatched_data_references": [], "example_data_reference": {}, } @mock_s3 def test_redundant_information_in_naming_convention_timestamp(empty_data_context): context = empty_data_context region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "log_file-2021-01-01-035419.163324.txt.gz", "log_file-2021-01-02-035513.905752.txt.gz", "log_file-2021-01-03-035455.848839.txt.gz", "log_file-2021-01-04-035251.47582.txt.gz", "log_file-2021-01-05-033034.289789.txt.gz", "log_file-2021-01-06-034958.505688.txt.gz", "log_file-2021-01-07-033545.600898.txt.gz", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) report_object = context.test_yaml_config( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: FAKE_DATASOURCE name: TEST_DATA_CONNECTOR bucket: {bucket} prefix: "" default_regex: group_names: - data_asset_name - year - month - day pattern: (log_file)-(\\d{{4}})-(\\d{{2}})-(\\d{{2}})-.*\\.*\\.txt\\.gz """, return_mode="report_object", ) assert report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 1, "example_data_asset_names": ["log_file"], "data_assets": { "log_file": { "batch_definition_count": 7, "example_data_references": [ "log_file-2021-01-01-*.txt.gz", "log_file-2021-01-02-*.txt.gz", "log_file-2021-01-03-*.txt.gz", ], } }, "unmatched_data_reference_count": 0, "example_unmatched_data_references": [], "example_data_reference": {}, } @mock_s3 def test_redundant_information_in_naming_convention_bucket(empty_data_context): context = empty_data_context region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "some_bucket/2021/01/01/log_file-20210101.txt.gz", "some_bucket/2021/01/02/log_file-20210102.txt.gz", "some_bucket/2021/01/03/log_file-20210103.txt.gz", "some_bucket/2021/01/04/log_file-20210104.txt.gz", "some_bucket/2021/01/05/log_file-20210105.txt.gz", "some_bucket/2021/01/06/log_file-20210106.txt.gz", "some_bucket/2021/01/07/log_file-20210107.txt.gz", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) report_object = context.test_yaml_config( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: FAKE_DATASOURCE name: TEST_DATA_CONNECTOR bucket: {bucket} prefix: "" default_regex: group_names: - data_asset_name - year - month - day pattern: (\\w{{11}})/(\\d{{4}})/(\\d{{2}})/(\\d{{2}})/log_file-.*\\.txt\\.gz """, return_mode="report_object", ) assert report_object == { "class_name": "InferredAssetS3DataConnector", "data_asset_count": 1, "example_data_asset_names": ["some_bucket"], "data_assets": { "some_bucket": { "batch_definition_count": 7, "example_data_references": [ "some_bucket/2021/01/01/log_file-*.txt.gz", "some_bucket/2021/01/02/log_file-*.txt.gz", "some_bucket/2021/01/03/log_file-*.txt.gz", ], } }, "unmatched_data_reference_count": 0, "example_unmatched_data_references": [], "example_data_reference": {}, } @mock_s3 def test_redundant_information_in_naming_convention_bucket_sorted(): region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "some_bucket/2021/01/01/log_file-20210101.txt.gz", "some_bucket/2021/01/02/log_file-20210102.txt.gz", "some_bucket/2021/01/03/log_file-20210103.txt.gz", "some_bucket/2021/01/04/log_file-20210104.txt.gz", "some_bucket/2021/01/05/log_file-20210105.txt.gz", "some_bucket/2021/01/06/log_file-20210106.txt.gz", "some_bucket/2021/01/07/log_file-20210107.txt.gz", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) my_data_connector_yaml = yaml.load( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: test_environment name: my_inferred_asset_filesystem_data_connector bucket: {bucket} prefix: "" default_regex: group_names: - data_asset_name - year - month - day - full_date pattern: (\\w{{11}})/(\\d{{4}})/(\\d{{2}})/(\\d{{2}})/log_file-(.*)\\.txt\\.gz sorters: - orderby: desc class_name: DateTimeSorter name: full_date """, ) my_data_connector: InferredAssetS3DataConnector = instantiate_class_from_config( config=my_data_connector_yaml, runtime_environment={ "name": "my_inferred_asset_filesystem_data_connector", "datasource_name": "test_environment", "execution_engine": "BASE_ENGINE", }, config_defaults={"module_name": "great_expectations.datasource.data_connector"}, ) sorted_batch_definition_list = ( my_data_connector.get_batch_definition_list_from_batch_request( BatchRequest( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", ) ) ) expected = [ BatchDefinition( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", partition_definition=PartitionDefinition( {"year": "2021", "month": "01", "day": "07", "full_date": "20210107"} ), ), BatchDefinition( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", partition_definition=PartitionDefinition( {"year": "2021", "month": "01", "day": "06", "full_date": "20210106"} ), ), BatchDefinition( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", partition_definition=PartitionDefinition( {"year": "2021", "month": "01", "day": "05", "full_date": "20210105"} ), ), BatchDefinition( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", partition_definition=PartitionDefinition( {"year": "2021", "month": "01", "day": "04", "full_date": "20210104"} ), ), BatchDefinition( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", partition_definition=PartitionDefinition( {"year": "2021", "month": "01", "day": "03", "full_date": "20210103"} ), ), BatchDefinition( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", partition_definition=PartitionDefinition( {"year": "2021", "month": "01", "day": "02", "full_date": "20210102"} ), ), BatchDefinition( datasource_name="test_environment", data_connector_name="my_inferred_asset_filesystem_data_connector", data_asset_name="some_bucket", partition_definition=PartitionDefinition( {"year": "2021", "month": "01", "day": "01", "full_date": "20210101"} ), ), ] assert expected == sorted_batch_definition_list @mock_s3 def test_redundant_information_in_naming_convention_bucket_sorter_does_not_match_group(): region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "some_bucket/2021/01/01/log_file-20210101.txt.gz", "some_bucket/2021/01/02/log_file-20210102.txt.gz", "some_bucket/2021/01/03/log_file-20210103.txt.gz", "some_bucket/2021/01/04/log_file-20210104.txt.gz", "some_bucket/2021/01/05/log_file-20210105.txt.gz", "some_bucket/2021/01/06/log_file-20210106.txt.gz", "some_bucket/2021/01/07/log_file-20210107.txt.gz", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) my_data_connector_yaml = yaml.load( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: test_environment name: my_inferred_asset_filesystem_data_connector bucket: {bucket} prefix: "" default_regex: group_names: - data_asset_name - year - month - day - full_date pattern: (\\w{{11}})/(\\d{{4}})/(\\d{{2}})/(\\d{{2}})/log_file-(.*)\\.txt\\.gz sorters: - orderby: desc class_name: DateTimeSorter name: not_matching_anything """, ) with pytest.raises(ge_exceptions.DataConnectorError): # noinspection PyUnusedLocal my_data_connector: InferredAssetS3DataConnector = instantiate_class_from_config( config=my_data_connector_yaml, runtime_environment={ "name": "my_inferred_asset_filesystem_data_connector", "datasource_name": "test_environment", "execution_engine": "BASE_ENGINE", }, config_defaults={ "module_name": "great_expectations.datasource.data_connector" }, ) @mock_s3 def test_redundant_information_in_naming_convention_bucket_too_many_sorters(): region_name: str = "us-east-1" bucket: str = "test_bucket" conn = boto3.resource("s3", region_name=region_name) conn.create_bucket(Bucket=bucket) client = boto3.client("s3", region_name=region_name) test_df: pd.DataFrame = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]}) keys: List[str] = [ "some_bucket/2021/01/01/log_file-20210101.txt.gz", "some_bucket/2021/01/02/log_file-20210102.txt.gz", "some_bucket/2021/01/03/log_file-20210103.txt.gz", "some_bucket/2021/01/04/log_file-20210104.txt.gz", "some_bucket/2021/01/05/log_file-20210105.txt.gz", "some_bucket/2021/01/06/log_file-20210106.txt.gz", "some_bucket/2021/01/07/log_file-20210107.txt.gz", ] for key in keys: client.put_object( Bucket=bucket, Body=test_df.to_csv(index=False).encode("utf-8"), Key=key ) my_data_connector_yaml = yaml.load( f""" module_name: great_expectations.datasource.data_connector class_name: InferredAssetS3DataConnector datasource_name: test_environment name: my_inferred_asset_filesystem_data_connector bucket: {bucket} prefix: "" default_regex: group_names: - data_asset_name - year - month - day - full_date pattern: (\\w{{11}})/(\\d{{4}})/(\\d{{2}})/(\\d{{2}})/log_file-(.*)\\.txt\\.gz sorters: - datetime_format: "%Y%m%d" orderby: desc class_name: DateTimeSorter name: timestamp - orderby: desc class_name: NumericSorter name: price """, ) with pytest.raises(ge_exceptions.DataConnectorError): # noinspection PyUnusedLocal my_data_connector: InferredAssetS3DataConnector = instantiate_class_from_config( config=my_data_connector_yaml, runtime_environment={ "name": "my_inferred_asset_filesystem_data_connector", "datasource_name": "test_environment", "execution_engine": "BASE_ENGINE", }, config_defaults={ "module_name": "great_expectations.datasource.data_connector" }, ) @pytest.mark.parametrize( "path,expectation", [("BUCKET/DIR/FILE.CSV", does_not_raise())] + [ (f"BUCKET/DIR/FILE{c}CSV", pytest.raises(ge_exceptions.ParserError)) for c in INVALID_S3_CHARS ], ) def test_bad_s3_regex_paths(path, expectation): with expectation: _check_valid_s3_path(path)
[ "noreply@github.com" ]
noreply@github.com
53c4d3223a86bdc4142d905742aa6d03c028bc0f
c968cbf08286394842d31fc9e8f6fe9d4e906d54
/pillo_demo.py
38f6ab4c109af56b1b5c128cc7be6e820b72a39c
[]
no_license
mchowdappa/python
0c605cb114599bad7402ab23bf259942c58f1926
8287dd3215f57624d6d08f4becf5711e6e3e411e
refs/heads/master
2021-08-23T19:34:13.003179
2017-12-06T07:34:05
2017-12-06T07:34:05
109,224,648
0
0
null
null
null
null
UTF-8
Python
false
false
47
py
import Image img = Image.open("") img.show()
[ "chowdappa_m@intuit.com" ]
chowdappa_m@intuit.com
0f70dba87c98286e35f2d03c257f406ec7147bce
89e60cc6c7ba38ef598941f2f9dbe85f81a32ee4
/todo/forms.py
3fc1a874d01663fe5ca1c4f4f34cc0478ea64313
[]
no_license
cokoyoh/comprehensive-todo
e701d3f22ff7655ac820e7c41f9de4408662abc8
08961b0dc683900d5a9498678868c373948411e7
refs/heads/master
2020-05-30T11:45:33.795912
2019-06-13T06:32:33
2019-06-13T06:32:33
189,712,263
0
0
null
null
null
null
UTF-8
Python
false
false
155
py
from django import forms from .models import Todo class TodoForm(forms.ModelForm): class Meta: model = Todo fields = ['task', 'date']
[ "charlesokoyoh@gmail.com" ]
charlesokoyoh@gmail.com
5c238ce0b9a909fcf22c755aac733637ade43929
3b451e8de359659a1648b95f86372549f29a193c
/searchlight_bound_match_GSBS_no_srm.py
0dbcd948da1c7882fb59eb9a23e82bbf9507ba97
[]
no_license
jamalw/music_event_structures_bucket
33dc0c5ffba46ab5a978a04268f88103148d2476
8ad5e9b2d767a3771cc618c061fbcb22f942cd51
refs/heads/master
2022-08-22T00:20:45.859935
2022-08-15T14:48:22
2022-08-15T14:48:22
126,224,420
0
0
null
null
null
null
UTF-8
Python
false
false
9,403
py
import numpy as np from scipy.stats import norm,zscore,pearsonr,stats from nilearn.image import load_img import sys from brainiak.funcalign.srm import SRM import nibabel as nib import os from scipy.spatial import distance from sklearn import linear_model from srm import SRM_V1, SRM_V2, SRM_V3 from statesegmentation import GSBS song_idx = int(sys.argv[1]) runNum = int(sys.argv[2]) subjs = ['MES_022817_0','MES_030217_0','MES_032117_1','MES_040217_0','MES_041117_0','MES_041217_0','MES_041317_0','MES_041417_0','MES_041517_0','MES_042017_0','MES_042317_0','MES_042717_0','MES_050317_0','MES_051317_0','MES_051917_0','MES_052017_0','MES_052017_1','MES_052317_0','MES_052517_0','MES_052617_0','MES_052817_0','MES_052817_1','MES_053117_0','MES_060117_0','MES_060117_1'] if runNum == 0: # run 1 times song_bounds = np.array([0,225,314,494,628,718,898,1032,1122,1301,1436,1660,1749,1973, 2198,2377,2511]) songs = ['Finlandia', 'Blue_Monk', 'I_Love_Music','Waltz_of_Flowers','Capriccio_Espagnole','Island','All_Blues','St_Pauls_Suite','Moonlight_Sonata','Symphony_Fantastique','Allegro_Moderato','Change_of_the_Guard','Boogie_Stop_Shuffle','My_Favorite_Things','The_Bird','Early_Summer'] elif runNum == 1: # run 2 times song_bounds = np.array([0,90,270,449,538,672,851,1031,1255,1480,1614,1704,1839,2063,2288,2377,2511]) songs = ['St_Pauls_Suite', 'I_Love_Music', 'Moonlight_Sonata', 'Change_of_the_Guard','Waltz_of_Flowers','The_Bird', 'Island', 'Allegro_Moderato', 'Finlandia', 'Early_Summer', 'Capriccio_Espagnole', 'Symphony_Fantastique', 'Boogie_Stop_Shuffle', 'My_Favorite_Things', 'Blue_Monk','All_Blues'] srm_k = 30 hrf = 5 datadir = '/jukebox/norman/jamalw/MES/' mask_img = load_img(datadir + 'data/mask_nonan.nii') mask = mask_img.get_data() mask_reshape = np.reshape(mask,(91*109*91)) human_bounds = np.load(datadir + 'prototype/link/scripts/data/searchlight_output/HMM_searchlight_K_sweep_srm/' + songs[song_idx] + '/' + songs[song_idx] + '_beh_seg.npy') + hrf def searchlight(coords,human_bounds,mask,subjs,song_idx,song_bounds,srm_k,hrf): """run searchlight Create searchlight object and perform voxel function at each searchlight location Parameters ---------- data1 : voxel by time ndarray (2D); leftout subject run 1 data2 : voxel by time ndarray (2D); average of others run 1 data3 : voxel by time ndarray (2D); leftout subject run 2 data4 : voxel by time ndarray (2D); average of others run 2 coords : voxel by xyz ndarray (2D, Vx3) K : # of events for GSBS (scalar) Returns ------- 3D data: brain (or ROI) filled with searchlight function scores (3D) """ stride = 5 radius = 5 min_vox = srm_k nPerm = 1000 SL_allvox = [] SL_results = [] datadir = '/jukebox/norman/jamalw/MES/prototype/link/scripts/data/searchlight_input/' for x in range(0,np.max(coords, axis=0)[0]+stride,stride): for y in range(0,np.max(coords, axis=0)[1]+stride,stride): for z in range(0,np.max(coords, axis=0)[2]+stride,stride): if not os.path.isfile(datadir + subjs[0] + '/' + str(x) + '_' + str(y) + '_' + str(z) + '.npy'): continue D = distance.cdist(coords,np.array([x,y,z]).reshape((1,3)))[:,0] SL_vox = D <= radius data = [] for i in range(len(subjs)): subj_data = np.load(datadir + subjs[i] + '/' + str(x) + '_' + str(y) + '_' + str(z) + '.npy') subj_regs = np.genfromtxt(datadir + subjs[i] + '/EPI_mcf1.par') motion = subj_regs.T regr = linear_model.LinearRegression() regr.fit(motion[:,0:2511].T,subj_data[:,:,0].T) subj_data1 = subj_data[:,:,0] - np.dot(regr.coef_, motion[:,0:2511]) - regr.intercept_[:, np.newaxis] data.append(np.nan_to_num(stats.zscore(subj_data1,axis=1,ddof=1))) for i in range(len(subjs)): subj_data = np.load(datadir + subjs[i] + '/' + str(x) + '_' + str(y) + '_' + str(z) + '.npy') subj_regs = np.genfromtxt(datadir + subjs[i] + '/EPI_mcf2.par') motion = subj_regs.T regr = linear_model.LinearRegression() regr.fit(motion[:,0:2511].T,subj_data[:,:,1].T) subj_data2 = subj_data[:,:,1] - np.dot(regr.coef_, motion[:,0:2511]) - regr.intercept_[:, np.newaxis] data.append(np.nan_to_num(stats.zscore(subj_data2,axis=1,ddof=1))) print("Running Searchlight") # only run function on searchlights with voxels greater than or equal to min_vox if data[0].shape[0] >= min_vox: SL_match = GSBS_helper(data,human_bounds,song_idx,song_bounds,srm_k,hrf) SL_results.append(SL_match) SL_allvox.append(np.array(np.nonzero(SL_vox)[0])) voxmean = np.zeros((coords.shape[0], nPerm+1)) vox_SLcount = np.zeros(coords.shape[0]) for sl in range(len(SL_results)): voxmean[SL_allvox[sl],:] += SL_results[sl] vox_SLcount[SL_allvox[sl]] += 1 voxmean = voxmean / vox_SLcount[:,np.newaxis] vox_z = np.zeros((coords.shape[0], nPerm+1)) for p in range(nPerm+1): vox_z[:,p] = (voxmean[:,p] - np.mean(voxmean[:,1:],axis=1))/np.std(voxmean[:,1:],axis=1) return vox_z,voxmean def GSBS_helper(X,human_bounds,song_idx,song_bounds,srm_k,hrf): """perform GSBS Fit GSBS to average data and cross-validate with leftout subject using within song and between song average correlations Parameters ---------- A: voxel by time ndarray (2D) B: voxel by time ndarray (2D) C: voxel by time ndarray (2D) D: voxel by time ndarray (2D) K: # of events for GSBS (scalar) Returns ------- z: z-score after performing permuted cross-validation analysis """ w = 3 nPerm = 1000 n_iter = 10 run1 = [X[i] for i in np.arange(0, int(len(X)/2))] run2 = [X[i] for i in np.arange(int(len(X)/2), len(X))] if runNum == 0: run1Data = np.asarray(run1) data = np.mean(run1Data[:,:,song_bounds[song_idx]:song_bounds[song_idx + 1]],axis=0) elif runNum == 1: run2Data = np.asarray(run2) data = np.mean(run2Data[:,:,song_bounds[song_idx]:song_bounds[song_idx + 1]],axis=0) nTR = data.shape[1] # fit model K = len(human_bounds) + 1 if data.T.shape[1] > 0: ev = GSBS(x=data.T,kmax=K) ev.fit() # get boundaries bounds = np.round(np.nonzero(ev.get_bounds(K))[0]) match = np.zeros(nPerm+1) perm_bounds = bounds.copy() for p in range(nPerm+1): for hb in human_bounds: if np.any(np.abs(perm_bounds - hb) <= w): match[p] += 1 match[p] /= len(human_bounds) np.random.seed(p) perm_bounds = np.random.choice(nTR,K-1,replace=False) return match # initialize data stores global_outputs_all = np.zeros((91,109,91)) results3d = np.zeros((91,109,91)) results3d_real = np.zeros((91,109,91)) results3d_perms = np.zeros((91,109,91,1001)) # create coords matrix x,y,z = np.mgrid[[slice(dm) for dm in tuple((91,109,91))]] x = np.reshape(x,(x.shape[0]*x.shape[1]*x.shape[2])) y = np.reshape(y,(y.shape[0]*y.shape[1]*y.shape[2])) z = np.reshape(z,(z.shape[0]*z.shape[1]*z.shape[2])) coords = np.vstack((x,y,z)).T coords_mask = coords[mask_reshape>0] print('Running Distribute...') voxmean,real_sl_scores = searchlight(coords_mask,human_bounds,mask,subjs,song_idx,song_bounds,srm_k,hrf) results3d[mask>0] = voxmean[:,0] results3d_real[mask>0] = real_sl_scores[:,0] for j in range(voxmean.shape[1]): results3d_perms[mask>0,j] = voxmean[:,j] print('Saving data to Searchlight Folder') print(songs[song_idx]) if runNum == 0: np.save('/jukebox/norman/jamalw/MES/prototype/link/scripts/data/searchlight_output/HMM_searchlight_human_bounds_fit_to_all/' + songs[song_idx] +'/raw/globals_raw_srm_k_' + str(srm_k) + '_test_run1_GSBS_no_srm', results3d_real) np.save('/jukebox/norman/jamalw/MES/prototype/link/scripts/data/searchlight_output/HMM_searchlight_human_bounds_fit_to_all/' + songs[song_idx] +'/zscores/globals_z_srm_k' + str(srm_k) + '_test_run1_GSBS_no_srm', results3d) np.save('/jukebox/norman/jamalw/MES/prototype/link/scripts/data/searchlight_output/HMM_searchlight_human_bounds_fit_to_all/' + songs[song_idx] +'/perms/globals_z_srm_k' + str(srm_k) + '_test_run1_GSBS_no_srm', results3d_perms) if runNum == 1: np.save('/jukebox/norman/jamalw/MES/prototype/link/scripts/data/searchlight_output/HMM_searchlight_human_bounds_fit_to_all/' + songs[song_idx] +'/raw/globals_raw_srm_k_' + str(srm_k) + '_test_run2_GSBS_no_srm', results3d_real) np.save('/jukebox/norman/jamalw/MES/prototype/link/scripts/data/searchlight_output/HMM_searchlight_human_bounds_fit_to_all/' + songs[song_idx] +'/zscores/globals_z_srm_k' + str(srm_k) + '_test_run2_GSBS_no_srm', results3d) np.save('/jukebox/norman/jamalw/MES/prototype/link/scripts/data/searchlight_output/HMM_searchlight_human_bounds_fit_to_all/' + songs[song_idx] +'/perms/globals_z_srm_k' + str(srm_k) + '_test_run2_GSBS_no_srm', results3d_perms)
[ "jamalw@princeton.edu" ]
jamalw@princeton.edu
4560b16d95bb169aab5d0111220c04b3b936e793
d1ce5d1a53eabf2dc7a51082e7374e53ee01a1e8
/dashboard/forms.py
d2f246d42ae1fe2f3e8adca14d59d4dc5e20d471
[]
no_license
Nitin15067/FCS-project
c3ecc1c733dd94e892eefb8b909182931908db23
55d84b3bbb636aa6f1cc2ebbb863c4fd1ab3bf47
refs/heads/master
2020-08-06T08:48:22.953304
2019-10-30T13:14:24
2019-10-30T13:14:24
212,912,497
0
0
null
null
null
null
UTF-8
Python
false
false
339
py
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from account.models import Account class EditProfileForm(UserChangeForm): class Meta: model = Account fields = ( 'email', 'first_name', 'last_name', 'phone_no', 'password' )
[ "nitin15067@iiitd.ac.in" ]
nitin15067@iiitd.ac.in
04d9ad1e786f05e26021f6185659f3aae41db9f9
ac2f43c8e0d9649a7f063c59b3dffdfed9fd7ed7
/tests2/tests/fuji/test_sensor.py
1d54acae68dd7d60074e321cc3d4aa4b3266471c
[]
no_license
facebook/openbmc
bef10604ced226288600f55248b7f1be9945aea4
32777c66a8410d767eae15baabf71c61a0bef13c
refs/heads/helium
2023-08-17T03:13:54.729494
2023-08-16T23:24:18
2023-08-16T23:24:18
31,917,712
684
331
null
2023-07-25T21:19:08
2015-03-09T19:18:35
C
UTF-8
Python
false
false
13,978
py
#!/usr/bin/env python3 # # Copyright 2020-present Facebook. All Rights Reserved. # # This program file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; version 2 of the License. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. # # You should have received a copy of the GNU General Public License # along with this program in a file named COPYING; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA # import os import unittest from abc import abstractmethod from common.base_sensor_test import SensorUtilTest from tests.fuji.helper.libpal import pal_is_fru_prsnt, pal_get_fru_id from tests.fuji.test_data.sensors.sensor import ( PIM1_SENSORS_16Q, PIM1_SENSORS_16O, PIM2_SENSORS_16Q, PIM2_SENSORS_16O, PIM3_SENSORS_16Q, PIM3_SENSORS_16O, PIM4_SENSORS_16Q, PIM4_SENSORS_16O, PIM5_SENSORS_16Q, PIM5_SENSORS_16O, PIM6_SENSORS_16Q, PIM6_SENSORS_16O, PIM7_SENSORS_16Q, PIM7_SENSORS_16O, PIM8_SENSORS_16Q, PIM8_SENSORS_16O, PSU1_SENSORS, PSU2_SENSORS, PSU3_SENSORS, PSU4_SENSORS, SCM_SENSORS, SMB_SENSORS, ) from utils.test_utils import qemu_check @unittest.skipIf(qemu_check(), "test env is QEMU, skipped") class ScmSensorTest(SensorUtilTest, unittest.TestCase): def set_sensors_cmd(self): self.sensors_cmd = ["/usr/local/bin/sensor-util scm"] def test_scm_sensor_keys(self): result = self.get_parsed_result() for key in SCM_SENSORS: with self.subTest(key=key): self.assertIn( key, result.keys(), "Missing key {} in scm sensor data".format(key) ) def test_scm_temp_sensor_range(self): result = self.get_parsed_result() SCM_TEMP_KEYS = [ "SCM_OUTLET_U7_TEMP", "SCM_INLET_U8_TEMP", "BMC_LM75_U9_TEMP", "MB_OUTLET_TEMP", "MB_INLET_TEMP", "PCH_TEMP", "VCCIN_VR_TEMP", "1V05MIX_VR_TEMP", "SOC_TEMP", "VDDR_VR_TEMP", "SOC_DIMMA0_TEMP", "SOC_DIMMB0_TEMP", ] for key in SCM_TEMP_KEYS: with self.subTest(key=key): value = result[key] self.assertAlmostEqual( float(value), 30, delta=20, msg="Sensor={} reported value={} not within range".format( key, value ), ) @unittest.skipIf(qemu_check(), "test env is QEMU, skipped") class PimSensorTest(SensorUtilTest, unittest.TestCase): @abstractmethod def get_pim_sensors(self): self._pim_id = 0 pass def get_pim_temp_keys(self): PIM_TEMP_KEYS = [] PIM_TEMP_KEYS.append("PIM{}_LM75_U37_TEMP_BASE".format(self._pim_id)) PIM_TEMP_KEYS.append("PIM{}_LM75_U26_TEMP".format(self._pim_id)) PIM_TEMP_KEYS.append("PIM{}_LM75_U37_TEMP_MEZZ".format(self._pim_id)) # PIM_TEMP_KEYS.append("PIM{}_QSFP_TEMP".format(self._pim_id)) return PIM_TEMP_KEYS def base_test_pim_sensor_keys(self): self.set_sensors_cmd() if not pal_is_fru_prsnt(pal_get_fru_id("pim{}".format(self._pim_id))): self.skipTest("pim{} is not present".format(self._pim_id)) result = self.get_parsed_result() for key in self.get_pim_sensors(): with self.subTest(key=key): self.assertIn( key, result.keys(), "Missing key {} in pim{} sensor data".format(key, self._pim_id), ) def base_test_pim_temp_sensor_range(self): self.set_sensors_cmd() if not pal_is_fru_prsnt(pal_get_fru_id("pim{}".format(self._pim_id))): self.skipTest("pim{} is not present".format(self._pim_id)) result = self.get_parsed_result() PIM_TEMP_KEYS = self.get_pim_temp_keys() for key in PIM_TEMP_KEYS: with self.subTest(key=key): value = result[key] self.assertAlmostEqual( float(value), 30, delta=20, msg="Sensor={} reported value={} not within range".format( key, value ), ) def get_pim_name(self, ver): """ """ pim_name = None ver = int(ver, 16) if ver & 0x80 == 0x0: pim_name = "PIM_TYPE_16Q" elif ver & 0x80 == 0x80: pim_name = "PIM_TYPE_16O" else: pim_name = None return pim_name def get_pim_sensor_type(self, pim_num): """ Get PIM sensors type by read i2c device board version """ pim_sensor_type = None bus = (pim_num * 8) + 80 PATH = "/sys/bus/i2c/devices/%d-0060/board_ver" % (bus) if not os.path.exists(PATH): raise Exception("Path for PIM board_ver doesn't exist") with open(PATH, "r") as fp: line = fp.readline() if line: ver = line.split("0x")[1] pim_sensor_type = self.get_pim_name(ver) else: raise Exception("PIM board_ver is empty") return pim_sensor_type class Pim1SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim1")): self.skipTest("pim1 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim1"] self._pim_id = 1 def get_pim_sensors(self): name = self.get_pim_sensor_type(0) if name == "PIM_TYPE_16Q": return PIM1_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM1_SENSORS_16O else: return PIM1_SENSORS_16Q def test_pim1_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim1_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() class Pim2SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim2")): self.skipTest("pim2 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim2"] self._pim_id = 2 def get_pim_sensors(self): name = self.get_pim_sensor_type(1) if name == "PIM_TYPE_16Q": return PIM2_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM2_SENSORS_16O else: return PIM2_SENSORS_16Q def test_pim2_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim2_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() class Pim3SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim3")): self.skipTest("pim3 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim3"] self._pim_id = 3 def get_pim_sensors(self): name = self.get_pim_sensor_type(2) if name == "PIM_TYPE_16Q": return PIM3_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM3_SENSORS_16O else: return PIM3_SENSORS_16Q def test_pim3_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim3_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() class Pim4SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim4")): self.skipTest("pim4 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim4"] self._pim_id = 4 def get_pim_sensors(self): name = self.get_pim_sensor_type(3) if name == "PIM_TYPE_16Q": return PIM4_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM4_SENSORS_16O else: return PIM4_SENSORS_16Q def test_pim4_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim4_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() class Pim5SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim5")): self.skipTest("pim5 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim5"] self._pim_id = 5 def get_pim_sensors(self): name = self.get_pim_sensor_type(4) if name == "PIM_TYPE_16Q": return PIM5_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM5_SENSORS_16O else: return PIM5_SENSORS_16Q def test_pim5_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim5_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() class Pim6SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim6")): self.skipTest("pim6 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim6"] self._pim_id = 6 def get_pim_sensors(self): name = self.get_pim_sensor_type(5) if name == "PIM_TYPE_16Q": return PIM6_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM6_SENSORS_16O else: return PIM6_SENSORS_16Q def test_pim6_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim6_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() class Pim7SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim7")): self.skipTest("pim7 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim7"] self._pim_id = 7 def get_pim_sensors(self): name = self.get_pim_sensor_type(6) if name == "PIM_TYPE_16Q": return PIM7_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM7_SENSORS_16O else: return PIM7_SENSORS_16Q def test_pim7_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim7_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() class Pim8SensorTest(PimSensorTest, unittest.TestCase): def set_sensors_cmd(self): if not pal_is_fru_prsnt(pal_get_fru_id("pim8")): self.skipTest("pim8 is not present") self.sensors_cmd = ["/usr/local/bin/sensor-util pim8"] self._pim_id = 8 def get_pim_sensors(self): name = self.get_pim_sensor_type(7) if name == "PIM_TYPE_16Q": return PIM8_SENSORS_16Q elif name == "PIM_TYPE_16O": return PIM8_SENSORS_16O else: return PIM8_SENSORS_16Q def test_pim8_sensor_keys(self): super().base_test_pim_sensor_keys() def test_pim8_temp_sensor_range(self): super().base_test_pim_temp_sensor_range() @unittest.skipIf(qemu_check(), "test env is QEMU, skipped") class PsuSensorTest(SensorUtilTest, unittest.TestCase): @abstractmethod def get_psu_sensors(self): self._psu_id = 0 pass def base_test_psu_sensor_keys(self): self.set_sensors_cmd() if not pal_is_fru_prsnt(pal_get_fru_id("psu{}".format(self._psu_id))): self.skipTest("psu{} is not present".format(self._psu_id)) result = self.get_parsed_result() for key in self.get_psu_sensors(): with self.subTest(key=key): self.assertIn( key, result.keys(), "Missing key {} in psu{} sensor data".format(key, self._psu_id), ) class Psu1SensorTest(PsuSensorTest, unittest.TestCase): def set_sensors_cmd(self): self.sensors_cmd = ["/usr/local/bin/sensor-util psu1"] self._psu_id = 1 def get_psu_sensors(self): return PSU1_SENSORS def test_psu1_sensor_keys(self): super().base_test_psu_sensor_keys() class Psu2SensorTest(PsuSensorTest, unittest.TestCase): def set_sensors_cmd(self): self.sensors_cmd = ["/usr/local/bin/sensor-util psu2"] self._psu_id = 2 def get_psu_sensors(self): return PSU2_SENSORS def test_psu2_sensor_keys(self): super().base_test_psu_sensor_keys() class Psu3SensorTest(PsuSensorTest, unittest.TestCase): def set_sensors_cmd(self): self.sensors_cmd = ["/usr/local/bin/sensor-util psu3"] self._psu_id = 3 def get_psu_sensors(self): return PSU3_SENSORS def test_psu3_sensor_keys(self): super().base_test_psu_sensor_keys() class Psu4SensorTest(PsuSensorTest, unittest.TestCase): def set_sensors_cmd(self): self.sensors_cmd = ["/usr/local/bin/sensor-util psu4"] self._psu_id = 4 def get_psu_sensors(self): return PSU4_SENSORS def test_psu4_sensor_keys(self): super().base_test_psu_sensor_keys() class SmbSensorTest(SensorUtilTest, unittest.TestCase): def set_sensors_cmd(self): self.sensors_cmd = ["/usr/local/bin/sensor-util smb"] def test_smb_sensor_keys(self): result = self.get_parsed_result() for key in SMB_SENSORS: with self.subTest(key=key): self.assertIn( key, result.keys(), "Missing key {} in SMB sensor data".format(key) )
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
0cdac74013d1815fdcf40dc9165e35d850ef2673
7b252f0c1b8ba7c9a35ead166482efbb4d804413
/mysite/books/views.py
aad9117e9fbeb9c02c506f754902dff380645397
[]
no_license
gzpgg3x/PythonExample
191024f04796a13106b46f4f00a59185c33af91b
c64563f91cd5188b6d3d01688d8184a37ded46eb
refs/heads/master
2021-01-10T19:38:53.325169
2013-04-11T22:36:29
2013-04-11T22:36:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,682
py
# Create your views here. # from django.shortcuts import render_to_response # from django.http import Http404, HttpResponse # def search_form(request): # return render_to_response('search_form.html') # def search(request): # if 'q' in request.GET: # message = 'You searched for: %r' % request.GET['q'] # else: # message = 'You submitted an empty form.' # return HttpResponse(message) # from django.http import HttpResponse # from django.shortcuts import render_to_response # from books.models import Book # def search_form(request): # return render_to_response('search_form.html') # def search(request): # if 'q' in request.GET and request.GET['q']: # q = request.GET['q'] # books = Book.objects.filter(title__icontains=q) # return render_to_response('search_results.html', # {'books': books, 'query': q}) # else: # # return HttpResponse('Please submit a search term.') # return render_to_response('search_form.html', {'error': True}) # def search(request): # error = False # if 'q' in request.GET: # q = request.GET['q'] # if not q: # error = True # elif len(q) > 20: # error = True # else: # books = Book.objects.filter(title__icontains=q) # return render_to_response('search_results.html', # {'books': books, 'query': q}) # return render_to_response('search_form.html', # {'error': error}) # def search(request): # errors = [] # if 'q' in request.GET: # q = request.GET['q'] # if not q: # errors.append('Enter a search term.') # elif len(q) > 20: # errors.append('Please enter at most 20 characters.') # else: # books = Book.objects.filter(title__icontains=q) # return render_to_response('search_results.html', # {'books': books, 'query': q}) # return render_to_response('search_form.html', # {'errors': errors}) from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from books.forms import ContactForm def search(request): errors = [] if 'q' in request.GET: q = request.GET['q'] if not q: errors.append('Enter a search term.') elif len(q) > 20: errors.append('Please enter at most 20 characters.') else: books = book.objects.filter(title__icontains=q) return render_to_response('search_results.html', {'books': books, 'query': q}) return render_to_response('search_form.html', {'errors': errors}) # def contact(request): # errors = [] # if request.method == 'POST': # if not request.POST.get('subject', ''): # errors.append('Enter a subject.') # if not request.POST.get('message', ''): # errors.append('Enter a message.') # if request.POST.get('email') and '@' not in request.POST['email']: # errors.append('Enter a valid e-mail address.') # if not errors: # send_mail( # request.POST['subject'], # request.POST['message'], # request.POST.get('email', 'noreply@example.com'), # ['siteowner@example.com'], # ) # return HttpResponseRedirect('/contact/thanks/') # return render_to_response('contact_form.html', # {'errors': errors}) # def contact(request): # errors = [] # if request.method == 'POST': # if not request.POST.get('subject', ''): # errors.append('Enter a subject.') # if not request.POST.get('message', ''): # errors.append('Enter a message.') # if request.POST.get('email') and '@' not in request.POST['email']: # errors.append('Enter a valid e-mail address.') # if not errors: # send_mail( # request.POST['subject'], # request.POST['message'], # request.POST.get('email', 'noreply@example.com'), # ['siteowner@example.com'], # ) # return HttpResponseRedirect('/contact/thanks/') # return render_to_response('contact_form.html', { # 'errors': errors, # 'subject': request.POST.get('subject', ''), # 'message': request.POST.get('message', ''), # 'email': request.POST.get('email', ''), # }) # def contact(request): # if request.method == 'POST': # form = ContactForm(request.POST) # if form.is_valid(): # cd = form.cleaned_data # send_mail( # cd['subject'], # cd['message'], # cd.get('email', 'noreply@example.com'), # ['siteowner@example.com'], # ) # return HttpResponseRedirect('/contact/thanks/') # else: # form = ContactForm() # return render_to_response('contact_form.html', {'form': form}) def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data send_mail( cd['subject'], cd['message'], cd.get('email', 'noreply@example.com'), ['siteowner@example.com'], ) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm( initial={'subject': 'I love your site!'} ) return render_to_response('contact_form.html', {'form': form})
[ "gzpgg3x@yahoo.com" ]
gzpgg3x@yahoo.com