seq_id
stringlengths 7
11
| text
stringlengths 156
1.7M
| repo_name
stringlengths 7
125
| sub_path
stringlengths 4
132
| file_name
stringlengths 4
77
| file_ext
stringclasses 6
values | file_size_in_byte
int64 156
1.7M
| program_lang
stringclasses 1
value | lang
stringclasses 38
values | doc_type
stringclasses 1
value | stars
int64 0
24.2k
⌀ | dataset
stringclasses 1
value | pt
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|
20445647795
|
import os
import importlib.util
import time
print("Checking Dependencies")
if importlib.util.find_spec("tkinter") is None:
print("tkinter NOT INSTALLED,RUN pip install tkinter")
os.system("pause")
exit()
print("Dependencies OK")
time.sleep(5.5)
from os import path
from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
print("Select Source Folder")
Source_Path = filedialog.askdirectory()
print("Source Path : ",Source_Path)
print("Select Destination Path")
Destination = filedialog.askdirectory()
print("Destination Path : ",Destination)
fileprfx = input("File Prefix :")
filetype = input("File Type (ex .doc .exe .png) :")
def main():
for count, filename in enumerate(os.listdir(Source_Path)):
dst = fileprfx + " " + str(count) + filetype
# rename all the files
os.rename(os.path.join(Source_Path, filename), os.path.join(Destination, dst))
# Driver Code
if __name__ == '__main__':
main()
|
JohnavonVincentius/FileRename
|
filerename.py
|
filerename.py
|
py
| 1,010 |
python
|
en
|
code
| 0 |
github-code
|
6
|
43219185037
|
#!/usr/bin/env python
from storytext import applicationEvent
import time, signal, sys
def handleSignal(signum, *args):
sys.stderr.write("Got signal " + repr(signum) + "\n")
signal.signal(signal.SIGQUIT, handleSignal)
signal.signal(signal.SIGINT, handleSignal)
time.sleep(0.5)
applicationEvent("nothing to happen")
applicationEvent("first sleep to complete", "first", delayLevel=1)
time.sleep(5)
time.sleep(0.5)
applicationEvent("second sleep to complete", "second")
time.sleep(5)
|
texttest/storytext-selftest
|
console/appevent_delayed/target_ui.py
|
target_ui.py
|
py
| 488 |
python
|
en
|
code
| 0 |
github-code
|
6
|
8400225965
|
# Importamos tkinter
from tkinter import *
# Cargamos el modulo de Imagenes Pillow Python
from PIL import Image, ImageTk
# Creamos la ventana raiz
ventana = Tk()
ventana.title("Imagenes | Curso de master en Python")
ventana.geometry("700x500")
Label(ventana, text="Hola!!, Soy Lcdo. José Fernando Frugone Jaramillo").pack(anchor=CENTER)
dibujo = Image.open("./21-tkinter/imagenes/leon.jpg")
render = ImageTk.PhotoImage(dibujo)
Label(ventana, image=render).pack(anchor=CENTER)
ventana.mainloop()
|
jfrugone1970/tkinter_python2020
|
21-tkinter/03-imagenes.py
|
03-imagenes.py
|
py
| 500 |
python
|
es
|
code
| 1 |
github-code
|
6
|
11783428086
|
# coding: utf-8
# In[1]:
#get_ipython().system(u'jupyter nbconvert --to script lstm_model.ipynb')
import os
import sys
import time
import pandas as pd
import datetime
#import pandas.io.data as web
from pandas_datareader import data
import matplotlib.pyplot as plt
from matplotlib import style
import glob
import numpy as np
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout
from keras.layers import Activation, LSTM
from keras.utils import plot_model
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from math import sqrt
from keras.callbacks import EarlyStopping
#import load_data
# fix random seed for reproducibility
np.random.seed(7)
# In[2]:
days_for_prediction = 30
source_dir='../data/samples'
models_dir = '../models/lstm/'
supervised_data_dir = '../data/samples2'
prediction_data_dir = '../data/prediction/samples'
rmse_csv = '../data/rsme_ltsm.csv'
# # Build train and test datasets
# In[3]:
# frame a sequence as a supervised learning problem
def to_supervised(df, lag, org_col_name='Adj Close', new_col_name='Adj Close+'):
# new_col_name's data is created by shifting values from org_col_name
df[new_col_name] = df.shift(-lag)[org_col_name]
# Remove the last lag rows
df = df.head(len(df) - lag)
df.fillna(0, inplace=True)
return df
def create_supervised_filename(directory, ticker):
return os.path.join(directory, ticker + "_supervised.csv")
def create_supervised_data(source_dir, dest_dir, days_for_prediction=30, new_col_name = 'Adj Close+'):
'''
Input:
- source_dir: directory where the stock price CSVs are located
- days_for_prediction: number of days for the prediction prices. Must be at least 30 days
Description:
Read csv files in source_dir, load into dataframes and split into
X_train, Y_train, X_test, Y_test
'''
#assert (days_for_prediction >= 30), "days_for_prediction must be >= 30"
csv_file_pattern = os.path.join(source_dir, "*.csv")
csv_files = glob.glob(csv_file_pattern)
dfs = {}
for filename in csv_files:
arr = filename.split('/')
ticker = arr[-1].split('.')[0]
new_file = create_supervised_filename(dest_dir, ticker)
#print(ticker, df.head())
# Date, Open, High , Low , Close, Adj Close, Volume
#df = pd.read_csv(filename, parse_dates=[0]) #index_col='Date')
# Open, High , Low , Close, Adj Close, Volume
df = pd.read_csv(filename, index_col='Date')
#print('Before\n', df[30:40])
#print(df.shift(2)['Adj Close'].head())
df = to_supervised(df, days_for_prediction, new_col_name=new_col_name)
df.to_csv(new_file)
#print('Adding new column...\n', df[['Adj Close', new_col_name]].head(days_for_prediction+1))
#print('After\n', df.tail())
dfs[ticker] = df
print(ticker, filename, new_file)
return dfs
# # Use LSTM model for each stock
# In[4]:
dfs = create_supervised_data(source_dir=source_dir, dest_dir=supervised_data_dir, days_for_prediction=days_for_prediction)
# In[5]:
def create_lstm_model(max_features, lstm_units):
model = Sequential()
#model.add(LSTM(neurons, input_shape=(None, X_train.shape[1]), return_sequences=True)) #, dropout=0.2))
#model.add(LSTM(max_features, batch_input_shape=(batch_size, None, train_X[i].shape[1]), dropout=0.2, stateful=True))
#model.add(LSTM(1, input_shape=(max_features,1), return_sequences=True, dropout=0.2))
#model.add(LSTM(max_features, return_sequences=False, dropout=0.2))
#model.add(LSTM(input_dim=max_features, output_dim=300, return_sequences=True))
model.add(LSTM(units=lstm_units[0], input_shape=(None, max_features), return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(lstm_units[1], return_sequences=False))
model.add(Dropout(0.2))
#model.add(Dense(1)) #, activation='sigmoid'))
model.add(Dense(1, activation='linear'))
#model.compile(loss='mse', optimizer='rmsprop')
#model.compile(loss='binary_crossentropy',optimizer='rmsprop', metrics=['accuracy'])
#model.compile(loss='mean_squared_error', optimizer='adam')
model.compile(loss='mse', optimizer='rmsprop', metrics=['accuracy'])
return model
# In[6]:
'''
def create_train_test(data):
X,y = data[:,0:-1], data[:, -1]
# Transform scale
X_scaler = MinMaxScaler(feature_range=(-1, 1))
y_scaler = MinMaxScaler(feature_range=(-1, 1))
scaled_X = X_scaler.fit_transform(X)
scaled_y = y_scaler.fit_transform(y)
print(scaled_y)
# Now split 80/20 for train and test data
#train_count = int(.8*len(data))
# last test_days is for test; the rest is for train
test_days = 90
train_count = len(data) - test_days
X_train, X_test = scaled_X[:train_count], scaled_X[train_count:]
y_train, y_test = scaled_y[:train_count], scaled_y[train_count:]
return y_scaler, X_train, y_train, X_test, y_test
'''
def create_train_test2(data):
#X,y = data[:,0:-1], data[:, -1]
# Transform scale
scaler = MinMaxScaler(feature_range=(-1, 1))
scaled_data = scaler.fit_transform(data)
# Now split 80/20 for train and test data
#train_count = int(.8*len(data))
# last test_days is for test; the rest is for train
test_days = 90
train_count = len(data) - test_days
train, test = scaled_data[:train_count], scaled_data[train_count:]
X_train, y_train = train[:,0:-1], train[:, -1]
X_test, y_test = test[:,0:-1], test[:, -1]
return scaler, X_train, y_train, X_test, y_test
def build_models(models_dir, supervised_data_dir, lstm_units):
# Define early stopping
early_stopping = EarlyStopping(monitor='val_loss', patience=2) #value=0.00001
rmse_list = list()
models = {}
predicted_dfs = {}
'''
load supervised data
create and save models
'''
csv_file_pattern = os.path.join(supervised_data_dir, "*.csv")
csv_files = glob.glob(csv_file_pattern)
dfs = {}
print_first_model=True
for filename in csv_files:
data = pd.read_csv(filename, index_col='Date')
#print(data.head())
arr = filename.split('/')
ticker = arr[-1].split('.')[0].split('_')[0]
print('Processing', ticker)
max_features = len(data.columns) -1
#y_scaler, X_train, y_train, X_test, y_test = create_train_test(data.values)
scaler, X_train, y_train, X_test, y_test = create_train_test2(data.values)
model = create_lstm_model(max_features, lstm_units)
#plot_model(model, to_file=ticker + '.png', show_shapes=True, show_layer_names=True)
if print_first_model:
print(model.summary())
print_first_model = False
# Train data
x1 = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
y1 = np.reshape(y_train, (y_train.shape[0], 1))
print(x1.shape, y1.shape)
# Test data
x2 = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
y2 = np.reshape(y_test, (y_test.shape[0], 1))
#model.fit(x, y, batch_size=100, epochs=5, shuffle=True)
print('Training...')
#model.fit(x1, y1, batch_size=50, epochs=20, verbose=1, validation_split=0.2, callbacks=[early_stopping])
# Note: Early stopping seems to give worse prediction?!! We want overfitting here?
model.fit(x1, y1, batch_size=5, epochs=20, verbose=1, validation_data=(x2, y2)) #, callbacks=[early_stopping])
model_fname = os.path.join(models_dir, ticker + ".h5")
print('Saving model to', model_fname)
model.save(model_fname)
# In[ ]:
# inverse scaling for a forecasted value
def invert_scale(scaler, X, value):
new_row = np.column_stack((X,value)) #[x for x in X] + [value]
inverted = scaler.inverse_transform(new_row)
return inverted[:, -1]
'''
Predict and evaluate test data
'''
def predict_evaluate(models_dir, supervised_data_dir, predicted_dir, rsme_csv):
model_file_pattern = os.path.join(models_dir, "*.h5")
model_files = glob.glob(model_file_pattern)
predicted_dfs = {}
rmse_list = list()
print(model_file_pattern)
for model_file in model_files:
print('loading', model_file)
arr = model_file.split('/')
ticker = arr[-1].split('.')[0]
'''
Read supervised data and set up test data for prediction
'''
supervised_filename = create_supervised_filename(supervised_data_dir, ticker)
data = pd.read_csv(supervised_filename, index_col='Date')
scaler, X_train, y_train, X_test, y_test = create_train_test2(data.values)
# Test data
x2 = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))
y2 = np.reshape(y_test, (y_test.shape[0], 1))
print('Predicting...')
model = load_model(model_file)
predicted = model.predict(x2)
predict_inversed = invert_scale(scaler, X_test, predicted)
actual_inversed = invert_scale(scaler, X_test, y_test)
rmse = sqrt(mean_squared_error(actual_inversed, predict_inversed))
print('Test RMSE: %.3f' % rmse)
rmse_list += [[ticker,rmse]]
predicted_dfs[ticker] = pd.DataFrame({'predicted': predict_inversed.reshape(len(predict_inversed)),
'actual': actual_inversed.reshape(len(actual_inversed))})
predicted_file = os.path.join(predicted_dir, ticker + "_predicted.csv")
print("Writing to", predicted_file)
predicted_dfs[ticker].to_csv(predicted_file, index=False)
rmse_df = pd.DataFrame(rmse_list, columns=['Stock Model', 'rsme'])
rmse_df = rmse_df.sort_values(by='rsme')
rmse_df.to_csv(rsme_csv, index=False)
return predicted_dfs, rmse_df
# In[ ]:
build_models(models_dir, supervised_data_dir, lstm_units=[40,10])
# In[ ]:
predicted_dfs, rmse_df = predict_evaluate(models_dir,
supervised_data_dir,
prediction_data_dir,
rmse_csv)
# In[ ]:
rmse_df
# In[ ]:
# Plot stocks based on rmse order (best -> worst)
#cnt = 0
#for index, row in rmse_df.iterrows():
# key = row['Stock Model']
# predicted_dfs[key].plot(title=key + ': predicted vs actual')
# plt.show()
# In[ ]:
'''
cnt = 1
for index, row in rmse_df.iterrows():
key = row['Stock Model']
if (cnt % 2 != 0):
fig, axes = plt.subplots(nrows=1, ncols=2)
ax=axes[0]
else:
ax=axes[1]
predicted_dfs[key].plot(title=key + ': price vs days', figsize=(15,4), ax=ax)
cnt += 1
plt.show()
'''
# In[ ]:
|
thongnbui/MIDS_capstone
|
code/lstm_model.py
|
lstm_model.py
|
py
| 10,757 |
python
|
en
|
code
| 0 |
github-code
|
6
|
14019383059
|
# Standard Library Imports
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
def mae(actual, preds):
#INPUT:
#actual - numpy array or pd series of actual y values
#preds - numpy array or pd series of predicted y values
#OUTPUT:
#returns the mean absolute error as a float
return np.sum(np.abs(actual-preds))/len(actual)
def mse(actual, preds):
#INPUT:
#actual - numpy array or pd series of actual y values
#preds - numpy array or pd series of predicted y values
#OUTPUT:
#returns the mean squared error as a float
return np.sum((actual-preds)**2)/len(actual)
def print_metrics(y_true, preds, model_name=None):
#INPUT:
#y_true - the y values that are actually true in the dataset (numpy array or pandas series)
#preds - the predictions for those values from some model (numpy array or pandas series)
#model_name - (str - optional) a name associated with the model if you would like to add it to the print statements
#OUTPUT:
#None - prints the mse, mae, r2
if model_name == None:
print(mse(y_true, preds))
print(mae(y_true, preds))
print(r2(y_true, preds))
print('\n\n')
else:
print(mse(y_true, preds))
print(mae(y_true, preds))
print(r2(y_true, preds))
print('\n\n')
def r2(actual, preds):
'''
INPUT:
actual - numpy array or pd series of actual y values
preds - numpy array or pd series of predicted y values
OUTPUT:
returns the r-squared score as a float
'''
sse = np.sum((actual-preds)**2)
sst = np.sum((actual-np.mean(actual))**2)
return 1 - sse/sst
|
tomgoral/Udacity_ML_Engineer_Nanodegree
|
3_capstone/utilities/print_metrics.py
|
print_metrics.py
|
py
| 1,738 |
python
|
en
|
code
| 0 |
github-code
|
6
|
29827950852
|
import featureEngineering
import progress
def get_classifier_score(classifier, settings={}) -> (float, float):
tbl = featureEngineering.get_featured_data_frame(settings)
train_data, test_data, train_survived_data, test_survived_data = featureEngineering.split_data_frame(tbl)
classifier.fit(train_data, train_survived_data.values.ravel())
score_train = classifier.score(train_data, train_survived_data)
score_test = classifier.score(test_data, test_survived_data)
return score_train, score_test
def find_best_classifier_score(classifier, base_settings={}) -> (float, dict):
variations_count = featureEngineering.get_settings_variations_count()
attempt_count = 10
progress_log = progress.Progress(variations_count * attempt_count)
results = list()
for settings_seed in range(0, variations_count):
settings = base_settings | featureEngineering.get_settings_variation(settings_seed)
avg_test_score = get_avg_test_score(classifier, settings, attempt_count, progress_log)
results.append((avg_test_score, settings))
best_settings = get_best_settings(results)
return results[0][0], best_settings
def get_avg_test_score(classifier, settings, attempt_count, progress_log) -> float:
tbl = featureEngineering.get_featured_data_frame(settings)
sum_test_score = 0
for attempt in range(0, attempt_count):
train_data, test_data, train_survived_data, test_survived_data = featureEngineering.split_data_frame(tbl)
classifier.fit(train_data, train_survived_data.values.ravel())
score_test = classifier.score(test_data, test_survived_data)
sum_test_score += score_test
progress_log.log()
avg_test_score = sum_test_score / attempt_count
return avg_test_score
def get_best_settings(results) -> object:
results.sort(key=lambda x: x[0], reverse=True)
low_test_score = results[0][0] * 0.95
results = list(filter(lambda x: x[0] >= low_test_score, results))
settings = featureEngineering.get_settings_variation(0)
for setting_key in settings:
true_count = 0
false_count = 0
for result in results:
if result[1][setting_key]:
true_count += 1
else:
false_count += 1
settings[setting_key] = true_count >= false_count
return settings
|
AliakseiDudko/PythonMachineLearning
|
solution.py
|
solution.py
|
py
| 2,370 |
python
|
en
|
code
| 0 |
github-code
|
6
|
8954419715
|
import requests,urllib
import os,sys,re,zipfile,shutil,io
from bs4 import BeautifulSoup
cwd = os.getcwd()
# taking the movie input
movie_name = [s for s in re.split("[^0-9a-zA-Z]",input("enter the movie name : \n"))]
movie_name = list(filter(lambda a: a != '', movie_name))
m1 = ' '.join(map(str,movie_name))
encodings = []
while len(encodings) == 0:
encodings = [s.lower() for s in re.split("[^0-9a-zA-Z]",input("enter the storage format (eg.720p,bluray,brrip,xvid,hdtv etc) (must) \n"))]
if len(encodings) == 0 :
print("You must enter some encoding format")
encodings = list(filter(lambda a: a != '', encodings))
m2 = ' '.join(map(str,encodings))
m1 = m1 + ' ' + m2
print("you have searched for \n",m1)
search_string = m1.split()
#search_string
''' Preparing the query '''
search_url = "https://subscene.com/subtitles/title?q="
search_url += search_string[0]
for words in search_string[1:]:
search_url += ("+" + words)
search_url += "&l="
print(search_url)
r = requests.get(search_url)
soup = BeautifulSoup(r.content,"lxml")
#print(soup)
subs = soup.find_all("td", class_ = "a1")
#print(subs)
for elements in range(len(subs)) :
res = subs[elements].find_all("span", class_="l r positive-icon")
s = str(res)
m = re.search('English',s)
if m :
target = subs[elements]
t = target.find("a")
download_link = t['href']
break
# download that link
r1 = requests.get("https://subscene.com" + download_link)
soup = BeautifulSoup(r1.content,"lxml")
download = soup.find_all('a',attrs={'id':'downloadButton'})[0].get("href")
#print(download)
r2 = requests.get("http://subscene.com" + download)
download_link = r2.url
#print(r2.encoding)
#print(file_path)
f = requests.get(download_link)
zipped = zipfile.ZipFile(io.BytesIO(f.content))
zipped.extractall()
print("subtitles downloaded succesfully")
|
styx97/movie_subs
|
movie_subs.py
|
movie_subs.py
|
py
| 1,880 |
python
|
en
|
code
| 4 |
github-code
|
6
|
14524764116
|
import random
from itertools import combinations
from ltga.Mutation import Mutation
class LTGA(object):
def buildTree(self, distance):
clusters = [(i,) for i in range(len(self.individuals[0].genes))]
subtrees = [(i,) for i in range(len(self.individuals[0].genes))]
random.shuffle(clusters)
random.shuffle(subtrees)
lookup = {}
def allLowest():
minVal = 3
results = []
for c1, c2 in combinations(clusters, 2):
result = distance(self.individuals, c1, c2, lookup)
if result < minVal:
minVal = result
results = [(c1, c2)]
if result == minVal:
results.append((c1, c2))
return results
while len(clusters) > 1:
c1, c2 = random.choice(allLowest())
clusters.remove(c1)
clusters.remove(c2)
combined = c1 + c2
clusters.append(combined)
if len(clusters) != 1:
subtrees.append(combined)
return subtrees
def smallestFirst(self, subtrees):
return sorted(subtrees, key=len)
def generate(self, initialPopulation, evaluator, distanceFcn, crossoverFcn):
self.individuals = initialPopulation
distance = distanceFcn
ordering = self.smallestFirst
crossover = crossoverFcn
beforeGenerationSet = set(self.individuals)
while True:
subtrees = self.buildTree(distance)
masks = ordering(subtrees)
generator = crossover(self.individuals, masks)
individual = next(generator)
while True:
fitness = yield individual
try:
individual = generator.send(fitness)
except StopIteration:
break
self.individuals = Mutation(evaluator).mutate(self.individuals)
#If all individuals are identical
currentSet = set(self.individuals)
if (len(currentSet) == 1 or
currentSet == beforeGenerationSet):
break
beforeGenerationSet = currentSet
|
Duzhinsky/scheduling
|
ltga/LTGA.py
|
LTGA.py
|
py
| 2,220 |
python
|
en
|
code
| 0 |
github-code
|
6
|
38199809243
|
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QDesktopWidget, QFileDialog
from PyQt5.QtGui import QPalette, QColor
import numpy as np
from typing import *
import json
import qtmodern.styles
import qtmodern.windows
from MyModules.MyWindow import Ui_MainWindow
from MyModules.Orbits import Satellite
from MyModules.MPL3Dwidget import *
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.center()
# Create the matplotlib 3D plot
self.plotCanvas = MplCanvas(self.plotWidget, width=5, height=5, dpi=100)
self.toolbar = NavigationToolbar(self.plotCanvas, self.plotWidget)
self.plotLayout.addWidget(self.plotCanvas)
self.plotLayout.addWidget(self.toolbar)
self.plotWidget.setLayout(self.plotLayout)
# connect every slider to the function that handles the ploting
sliders = [self.slider_MA, self.slider_AOP, self.slider_ECC, self.slider_INC, self.slider_LAN, self.slider_SMA]
for slider in sliders:
slider.sliderReleased.connect(self.slider_released)
self.slider_released() # Initialize the plot
self.actionExport_to_json.triggered.connect(lambda: self.export_to_json())
self.actionImport_from_json.triggered.connect(lambda: self.import_from_json())
self.planet_actions = [self.actionMercury, self.actionVenus, self.actionEarth, self.actionMars,
self.actionJupiter, self.actionSaturn, self.actionUranus, self.actionNeptune, self.actionPluto]
for act in self.planet_actions:
act.triggered.connect(lambda: self.display_planets())
def center(self):
""" This function centers the window at launch"""
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def slider_released(self):
""" Triggered when a slider is released. Computes the new positions and plots the new graph"""
pos = self.calculate_position(self.getSliderValues())
self.plot(pos)
def plot(self, pos):
""" Handles the ploting"""
self.plotCanvas.axes.cla()
self.plotCanvas.axes.plot(pos[:, 0], pos[:, 1], pos[:, 2], 'o', markersize=1)
self.plotCanvas.axes.plot([0], [0], [0], 'o', color='yellow', markersize='10')
self.plotCanvas.axes.mouse_init(rotate_btn=1, zoom_btn=3)
set_axes_equal(self.plotCanvas.axes)
self.plotCanvas.fig.set_facecolor(plot_background_color)
self.plotCanvas.axes.patch.set_facecolor(plot_face_color)
self.plotCanvas.draw()
def getSliderValues(self) -> List[float]:
""" Returns the current values displayed by the sliders"""
return [float(self.slider_SMA.value()),
float(self.slider_INC.value()),
float(self.slider_ECC.value()) / 1e3,
float(self.slider_LAN.value()),
float(self.slider_AOP.value()),
float(self.slider_MA.value())]
def setSliderValues(self, values: Dict[str, float]):
self.slider_SMA.setValue(int(values['SMA']))
self.slider_INC.setValue(int(values['INC']))
self.slider_ECC.setValue(int(values['ECC'] * 1e3))
self.slider_LAN.setValue(int(values['LAN']))
self.slider_AOP.setValue(int(values['AOP']))
self.slider_MA.setValue(int(values['MA']))
self.slider_released()
def calculate_position(self, values: List[float]):
obj = Satellite(*values)
time = np.linspace(0, obj.T, 200)
pos = obj.orbitalparam2vectorList(time)
return pos
def export_to_json(self):
"""Writes the current values of the sliders to a new JSON file"""
file_name = self.FileDialog()
with open(file_name, 'w') as f:
keys = ["SMA", "INC", "ECC", "LAN", "AOP", "MA"]
values = self.getSliderValues()
json.dump(dict(zip(keys, values)), f)
def import_from_json(self):
file_name = self.FileDialog(save=False)
with open(file_name, 'r') as f:
content = json.load(f)
self.setSliderValues(content)
def FileDialog(self, save=True):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
if save:
file_name, _ = QFileDialog.getSaveFileName(
self, "Save as", "", "JSON Files (*.json)", options=options)
else:
file_name, _ = QFileDialog.getOpenFileName(
self, "Open", "", "JSON Files (*.json)", options=options)
if file_name != '':
if not file_name.endswith('.json'):
file_name += '.json'
return file_name
def display_planets(self):
for planet in self.planet_actions:
if planet.isChecked():
print('hello')
if __name__ == "__main__":
app = QApplication(sys.argv)
app.setStyle("Fusion")
dark_palette = QPalette()
dark_palette.setColor(QPalette.Window, QColor(51, 54, 63))
dark_palette.setColor(QPalette.WindowText, QColor(250, 250, 250))
dark_palette.setColor(QPalette.Base, QColor(39, 42, 49))
dark_palette.setColor(QPalette.AlternateBase, QColor(51, 54, 63))
dark_palette.setColor(QPalette.ToolTipBase, QColor(250, 250, 250))
dark_palette.setColor(QPalette.ToolTipText, QColor(250, 250, 250))
dark_palette.setColor(QPalette.Text, QColor(250, 250, 250))
dark_palette.setColor(QPalette.Button, QColor(51, 54, 63))
dark_palette.setColor(QPalette.ButtonText, QColor(250, 250, 250))
dark_palette.setColor(QPalette.BrightText, QColor(255, 0, 0))
dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
dark_palette.setColor(QPalette.HighlightedText, QColor(0, 0, 0))
app.setPalette(dark_palette)
plot_background_color = (51/255, 54/255, 63/255)
plot_face_color = (39/255, 42/255, 49/255)
win = MainWindow()
mw = qtmodern.windows.ModernWindow(win)
mw.show()
sys.exit(app.exec_())
|
Keith-Maxwell/OrbitViewer
|
OrbitViewer.py
|
OrbitViewer.py
|
py
| 6,219 |
python
|
en
|
code
| 0 |
github-code
|
6
|
13498241289
|
import numpy as np
from edges import *
def allVertexOneRings(V,F):
E = edges(F)
keys = np.array([])
values = np.array([])
keys = np.append(keys, E[:,0])
keys = np.append(keys, E[:,1])
values = np.append(values, E[:,1])
values = np.append(values, E[:,0])
faceDict = {}
keys = keys.astype(int)
values = values.astype(int)
for ii in xrange(keys.shape[0]):
faceDict.setdefault(keys[ii],[]).append(values[ii])
return faceDict.values() # return type is a list of list
|
oarriaga/PyGPToolbox
|
src/allVertexOneRings.py
|
allVertexOneRings.py
|
py
| 479 |
python
|
en
|
code
| 2 |
github-code
|
6
|
5229315790
|
from django.http import HttpResponsePermanentRedirect, HttpResponseGone
def redirect_to(request, url, convert_funcs=None, **kwargs):
"""
A version of django.views.generic.simple.redirect_to which can handle
argument conversion. The 'convert_funcs' parameter is a dictionary mapping
'kwargs' keys to a function. The 'kwargs' value is run through the function
before the redirect is applied.
Mostly, this is useful for converting a parameter to an int before passing
it back to the redirect for formatting via %02d, for example.
"""
if not url:
return HttpResponseGone()
if convert_funcs:
for name, fn in convert_funcs.items():
if name in kwargs:
kwargs[name] = fn(kwargs[name])
return HttpResponsePermanentRedirect(url % kwargs)
|
gboue/django-util
|
django_util/view_utils.py
|
view_utils.py
|
py
| 819 |
python
|
en
|
code
| 2 |
github-code
|
6
|
2089542339
|
import IMP
import IMP.pmi
import IMP.pmi.macros
import IMP.test
import glob
class Tests(IMP.test.TestCase):
def test_analysis_replica_exchange(self):
try:
import matplotlib
except ImportError:
self.skipTest("no matplotlib package")
if IMP.get_check_level() >= IMP.USAGE_AND_INTERNAL:
self.skipTest("test too slow to run in debug mode")
model=IMP.Model()
sts=sorted(glob.glob(self.get_input_file_name("output_test/stat.0.out").replace(".0.",".*.")))
are=IMP.pmi.macros.AnalysisReplicaExchange(model,sts,10)
ch=IMP.pmi.tools.ColorHierarchy(are.stath1)
are.set_alignment_selection(molecule="Rpb4")
are.save_data()
are.cluster(20)
self.assertEqual(len(are),4)
print(are)
are.refine(40)
print(are)
self.assertEqual(len(are),2)
dcr={"Rpb4":["Rpb4"],"Rpb7":["Rpb7"],"All":["Rpb4","Rpb7"]}
for cluster in are:
are.save_coordinates(cluster)
ch.color_by_resid()
#are.save_coordinates(cluster,rmf_name="resid."+str(cluster.cluster_id)+".rmf3")
are.save_densities(cluster,dcr,prefix="densities_out/")
are.compute_cluster_center(cluster)
are.precision(cluster)
for mol in ["Rpb4","Rpb7"]:
rmsf=are.rmsf(cluster,mol)
rs=[]
rmsfs=[]
for r in rmsf:
rs.append(r)
rmsfs.append(rmsf[r])
IMP.pmi.output.plot_xy_data(rs,rmsfs,out_fn=mol+"."+str(cluster.cluster_id)+".rmsf.pdf")
ch.color_by_uncertainty()
#are.save_coordinates(cluster,rmf_name="beta."+str(cluster.cluster_id)+".rmf3")
ch.get_color_bar("colorbar.pdf")
print(cluster)
#for member in cluster:
# print(member)
are.contact_map(cluster)
for c1 in are:
for c2 in are:
print(c1.cluster_id,c2.cluster_id,are.bipartite_precision(c1,c2))
are.apply_molecular_assignments(1)
are.save_clusters()
# read from data
are=IMP.pmi.macros.AnalysisReplicaExchange(model,"data.pkl")
# read clusters
are.load_clusters("clusters.pkl")
if __name__ == '__main__':
IMP.test.main()
|
salilab/pmi
|
test/medium_test_analysis3.py
|
medium_test_analysis3.py
|
py
| 2,367 |
python
|
en
|
code
| 12 |
github-code
|
6
|
74575078906
|
from __future__ import print_function, unicode_literals
from django.core.urlresolvers import reverse
from cba import components
from cba.base import CBAView
class LinksRoot(components.Group):
def init_components(self):
self.initial_components = [
components.Group(
css_class="ui form container mt",
tag="div",
initial_components=[
components.HTML(tag="h1", content="Links", css_class="mb"),
components.HTML(tag="p", content="A normal, a disabled and hidden link.", css_class="mb"),
components.Link(text="Link 1", href="."),
components.Link(text="Link 2", href=".", disabled=True),
components.Link(text="Link 3", href=".", displayed=False),
]
)
]
class LinksView(CBAView):
root = LinksRoot
|
diefenbach/cba-examples
|
cba_examples/views/links.py
|
links.py
|
py
| 907 |
python
|
en
|
code
| 0 |
github-code
|
6
|
19400757649
|
import os
import sys
import unittest
import logging
from datetime import datetime
import json
from flask import Flask, request
from flask_restful import Resource
import settings as CONST
curpath = os.path.dirname(__file__)
sys.path.append(os.path.abspath(os.path.join (curpath, "../")))
from app_models import Customer
from app_utils import MongoRepository, DbEntity
class CustomerAPI(Resource):
def __init__(self):
#Create and configure logger
logfile= os.path.abspath("{0}/{1}".format(CONST.log_settings["log_folder"], CONST.log_settings["log_file"]))
os.makedirs( os.path.dirname(logfile), exist_ok=True)
logging.basicConfig(
filename=logfile,
format='%(asctime)s %(message)s',
filemode='a'
)
#Creating an object
self.logger=logging.getLogger()
#Setting the threshold of logger to DEBUG
self.logger.setLevel(CONST.log_settings["log_level"])
self.entity = "customers"
self.repo = MongoRepository(logger=self.logger,
server=CONST.db_customer["url"],
port=CONST.db_customer["port"],
database=CONST.db_customer["db"],
collection=self.entity,
session_id=1)
###########################################################################
# GET /customers
# GET /customers/1
def get(self,id=None):
'''
Used to read one records
'''
if id:
msg = 'Processing request to get {0} with id:{1}'.format(self.entity, id)
self.logger.debug(msg)
else:
msg = 'Processing request to get all {0}'.format(self.entity)
self.logger.debug(msg)
try:
if id:
records = self.repo.find_by_id(id)
else:
records = [c for c in self.repo.fetchall()]
return json.dumps(records), 200
except Exception as e:
msg = 'Error in processing GET request.', str(e)
self.logger.error(msg)
return { 'status' : 'error' }, 500
###########################################################################
# POST /customers
def post(self):
'''
Used to create entity
'''
self.logger.debug('Processing POST request')
if not request.data:
msg = "Request to create entity needs to come with form 'data' "
self.logger.error(msg)
return {
'status' : 'error',
'msg' : msg
}, 400
try:
entity = Customer( json=json.loads(request.data) )
wellformed, msg = entity.isValid()
if not wellformed:
self.logger.error(msg)
return {
'status' : 'error',
'msg' : msg
}, 400
result = self.repo.create(entity)
return { 'status' : 'success' }, 200
except Exception as e:
msg = 'Error in processing POST request.', str(e)
self.logger.error(msg)
return { 'status' : 'error' }, 500
###########################################################################
# PUT /customers/id
def put(self, id=None):
'''
Used for update
'''
if (not id) or (not request.data):
msg = "Request to update entity needs to come for a specific entity id and 'data' "
self.logger.error(msg)
return {
'status' : 'error',
'msg' : msg
}, 400
msg = 'Processing request to update entity:{0} with id:{1}'.format(self.entity, id)
try:
entity = Customer( json=json.loads(request.data) )
wellformed, msg = entity.isValid()
if not wellformed:
self.logger.error(msg)
return {
'status' : 'error',
'msg' : msg
}, 400
result = self.repo.update_by_id(id,entity)
return { 'status' : 'success' }, 200
except Exception as e:
msg = 'Error in processing PUT request.', str(e)
self.logger.error(msg)
return { 'status' : 'error' }, 500
###########################################################################
# DELETE /customers/id
def delete(self, id):
'''
Used for update
'''
msg = 'Processing request to delete entity:{0} with id:{1}'.format(self.entity, id)
self.logger.debug(msg)
try:
result = self.repo.delete_by_id(id)
return { 'status' : 'success' }, 200
except Exception as e:
msg = 'Error in processing DELETE request.', str(e)
self.logger.error(msg)
return { 'status' : 'error' }, 500
###########################################################################
###############################################################################
|
bbcCorp/py_microservices
|
src/flask_api_customers/customers.py
|
customers.py
|
py
| 5,316 |
python
|
en
|
code
| 1 |
github-code
|
6
|
37131397687
|
#!/usr/bin/env python
#_*_coding:utf-8_*_
import re
def checkFasta(fastas):
status = True
lenList = set()
for i in fastas:
lenList.add(len(i[1]))
if len(lenList) == 1:
return True
else:
return False
def minSequenceLength(fastas):
minLen = 10000
for i in fastas:
if minLen > len(i[1]):
minLen = len(i[1])
return minLen
def minSequenceLengthWithNormalAA(fastas):
minLen = 10000
for i in fastas:
if minLen > len(re.sub('-', '', i[1])):
minLen = len(re.sub('-', '', i[1]))
return minLen
|
Superzchen/iFeature
|
codes/checkFasta.py
|
checkFasta.py
|
py
| 513 |
python
|
en
|
code
| 152 |
github-code
|
6
|
28493654402
|
from cProfile import label
from tkinter import *
import tkinter as tk
import Calculos as Cal
import numpy as np
def fila_vacia(donde,cuantas,frame,tamaño): #Crear Filas Vacias
for n in range (0,cuantas):
fila = Label(frame,width=tamaño)
fila.grid(column=0, row=donde+n)
def columna_vacia(donde,cuantas,frame,tamano): #Crear Columnas Vacias
for n in range (0,cuantas):
blanco = Label(frame, width=tamano)
blanco.grid(column=donde+n, row=0)
def creacion(): #Creacion De Variables En Masa
for n in range(1,16):
for i in range(0,4):
for j in range(0,4):
globals()["arr"+str(n)+"_" + str(i) + str(j)]=StringVar()
for n in range(2,5):
for i in range(0,6):
for j in range(0,int(12/n)):
globals()["jaco" + str(n-1) + "_" + str(i) + str(j)]=StringVar()
def matrices(m,f,k,frame): #Creación Matrices Cinemática Directa
for r in range(0, 4):
for c in range(0, 4):
cell = tk.Label(frame, width=11, textvariable=globals()["arr" + str(m) + "_" + str(r) + str(c)], bg='white')
cell.grid(row=r+f, column=c+k,ipady=3)
def matrices_J(m,grados,frame,f,k): #Creación Matrices Jacobianos
for r in range(0, 6):
for c in range(0, grados):
cell = Entry(frame, width=12, textvariable=globals()["jaco" + str(m) +"_" + str(r) + str(c)], state= DISABLED)
cell.grid(row=r+f, column=c+k, ipady=4)
def llenado (matri,M,K): #Llenado Matrices
for n in range(M,K):
for i in range(0,4):
for j in range(0,4):
globals()["arr"+ str(n) +"_" + str(i) + str(j)].set(matri[1][n-M][i][j])
globals()["arr"+ str(K) +"_"+ str(i) + str(j)].set(matri[0][i][j])
def llenado_JACO (JA,JS,JR): #Llenado Matrices JACO
for n in range (3,5):
s=n-1
if (s==1):
J=JR
elif (s==2):
J=JS
elif (s==3):
J=JA
for i in range(0,2):
i=i*3
for j in range(0,int(12/n)):
for k in range(0,3):
globals()["jaco" + str(n-1) +"_" + str(i+k) + str(j)].set(J[i-2][j][k])
def Perfil(tipo,mani,codo,tf,xi,yi,zi,xf,yf,zf,resol,var): #Determinar el tipo de Perfil A Utilizar
if tipo==1: #Perfil Cuadratico
Qs=Manipulador(mani,codo,xi,yi,zi,xf,yf,zf)
perfiles=Cal.Perf_Cuadra(tf,resol,Qs[0],Qs[1])
elif tipo==2: #Perfil Trapezoidal Tipo I
Qs=Manipulador(mani,codo,xi,yi,zi,xf,yf,zf)
perfiles=Cal.Perf_Trape(tf,resol,Qs[0],Qs[1],var,1)
else: #Perfil Trapezoidal Tipo II
Qs=Manipulador(mani,codo,xi,yi,zi,xf,yf,zf)
perfiles=Cal.Perf_Trape(tf,resol,Qs[0],Qs[1],var,2)
return perfiles
def Manipulador(manipu,cod,Pxi,Pyi,Pzi,Pxf,Pyf,Pzf): #Determina el Manipulador a Utilizar
if manipu==1:
Inversai=Cal.IK_Scara_P3R(Pxi,Pyi,Pzi) #Cinematica Inversa para Punto Inicial
Inversaf=Cal.IK_Scara_P3R(Pxf,Pyf,Pzf) #Cinematica Inversa para Punto Final
Junturas=Solucion(cod,Inversai,Inversaf)
else:
Inversai=Cal.IK_Antropo_3R(Pxi,Pyi,Pzi) #Cinematica Inversa para Punto Inicial
Inversaf=Cal.IK_Antropo_3R(Pxf,Pyf,Pzf) #Cinematica Inversa para Punto Final
Junturas=Solucion(cod,Inversai,Inversaf)
return Junturas
def Solucion(sol,Ini,Fin): #Determina la Solución a utilizar (Codo Arriba o Codo Abajo)
if sol==1: #Codo Abajo
Qi=[Ini[0],Ini[1],Ini[2]] #Toma los valores de las junturas iniciales para Codo Abajo
Qf=[Fin[0],Fin[1],Fin[2]] #Toma los valores de las junturas finales para Codo Abajo
else: #Codo Arriba
Qi=[Ini[0],Ini[3],Ini[4]] #Toma los valores de las junturas iniciales para Codo Arriba
Qf=[Fin[0],Fin[3],Fin[4]] #Toma los valores de las junturas finales para Codo Arriba
return Qi,Qf
def Signo(x): #Determina El signo del numero
if x>=0:
sgn=1
else:
sgn=-1
return sgn
def prueba():
exec(open("sera.py").read())
#prueba()
|
daridel99/UMNG-robotica
|
Funciones.py
|
Funciones.py
|
py
| 4,155 |
python
|
es
|
code
| 0 |
github-code
|
6
|
71091610109
|
root_path = '/mnt/d/KLTN/CNN-Based-Image-Inpainting/'
train_glob = root_path + 'dataset/places2/train/*/*/*.jpg'
test_glob = root_path + 'dataset/places2/test/*.jpg'
mask_glob = root_path + 'dataset/irregular_mask1/*.png' #2 for partialconv
log_dir = root_path + 'training_logs'
save_dir = root_path + 'models'
checkpoint_path = root_path + "models/gatedconv.pth"
learning_rate = 1e-4 #5e-4 for gated conv
epoch = 50
train_batch_size = 4
test_batch_size = 4
log_interval = -1 #no log
import os
import torch
from dataloader.dataset import *
from gatedconvworker.gatedconvworker import GatedConvWorker
print("Creating output directories")
if not os.path.exists(save_dir):
os.makedirs(save_dir)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
print("Initiating training sequence")
torch.cuda.empty_cache()
print("Initializing dataset with globs:", train_glob, test_glob, mask_glob)
data_train = Dataset(train_glob, mask_glob, False)
data_test = Dataset(test_glob, mask_glob, False)
worker = GatedConvWorker(checkpoint_path, learning_rate)
worker.Train(epoch, train_batch_size, test_batch_size, data_train, data_test, log_interval)
|
realphamanhtuan/CNN-Based-Image-Inpainting
|
traingatedconv.py
|
traingatedconv.py
|
py
| 1,142 |
python
|
en
|
code
| 0 |
github-code
|
6
|
26238944709
|
# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function, division
import errno
import json
import os.path
import sys
from sopel.tools import Identifier
from sqlalchemy import create_engine, Column, ForeignKey, Integer, String
from sqlalchemy.engine.url import URL
from sqlalchemy.exc import OperationalError, SQLAlchemyError
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
if sys.version_info.major >= 3:
unicode = str
basestring = str
def _deserialize(value):
if value is None:
return None
# sqlite likes to return ints for strings that look like ints, even though
# the column type is string. That's how you do dynamic typing wrong.
value = unicode(value)
# Just in case someone's mucking with the DB in a way we can't account for,
# ignore json parsing errors
try:
value = json.loads(value)
except ValueError:
pass
return value
BASE = declarative_base()
MYSQL_TABLE_ARGS = {'mysql_engine': 'InnoDB',
'mysql_charset': 'utf8mb4',
'mysql_collate': 'utf8mb4_unicode_ci'}
class NickIDs(BASE):
"""
NickIDs SQLAlchemy Class
"""
__tablename__ = 'nick_ids'
nick_id = Column(Integer, primary_key=True)
class Nicknames(BASE):
"""
Nicknames SQLAlchemy Class
"""
__tablename__ = 'nicknames'
__table_args__ = MYSQL_TABLE_ARGS
nick_id = Column(Integer, ForeignKey('nick_ids.nick_id'), primary_key=True)
slug = Column(String(255), primary_key=True)
canonical = Column(String(255))
class NickValues(BASE):
"""
NickValues SQLAlchemy Class
"""
__tablename__ = 'nick_values'
__table_args__ = MYSQL_TABLE_ARGS
nick_id = Column(Integer, ForeignKey('nick_ids.nick_id'), primary_key=True)
key = Column(String(255), primary_key=True)
value = Column(String(255))
class ChannelValues(BASE):
"""
ChannelValues SQLAlchemy Class
"""
__tablename__ = 'channel_values'
__table_args__ = MYSQL_TABLE_ARGS
channel = Column(String(255), primary_key=True)
key = Column(String(255), primary_key=True)
value = Column(String(255))
class PluginValues(BASE):
"""
PluginValues SQLAlchemy Class
"""
__tablename__ = 'plugin_values'
__table_args__ = MYSQL_TABLE_ARGS
plugin = Column(String(255), primary_key=True)
key = Column(String(255), primary_key=True)
value = Column(String(255))
class SopelDB(object):
"""*Availability: 5.0+*
This defines an interface for basic, common operations on a sqlite
database. It simplifies those common operations, and allows direct access
to the database, wherever the user has configured it to be.
When configured with a relative filename, it is assumed to be in the directory
set (or defaulted to) in the core setting ``homedir``.
"""
def __init__(self, config):
# MySQL - mysql://username:password@localhost/db
# SQLite - sqlite:////home/sopel/.sopel/default.db
db_type = config.core.db_type
# Handle SQLite explicitly as a default
if db_type == 'sqlite':
path = config.core.db_filename
if path is None:
path = os.path.join(config.core.homedir, config.basename + '.db')
path = os.path.expanduser(path)
if not os.path.isabs(path):
path = os.path.normpath(os.path.join(config.core.homedir, path))
if not os.path.isdir(os.path.dirname(path)):
raise OSError(
errno.ENOENT,
'Cannot create database file. '
'No such directory: "{}". Check that configuration setting '
'core.db_filename is valid'.format(os.path.dirname(path)),
path
)
self.filename = path
self.url = 'sqlite:///%s' % path
# Otherwise, handle all other database engines
else:
query = {}
if db_type == 'mysql':
drivername = config.core.db_driver or 'mysql'
query = {'charset': 'utf8mb4'}
elif db_type == 'postgres':
drivername = config.core.db_driver or 'postgresql'
elif db_type == 'oracle':
drivername = config.core.db_driver or 'oracle'
elif db_type == 'mssql':
drivername = config.core.db_driver or 'mssql+pymssql'
elif db_type == 'firebird':
drivername = config.core.db_driver or 'firebird+fdb'
elif db_type == 'sybase':
drivername = config.core.db_driver or 'sybase+pysybase'
else:
raise Exception('Unknown db_type')
db_user = config.core.db_user
db_pass = config.core.db_pass
db_host = config.core.db_host
db_port = config.core.db_port # Optional
db_name = config.core.db_name # Optional, depending on DB
# Ensure we have all our variables defined
if db_user is None or db_pass is None or db_host is None:
raise Exception('Please make sure the following core '
'configuration values are defined: '
'db_user, db_pass, db_host')
self.url = URL(drivername=drivername, username=db_user,
password=db_pass, host=db_host, port=db_port,
database=db_name, query=query)
self.engine = create_engine(self.url)
# Catch any errors connecting to database
try:
self.engine.connect()
except OperationalError:
print("OperationalError: Unable to connect to database.")
raise
# Create our tables
BASE.metadata.create_all(self.engine)
self.ssession = scoped_session(sessionmaker(bind=self.engine))
def connect(self):
"""Return a raw database connection object."""
return self.engine.connect()
def execute(self, *args, **kwargs):
"""Execute an arbitrary SQL query against the database.
Returns a cursor object, on which things like `.fetchall()` can be
called per PEP 249."""
with self.connect() as conn:
return conn.execute(*args, **kwargs)
def get_uri(self):
"""Returns a URL for the database, usable to connect with SQLAlchemy."""
return 'sqlite:///{}'.format(self.filename)
# NICK FUNCTIONS
def get_nick_id(self, nick, create=True):
"""Return the internal identifier for a given nick.
This identifier is unique to a user, and shared across all of that
user's aliases. If create is True, a new ID will be created if one does
not already exist"""
session = self.ssession()
slug = nick.lower()
try:
nickname = session.query(Nicknames) \
.filter(Nicknames.slug == slug) \
.one_or_none()
if nickname is None:
if not create:
raise ValueError('No ID exists for the given nick')
# Generate a new ID
nick_id = NickIDs()
session.add(nick_id)
session.commit()
# Create a new Nickname
nickname = Nicknames(nick_id=nick_id.nick_id, slug=slug, canonical=nick)
session.add(nickname)
session.commit()
return nickname.nick_id
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def alias_nick(self, nick, alias):
"""Create an alias for a nick.
Raises ValueError if the alias already exists. If nick does not already
exist, it will be added along with the alias."""
nick = Identifier(nick)
alias = Identifier(alias)
nick_id = self.get_nick_id(nick)
session = self.ssession()
try:
result = session.query(Nicknames) \
.filter(Nicknames.slug == alias.lower()) \
.filter(Nicknames.canonical == alias) \
.one_or_none()
if result:
raise ValueError('Given alias is the only entry in its group.')
nickname = Nicknames(nick_id=nick_id, slug=alias.lower(), canonical=alias)
session.add(nickname)
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def set_nick_value(self, nick, key, value):
"""Sets the value for a given key to be associated with the nick."""
nick = Identifier(nick)
value = json.dumps(value, ensure_ascii=False)
nick_id = self.get_nick_id(nick)
session = self.ssession()
try:
result = session.query(NickValues) \
.filter(NickValues.nick_id == nick_id) \
.filter(NickValues.key == key) \
.one_or_none()
# NickValue exists, update
if result:
result.value = value
session.commit()
# DNE - Insert
else:
new_nickvalue = NickValues(nick_id=nick_id, key=key, value=value)
session.add(new_nickvalue)
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def delete_nick_value(self, nick, key):
"""Deletes the value for a given key associated with a nick."""
nick = Identifier(nick)
nick_id = self.get_nick_id(nick)
session = self.ssession()
try:
result = session.query(NickValues) \
.filter(NickValues.nick_id == nick_id) \
.filter(NickValues.key == key) \
.one_or_none()
# NickValue exists, delete
if result:
session.delete(result)
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def get_nick_value(self, nick, key):
"""Retrieves the value for a given key associated with a nick."""
nick = Identifier(nick)
session = self.ssession()
try:
result = session.query(NickValues) \
.filter(Nicknames.nick_id == NickValues.nick_id) \
.filter(Nicknames.slug == nick.lower()) \
.filter(NickValues.key == key) \
.one_or_none()
if result is not None:
result = result.value
return _deserialize(result)
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def unalias_nick(self, alias):
"""Removes an alias.
Raises ValueError if there is not at least one other nick in the group.
To delete an entire group, use `delete_group`.
"""
alias = Identifier(alias)
nick_id = self.get_nick_id(alias, False)
session = self.ssession()
try:
count = session.query(Nicknames) \
.filter(Nicknames.nick_id == nick_id) \
.count()
if count <= 1:
raise ValueError('Given alias is the only entry in its group.')
session.query(Nicknames).filter(Nicknames.slug == alias.lower()).delete()
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def delete_nick_group(self, nick):
"""Removes a nickname, and all associated aliases and settings."""
nick = Identifier(nick)
nick_id = self.get_nick_id(nick, False)
session = self.ssession()
try:
session.query(Nicknames).filter(Nicknames.nick_id == nick_id).delete()
session.query(NickValues).filter(NickValues.nick_id == nick_id).delete()
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def merge_nick_groups(self, first_nick, second_nick):
"""Merges the nick groups for the specified nicks.
Takes two nicks, which may or may not be registered. Unregistered
nicks will be registered. Keys which are set for only one of the given
nicks will be preserved. Where multiple nicks have values for a given
key, the value set for the first nick will be used.
Note that merging of data only applies to the native key-value store.
If modules define their own tables which rely on the nick table, they
will need to have their merging done separately."""
first_id = self.get_nick_id(Identifier(first_nick))
second_id = self.get_nick_id(Identifier(second_nick))
session = self.ssession()
try:
# Get second_id's values
res = session.query(NickValues).filter(NickValues.nick_id == second_id).all()
# Update first_id with second_id values if first_id doesn't have that key
for row in res:
first_res = session.query(NickValues) \
.filter(NickValues.nick_id == first_id) \
.filter(NickValues.key == row.key) \
.one_or_none()
if not first_res:
self.set_nick_value(first_nick, row.key, _deserialize(row.value))
session.query(NickValues).filter(NickValues.nick_id == second_id).delete()
session.query(Nicknames) \
.filter(Nicknames.nick_id == second_id) \
.update({'nick_id': first_id})
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
# CHANNEL FUNCTIONS
def set_channel_value(self, channel, key, value):
"""Sets the value for a given key to be associated with the channel."""
channel = Identifier(channel).lower()
value = json.dumps(value, ensure_ascii=False)
session = self.ssession()
try:
result = session.query(ChannelValues) \
.filter(ChannelValues.channel == channel)\
.filter(ChannelValues.key == key) \
.one_or_none()
# ChannelValue exists, update
if result:
result.value = value
session.commit()
# DNE - Insert
else:
new_channelvalue = ChannelValues(channel=channel, key=key, value=value)
session.add(new_channelvalue)
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def delete_channel_value(self, channel, key):
"""Deletes the value for a given key associated with a channel."""
channel = Identifier(channel).lower()
session = self.ssession()
try:
result = session.query(ChannelValues) \
.filter(ChannelValues.channel == channel)\
.filter(ChannelValues.key == key) \
.one_or_none()
# ChannelValue exists, delete
if result:
session.delete(result)
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def get_channel_value(self, channel, key):
"""Retrieves the value for a given key associated with a channel."""
channel = Identifier(channel).lower()
session = self.ssession()
try:
result = session.query(ChannelValues) \
.filter(ChannelValues.channel == channel)\
.filter(ChannelValues.key == key) \
.one_or_none()
if result is not None:
result = result.value
return _deserialize(result)
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
# PLUGIN FUNCTIONS
def set_plugin_value(self, plugin, key, value):
"""Sets the value for a given key to be associated with a plugin."""
plugin = plugin.lower()
value = json.dumps(value, ensure_ascii=False)
session = self.ssession()
try:
result = session.query(PluginValues) \
.filter(PluginValues.plugin == plugin)\
.filter(PluginValues.key == key) \
.one_or_none()
# PluginValue exists, update
if result:
result.value = value
session.commit()
# DNE - Insert
else:
new_pluginvalue = PluginValues(plugin=plugin, key=key, value=value)
session.add(new_pluginvalue)
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def delete_plugin_value(self, plugin, key):
"""Deletes the value for a given key associated with a plugin."""
plugin = plugin.lower()
session = self.ssession()
try:
result = session.query(PluginValues) \
.filter(PluginValues.plugin == plugin)\
.filter(PluginValues.key == key) \
.one_or_none()
# PluginValue exists, update
if result:
session.delete(result)
session.commit()
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
def get_plugin_value(self, plugin, key):
"""Retrieves the value for a given key associated with a plugin."""
plugin = plugin.lower()
session = self.ssession()
try:
result = session.query(PluginValues) \
.filter(PluginValues.plugin == plugin)\
.filter(PluginValues.key == key) \
.one_or_none()
if result is not None:
result = result.value
return _deserialize(result)
except SQLAlchemyError:
session.rollback()
raise
finally:
session.close()
# NICK AND CHANNEL FUNCTIONS
def get_nick_or_channel_value(self, name, key):
"""Gets the value `key` associated to the nick or channel `name`."""
name = Identifier(name)
if name.is_nick():
return self.get_nick_value(name, key)
else:
return self.get_channel_value(name, key)
def get_preferred_value(self, names, key):
"""Gets the value for the first name which has it set.
`names` is a list of channel and/or user names. Returns None if none of
the names have the key set."""
for name in names:
value = self.get_nick_or_channel_value(name, key)
if value is not None:
return value
|
examknow/Exambot-Source
|
sopel/db.py
|
db.py
|
py
| 19,385 |
python
|
en
|
code
| 2 |
github-code
|
6
|
22997884829
|
_base_ = [
'../../_base_/models/faster_rcnn_r50_fpn.py',
'../../_base_/datasets/waymo_detection_1280x1920.py',
'../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py'
]
# model
model = dict(
rpn_head=dict(
anchor_generator=dict(
type='AnchorGenerator',
scales=[3],
ratios=[0.5, 1.0, 2.0],
strides=[4, 8, 16, 32, 64]),),
roi_head=dict(
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0),
out_channels=256,
featmap_strides=[4, 8, 16, 32],
finest_scale=19),
bbox_head=dict(num_classes=3))
)
# data
data = dict(samples_per_gpu=4)
# lr is set for a batch size of 8
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[8, 11])
runner = dict(type='EpochBasedRunner', max_epochs=12)
# load_from = 'https://open-mmlab.s3.ap-northeast-2.amazonaws.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_2x_coco/faster_rcnn_r50_fpn_2x_coco_bbox_mAP-0.384_20200504_210434-a5d8aa15.pth' # noqa
resume_from = 'saved_models/study/faster_rcnn_r50_fpn_fp16_4x2_1x_1280x1920_improved/epoch_10.pth'
# fp16 settings
fp16 = dict(loss_scale=512.)
|
carranza96/waymo-detection-fusion
|
configs/waymo_open/study/faster_rcnn_r50_fpn_fp16_4x2_1x_1280x1920_redanchors.py
|
faster_rcnn_r50_fpn_fp16_4x2_1x_1280x1920_redanchors.py
|
py
| 1,460 |
python
|
en
|
code
| 0 |
github-code
|
6
|
25040767672
|
# 인하은행에는 ATM이 1대밖에 없다. 지금 이 ATM앞에 N명의 사람들이 줄을 서있다.
# 사람은 1번부터 N번까지 번호가 매겨져 있으며, i번 사람이 돈을 인출하는데 걸리는 시간은 Pi분이다.
# 사람들이 줄을 서는 순서에 따라서, 돈을 인출하는데 필요한 시간의 합이 달라지게 된다.
# 예를 들어, 총 5명이 있고, P1 = 3, P2 = 1, P3 = 4, P4 = 3, P5 = 2 인 경우를 생각해보자. [1, 2, 3, 4, 5] 순서로 줄을 선다면,
# 1번 사람은 3분만에 돈을 뽑을 수 있다. 2번 사람은 1번 사람이 돈을 뽑을 때 까지 기다려야 하기 때문에, 3+1 = 4분이 걸리게 된다.
# 3번 사람은 1번, 2번 사람이 돈을 뽑을 때까지 기다려야 하기 때문에, 총 3+1+4 = 8분이 필요하게 된다. 4번 사람은 3+1+4+3 = 11분, 5번 사람은 3+1+4+3+2 = 13분이 걸리게 된다.
# 이 경우에 각 사람이 돈을 인출하는데 필요한 시간의 합은 3+4+8+11+13 = 39분이 된다.
# 줄을 [2, 5, 1, 4, 3] 순서로 줄을 서면, 2번 사람은 1분만에, 5번 사람은 1+2 = 3분, 1번 사람은 1+2+3 = 6분, 4번 사람은 1+2+3+3 = 9분, 3번 사람은 1+2+3+3+4 = 13분이 걸리게 된다.
# 각 사람이 돈을 인출하는데 필요한 시간의 합은 1+3+6+9+13 = 32분이다.
# 이 방법보다 더 필요한 시간의 합을 최소로 만들 수는 없다.
# 줄을 서 있는 사람의 수 N과 각 사람이 돈을 인출하는데 걸리는 시간 Pi가 주어졌을 때, 각 사람이 돈을 인출하는데 필요한 시간의 합의 최솟값을 구하는 프로그램을 작성하시오.
import sys
n = int(input())
a = list(map(int, sys.stdin.readline().split()))
# 가장 시간이 덜 드는 사람부터 오도록 정렬하고, 각 사람별로 걸리는 시간들을 합에 넣어주면 된다.
answer = 0
each_time = 0
person_list = sorted(a)
for i in range(len(person_list)):
# n번째 사람은 1번째 사람의 시간에서 n번째 사람의 시간들을 모두 더한 시간이 걸린다.
each_time += person_list[i]
# 걸린 시간을 추가해 준다.
answer += each_time
print(answer)
|
pnu-k-digital-2/pnu-k-digital-training-2023-2-coding-test-study
|
sangwook/Week1_그리디알고리즘/ATM.py
|
ATM.py
|
py
| 2,183 |
python
|
ko
|
code
| 0 |
github-code
|
6
|
4869208113
|
import socket
import select
import sys
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if len(sys.argv) != 3:
print ("Print in the following order : script, IP address, port number")
exit()
IP_address = str(sys.argv[1])
Port = int(sys.argv[2])
client_socket.connect((IP_address, Port))
while True:
sockets_list = [sys.stdin, client_socket]
read_sockets,write_socket, error_socket = select.select(sockets_list,[],[])
for socks in read_sockets:
if socks == client_socket:
message = socks.recv(1024)
print (message)
else:
message = sys.stdin.readline()
client_socket.send(message.encode('utf-8'))
sys.stdout.flush()
client_socket.close()
sys.exit()
|
asyranasyran/GROUP-PROJECT
|
client.py
|
client.py
|
py
| 764 |
python
|
en
|
code
| 0 |
github-code
|
6
|
71839381629
|
# coding=utf-8
from __future__ import print_function
from ActionSpace import settings
from om.util import update_from_salt, syn_data_outside, fmt_salt_out, check_computer
from om.models import CallLog
from django.contrib.auth.models import User, AnonymousUser
from om.proxy import Salt
from channels.generic.websockets import JsonWebsocketConsumer
from om.models import SaltMinion
from utils.util import CheckFireWall
import traceback
import re
class OmConsumer(JsonWebsocketConsumer):
http_user = True
def raw_connect(self, message, **kwargs):
user = 'unknown'
# noinspection PyBroadException
try:
not_login_user = User.objects.get_or_create(username='not_login_yet', is_active=False)[0]
user = not_login_user if isinstance(message.user, AnonymousUser) else message.user
except Exception as e:
settings.logger.error(repr(e))
CallLog.objects.create(
user=user,
type='message',
action=message['path'],
detail=message.content
)
settings.logger.info('recv_data:{data}'.format(data=message.content, path=message['path']))
super(OmConsumer, self).raw_connect(message, **kwargs)
def receive(self, content, **kwargs):
try:
CallLog.objects.create(
user=User.objects.get(username=self.message.user.username),
type='message',
action=self.message['path'],
detail=self.message.content
)
except Exception as e:
settings.logger.error(repr(e))
try:
settings.logger.error(self.message.user.username)
except Exception as e:
settings.logger.error(repr(e))
settings.logger.info('recv_data:{data}'.format(data=content, path=self.message['path']))
super(OmConsumer, self).receive(content, **kwargs)
class SaltConsumer(OmConsumer):
def receive(self, content, **kwargs):
super(SaltConsumer, self).receive(content, **kwargs)
if not self.message.user.is_authenticated:
self.send({'result': '未授权,请联系管理员!'})
return
if not self.message.user.is_superuser:
self.send({'result': '仅管理员有权限执行该操作!'})
return
info = content.get('info', '')
if info == 'refresh-server':
update_from_salt(None if settings.OM_ENV == 'PRD' else 'UAT')
self.send({'result': 'Y', 'info': 'refresh-server'})
elif info == 'check_computer':
self.send({'return': check_computer(), 'info': 'check_computer'})
else:
self.send({'result': '未知操作!'})
class ServerConsumer(OmConsumer):
def receive(self, content, **kwargs):
super(ServerConsumer, self).receive(content, **kwargs)
if not self.message.user.is_authenticated:
self.send({'result': '未授权,请联系管理员!'})
return
if not self.message.user.is_superuser:
self.send({'result': '仅管理员有权限执行该操作!'})
return
if content.get('info', None) != 'syn_data_outside':
self.send({'result': '未知操作!'})
return
syn_data_outside()
self.send({'result': 'Y'})
class ActionDetailConsumer(OmConsumer):
group_prefix = 'action_detail-'
yes = {"result": 'Y'}
no = {"result": 'N'}
def label(self):
reg = r'^/om/action_detail/(?P<task_id>[0-9]+)/$'
task_id = re.search(reg, self.message['path']).group('task_id')
return f'{self.group_prefix}{task_id}'
def connection_groups(self, **kwargs):
return self.groups or [self.label()]
def receive(self, content, **kwargs):
super(ActionDetailConsumer, self).receive(content, **kwargs)
if not self.message.user.is_authenticated:
self.send({'result': '未授权,请联系管理员!'})
return
self.group_send(self.label(), self.yes)
@classmethod
def task_change(cls, task_id):
settings.logger.info(f'{cls.group_prefix}{task_id}')
ActionDetailConsumer.group_send(f'{cls.group_prefix}{task_id}', cls.yes)
class UnlockWinConsumer(OmConsumer):
def receive(self, content, **kwargs):
super(UnlockWinConsumer, self).receive(content, **kwargs)
if not self.message.user.is_authenticated:
self.send({'result': '未授权,请联系管理员!'})
return
user = content.get('user', None)
server_info = content.get('server_info', None)
if not all([user, server_info]) or not all([user.strip(), server_info]):
self.send({'result': '参数选择错误,请检查!'})
agents = [x['name'] for x in server_info]
if settings.OM_ENV == 'PRD': # 只有生产环境可以双通
prd_agents = list(SaltMinion.objects.filter(name__in=agents, env='PRD', os='Windows').values_list('name', flat=True))
settings.logger.info('prd_agents:{ag}'.format(ag=repr(prd_agents)))
uat_agents = list(SaltMinion.objects.exclude(env='PRD').filter(name__in=agents, os='Windows').values_list('name', flat=True))
settings.logger.info('uat_agents:{ag}'.format(ag=repr(uat_agents)))
if len(prd_agents) > 0:
prd_result, prd_output = Salt('PRD').shell(prd_agents, f'net user {user} /active:yes')
else:
prd_result, prd_output = True, ''
if len(uat_agents) > 0:
uat_result, uat_output = Salt('UAT').shell(uat_agents, f'net user {user} /active:yes')
else:
uat_result, uat_output = True, ''
salt_result = prd_result and uat_result
salt_output = fmt_salt_out('{prd}\n{uat}'.format(prd=fmt_salt_out(prd_output), uat=fmt_salt_out(uat_output)))
else:
agents = list(SaltMinion.objects.exclude(env='PRD').filter(name__in=agents, os='Windows').values_list('name', flat=True))
settings.logger.info('agents:{ag}'.format(ag=repr(agents)))
if len(agents) > 0:
salt_result, salt_output = Salt('UAT').shell(agents, 'net user {user} /active:yes'.format(user=user))
else:
salt_result, salt_output = True, ''
salt_output = fmt_salt_out(salt_output)
if salt_result:
settings.logger.info('unlock success!')
result = salt_output.replace('The command completed successfully', '解锁成功')
result = result.replace('[{}]', '选中的机器不支持解锁,请联系基础架构同事解锁!')
self.send({"result": result})
else:
settings.logger.info('unlock false for salt return false')
self.send({"result": '解锁失败!'})
class CmdConsumer(OmConsumer):
# noinspection PyBroadException
def receive(self, content, **kwargs):
super(CmdConsumer, self).receive(content, **kwargs)
if not self.message.user.is_authenticated:
self.send({'result': '未授权,请联系管理员!'})
return
name = content.get('name', '').strip()
cmd = content.get('cmd', '').strip()
user = content.get('user', '').strip()
if not all([name, cmd, user]):
self.send({'result': '参数错误!'})
return
try:
pc = SaltMinion.objects.get(name=name, status='up')
if not any(
[self.message.user.has_perm('om.can_exec_cmd'),
self.message.user.has_perm('om.can_exec_cmd', pc)]
):
self.send({'result': '没有执行命令权限,请联系管理员!'})
return
if not any([self.message.user.has_perm('om.can_root'), self.message.user.has_perm('om.can_root', pc)]):
if user == 'root':
self.send({'result': '没有root权限,请联系管理员!'})
return
_, back = Salt(pc.env).shell(pc.name, cmd, None if user == 'NA' else user)
self.send({'result': back['return'][0].get(name, '未知结果!')})
except Exception as e:
self.send({'result': f"{e}\n{content}"})
class MakeFireWallConsumer(OmConsumer):
# noinspection PyBroadException
def receive(self, content, **kwargs):
super(MakeFireWallConsumer, self).receive(content, **kwargs)
if not self.message.user.is_authenticated:
self.send({'result': '未授权,请联系管理员!'})
return
s_ip = content.get('s_ip', '').strip()
t_ip = content.get('t_ip', '').strip()
port = content.get('port', '').strip()
if not all([s_ip, t_ip, port]):
self.send({'result': '参数错误!'})
return
s_ip = s_ip.replace('<pre>', '').replace('</pre>', '').split('<br>')
t_ip = t_ip.replace('<pre>', '').replace('</pre>', '').split('<br>')
port = port.replace('<pre>', '').replace('</pre>', '').split('<br>')
try:
src_ag = [SaltMinion.objects.get(name__endswith='-'+x) for x in s_ip]
dst_ag = [SaltMinion.objects.get(name__endswith='-'+x) for x in t_ip]
result = []
for p in port:
cf = CheckFireWall(src_ag, dst_ag, int(p))
result.append(cf.check())
# self.message.reply_channel.send({'text': json.dumps(result)}, immediately=True)
self.send(result)
except Exception as e:
if self.message.user.is_superuser:
self.send({'result': f"{e}\n{traceback.format_exc()}\n{content}"})
else:
self.send({'result': 'error'})
class CheckFireWallConsumer(OmConsumer):
def check_port(self, src_list, dst_list, port):
result = []
for p in port:
cf = CheckFireWall(src_list, dst_list, int(p))
result.append(cf.check())
self.send(result)
def check_policy(self, src_list, dst_list, port):
from utils.util import FireWallPolicy
src = ';'.join([x.ip() for x in src_list])
dst = ';'.join([x.ip() for x in dst_list])
srv = ','.join([f'tcp/{x}' for x in port])
self.send({
'src': [x.ip() for x in src_list],
'dst': [x.ip() for x in dst_list],
'port': port,
'protocol': 'TCP',
'result': FireWallPolicy(src, dst, srv).check()
})
def receive(self, content, **kwargs):
super(CheckFireWallConsumer, self).receive(content, **kwargs)
if not self.message.user.is_authenticated:
self.send({'result': '未授权,请联系管理员!'})
return
check_type = content.get('check_type', '')
src = content.get('src', [])
dst = content.get('dst', [])
port = [int(x) for x in re.split(r'\W+', content.get('port', [''])[0]) if x.strip() != '']
try:
if all([src, dst, port]):
src_list = [x for x in SaltMinion.objects.filter(pk__in=src)]
dst_list = [x for x in SaltMinion.objects.filter(pk__in=dst)]
if all([src_list, dst_list]):
if check_type == 'port':
self.check_port(src_list, dst_list, port)
elif check_type == 'policy':
self.check_policy(src_list, dst_list, port)
else:
self.send({'result': '类型错误'})
except Exception as e:
settings.logger.error(repr(e))
if self.message.user.is_superuser:
self.send({'result': f"{e}\n{traceback.format_exc()}\n{content}"})
else:
self.send({'result': '执行报错,请联系管理员检查!'})
om_routing = [
SaltConsumer.as_route(path=r"^/om/salt_status/"),
ActionDetailConsumer.as_route(path=r"^/om/action_detail/", attrs={'group_prefix': 'action_detail-'}),
UnlockWinConsumer.as_route(path=r"^/om/unlock_win/"),
CmdConsumer.as_route(path=r'^/om/admin_action/'),
MakeFireWallConsumer.as_route(path=r'^/utils/make_firewall_table/'),
CheckFireWallConsumer.as_route(path=r'^/utils/check_firewall/'),
ServerConsumer.as_route(path=r'^/om/show_server/')
]
|
cash2one/ActionSpace
|
om/worker.py
|
worker.py
|
py
| 12,465 |
python
|
en
|
code
| 0 |
github-code
|
6
|
41996577461
|
import socket
TCP_IP = '0.0.0.0'
TCP_PORT = 5
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print("connection addr: {}".format(addr))
while True:
data = conn.recv(1)
print("recieved data: {}".format(data))
conn.send(data)
conn.close()
|
Pgovalle/Proyecto_lab_control
|
Proyecto_redes/Photon/Codigo_Ejemplo/sockets/sockkk/server.py
|
server.py
|
py
| 311 |
python
|
en
|
code
| 0 |
github-code
|
6
|
23500788401
|
from alipy.index import IndexCollection
from alipy.experiment import State
from alipy.data_manipulate import split
from sklearn.preprocessing import StandardScaler
def cancel_step(select_ind, lab, unlab):
lab = IndexCollection(lab)
unlab = IndexCollection(unlab)
unlab.update(select_ind)
lab.difference_update(select_ind)
lab_list, unlab_list = [], []
for i in lab:
lab_list.append(i)
for i in unlab:
unlab_list.append(i)
return lab_list, unlab_list
def update(select_ind, lab, unlab):
lab = IndexCollection(lab)
unlab = IndexCollection(unlab)
lab.update(select_ind)
unlab.difference_update(select_ind)
lab_list, unlab_list = [],[]
for i in lab:
lab_list.append(i)
for i in unlab:
unlab_list.append(i)
return lab_list, unlab_list
def save_state(data, select_ind, current_ac):
quried_label = data.loc[select_ind,['target']]
st = State(select_ind,current_ac,queried_label=quried_label)
return st
def separate(data):
if 'start' or 'end' in data.columns:
data = data.drop(columns=['start', 'end'])
if 'video' in data.columns:
data = data.drop(columns=['video'])
if 'color' in data.columns:
data = data.drop(columns=['color'])
y = labels = data['target']
features = data.drop(columns=['target'])
X = features = StandardScaler().fit_transform(features)
train, test, lab, unlab = split(X, y, test_ratio=0.3, initial_label_rate=0.2, split_count=1, all_class=True,
saving_path='.')
train_list, test_list, lab_list, unlab_list = [] , [] ,[] ,[]
for i in train[0]:
train_list.append(i)
for i in test[0]:
test_list.append(i)
for i in lab[0]:
lab_list.append(i)
for i in unlab[0]:
unlab_list.append(i)
return X[lab_list], y[lab_list]
|
weiweian1996/VERSION2.0
|
GUI/Function/index_handle.py
|
index_handle.py
|
py
| 1,941 |
python
|
en
|
code
| 0 |
github-code
|
6
|
1121085852
|
'''
https://programmers.co.kr/learn/courses/30/lessons/42577?language=python3#
전화번호 목록 - 해시
'''
def solution(phoneBook):
phoneBook = list(map(str,sorted(map(int,phoneBook))))
#phoneBook = sorted(list(set(phoneBook)), key=lambda x :len(x)and int(x)) #길이로 정렬 + 숫자로 정렬 -> 순서 바뀌면 안됨
for j in range(len(phoneBook)):
for i in range(1+j,len(phoneBook)):
if phoneBook[j] in phoneBook[i][:len(phoneBook[j])]:
return False
return True
|
thdwlsgus0/algorithm_study
|
python/전화번호 목록.py
|
전화번호 목록.py
|
py
| 528 |
python
|
en
|
code
| 0 |
github-code
|
6
|
30515350804
|
import typing as _
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from pypugjs.ext.jinja import PyPugJSExtension
asset_folder = ''
def _get_asset(fname: str) -> Path:
return Path(asset_folder, fname)
def _data_with_namespace(data: 'Data', namespace: _.Dict) -> 'DataWithNS':
return DataWithNS(data.data, namespace)
class Data:
def __init__(self, data: _.Dict | _.List | str):
self.data = data
def __repr__(self) -> str:
return f'Data({self.data!r})'
def __eq__(self, other: 'Data') -> bool:
return self.data == getattr(other, 'data', None)
def __getattr__(self, item: _.Any) -> 'Data':
data = self.data
if isinstance(data, dict):
if item in data:
return Data(data[item])
children = data.get('children', [])
return Data([c[item] for c in children if item in c])
elif isinstance(data, list) and len(data) == 1:
data = data[0]
if item in data:
return Data(data[item])
children = data.get('children', [])
return Data([c[item] for c in children if item in c])
return Data('')
def __getitem__(self, item: str) -> str | list['Data']:
data = self.data
if item == '$':
if isinstance(data, str):
return data
elif isinstance(data, dict):
return '\n'.join(data.get('children', []))
elif isinstance(data, list):
if len(data) == 1 and isinstance(data[0], dict):
return '\n'.join(data[0].get('children', []))
return '\n'.join(data)
elif item.startswith('@'):
att_name = item[1:]
if isinstance(data, list):
if len(data) == 1 and isinstance(data[0], dict):
return data[0].get('attributes', {}).get(att_name, '')
return ''
elif isinstance(data, str):
return ''
return data.get('attributes', {}).get(att_name, '')
elif item == '*':
return [Data(d) for d in data] if isinstance(data, list) else []
class DataWithNS(Data):
def __init__(self, data: dict | list | str, ns: _.Dict):
super(DataWithNS, self).__init__(data)
self.ns = ns
def __getattr__(self, item: str) -> 'Data':
name = item
if '__' in item:
ns, name = item.split('__')
name = '{' + self.ns.get(ns, '') + '}' + name
ret = super(DataWithNS, self).__getattr__(name)
return DataWithNS(ret.data, self.ns)
def __getitem__(self, item: str) -> str | list['Data']:
ret = super(DataWithNS, self).__getitem__(item)
if isinstance(ret, list):
return [DataWithNS(i.data, self.ns) for i in ret]
return ret
def build_environment(*, template_dir: Path, asset_dir: Path) -> Environment:
global asset_folder
asset_folder = asset_dir
return Environment(
extensions=[PyPugJSExtension],
loader=FileSystemLoader(template_dir),
variable_start_string="{%#.-.**",
variable_end_string="**.-.#%}",
)
def build_renderer(jinja_env: Environment) -> _.Callable:
def render(template, **kwargs):
return jinja_env\
.get_template(f'{template}.pug')\
.render(enumerate=enumerate,
asset=_get_asset,
dataNS=_data_with_namespace,
**kwargs)
return render
def build_data(data: _.Dict | _.List | str) -> 'Data':
return Data(data)
|
OnoArnaldo/py-report-generator
|
src/reportgen/utils/pug_to_xml.py
|
pug_to_xml.py
|
py
| 3,635 |
python
|
en
|
code
| 0 |
github-code
|
6
|
28838106101
|
import numpy as np
try:
from math import prod
except:
from functools import reduce
def prod(iterable):
return reduce(operator.mul, iterable, 1)
import zipfile
import pickle
import sys
import ast
import re
from fickling.pickle import Pickled
if sys.version_info >= (3, 9):
from ast import unparse
else:
from astunparse import unparse
NO_PICKLE_DEBUG = False
### Unpickling import:
def my_unpickle(fb0):
key_prelookup = {}
class HackTensor:
def __new__(cls, *args):
#print(args)
ident, storage_type, obj_key, location, obj_size = args[0][0:5]
assert ident == 'storage'
assert prod(args[2]) == obj_size
ret = np.zeros(args[2], dtype=storage_type)
if obj_key not in key_prelookup:
key_prelookup[obj_key] = []
key_prelookup[obj_key].append((storage_type, obj_size, ret, args[2], args[3]))
#print(f"File: {obj_key}, references: {len(key_prelookup[obj_key])}, size: {args[2]}, storage_type: {storage_type}")
return ret
class HackParameter:
def __new__(cls, *args):
#print(args)
pass
class Dummy:
pass
class MyPickle(pickle.Unpickler):
def find_class(self, module, name):
#print(module, name)
if name == 'FloatStorage':
return np.float32
if name == 'LongStorage':
return np.int64
if name == 'HalfStorage':
return np.float16
if module == "torch._utils":
if name == "_rebuild_tensor_v2":
return HackTensor
elif name == "_rebuild_parameter":
return HackParameter
else:
try:
return pickle.Unpickler.find_class(self, module, name)
except Exception:
return Dummy
def persistent_load(self, pid):
return pid
return MyPickle(fb0).load(), key_prelookup
def fake_torch_load_zipped(fb0, load_weights=True):
with zipfile.ZipFile(fb0, 'r') as myzip:
folder_name = [a for a in myzip.namelist() if a.endswith("/data.pkl")]
if len(folder_name)== 0:
raise ValueError("Looke like the checkpoints file is in the wrong format")
folder_name = folder_name[0].replace("/data.pkl" , "").replace("\\data.pkl" , "")
with myzip.open(folder_name+'/data.pkl') as myfile:
ret = my_unpickle(myfile)
if load_weights:
for k, v_arr in ret[1].items():
with myzip.open(folder_name + f'/data/{k}') as myfile:
#print(f"Eating data file {k} now")
file_data = myfile.read()
for v in v_arr:
if v[2].dtype == "object":
print(f"issue assigning object on {k}")
continue
#weight = np.frombuffer(file_data, v[2].dtype).reshape(v[3])
#np.copyto(v[2], weight)
np.copyto(v[2], np.frombuffer(file_data, v[2].dtype).reshape(v[3]))
return ret[0]
### No-unpickling import:
def extract_weights_from_checkpoint(fb0):
torch_weights = {}
torch_weights['state_dict'] = {}
with zipfile.ZipFile(fb0, 'r') as myzip:
folder_name = [a for a in myzip.namelist() if a.endswith("/data.pkl")]
if len(folder_name)== 0:
raise ValueError("Looks like the checkpoints file is in the wrong format")
folder_name = folder_name[0].replace("/data.pkl" , "").replace("\\data.pkl" , "")
with myzip.open(folder_name+'/data.pkl') as myfile:
load_instructions = examine_pickle(myfile)
for sd_key,load_instruction in load_instructions.items():
with myzip.open(folder_name + f'/data/{load_instruction.obj_key}') as myfile:
if (load_instruction.load_from_file_buffer(myfile)):
torch_weights['state_dict'][sd_key] = load_instruction.get_data()
#if len(special_instructions) > 0:
# torch_weights['state_dict']['_metadata'] = {}
# for sd_key,special in special_instructions.items():
# torch_weights['state_dict']['_metadata'][sd_key] = special
return torch_weights
def examine_pickle(fb0, return_special=False):
## return_special:
## A rabbit hole I chased trying to debug a model that wouldn't import that had 1300 metadata statements
## If for some reason it's needed in the future turn it on. It is passed into the class AssignInstructions and
## if turned on collect_special will be True
##
## If, by 2023, this hasn't been required, I would strip it out.
#turn the pickle file into text we can parse
decompiled = unparse(Pickled.load(fb0).ast).splitlines()
## Parsing the decompiled pickle:
## LINES WE CARE ABOUT:
## 1: this defines a data file and what kind of data is in it
## _var1 = _rebuild_tensor_v2(UNPICKLER.persistent_load(('storage', HalfStorage, '0', 'cpu', 11520)), 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
##
## 2: this massive line assigns the previous data to dictionary entries
## _var2262 = {'model.diffusion_model.input_blocks.0.0.weight': _var1, [..... continue for ever]}
##
## 3: this massive line also assigns values to keys, but does so differently
## _var2262.update({ 'cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.bias': _var2001, [ .... and on and on ]})
##
## 4: in some pruned models, the last line is instead a combination of 2/3 into the final variable:
## result = {'model.diffusion_model.input_blocks.0.0.weight': _var1, 'model.diffusion_model.input_blocks.0.0.bias': _var3, }
##
## that's it
# make some REs to match the above.
re_rebuild = re.compile('^_var\d+ = _rebuild_tensor_v2\(UNPICKLER\.persistent_load\(\(.*\)$')
re_assign = re.compile('^_var\d+ = \{.*\}$')
re_update = re.compile('^_var\d+\.update\(\{.*\}\)$')
re_ordered_dict = re.compile('^_var\d+ = OrderedDict\(\)$')
re_result = re.compile('^result = \{.*\}$')
load_instructions = {}
assign_instructions = AssignInstructions()
for line in decompiled:
## see if line matches patterns of lines we care about:
line = line.strip()
if re_rebuild.match(line):
variable_name, load_instruction = line.split(' = ', 1)
load_instructions[variable_name] = LoadInstruction(line, variable_name)
elif re_assign.match(line) or re_result.match(line):
assign_instructions.parse_assign_line(line)
elif re_update.match(line):
assign_instructions.parse_update_line(line)
elif re_ordered_dict.match(line):
#do nothing
continue
elif NO_PICKLE_DEBUG:
print(f'unmatched line: {line}')
if NO_PICKLE_DEBUG:
print(f"Found {len(load_instructions)} load instructions")
assign_instructions.integrate(load_instructions)
if return_special:
return assign_instructions.integrated_instructions, assign_instructions.special_instructions
return assign_instructions.integrated_instructions
class AssignInstructions:
def __init__(self, collect_special=False):
self.instructions = {}
self.special_instructions = {}
self.integrated_instructions = {}
self.collect_special = collect_special;
def parse_result_line(self, line):
garbage, huge_mess = line.split(' = {', 1)
assignments = huge_mess.split(', ')
del huge_mess
assignments[-1] = assignments[-1].strip('}')
#compile RE here to avoid doing it every loop iteration:
re_var = re.compile('^_var\d+$')
assignment_count = 0
for a in assignments:
if self._add_assignment(a, re_var):
assignment_count = assignment_count + 1
if NO_PICKLE_DEBUG:
print(f"Added/merged {assignment_count} assignments. Total of {len(self.instructions)} assignment instructions")
def parse_assign_line(self, line):
# input looks like this:
# _var2262 = {'model.diffusion_model.input_blocks.0.0.weight': _var1, 'model.diffusion_model.input_blocks.0.0.bias': _var3,\
# ...\
# 'cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.weight': _var1999}
# input looks like the above, but with 'result' in place of _var2262:
# result = {'model.diffusion_model.input_blocks.0.0.weight': _var1, ... }
#
# or also look like:
# result = {'state_dict': _var2314}
# ... which will be ignored later
garbage, huge_mess = line.split(' = {', 1)
assignments = huge_mess.split(', ')
del huge_mess
assignments[-1] = assignments[-1].strip('}')
#compile RE here to avoid doing it every loop iteration:
re_var = re.compile('^_var\d+$')
assignment_count = 0
for a in assignments:
if self._add_assignment(a, re_var):
assignment_count = assignment_count + 1
if NO_PICKLE_DEBUG:
print(f"Added/merged {assignment_count} assignments. Total of {len(self.instructions)} assignment instructions")
def _add_assignment(self, assignment, re_var):
# assignment can look like this:
# 'cond_stage_model.transformer.text_model.encoder.layers.3.self_attn.out_proj.weight': _var2009
# or assignment can look like this:
# 'embedding_manager.embedder.transformer.text_model.encoder.layers.6.mlp.fc1': {'version': 1}
sd_key, fickling_var = assignment.split(': ', 1)
sd_key = sd_key.strip("'")
if sd_key != 'state_dict' and re_var.match(fickling_var):
self.instructions[sd_key] = fickling_var
return True
elif self.collect_special:
# now convert the string "{'version': 1}" into a dictionary {'version': 1}
entries = fickling_var.split(',')
special_dict = {}
for e in entries:
e = e.strip("{}")
k, v = e.split(': ')
k = k.strip("'")
v = v.strip("'")
special_dict[k] = v
self.special_instructions[sd_key] = special_dict
return False
def integrate(self, load_instructions):
unfound_keys = {}
for sd_key, fickling_var in self.instructions.items():
if fickling_var in load_instructions:
self.integrated_instructions[sd_key] = load_instructions[fickling_var]
else:
if NO_PICKLE_DEBUG:
print(f"no load instruction found for {sd_key}")
if NO_PICKLE_DEBUG:
print(f"Have {len(self.integrated_instructions)} integrated load/assignment instructions")
def parse_update_line(self, line):
# input looks like:
# _var2262.update({'cond_stage_model.transformer.text_model.encoder.layers.3.layer_norm2.bias': _var2001,\
# 'cond_stage_model.transformer.text_model.encoder.layers.4.self_attn.k_proj.weight': _var2003,\
# ...\
#'cond_stage_model.transformer.text_model.final_layer_norm.bias': _var2261})
garbage, huge_mess = line.split('({', 1)
updates = huge_mess.split(', ')
del huge_mess
updates[-1] = updates[-1].strip('})')
re_var = re.compile('^_var\d+$')
update_count = 0
for u in updates:
if self._add_assignment(u, re_var):
update_count = update_count + 1
if NO_PICKLE_DEBUG:
print(f"Added/merged {update_count} updates. Total of {len(self.instructions)} assignment instructions")
class LoadInstruction:
def __init__(self, instruction_string, variable_name, extra_debugging = False):
self.ident = False
self.storage_type = False
self.obj_key = False
self.location = False #unused
self.obj_size = False
self.stride = False #unused
self.data = False
self.variable_name = variable_name
self.extra_debugging = extra_debugging
self.parse_instruction(instruction_string)
def parse_instruction(self, instruction_string):
## this function could probably be cleaned up/shortened.
## this is the API def for _rebuild_tensor_v2:
## _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):
#
## sample instruction from decompiled pickle:
# _rebuild_tensor_v2(UNPICKLER.persistent_load(('storage', HalfStorage, '0', 'cpu', 11520)), 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
#
# the following comments will show the output of each string manipulation as if it started with the above.
if self.extra_debugging:
print(f"input: '{instruction_string}'")
garbage, storage_etc = instruction_string.split('((', 1)
# storage_etc = 'storage', HalfStorage, '0', 'cpu', 11520)), 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
if self.extra_debugging:
print("storage_etc, reference: ''storage', HalfStorage, '0', 'cpu', 11520)), 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)'")
print(f"storage_etc, actual: '{storage_etc}'\n")
storage, etc = storage_etc.split('))', 1)
# storage = 'storage', HalfStorage, '0', 'cpu', 11520
# etc = , 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
if self.extra_debugging:
print("storage, reference: ''storage', HalfStorage, '0', 'cpu', 11520'")
print(f"storage, actual: '{storage}'\n")
print("etc, reference: ', 0, (320, 4, 3, 3), (36, 9, 3, 1), False, _var0)'")
print(f"etc, actual: '{etc}'\n")
## call below maps to: ('storage', HalfStorage, '0', 'cpu', 11520)
self.ident, self.storage_type, self.obj_key, self.location, self.obj_size = storage.split(', ', 4)
self.ident = self.ident.strip("'")
self.obj_key = self.obj_key.strip("'")
self.location = self.location.strip("'")
self.obj_size = int(self.obj_size)
self.storage_type = self._torch_to_numpy(self.storage_type)
if self.extra_debugging:
print(f"{self.ident}, {self.obj_key}, {self.location}, {self.obj_size}, {self.storage_type}")
assert (self.ident == 'storage')
garbage, etc = etc.split(', (', 1)
# etc = 320, 4, 3, 3), (36, 9, 3, 1), False, _var0)
if self.extra_debugging:
print("etc, reference: '320, 4, 3, 3), (36, 9, 3, 1), False, _var0)'")
print(f"etc, actual: '{etc}'\n")
size, stride, garbage = etc.split('), ', 2)
# size = 320, 4, 3, 3
# stride = (36, 9, 3, 1
stride = stride.strip('(,')
size = size.strip(',')
if (size == ''):
# rare case where there is an empty tuple. SDv1.4 has two of these.
self.size_tuple = ()
else:
self.size_tuple = tuple(map(int, size.split(', ')))
if (stride == ''):
self.stride = ()
else:
self.stride = tuple(map(int, stride.split(', ')))
if self.extra_debugging:
print(f"size: {self.size_tuple}, stride: {self.stride}")
prod_size = prod(self.size_tuple)
assert prod(self.size_tuple) == self.obj_size # does the size in the storage call match the size tuple
# zero out the data
self.data = np.zeros(self.size_tuple, dtype=self.storage_type)
@staticmethod
def _torch_to_numpy(storage_type):
if storage_type == 'FloatStorage':
return np.float32
if storage_type == 'HalfStorage':
return np.float16
if storage_type == 'LongStorage':
return np.int64
if storage_type == 'IntStorage':
return np.int32
raise Exception("Storage type not defined!")
def load_from_file_buffer(self, fb):
if self.data.dtype == "object":
print(f"issue assigning object on {self.obj_key}")
return False
else:
np.copyto(self.data, np.frombuffer(fb.read(), self.data.dtype).reshape(self.size_tuple))
return True
def get_data(self):
return self.data
|
divamgupta/diffusionbee-stable-diffusion-ui
|
backends/model_converter/fake_torch.py
|
fake_torch.py
|
py
| 15,028 |
python
|
en
|
code
| 11,138 |
github-code
|
6
|
73919945469
|
import unittest
from bs4 import BeautifulSoup
from src import get_html_script as ghs
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from models.models import JobDataModel
from models import domain_db_mappings as dbm
from models.database_models import JobDataDbModel
import models.database_methods as db_ops
from src.email_generator import TextEmailContent, HtmlEmailContent, generate_full_email_content
from src.email_sender import send_email_to_user, get_data_and_send_email
from datetime import date
Base = declarative_base()
class TestScrapeMethods(unittest.TestCase):
def test_successfully_scrapes_site(self):
# Phil comes by, he wants to use this web scraper tool.
# He plans to see if it can find data on mechanics jobs,
# and he wants to move to tampa, so he checks monster.
query = 'mechanic'
location = 'Tampa'
site = 'https://www.monster.com'
#url = 'https://www.monster.com/jobs/search/?q=mechanic&where=Tampa'
results = ghs.scrape_site(site, query, location)
# Phil sees that he was able to get a successful response
self.assertEqual(results.status_code, 200)
# Phil sees that it did in fact search the site he wanted.
self.assertTrue(site in results.url)
# Phil sees that it definitely searched for the type of job he wanted.results
self.assertTrue(query in results.url)
# He also sees that it certainly searched the location he wanted.
self.assertTrue(location in results.url)
def test_successfully_parses_data(self):
# Mary is a bit more discerning than Phil.
# She wants to make sure her data makes sense.
query = 'developer'
location = 'New York'
site = 'monster.com'
location_names = ['New York', 'NY']
results = ghs.scrape_full_page(site, query, location)
# Results are not empty. Mary managed to scrape data from a site!
self.assertTrue(results)
# Mary does not see any html.
results_names = [result.title for result in results]
results_locations = [result.location for result in results]
results_sites = [result.link for result in results]
self.assertFalse(any(
[
bool(BeautifulSoup(results_name, "html.parser").find())
for results_name in results_names
]
))
self.assertFalse(any(
bool(BeautifulSoup(results_location, "html.parser").find())
for results_location in results_locations
))
# Mary sees that she did get radiologist jobs in her results.
self.assertTrue(any([(query in results_name) for results_name in results_names]))
# Mary also sees that she got results in New York.
self.assertTrue(any(
[
[loc in results_location for loc in location_names]
for results_location in results_locations
]
))
# Mary lastly sees that all of the job links are, in fact from monster.
self.assertTrue(all([site in result_site for result_site in results_sites]))
# Amazed at how far technology has come, a satisfied Mary goes to bed.
class EndToEndHtmlScrapeSaveToDbTest(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=self.engine)
self.session = Session()
Base.metadata.create_all(self.engine, tables=[JobDataDbModel.__table__])
def tearDown(self):
Base.metadata.drop_all(self.engine)
def test_scrapes_and_saves_job_data(self):
job_sites = ['monster.com']
location = 'utah'
query = 'hairdresser'
before_data = self.session.query(JobDataDbModel).all()
self.assertFalse(before_data)
ghs.scrape_sites_and_save_jobs(job_sites, query, location, self.session)
after_data = self.session.query(JobDataDbModel).all()
self.assertTrue(after_data)
class StoresDataAndSendsEmailTest(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=self.engine)
self.session = Session()
Base.metadata.create_all(self.engine, tables=[JobDataDbModel.__table__])
def tearDown(self):
Base.metadata.drop_all(self.engine)
def test_emails_saved_job_data(self):
# Larry is lazy. He doesn't want to have to keep checking everything himself, so
# He wants the app to email him only results that haven't already been emailed to him yet.
query = 'hairdresser'
location = 'utah'
site = 'monster.com'
class_data = ghs.scrape_full_page(site, query, location)
# His data is saved to the database. It is the exact same data that he had before.
mapped_data = dbm.map_job_data_models_to_db_models(class_data)
for data_point in mapped_data:
self.session.add(data_point)
self.session.commit()
saved_data = self.session.query(JobDataDbModel).all()
response = get_data_and_send_email(self.session)
# Larry has received the email after a short amount of time has passed.
self.assertDictEqual(response, {})
# All of the items that were sent are now marked as having been sent.
# Because of this, none of them should show if we filter out sent items in the DB.
updated_data = self.session.query(JobDataDbModel).filter(JobDataDbModel.has_been_emailed == False).all()
self.assertTrue(len(updated_data) == 0)
# Satisfied that it works as expected, Larry goes to bed.
if __name__ == '__main__':
unittest.main()
|
ctiller15/Board-scrape-tool
|
tests/functional_tests.py
|
functional_tests.py
|
py
| 5,831 |
python
|
en
|
code
| 0 |
github-code
|
6
|
31065262082
|
from tensorflow.keras.backend import clear_session
from tensorflow.keras.models import load_model
from tensorflow.keras.callbacks import ModelCheckpoint, Callback as keras_callback
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import numpy as np
from static.models.unet_model import unet
from scipy.io import loadmat
import json
import random
import logging
# This script uses a set of training data assembled into a .mat file consisting of a stack of images
# and a corresponding set of binary masks that label the pixels in the image stacks into two classes.
# The script then initializes a randomized U-NET (using the topology defined in the file model.py).
# It then initiates training using a given batch size and # of epochs, saving the best net at each
# step to the given .hdf5 file path.
#
# Written by Teja Bollu, documented and modified by Brian Kardon
def createDataAugmentationParameters(rotation_range=None, width_shift_range=0.1,
height_shift_range=0.3, zoom_range=0.4, horizontal_flip=True,
vertical_flip=True):
# Create dictionary of data augmentation parameter
return {
"rotation_range":rotation_range,
"width_shift_range":width_shift_range,
"height_shift_range":height_shift_range,
"zoom_range":zoom_range,
"horizontal_flip":horizontal_flip,
"vertical_flip":vertical_flip
}
class PrintLogger:
def __init__(self):
pass
def log(lvl, msg):
print(msg)
def trainNetwork(trained_network_path, training_data_path, start_network_path=None,
augment=True, batch_size=10, epochs=512, image_field_name='imageStack',
mask_field_name='maskStack', data_augmentation_parameters={},
epoch_progress_callback=None, logger=None):
# Actually train the network, saving the best network to a file after each epoch.
# augment = boolean flag indicating whether to randomly augment training data
# batch_size = Size of training batches (size of batches that dataset is divided into for each epoch):
# epochs = Number of training epochs (training runs through whole dataset):
# training_data_path = .mat file containing the training data (image data and corresponding manually created mask target output):
# image_field_name = Field within .mat file that contains the relevant images:
# mask_field_name = Field within .mat file that contains the relevant masks:
# trained_network_path = File path to save trained network to:
# data_augmentation_parameters = to use for data augmentation:
# epoch_progress_callback = a function to call at the end of each epoch,
# which takes a progress argument which will be a dictionary of progress
# indicators
if logger is None:
logger = PrintLogger()
# Reset whatever buffers or saved state exists...not sure exactly what that consists of.
# This may not actually work? Word is you have to restart whole jupyter server to get this to work.
clear_session()
# Convert inter-epoch progress callback to a tf.keras.Callback object
epoch_progress_callback = TrainingProgressCallback(epoch_progress_callback)
# Load training data
print('Loading images and masks...')
data = loadmat(training_data_path)
img = data[image_field_name]
mask = data[mask_field_name]
# Process image and mask data into the proper format
img_shape = img.shape;
num_samples = img_shape[0]
img_size_x = img_shape[1]
img_size_y = img_shape[2]
img = img.reshape(num_samples, img_size_x, img_size_y, 1)
mask = mask.reshape(num_samples, img_size_x, img_size_y, 1)
print("...image and mask data loaded.")
print("Image stack dimensions:", img.shape)
print(" Mask stack dimensions:", mask.shape)
print('start path:', start_network_path)
print('train path:', trained_network_path)
if augment:
imgGen = ImageDataGenerator(**data_augmentation_parameters)
maskGen = ImageDataGenerator(**data_augmentation_parameters)
if start_network_path is None:
# Randomize new network structure using architecture in model.py file
lickbot_net = unet(net_scale = 1)
else:
# Load previously trained network from a file
lickbot_net = load_model(start_network_path)
# Instruct training algorithm to save best network to disk whenever an improved network is found.
model_checkpoint = ModelCheckpoint(str(trained_network_path), monitor='loss', verbose=1, save_best_only=True)
callback_list = [model_checkpoint]
if epoch_progress_callback is not None:
callback_list.append(epoch_progress_callback)
if augment:
print("Using automatically augmented training data.")
# Train network using augmented dataset
seed = random.randint(0, 1000000000)
imgIterator = imgGen.flow(img, seed=seed, shuffle=False, batch_size=batch_size)
maskIterator = maskGen.flow(mask, seed=seed, shuffle=False, batch_size=batch_size)
steps_per_epoch = int(num_samples / batch_size)
lickbot_net.fit(
((imgBatch, maskBatch) for imgBatch, maskBatch in zip(imgIterator, maskIterator)),
steps_per_epoch=steps_per_epoch, # # of batches of generated data per epoch
epochs=epochs,
verbose=1,
callbacks=callback_list
)
else:
lickbot_net.fit(
img,
mask,
epochs=epochs,
verbose=1,
callbacks=callback_list
)
class TrainingProgressCallback(keras_callback):
def __init__(self, progressFunction):
super(TrainingProgressCallback, self).__init__()
self.logs = []
self.progressFunction = progressFunction
def on_epoch_end(self, epoch, logs=None):
# self.logs.append(logs)
# keys = list(logs.keys())
if 'loss' in logs:
loss = logs['loss']
else:
loss = None
if 'acc' in logs:
accuracy = logs['acc']
else:
accuracy = None
exitFlag = self.progressFunction(epoch=epoch, loss=loss, accuracy=accuracy)
if exitFlag:
self.model.stop_training = True
# print("End epoch {} of training; got log keys: {}".format(epoch, keys))
def validateNetwork(trained_network_path, img=None, imgIterator=None, maskIterator=None):
# Load trained network
lickbot_net = load_model(trained_network_path)
if augment:
img_validate = imgIterator.next()
mask_validate = maskIterator.next()
else:
print('Using original dataset for visualization')
img_validate = img
mask_validate = mask
mask_pred = lickbot_net.predict(img_validate)
mask_pred.shape
# %matplotlib inline
from matplotlib import pyplot as plt
from matplotlib import gridspec
numValidation = img_validate.shape[0]
img_shape = img.shape;
num_samples = img_shape[0]
img_size_x = img_shape[1]
img_size_y = img_shape[2]
img_disp = img_validate.reshape(numValidation,img_size_x,img_size_y)
mask_disp = mask_validate.reshape(numValidation,img_size_x,img_size_y)
mask_pred = lickbot_net.predict(img_validate).reshape(numValidation,img_size_x,img_size_y)
scaleFactor = 3
plt.figure(figsize=(scaleFactor*3,scaleFactor*numValidation))
plt.subplots_adjust(wspace=0, hspace=0)
gs = gridspec.GridSpec(nrows=numValidation, ncols=3, width_ratios=[1, 1, 1],
wspace=0.0, hspace=0.0, bottom=0, top=1, left=0, right=1)
for k in range(numValidation):
plt.subplot(gs[k, 0])
plt.imshow(mask_disp[k])
plt.subplot(gs[k, 1])
plt.imshow(mask_pred[k])
plt.subplot(gs[k, 2])
plt.imshow(img_disp[k])
|
GoldbergLab/tongueSegmentationServer
|
NetworkTraining.py
|
NetworkTraining.py
|
py
| 7,819 |
python
|
en
|
code
| 1 |
github-code
|
6
|
29537697201
|
# -*- coding: utf-8 -*-
from openerp import models, fields, api
class purchase_order(models.Model):
_inherit = 'purchase.order'
@api.multi
def action_picking_create(self):
res = super(purchase_order, self).action_picking_create()
if self.picking_ids:
picking_ids = [x.id for x in self.picking_ids]
self.env['sftp.more'].sftp_send(picking_ids)
return res
|
odoopruebasmp/productions_stage_venv
|
document_sftp_more/models/purchase_order.py
|
purchase_order.py
|
py
| 418 |
python
|
en
|
code
| 0 |
github-code
|
6
|
14493907058
|
# -*- coding: utf-8 -*- #
'''
--------------------------------------------------------------------------
# File Name: PATH_ROOT/utils/signal_vis.py
# Author: JunJie Ren
# Version: v1.1
# Created: 2021/06/15
# Description: — — — — — — — — — — — — — — — — — — — — — — — — — — —
--> DD信号识别(可解释)系列代码 <--
-- 可视化信号输入
— — — — — — — — — — — — — — — — — — — — — — — — — — —
# Module called: <0> PATH_ROOT/config.py
<1> PATH_TOOT/dataset/RML2016.py
— — — — — — — — — — — — — — — — — — — — — — — — — — —
# Function List: <0> drawAllOriSignal():
绘制所有信号输入样本的图像,并保存至相应标签的文件夹下
<1> showOriSignal():
绘制并展示一个样本信号的图像
<2> showImgSignal():
绘制并展示一个信号样本的二维可视化图像
<3> showCamSignal():
叠加信号与CAM图,可视化CAM解释结果,并按类型保存
<4> mask_image():
软阈值擦除CAM对应的判别性特征区域
— — — — — — — — — — — — — — — — — — — — — — — — — — —
# Class List: None
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# History:
| <author> | <version> | <time> | <desc>
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<0> | JunJie Ren | v1.0 | 2020/06/15 | creat
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<1> | JunJie Ren | v1.1 | 2020/07/09 | 优化无name的数据集调用问题
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
<2> | JunJie Ren | v1.2 | 2020/07/13 | 增加CAM阈值擦除函数
--------------------------------------------------------------------------
'''
import sys
import os
import cv2
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import matplotlib; matplotlib.use('TkAgg')
from sklearn.metrics import confusion_matrix
sys.path.append("../")
from app.configs import cfgs
from app.dataset.RML2016 import loadNpy
# from app.dataset.RML2016_04c.classes import modName
def t2n(t):
return t.detach().cpu().numpy().astype(np.int)
def fig2data(fig):
"""
fig = plt.figure()
image = fig2data(fig)
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA values
"""
import PIL.Image as Image
# draw the renderer
fig.canvas.draw()
# Get the RGBA buffer from the figure
w, h = fig.canvas.get_width_height()
buf = np.fromstring(fig.canvas.tostring_argb(), dtype=np.uint8)
buf.shape = (w, h, 4)
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll(buf, 3, axis=2)
image = Image.frombytes("RGBA", (w, h), buf.tostring())
image = np.asarray(image)
return image
def showOriSignal(sample, mod_name, idx):
''' 绘制并展示一个样本信号的图像 '''
signal_data = sample[0]
figure = plt.figure(figsize=(9, 6))
plt.title(str(idx)+" "+str(mod_name), fontsize=30)
plt.xlabel('N', fontsize=20)
plt.ylabel("Value", fontsize=20)
plt.plot(signal_data[:, 0], label = 'I', linewidth=2.0)
plt.plot(signal_data[:, 1], color = 'red', label = 'Q', linewidth=2.0)
plt.legend(loc="upper right", fontsize=30)
plt.close()
image = fig2data(figure)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
return image
def showCamSignal(signal, CAM, mod):
"""
Args:
signal: numpy.ndarray(size=(1, 128, 2), dtype=np.float)
CAM: numpy.ndarray(size=(128, 2), dtype=np.float)
Funcs:
叠加信号与CAM图,可视化CAM解释结果,并按类型保存
"""
# 绘制信号
signal_data = signal[0]
sig_len, channel = signal_data.shape
figure = plt.figure(figsize=(18, 12))
plt.title(mod, fontsize=26)
plt.xlabel('N', fontsize=20)
plt.ylabel("Value", fontsize=20)
plt.plot(signal_data[:, 0]*(sig_len//10), label = 'I' ,linewidth=4.0)
plt.plot(signal_data[:, 1]*(sig_len//10), color = 'red', label = 'Q', linewidth=4.0)
plt.legend(loc="upper right", fontsize=26)
# 绘制CAM
sig_min, sig_max = np.min(signal_data), np.max(signal_data)
CAM = CAM.T # (2, 128)
CAM = CAM - np.min(CAM)
CAM = CAM / np.max(CAM) # CAM取值归一化
plt.imshow(CAM, cmap='jet', extent=[0., sig_len, (sig_min-0.5)*(sig_len//10), (sig_max+0.5)*(sig_len//10)]) # jet, rainbow
# plt.colorbar()
'''
save_path = "figs_CAM_ACARS/{}".format(mod_name)
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + '/' + str(idx+1)+"_CAM")
plt.close()
'''
# plt.savefig("figs/CAM_cur")
# plt.show()
image = fig2data(figure)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
plt.close()
return image
def plot_confusion_matrix(y_true, y_pred, labels, title='Normalized confusion matrix', intFlag = 0):
''' 绘制混淆矩阵 '''
cmap = plt.cm.Blues
''' 颜色参考http://blog.csdn.net/haoji007/article/details/52063168'''
cm = confusion_matrix(y_true, y_pred)
tick_marks = np.array(range(len(labels))) + 0.5
np.set_printoptions(precision=2)
if cm.sum(axis=1)[:, np.newaxis].all() != 0:
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
else:
intFlag = 1
figure = plt.figure(figsize=(10, 9), dpi=360)
ind_array = np.arange(len(labels))
x, y = np.meshgrid(ind_array, ind_array)
# intFlag = 0 # 标记在图片中对文字是整数型还是浮点型
for x_val, y_val in zip(x.flatten(), y.flatten()):
if (intFlag):
c = cm[y_val][x_val]
plt.text(x_val, y_val, "%d" % (c,), color='red', fontsize=12, va='center', ha='center')
else:
c = cm_normalized[y_val][x_val]
if (c > 0.0001):
#这里是绘制数字,可以对数字大小和颜色进行修改
plt.text(x_val, y_val, "%0.2f" % (c*100,) + "%", color='red', fontsize=10, va='center', ha='center')
else:
plt.text(x_val, y_val, "%d" % (0,), color='red', fontsize=10, va='center', ha='center')
if(intFlag):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
else:
plt.imshow(cm_normalized, interpolation='nearest', cmap=cmap)
plt.gca().set_xticks(tick_marks, minor=True)
plt.gca().set_yticks(tick_marks, minor=True)
plt.gca().xaxis.set_ticks_position('none')
plt.gca().yaxis.set_ticks_position('none')
plt.grid(True, which='minor', linestyle='-')
plt.gcf().subplots_adjust(bottom=0.15)
plt.title('Confusion Matrix', fontsize=18)
plt.colorbar()
xlocations = np.array(range(len(labels)))
plt.xticks(xlocations, labels, rotation=90)
plt.yticks(xlocations, labels)
plt.ylabel('Index of True Classes')
plt.xlabel('Index of Predict Classes')
plt.savefig('./app/figs/confusion_matrix.jpg', dpi=300)
image = fig2data(figure)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
return image
# plt.title(title)
# plt.show()
def drawAllOriSignal(X, Y):
"""
Args:
X: numpy.ndarray(size = (bz, 1, 128, 2)), 可视化信号原始数据
Y: numpy.ndarray(size = (bz,)), 可视化信号标签
Returns:
None
Funcs:
绘制所有信号输入样本的图像,并保存至相应标签的文件夹下
"""
for idx in range(len(X)):
if (idx+1)%50 == 0:
print("{} complete!".format(idx+1))
signal_data = X[idx][0]
mod_name = str(modName[Y[idx]], "utf-8") \
if cfgs.dataset_name == "RML2016.04c" else "label-"+str(t2n(Y[idx]))
plt.figure(figsize=(6, 4))
plt.title(mod_name)
plt.xlabel('N')
plt.ylabel("Value")
plt.plot(signal_data[:, 0], label = 'I')
plt.plot(signal_data[:, 1], color = 'red', label = 'Q')
plt.legend(loc="upper right")
save_path = "../figs/original_signal/{}".format(mod_name)
if not os.path.exists(save_path):
os.makedirs(save_path)
plt.savefig(save_path + '/' + str(idx+1))
plt.close()
print(X.shape)
print(Y.shape)
print("Complete the drawing of all original signals !!!")
def showImgSignal(sample, label):
''' 绘制并展示一个信号样本的二维可视化图像 '''
data = sample[0].T # 2*128
data = data - np.min(data)
data = data / np.max(data)
mod_name = str(modName[label], "utf-8")\
if cfgs.dataset_name == "RML2016.04c" else "label-"+str(t2n(label))
# print(data.shape)
h, sig_len = data.shape
# 叠加信号,以便显示
img_sig = np.empty([sig_len, sig_len], dtype = float)
# for row in range(int(sig_len/h)):
# img_sig[row*h:row*h+h, :] = data
for row in range(sig_len):
if row<sig_len/2:
img_sig[row:row+1, :] = data[0]
else:
img_sig[row:row+1, :] = data[1]
img_sig = cv2.resize(img_sig, (sig_len*2,sig_len*2))
cv2.imshow(mod_name, img_sig)
cv2.waitKey(0)
return img_sig
def mask_image(cam, image, reserveORerase):
"""
Args:
cam: numpy.ndarray(size=(4096, 2), dtype=np.float), 0-1
image: torch.Tensor, torch.Size([1, 4096, 2])
reserveORerase: bool 保留(0)或擦除(1)判别性区域
Funcs:
软阈值擦除/保留CAM对应的判别性特征区域
"""
cam = torch.from_numpy(cam).cuda()
mask = torch.sigmoid(cfgs.CAM_omega * (cam - cfgs.Erase_thr)).squeeze()
masked_image = image - (image * mask) if reserveORerase else image * mask
return masked_image.float()
def mask_image_hard(cam, image, reserveORerase, thr):
''' 阈值硬擦除 '''
mask = np.zeros_like(cam)
mask[cam >= thr] = 1
mask[cam < thr] = 0
mask = torch.from_numpy(mask).cuda()
# print(mask.shape, image.shape)
masked_image = image - (image * mask) if reserveORerase else image * mask
return masked_image.float()
if __name__ == "__main__":
x_train, y_train, x_test, y_test = loadNpy(cfgs.train_path, cfgs.test_path)
print(x_train.shape, y_train.shape)
# drawAllOriSignal(X=x_train, Y=y_train)
for idx in range(len(x_train)):
showImgSignal(x_train[idx], y_train[idx])
showOriSignal(x_train[idx], y_train[idx])
|
jjRen-xd/PyOneDark_Qt_GUI
|
app/utils/signal_vis.py
|
signal_vis.py
|
py
| 11,107 |
python
|
en
|
code
| 2 |
github-code
|
6
|
31267028151
|
## Archived on the 22/09/2021
## Original terrain.py lived at io_ogre/terrain.py
import bpy
def _get_proxy_decimate_mod( ob ):
proxy = None
for child in ob.children:
if child.subcollision and child.name.startswith('DECIMATED'):
for mod in child.modifiers:
if mod.type == 'DECIMATE':
return mod
def bake_terrain( ob, normalize=True ):
assert ob.collision_mode == 'TERRAIN'
terrain = None
for child in ob.children:
if child.subcollision and child.name.startswith('TERRAIN'):
terrain = child
break
assert terrain
data = terrain.to_mesh(bpy.context.scene, True, "PREVIEW")
raw = [ v.co.z for v in data.vertices ]
Zmin = min( raw )
Zmax = max( raw )
depth = Zmax-Zmin
m = 1.0 / depth
rows = []
i = 0
for x in range( ob.collision_terrain_x_steps ):
row = []
for y in range( ob.collision_terrain_y_steps ):
v = data.vertices[ i ]
if normalize:
z = (v.co.z - Zmin) * m
else:
z = v.co.z
row.append( z )
i += 1
if x%2:
row.reverse() # blender grid prim zig-zags
rows.append( row )
return {'data':rows, 'min':Zmin, 'max':Zmax, 'depth':depth}
def save_terrain_as_NTF( path, ob ): # Tundra format - hardcoded 16x16 patch format
info = bake_terrain( ob )
url = os.path.join( path, '%s.ntf' % clean_object_name(ob.data.name) )
f = open(url, "wb")
# Header
buf = array.array("I")
xs = ob.collision_terrain_x_steps
ys = ob.collision_terrain_y_steps
xpatches = int(xs/16)
ypatches = int(ys/16)
header = [ xpatches, ypatches ]
buf.fromlist( header )
buf.tofile(f)
# Body
rows = info['data']
for x in range( xpatches ):
for y in range( ypatches ):
patch = []
for i in range(16):
for j in range(16):
v = rows[ (x*16)+i ][ (y*16)+j ]
patch.append( v )
buf = array.array("f")
buf.fromlist( patch )
buf.tofile(f)
f.close()
path,name = os.path.split(url)
R = {
'url':url, 'min':info['min'], 'max':info['max'], 'path':path, 'name':name,
'xpatches': xpatches, 'ypatches': ypatches,
'depth':info['depth'],
}
return R
class OgreCollisionOp(bpy.types.Operator):
'''Ogre Collision'''
bl_idname = "ogre.set_collision"
bl_label = "modify collision"
bl_options = {'REGISTER'}
MODE = StringProperty(name="toggle mode", maxlen=32, default="disable")
@classmethod
def poll(cls, context):
if context.active_object and context.active_object.type == 'MESH':
return True
def get_subcollisions( self, ob, create=True ):
r = get_subcollisions( ob )
if not r and create:
method = getattr(self, 'create_%s'%ob.collision_mode)
p = method(ob)
p.name = '%s.%s' %(ob.collision_mode, ob.name)
p.subcollision = True
r.append( p )
return r
def create_DECIMATED(self, ob):
child = ob.copy()
bpy.context.scene.collection.objects.link( child )
child.matrix_local = mathutils.Matrix()
child.parent = ob
child.hide_select = True
child.draw_type = 'WIRE'
#child.select = False
child.lock_location = [True]*3
child.lock_rotation = [True]*3
child.lock_scale = [True]*3
decmod = child.modifiers.new('proxy', type='DECIMATE')
decmod.ratio = 0.5
return child
def create_TERRAIN(self, ob):
x = ob.collision_terrain_x_steps
y = ob.collision_terrain_y_steps
#################################
#pos = ob.matrix_world.to_translation()
bpy.ops.mesh.primitive_grid_add(
x_subdivisions=x,
y_subdivisions=y,
size=1.0 ) #, location=pos )
grid = bpy.context.active_object
assert grid.name.startswith('Grid')
grid.collision_terrain_x_steps = x
grid.collision_terrain_y_steps = y
#############################
x,y,z = ob.dimensions
sx,sy,sz = ob.scale
x *= 1.0/sx
y *= 1.0/sy
z *= 1.0/sz
grid.scale.x = x/2
grid.scale.y = y/2
grid.location.z -= z/2
grid.data.show_all_edges = True
grid.draw_type = 'WIRE'
grid.hide_select = True
#grid.select = False
grid.lock_location = [True]*3
grid.lock_rotation = [True]*3
grid.lock_scale = [True]*3
grid.parent = ob
bpy.context.scene.objects.active = ob
mod = grid.modifiers.new(name='temp', type='SHRINKWRAP')
mod.wrap_method = 'PROJECT'
mod.use_project_z = True
mod.target = ob
mod.cull_face = 'FRONT'
return grid
def invoke(self, context, event):
ob = context.active_object
game = ob.game
subtype = None
if ':' in self.MODE:
mode, subtype = self.MODE.split(':')
##BLENDERBUG##ob.game.collision_bounds_type = subtype # BUG this can not come before
if subtype in 'BOX SPHERE CYLINDER CONE CAPSULE'.split():
ob.draw_bounds_type = subtype
else:
ob.draw_bounds_type = 'POLYHEDRON'
ob.game.collision_bounds_type = subtype # BLENDERBUG - this must come after draw_bounds_type assignment
else:
mode = self.MODE
ob.collision_mode = mode
if ob.data.show_all_edges:
ob.data.show_all_edges = False
if ob.show_texture_space:
ob.show_texture_space = False
if ob.show_bounds:
ob.show_bounds = False
if ob.show_wire:
ob.show_wire = False
for child in ob.children:
if child.subcollision and not child.hide_viewport:
child.hide_viewport = True
if mode == 'NONE':
game.use_ghost = True
game.use_collision_bounds = False
elif mode == 'PRIMITIVE':
game.use_ghost = False
game.use_collision_bounds = True
ob.show_bounds = True
elif mode == 'MESH':
game.use_ghost = False
game.use_collision_bounds = True
ob.show_wire = True
if game.collision_bounds_type == 'CONVEX_HULL':
ob.show_texture_space = True
else:
ob.data.show_all_edges = True
elif mode == 'DECIMATED':
game.use_ghost = True
game.use_collision_bounds = False
game.use_collision_compound = True
proxy = self.get_subcollisions(ob)[0]
if proxy.hide_viewport: proxy.hide_viewport = False
ob.game.use_collision_compound = True # proxy
mod = _get_proxy_decimate_mod( ob )
mod.show_viewport = True
if not proxy.select: # ugly (but works)
proxy.hide_select = False
proxy.select = True
proxy.hide_select = True
if game.collision_bounds_type == 'CONVEX_HULL':
ob.show_texture_space = True
elif mode == 'TERRAIN':
game.use_ghost = True
game.use_collision_bounds = False
game.use_collision_compound = True
proxy = self.get_subcollisions(ob)[0]
if proxy.hide_viewport:
proxy.hide_viewport = False
elif mode == 'COMPOUND':
game.use_ghost = True
game.use_collision_bounds = False
game.use_collision_compound = True
else:
assert 0 # unknown mode
return {'FINISHED'}
|
OGRECave/blender2ogre
|
archived_code/terrain.py
|
terrain.py
|
py
| 7,840 |
python
|
en
|
code
| 187 |
github-code
|
6
|
30197691279
|
from sense_hat import SenseHat
import time
import socket
import gyrodata
import sys
host = '10.44.15.35'
port = 5802
gyrodata.initGetGyroAngle()
gyro_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
gyro_socket.bind((host, port))
print('Socket created')
print('Listening...')
gyro_socket.listen(1)
conn, addr = gyro_socket.accept()
print ("Connected with " + addr[0] + ":" + str(addr[1]))
while 1:
data = conn.recv(1024)
print (str(data))
if data == (b'Requesting Gyro\r\n'):
gyrodata.sendGyroData(conn)
conn.close
#while 1:
# data = conn.recv(1024)
#
# robotAngle = bytes(gyroAngle, 'utf-8')
# conn.send(robotAngle)
# print('data sent: ' + gyroAngle)
# if not data:
# break
#conn.close
|
VCHSRobots/2017NavSys
|
gyroreader.py
|
gyroreader.py
|
py
| 714 |
python
|
en
|
code
| 0 |
github-code
|
6
|
844258019
|
# coding: utf-8
"""Train an ESN with a recursive least squares filter."""
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import logging
import hyperopt
import hyperopt.mongoexp
import numpy as np
from esn import RlsEsn
from esn.activation_functions import lecun
from esn.preprocessing import add_noise
from . import SuperposedSinusoidExample
logger = logging.getLogger(__name__)
class RlsExample(SuperposedSinusoidExample):
def __init__(self):
super(RlsExample, self).__init__()
self.num_training_samples = 10000
self.num_test_samples = 500
self.title = 'Superposed sine; RLS; {} samples'.format(
self.num_training_samples
)
self.hyper_parameters = {
'spectral_radius': 1.11,
'leaking_rate': 0.75,
'forgetting_factor': 0.99998,
'autocorrelation_init': 0.1,
'bias_scale': -0.4,
'signal_scale': 1.2,
'state_noise': 0.004,
'input_noise': 0.007,
}
self.search_space = (
hyperopt.hp.quniform('spectral_radius', 0, 1.5, 0.01),
hyperopt.hp.quniform('leaking_rate', 0, 1, 0.01),
hyperopt.hp.quniform('forgetting_factor', 0.98, 1, 0.0001),
hyperopt.hp.qloguniform('autocorrelation_init', np.log(0.1), np.log(1), 0.0001),
hyperopt.hp.qnormal('bias_scale', 1, 1, 0.1),
hyperopt.hp.qnormal('signal_scale', 1, 1, 0.1),
hyperopt.hp.quniform('state_noise', 1e-10, 1e-2, 1e-10),
hyperopt.hp.quniform('input_noise', 1e-10, 1e-2, 1e-10),
)
def _load_data(self, offset=False):
super(RlsExample, self)._load_data(offset)
# remove every other label
self.training_outputs[1::2] = np.nan
def _train(
self,
spectral_radius,
leaking_rate,
forgetting_factor,
autocorrelation_init,
bias_scale,
signal_scale,
state_noise,
input_noise,
):
self.esn = RlsEsn(
in_size=1,
reservoir_size=1000,
out_size=1,
spectral_radius=spectral_radius,
leaking_rate=leaking_rate,
forgetting_factor=forgetting_factor,
autocorrelation_init=autocorrelation_init,
state_noise=state_noise,
sparsity=0.95,
initial_transients=300,
squared_network_state=True,
activation_function=lecun,
)
self.esn.W_in *= [bias_scale, signal_scale]
# train
self.esn.fit(
np.array([self.training_inputs[0]]),
np.array([self.training_outputs[0]])
)
for input_date, output_date in zip(
add_noise(self.training_inputs[1:], input_noise),
self.training_outputs[1:]
):
if not np.isnan(output_date.item()):
self.esn.partial_fit(
np.array([input_date]),
np.array([output_date])
)
else:
# drive reservoir
self.esn.predict(input_date)
# test
predicted_outputs = [self.esn.predict(self.test_inputs[0])]
for i in range(len(self.test_inputs)-1):
predicted_outputs.append(self.esn.predict(predicted_outputs[i]))
return np.array(predicted_outputs)
|
0x64746b/python-esn
|
examples/superposed_sinusoid/rls.py
|
rls.py
|
py
| 3,499 |
python
|
en
|
code
| 0 |
github-code
|
6
|
73817307386
|
#
# test_ab.py - generic tests for analysis programs
# repagh <[email protected], May 2020
import pytest
from slycot import analysis
from slycot.exceptions import SlycotArithmeticError, SlycotResultWarning
from .test_exceptions import assert_docstring_parse
@pytest.mark.parametrize(
'fun, exception_class, erange, checkvars',
((analysis.ab05nd, SlycotArithmeticError, 1, {'p1': 1}),
(analysis.ab07nd, SlycotResultWarning, 2, {'m': 1}),
(analysis.ab09ad, SlycotArithmeticError, 3, {'dico': 'C'}),
(analysis.ab09ad, SlycotArithmeticError, (2,), {'dico': 'D'}),
(analysis.ab09ad, SlycotResultWarning, ((1, 0), ), {'nr': 3,
'Nr': 2}),
(analysis.ab09ax, SlycotArithmeticError, 2, {'dico': 'C'}),
(analysis.ab09ax, SlycotResultWarning, ((1, 0), ), {'nr': 3,
'Nr': 2}),
(analysis.ab09ad, SlycotArithmeticError, 3, {'dico': 'C'}),
(analysis.ab09ad, SlycotResultWarning, ((1, 0), ), {'nr': 3,
'Nr': 2}),
(analysis.ab09md, SlycotArithmeticError, 3, {'alpha': -0.1}),
(analysis.ab09md, SlycotResultWarning, ((1, 0), (2, 0)), {'nr': 3,
'Nr': 2,
'alpha': -0.1}),
(analysis.ab09nd, SlycotArithmeticError, 3, {'alpha': -0.1}),
(analysis.ab09nd, SlycotResultWarning, ((1, 0), (2, 0)), {'nr': 3,
'Nr': 2,
'alpha': -0.1}),
(analysis.ab13bd, SlycotArithmeticError, 6, {'dico': 'C'}),
(analysis.ab13bd, SlycotResultWarning, ((1, 0),), {}),
(analysis.ab13dd, SlycotArithmeticError, 4, {}),
(analysis.ab13ed, SlycotArithmeticError, 1, {}),
(analysis.ab13fd, SlycotArithmeticError, (2,), {}),
(analysis.ab13fd, SlycotResultWarning, (1,), {})))
def test_ab_docparse(fun, exception_class, erange, checkvars):
assert_docstring_parse(fun.__doc__, exception_class, erange, checkvars)
|
python-control/Slycot
|
slycot/tests/test_analysis.py
|
test_analysis.py
|
py
| 2,436 |
python
|
en
|
code
| 115 |
github-code
|
6
|
71888974267
|
# Fn = F[n-1]+ F[n-2](n=>2)
def fib(n):
if n==0 :
return [0]
elif n==1 :
return [0,1]
else:
fibs=[0,1,1]
for i in range(3,n):
fibs.append(fibs[-1]+fibs[-2])
return fibs
# 输出了第10个斐波那契数列
print(fib(8))
# a,b=0,1
# while a<1000:
# print(a,end=",")
# a,b=b,a+b
|
fivespeedasher/Pieces
|
pra6.py
|
pra6.py
|
py
| 353 |
python
|
en
|
code
| 0 |
github-code
|
6
|
16151353249
|
from tqdm import tqdm
import time
import argparse
N = int(1e9)
T = 1e-2
MAX_LEN = 100
def parse_args():
parser = argparse.ArgumentParser(description='i really wanna have a rest.')
parser.add_argument('-n', '--iters', type=int, default=N, help='rest iters.')
parser.add_argument('-f', '--frequency', type=float, default=1/T, help='rest frequency per iter.')
args = parser.parse_args()
return args
def have_a_rest():
args = parse_args()
str_ = ''
for idx in tqdm(range(args.iters)):
str_ = str_ + ' '
if len(str_) > MAX_LEN:
str_ = str_[MAX_LEN:]
str_to_print = str_ + 'kaizhong faker'
if idx % 10 < 5:
print(str_to_print)
else:
print(str_to_print + str_to_print)
time.sleep(1.0 / args.frequency)
if __name__ == '__main__':
have_a_rest()
|
I-Doctor/have-a-rest
|
have-a-rest.py
|
have-a-rest.py
|
py
| 871 |
python
|
en
|
code
| 0 |
github-code
|
6
|
7918280184
|
import os
import sys
import argparse
import netaddr
from netaddr import EUI
def _parse_args( args_str):
parser = argparse.ArgumentParser()
args, remaining_argv = parser.parse_known_args(args_str.split())
parser.add_argument(
"--username", nargs='?', default="admin",help="User name")
parser.add_argument(
"--password", nargs='?', default="contrail123",help="password")
parser.add_argument(
"--tenant_id", nargs='?', help="trnant id",required=True)
parser.add_argument(
"--config_node_port", help="config node port")
parser.add_argument(
"--config_node_ip", help="config node ip",required=True)
parser.add_argument(
"--physical_router_id", help="Physical router id")
parser.add_argument(
"--start_mac", help="Mac address of vcenter vm ",required=True)
parser.add_argument(
"--start_vn_name", help="Vn name to launch vmi",required=True)
parser.add_argument(
"--start_vlan", help="Initial vlan",required=True)
parser.add_argument(
"--number_of_vlan", help="number of vlans to be created",required=True)
parser.add_argument(
"--auth_url", nargs='?', default="check_string_for_empty",help="Auth Url",required=True)
args = parser.parse_args(remaining_argv)
return args
def get_mac_address_iter_obj(mac,start_range,end_range):
return iter(["{:012X}".format(int(mac, 16) + x) for x in range(int(start_range),int(end_range)+1)])
def get_subnet_iter_obj(subnet='1.1.1.0/24'):
addr,prefix = subnet.split('/')
ad1,ad2,ad3,ad4 = addr.split('.')
return iter([ad1+'.'+str(int(ad2)+x)+'.'+str(int(ad3)+y)+'.'+ad4+'/'+prefix for x in range(1,250) for y in range(1,250)])
def get_subnet_iter_obj_for_static_route(subnet='1.1.1.0/24'):
addr,prefix = subnet.split('/')
ad1,ad2,ad3,ad4 = addr.split('.')
return iter([str(int(ad1)+x)+'.'+ad2+'.'+ad3+'.'+ad4+'/'+prefix for x in range(1,250)])
def get_vn_name(base_vn_name,counter):
return base_vn_name + str(counter)
def get_vlan_range(start_vlan,numbers):
vlan_range=[]
end_vlan= int(start_vlan) + int(numbers)
for x in range(int(start_vlan),int(end_vlan)+1):
vlan_range.append(str(x))
return vlan_range
def main(args_str = None):
if not args_str:
script_args = ' '.join(sys.argv[1:])
script_args = _parse_args(script_args)
start_vlan = script_args.start_vlan
number_of_vlan = script_args.number_of_vlan
vlans = get_vlan_range(start_vlan,number_of_vlan)
mac = get_mac_address_iter_obj(script_args.start_mac,'0',number_of_vlan)
subnet = get_subnet_iter_obj()
static_route_subnet = get_subnet_iter_obj_for_static_route(subnet='2.0.1.0/24')
for vlan in vlans:
try:
m_addr = mac.next()
sub = subnet.next()
static_route_sub = static_route_subnet.next()
except StopIteration:
return
vn_name = get_vn_name(script_args.start_vn_name,vlan)
os.system("python vmi.py --static_route_subnet %s\
--tenant_id %s\
--config_node_ip %s\
--vcenter_vm_mac %s\
--vn_name %s\
--subnet %s\
--auth_url %s"
%(static_route_sub,
script_args.tenant_id,
script_args.config_node_ip,
m_addr,vn_name,sub,
script_args.auth_url
)
)
#python vmi_scale.py --tenant_id 74ebcac4-21da-4fe3-8c7f-e84c9e0424ca --config_node_ip 192.168.192.60 --start_mac 000029572113 --start_vn_name tor_vn_ --start_vlan 6 --number_of_vlan 7 --auth_url http://10.204.217.144:5000/v2.0
if __name__ == "__main__":
main()
|
sandip-d/scripts
|
vmi_scale.py
|
vmi_scale.py
|
py
| 3,983 |
python
|
en
|
code
| 0 |
github-code
|
6
|
73813195389
|
# physic_tank.py
'''
-----------------------------------------------------
function for calculating physics formula
1) Calculate Parameter : Charging Time, Discharging Time
2) Reverse Compute Tank Outlet Temperature
-----------------------------------------------------
'''
'==============================================================================================================================='
import numpy as np
def __init__(self, SWIT, SWOT, LWIT, LWOT, SWF, LWF, SWOT_1min, LOWT_1min, Node10_Heat_Discharg, Node1_Heat_Charg, Tank_ChargStorage, Tank_DischargStorage):
self.SWIT = SWIT
self.SWOT = SWOT
self.LWIT = LWIT
self.LWOT = LWOT
self.SWF = SWF
self.LWF = LWF
self.Node10_Heat_Discharg = Node10_Heat_Discharg
self.Tank_ChargStorage = Tank_ChargStorage
self.Node1_Heat_Charg = Node1_Heat_Charg
self.Tank_DischargStorage = Tank_DischargStorage
self.SWOT_1min = SWOT_1min
self.LOWT_1min = LOWT_1min
'------------------------'
# Parameter Calculate
'------------------------'
# 10 layer's Parmeter (kW - m^3/h)
# charging time
def Charging_para(SWIT, SWOT, SWF):
charge_para = ((SWOT - SWIT) * 2 * SWF * 1.162) / 10
return charge_para
# discharging time
def layer10_para(LWIT, SWOT, LFW, Node10_Heat_Discharg):
layer10parameter = []
for i, (a, b, c, d) in enumerate(zip(LWIT, SWOT, LFW, Node10_Heat_Discharg)):
if i == 0:
layer10para = d - (c * 1.162 * (a - b))
if layer10para < 0:
layer10para = 0
else:
layer10para = layer10para
else:
layer10para = d - (c * 1.162 * (a - b))
if layer10para < 0:
layer10para = 0
else:
layer10para = layer10para
layer10parameter.append(layer10para)
# 1 layer's Parmeter
# discharging time
def Discharging_para(LWIT, LWOT, LWF):
discharge_para = ((LWOT - LWIT) * 2 * LWF * 1.162) / -10
return discharge_para
# charging time
def layer01_para(SWIT, LOWT, SWF, Node1_Heat_Charg):
layer01parameter = []
for i, (a, b, c, d) in enumerate(zip(SWIT, LOWT, SWF, Node1_Heat_Charg)):
if i == 0:
layer01para = d - (c * 1.162 * (a - b))
if layer01para < 0:
layer01para = 0
else:
layer01para = layer01para
else:
layer01para = d - (c * 1.162 * (a - b))
if layer01para < 0:
layer01para = 0
else:
layer01para = layer01para
layer01parameter.append(layer01para)
'------------------------'
# Reverse Calculate
'------------------------'
# 10 layer
def Tank_SWOT(SWIT, LWIT, SWOT_1min, Node10_Heat_Discharg, SWF, LWF, Charging_para, layer10para):
# charging time
if SWF != 0 and LWF == 0:
TankSWOT = SWIT + ((1 / (2 * SWF * 1.162)) * Charging_para * 10)
# discharging time
elif LWF != 0 and SWF == 0:
if layer10para == 0:
TankSWOT = SWOT_1min
else:
TankSWOT = LWIT - (Node10_Heat_Discharg / (LWF * 1.162)) + (layer10para / (LWF * 1.162))
# 100% off
else:
TankSWOT = SWOT_1min
return TankSWOT
# Tank Total Charging Heat Sotrage
def Tank_Charging(SWIT, TankSWOT, SWF, LWF):
if SWF != 0 and LWF == 0:
TankCharging = ((SWIT-TankSWOT)*SWF*1000*4.184)
else:
TankCharging = 0
return TankCharging
# 10layer Heat Sotrage
def Tank_10layer_charging(LWIT, TankSWOT, SWF, LWF, layer10para):
if LWF != 0 and SWF == 0:
Tank_10layer_charging = ((LWIT - TankSWOT) * LWF * 1.162) + layer10para
else:
Tank_10layer_charging = 0
return Tank_10layer_charging
# 01 layer outlet temperature
def Tank_LWOT(LWIT, SWIT, LOWT_1min, Node1_Heat_Charg, LWF, SWF, Discharging_para, layer01para):
# discharging time
if LWF != 0 and SWF == 0:
TankLWOT = LWIT + ((1 / (2 * LWF * 1.162)) * Discharging_para * -10)
# charging time
elif SWF != 0 and LWF == 0:
if layer01para == 0:
TankLWOT = LOWT_1min
else:
TankLWOT = SWIT - (Node1_Heat_Charg / (SWF * 1.162)) + (layer01para / (SWF * 1.162))
# 100% off
else:
TankLWOT = LOWT_1min
return TankLWOT
# Tank Total Discharging Heat Sotrage
def Tank_Discharging(LWIT, TankLWOT, SWF, LWF):
if LWF != 0 and SWF == 0:
TankDischarging = ((LWIT-TankLWOT)*LWF*1000*4.184)
else:
TankDischarging = 0
return TankDischarging
# 01layer Heat Sotrage
def Tank_01layer_charging(SWIT, TankLWOT, SWF, LWF, layer01para):
if SWF != 0 and LWF == 0:
Tank_01layer_charging = ((SWIT - TankLWOT) * SWF * 1.162) + layer01para
else:
Tank_01layer_charging = 0
return Tank_01layer_charging
'==============================================================================================================================='
|
hyemi2022/hyemi2022
|
TotalModel_System_Calcuation/physic_tank.py
|
physic_tank.py
|
py
| 5,119 |
python
|
en
|
code
| 1 |
github-code
|
6
|
36703905624
|
import soundfile as sf
import numpy as np
import time
import matplotlib.pyplot as plt
from parameterization import STFT, iSTFT, optimal_synth_window, first_larger_square
DEF_PARAMS = {
"win_len": 25,
"win_ovlap": 0.75,
"blocks": 800,
"max_h_type": "lin-lin",
"min_gain_dry": 0,
"bias": 1.01,
"alpha": 0.1,
"gamma": 0.7,
}
TITLES = ["aula1_12", "kitchen_12", "stairway1_1", "test"]
SAMPLES = ["sploty/aula1/aula1_12.wav", "sploty/kitchen/kitchen_12.wav", "sploty/stairway1/stairway1_1.wav", "deverb_test_samples/test_raw.wav"]
TEST_SCOPE = False
def get_max_h_matrix(type, freqs, blocks):
if type == "log-log":
return (np.logspace(np.ones(freqs), np.ones(freqs) * np.finfo(np.float32).eps, blocks) *
np.logspace(np.ones(blocks), np.ones(blocks) * np.finfo(np.float32).eps, freqs).T - 1) / 99
elif type == "log-lin":
return (np.logspace(np.ones(freqs), np.ones(freqs) * np.finfo(np.float32).eps, blocks) *
np.linspace(np.ones(blocks), np.zeros(blocks), freqs).T) / 9
elif type == "log-full":
return (np.logspace(np.ones(freqs), np.ones(freqs) * np.finfo(np.float32).eps, blocks) - 1) / 9
elif type == "lin-log":
return (np.logspace(np.ones(freqs), np.ones(freqs) * np.finfo(np.float32).eps, blocks) *
np.logspace(np.ones(blocks), np.ones(blocks) * np.finfo(np.float32).eps, freqs).T - 1) / 9
elif type == "lin-lin":
return np.linspace(np.ones(freqs), np.zeros(freqs), blocks) * \
np.linspace(np.ones(blocks), np.zeros(blocks), freqs).T
elif type == "lin-full":
return np.linspace(np.ones(freqs), np.zeros(freqs), blocks)
else:
return np.ones((freqs, blocks)).T
def reconstruct(stft, window, overlap):
frame_count, frequency_count = stft.shape
sym_stft = np.hstack((stft, np.flipud(np.conj(stft[:, 0:frequency_count - 2]))))
signal = np.real(iSTFT(sym_stft, window, overlap))
return signal
def read_impulse_response(path, target_fs, target_bins, win_len, win_ovlap):
h, h_fs = sf.read(path)
h /= np.max(np.abs(h))
nfft = int(target_bins * h_fs / target_fs)
win_len = int(win_len / 1000 * h_fs)
win_ovlap = int(win_len * win_ovlap)
window = np.hanning(win_len)
H = STFT(h, window, win_ovlap, nfft, power=True)
return H[:, 0:target_bins // 2 + 1], H.shape[0]
def printProgressBar (iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd="\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
# Print New Line on Complete
if iteration == total:
print()
def dereverberate(wave, fs, params=None, estimate_execution_time=True, show_progress_bar=True):
"""
Estimates the impulse response in a room the recording took place
:param wave: 1-D ndarray of wave samples
:param fs: int - sampling frequency
:param params: dict containing the algorithm parameters - keys:
:param estimate_execution_time: should we print estimated execution time for each next frame
:param show_progress_bar: should we print progress bar of estimation
:returns: (h_stft_pow) 2-D ndarray power STFT of h_rir,
(wave_dry) 1-D ndarray of the dry signal,
(wave_wet) 1-D ndarray of the wet signal
"""
# estimating execution time
loop_times = np.zeros(10)
# =================== Parameters ===================
if params is None:
params = DEF_PARAMS
# ==================== Windowing ===================
win_len_ms = params["win_len"]
win_ovlap_p = params["win_ovlap"]
# ================ Times to samples ================
win_len = int(win_len_ms / 1000 * fs)
win_ovlap = int(win_len * win_ovlap_p)
window = np.hanning(win_len)
# =================== Signal stft ==================
nfft = first_larger_square(win_len)
sig_stft = STFT(wave, window, win_ovlap, nfft)
sig_stft = sig_stft[:, 0:nfft // 2 + 1]
frame_count, frequency_count = sig_stft.shape
# ==================== Constants ===================
# length of the impulse response
blocks = params["blocks"]
# minimum gain of dry signal per frequency
min_gain_dry = params["min_gain_dry"]
# maximum impulse response estimate
# max_h, blocks = read_impulse_response("deverb_test_samples/stalbans_a_mono.wav", fs, nfft, win_len_ms, win_ovlap_p)
max_h = get_max_h_matrix('const', frequency_count, blocks)
# bias used to keep magnitudes from getting stuck on a wrong minimum
bias = params["bias"]
# alpha and gamma - smoothing factors for impulse response magnitude and gain
alpha = params["alpha"]
gamma = params["gamma"]
# ==================== Algorithm ===================
# dry_stft and wet_stft are the estimated dry and reverberant signals in frequency-time domain
dry_stft = np.zeros((frame_count, frequency_count), dtype=np.csingle)
wet_stft = np.zeros((frame_count, frequency_count), dtype=np.csingle)
# h_stft_pow is the estimated impulse response in frequency-time domain
h_stft_pow = max_h / 2
# matrices with the information of currently estimated raw and dry signal (power spectra)
raw_frames = np.ones((blocks, frequency_count))
dry_frames = np.zeros((blocks, frequency_count))
# c is a matrix to keep the raw estimated powers of the impulse response
c = np.zeros((blocks, frequency_count))
# gain_dry and gain_wet are the frequency gains of the dry and wet signals
gain_dry = np.ones(frequency_count)
gain_wet = np.zeros(frequency_count)
for i in range(frame_count):
if estimate_execution_time:
remaining = round(np.mean(loop_times) * (frame_count - i))
loop_times[1:] = loop_times[0:-1]
loop_times[0] = time.time()
print("Processing frame {} of {}, estimated time left: {} ms".format(i + 1, frame_count, remaining))
frame = sig_stft[i, :]
frame_power = np.power(np.abs(frame), 2)
# estimate signals based on i-th frame
for b in range(blocks):
estimate = frame_power / raw_frames[b, :]
np.place(estimate, estimate >= h_stft_pow[b, :], h_stft_pow[b, :] * bias + np.finfo(np.float32).eps)
np.fmin(estimate, max_h[b, :], out=c[b, :])
h_stft_pow[b, :] = alpha * h_stft_pow[b, :] + (1 - alpha) * c[b, :]
# calculating gains
new_gain_dry = 1 - np.sum(dry_frames * h_stft_pow, axis=0) / frame_power
np.place(new_gain_dry, new_gain_dry < min_gain_dry, min_gain_dry)
gain_dry = gamma * gain_dry + (1 - gamma) * new_gain_dry
new_gain_wet = 1 - gain_dry
gain_wet = gamma * gain_wet + (1 - gamma) * new_gain_wet
# calculatnig signals
dry_stft[i, :] = gain_dry * frame
wet_stft[i, :] = gain_wet * frame
# shifting previous frames
dry_frames[1:blocks, :] = dry_frames[0:blocks - 1, :]
dry_frames[0, :] = np.power(np.abs(dry_stft[i, :]), 2)
raw_frames[1:blocks, :] = raw_frames[0:blocks - 1, :]
raw_frames[0, :] = frame_power
if estimate_execution_time:
loop_times[0] = round(1000 * (time.time() - loop_times[0]))
if show_progress_bar:
printProgressBar(i, frame_count, prefix='Progress', suffix='Complete', length=30)
window = optimal_synth_window(window, win_ovlap)
if TEST_SCOPE:
t = (np.arange(frame_count) * (win_len_ms * (1 - win_ovlap_p))).astype(int)
f = np.linspace(0, fs / 2, frequency_count).astype(int)
txx, fxx = np.meshgrid(t, f)
fig, axes = plt.subplots(3, 1, figsize=(10, 10))
axes[0].pcolormesh(txx, fxx, np.log10(np.power(np.abs(sig_stft.T), 2)), cmap=plt.get_cmap('plasma'))
axes[0].set_title("Original signal")
axes[1].pcolormesh(txx, fxx, np.log10(np.power(np.abs(dry_stft.T), 2)), cmap=plt.get_cmap('plasma'))
axes[1].set_title("Dry signal")
axes[2].pcolormesh(txx, fxx, np.log10(np.power(np.abs(wet_stft.T), 2)), cmap=plt.get_cmap('plasma'))
axes[2].set_title("Reverberant signal")
fig.show()
wave_dry = reconstruct(dry_stft, window, win_ovlap)
wave_wet = reconstruct(wet_stft, window, win_ovlap)
return h_stft_pow, wave_dry, wave_wet
def test_deverb():
for i, item in enumerate(SAMPLES):
# i = 3
# item = SAMPLES[3]
print("Estimating " + item)
wave, fs = sf.read(item)
wave = wave / np.max(np.abs(wave))
H_rir, dry_wav, wet_wav = dereverberate(wave, fs, estimate_execution_time=False)
min_size = np.min([wave.size, dry_wav.size, wet_wav.size])
t = np.linspace(0, min_size / fs, min_size)
fig, axes = plt.subplots(3, 1, figsize=(10, 10))
fig.suptitle("estimated signals - {} reverb".format(TITLES[i]))
axes[0].plot(t, wave[0:min_size])
axes[0].set_title("original")
axes[1].plot(t, dry_wav[0:min_size])
axes[1].set_title("dry")
axes[2].plot(t, wet_wav[0:min_size])
axes[2].set_title("reverberant")
axes[2].set_xlabel(r"time $[s]$")
fig.tight_layout()
fig.show()
frames, freqs = H_rir.shape
hop = DEF_PARAMS["win_len"] * (1 - DEF_PARAMS["win_ovlap"]) / 1000
f = np.linspace(0, fs / 2000, freqs)
t = np.linspace(0, hop * frames, frames)
fxx, txx = np.meshgrid(f, t)
fig, ax = plt.subplots(figsize=(6, 5))
ax.pcolormesh(txx, fxx, np.log10(H_rir), cmap=plt.get_cmap('plasma'))
ax.set_title(r"estimated $H_{rir}$: " + TITLES[i])
ax.set_xlabel(r"time $[s]$")
ax.set_ylabel(r"frequency $[kHz]$")
fig.show()
with open("tmp/dry_{}.wav".format(TITLES[i]), "wb") as f:
sf.write(f, dry_wav, fs)
with open("tmp/wet_{}.wav".format(TITLES[i]), "wb") as f:
sf.write(f, wet_wav, fs)
if __name__ == "__main__":
TEST_SCOPE = True
test_deverb()
|
Revzik/AGH-ZTPS_Acoustical-Environment-Classification
|
deverb.py
|
deverb.py
|
py
| 10,820 |
python
|
en
|
code
| 0 |
github-code
|
6
|
31865827642
|
import tensorflow as tf
import numpy as np
import sys
class conv3:
def __init__(self,numfilter):
self.numfilter=numfilter
self.filmat=np.random.randn(3,3,numfilter)/9 #to decrease
def forward(self,input):
l,b=input.shape
self.chache_input=input
#paddedinput=zeros(input.shape[0]+2,input.shape[1]+2)
#paddedinput[1:input.shape[0]+1,1:input.shape[1]+1]+=input
out=np.zeros((l-2,b-2,8))
for i in range(l-2):
for j in range(b-2):
for f in range(self.numfilter):
#dl_dfilter[:,:,f]+=dl_dout[i,j,f]*self.chache_input[i:i+3,j:j+3]
out[i,j,f]=np.sum(input[i:i+3,j:j+3]*self.filmat[:,:,f],axis=(0,1))
return out
def backward(self,dl_dout,learning):
l,b,h=self.filmat.shape
dl_dfilter=np.zeros((l,b,h))
for i in range(l-2):
for j in range(b-2):
for f in range(h):
dl_dfilter[:,:,f]+=dl_dout[i,j,f]*self.chache_input[i:i+3,j:j+3]
self.filmat-=learning*dl_dfilter
return None
class maxpool2:
def forward(self,input):
l,b,h=input.shape
self.chache_input=input
out=np.zeros((l//2,b//2,h))
for i in range(l//2):
for j in range(b//2):
out[i,j,:]=np.amax(input[2*i:2*i+2,2*j:2*j+2,:],axis=(0,1))
return out
def backward(self,gradient):
l,b,h=self.chache_input.shape
dl_dinput=np.zeros((l,b,h))
for i in range(l//2):
for j in range(b//2):
for k in range(h):
amaxi=np.amax(self.chache_input[2*i:2*i+2,2*j:2*j+2,k],axis=(0,1))
if self.chache_input[2*i,2*j,k]==amaxi :
dl_dinput[2*i,2*j,k]=gradient[i,j,k]
elif self.chache_input[2*i+1,2*j,k]==amaxi :
dl_dinput[2*i+1,2*j,k]=gradient[i,j,k]
elif self.chache_input[2*i,2*j+1,k]==amaxi :
dl_dinput[2*i,2*j+1,k]=gradient[i,j,k]
elif self.chache_input[2*i+1,2*j+1,k]==amaxi :
dl_dinput[2*i+1,2*j+1,k]=gradient[i,j,k]
return dl_dinput
class Softmax:
def __init__(self,input_length,nodes):
self.weights=np.random.randn(input_length,nodes)/input_length #1
self.biases = np.zeros(nodes)
def forward(self,input):
self.chache_shape=input.shape
input=input.flatten()
self.chache_input=input
input_len, nodes = self.weights.shape
total=np.dot(input,self.weights)+self.biases
total=total.astype(np.float128)
# self.chache_total=tot
#total=tota/np.amax(tota)
ex=np.exp(total)
self.chache_prob=ex/np.sum(ex,axis=0) #2
return self.chache_prob
def backward(self , dl_dout,learning,label): #gradient is dl_dout
dout_dt=-(self.chache_prob)*self.chache_prob[label]
dout_dt[label]+=self.chache_prob[label]
dl_dt= dl_dout * dout_dt #dl/dt=dl/dout * dout/dt
#totals=input*weight+bias
dt_db=1
dt_dinput=self.weights
dt_dw=self.chache_input
#dl/dinput=dl/dt*dt/dinput
dl_dinput= dt_dinput @ dl_dt
#dl/dw=dl/dt*dt/dw
dl_dw=dt_dw[np.newaxis].T @ dl_dt[np.newaxis]
#dl/db=dl/dt*dt/db (dt/db=1)
dl_db=dl_dt
#print(learning)
self.weights-=learning * dl_dw
self.biases-=learning * dl_db
return dl_dinput.reshape(self.chache_shape)
# Data initialisation
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
print([i.shape for i in (x_train, y_train, x_test, y_test)])
#taking only 2000 examples
x_train=x_train[0:1000]
y_train=y_train[0:1000]
x_test, y_test=x_test[0:1000], y_test[:1000]
numfilter=8
conv = conv3(8) #8 layer filters
pool = maxpool2() # 26x26x8 -> 13x13x8 ,pool size=2
softmax = Softmax(13 * 13 * 8, 10) # 13x13x8 -> 10 ,10nodes
def forward(image, label):
out = conv.forward((image / 255) - 0.5)
out = pool.forward(out)
out = softmax.forward(out)
# Calculate cross-entropy loss and accuracy. np.log() is the natural log.
loss = -np.log(out[label])
acc = 1 if np.argmax(out) == label else 0
return out, loss, acc
def train(image,label,learning):
lr=learning
out, loss, acc=forward(image,label) #array with probability , 10*1
gradient=np.zeros(10)
if out[label]!=0:
gradient[label]=-1/out[label] #3
gradient=softmax.backward( gradient,learning,label )
gradient=pool.backward(gradient)
gradient=conv.backward(gradient,lr)
return loss,acc
print('MNIST CNN initialized!')
loss = 0
num_correct = 0
for j in range(1,4):
print("training round %d"%(j))
permut=np.random.permutation(len(x_train))
x_train=x_train[permut]
y_train=y_train[permut]
for i, (im, label) in enumerate(zip(x_train, y_train)):
# Do a forward pass.
# Print stats every 100 steps.
if i % 100 == 99:
print(
'[Step %d] Past 100 steps: Average Loss %.3f | Accuracy: %d%%' %
(i + 1, loss / 100, num_correct)
)
loss = 0
num_correct = 0
l, acc = train(im, label,0.005)
loss += l
num_correct += acc
loss = 0
num_correct = 0
for i, (im, label) in enumerate(zip(x_test, y_test)):
# Do a forward pass.
_, l, acc = forward(im, label)
loss += l
num_correct += acc
#num_tests = len(x_test)
print('Test Loss:', loss / 1000)
print('Test Accuracy:', num_correct / 1000)
|
Jitendra29-78/Sudoku-Digit-Recognition
|
cnn.py
|
cnn.py
|
py
| 5,170 |
python
|
en
|
code
| 0 |
github-code
|
6
|
27593505084
|
import logging
from logging.handlers import TimedRotatingFileHandler
import os
server_logger = logging.getLogger('server')
PATH = os.path.dirname(os.path.abspath(__file__))
PATH = os.path.join(PATH, 'server.log')
formatter = logging.Formatter(
'%(asctime)s %(levelname)-8s %(funcName)s %(message)s',
datefmt='%Y %b %d %H:%M:%S',
)
file_hand = logging.handlers.TimedRotatingFileHandler(
filename=PATH, when='D', interval=1, encoding='utf-8', delay=True,
backupCount=31, atTime=None
)
file_hand.setFormatter(formatter)
file_hand.setLevel(logging.DEBUG)
server_logger.addHandler(file_hand)
server_logger.setLevel(logging.DEBUG)
if __name__ == '__main__':
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(formatter)
server_logger.addHandler(console)
server_logger.info('Тестовый запуск логирования')
|
ide007/DB_and_PyQT
|
Lesson_1/logs/server_log_config.py
|
server_log_config.py
|
py
| 902 |
python
|
en
|
code
| 0 |
github-code
|
6
|
71409709627
|
###############################
####### SETUP (OVERALL) #######
###############################
## Import statements
# Import statements
import os
from flask import Flask, render_template, session, redirect, url_for, flash, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, RadioField, ValidationError # Note that you may need to import more here! Check out examples that do what you want to figure out what.
from wtforms.validators import Required, Length # Here, too
from flask_sqlalchemy import SQLAlchemy
import json
import requests
## App setup code
app = Flask(__name__)
app.debug = True
app.use_reloader = True
app.config['SECRET_KEY'] = 'pokemonpokemon'
## All app.config values
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://localhost/Midterm-katmazan"
## Provided:
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
## Statements for db setup (and manager setup if using Manager)
db = SQLAlchemy(app)
######################################
######## HELPER FXNS (If any) ########
######################################
##################
##### MODELS #####
##################
class Name(db.Model):
__tablename__ = "names"
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String)
height_value = db.Column(db.Integer, db.ForeignKey('heights.id'))
weight_value = db.Column(db.Integer, db.ForeignKey('weights.id'))
def __repr__(self):
return ('{' + str(self.name) + '} | ID: {' + str(self.id) + '}')
class Height(db.Model):
__tablename__ = 'heights'
id = db.Column(db.Integer, primary_key=True)
poke_height = db.Column(db.Integer)
poke_name = db.Column(db.String)
names = db.relationship('Name',backref='Height')
class Weight(db.Model):
__tablename__ = 'weights'
id = db.Column(db.Integer,primary_key=True)
poke_name = db.Column(db.String)
poke_weight = db.Column(db.Integer)
names = db.relationship('Name',backref='Weight')
###################
###### FORMS ######
###################
class NameForm(FlaskForm):
name = StringField("Pokemon_name",validators=[Required()])
submit = SubmitField()
def validate_name(self, field):
if len(field.data) <= 1:
raise ValidationError('Pokemon does not exist')
class FavoriteForm(FlaskForm):
fav_name = StringField("Add one of your favorite Pokemon:")
nick_name = StringField("Give your favorite a nickname:")
submit = SubmitField()
def validate_nick_name(self,field):
if field.data[-1] != 'y':
raise ValidationError("Your nickname must end in y!")
class RankForm(FlaskForm):
name = StringField('Enter a Pokemon name:', validators = [Required()])
rate = RadioField('Rate this pokemon in terms of how powerful you think it is', choices = [('1', '1 (low)'), ('2', '2'), ('3', '3 (high)')])
submit = SubmitField('Submit')
#######################
###### VIEW FXNS ######
#######################
@app.errorhandler(404)
def page_not_found(e):
return render_template('404_error.html'), 404
@app.route('/', methods = ['GET', 'POST'])
def home():
form = NameForm() # User should be able to enter name after name and each one will be saved, even if it's a duplicate! Sends data with GET
if form.validate_on_submit():
poke_name = form.name.data
pokemon = Name.query.filter_by(name=poke_name).first()
##only adds pokemon if it is not in database
if not pokemon:
params = {}
params['name'] = str(poke_name)
print(params)
response = requests.get('http://pokeapi.co/api/v2/pokemon/' + params['name'] + '/')
##if response.status_code != '200':
##return("The data you entered was not available in the data, check spelling")
poke_height = int(json.loads(response.text)['height'])
new_height = Height(poke_height = poke_height, poke_name = poke_name)
db.session.add(new_height)
db.session.commit()
poke_weight = int(json.loads(response.text)['weight'])
new_weight = Weight(poke_weight = poke_weight, poke_name = poke_name)
db.session.add(new_weight)
db.session.commit()
print('hello')
newname = Name(name = poke_name, height_value = new_height.id, weight_value = new_weight.id)
db.session.add(newname)
db.session.commit()
return redirect(url_for('all_names'))
errors = [v for v in form.errors.values()]
if len(errors) > 0:
flash("!!!! ERRORS IN FORM SUBMISSION - " + str(errors))
return render_template('base.html',form=form)
@app.route('/names')
def all_names():
names = Name.query.all()
return render_template('name_example.html',names=names)
@app.route('/tallest')
def tallest_pokemon():
all_heights = Height.query.all()
tallest_pokemon = 0
for h in all_heights:
height = h.poke_height
if height > tallest_pokemon:
tallest_pokemon = height
tp = h
tallest = tp.poke_name
height = tp.poke_height
return render_template('tallest_pokemon.html', tallest = tallest, height = height, names = all_heights)
@app.route('/heaviest')
def heaviest_pokemon():
all_weights = Weight.query.all()
heaviest_pokemon = 0
for w in all_weights:
weight = w.poke_weight
if weight > heaviest_pokemon:
heaviest_pokemon = weight
hp = w
heaviest = hp.poke_name
weight = hp.poke_weight
return render_template('heaviest.html', heaviest = heaviest, weight = weight, names = all_weights)
@app.route('/favorite_pokemon')
def favorite_form():
form = FavoriteForm()
return render_template('favorite_form.html', form = form)
@app.route('/fav_answers',methods=["GET","POST"])
def show_favs():
form = FavoriteForm()
if request.args:
fav_name = form.fav_name.data
nickname = form.nick_name.data
return render_template('fav_results.html',fav_name=fav_name, nick_name=nickname)
flash(form.errors)
return redirect(url_for('favorite_form'))
## Code to run the application...
# Put the code to do so here!
# NOTE: Make sure you include the code you need to initialize the database structure when you run the application!
if __name__ == '__main__':
db.create_all() # Will create any defined models when you run the application
app.run(use_reloader=True,debug=True) # The usual
|
katmazan/SI364midtermKatmazan
|
SI364midterm.py
|
SI364midterm.py
|
py
| 6,662 |
python
|
en
|
code
| 0 |
github-code
|
6
|
40056102923
|
#Link: https://leetcode.com/problems/kth-largest-element-in-an-array/
# Name: Kth Largest Element in an Array
# Difficulty: Medium
# Topic: Min Heap
#Time: O(n log k) since we update the root a maximum of n times, each update is a log k operation
#Space: O(k) for size of heap used
import heapq
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
if(k > len(nums)):
return
#Initialize Heap
minHeap = []
heapq.heapify(minHeap)
for i in range(k):
heapq.heappush(minHeap, nums[i])
#Update heap
for i in range(k, len(nums)):
root = minHeap[0]
if(nums[i] >= root):
removed = heapq.heappop(minHeap)
heapq.heappush(minHeap, nums[i])
#return lowest number in heap
return heapq.heappop(minHeap)
|
Shivaansh/AlgoExpert-LeetCode-Solutions
|
LeetCode Problems/Python/KthLargestElementInAnArray.py
|
KthLargestElementInAnArray.py
|
py
| 879 |
python
|
en
|
code
| 2 |
github-code
|
6
|
29433457016
|
#! /usr/bin/env python
#
# Implementation of elliptic curves, for cryptographic applications.
#
# This module doesn't provide any way to choose a random elliptic
# curve, nor to verify that an elliptic curve was chosen randomly,
# because one can simply use NIST's standard curves.
#
# Notes from X9.62-1998 (draft):
# Nomenclature:
# - Q is a public key.
# The "Elliptic Curve Domain Parameters" include:
# - q is the "field size", which in our case equals p.
# - p is a big prime.
# - G is a point of prime order (5.1.1.1).
# - n is the order of G (5.1.1.1).
# Public-key validation (5.2.2):
# - Verify that Q is not the point at infinity.
# - Verify that X_Q and Y_Q are in [0,p-1].
# - Verify that Q is on the curve.
# - Verify that nQ is the point at infinity.
# Signature generation (5.3):
# - Pick random k from [1,n-1].
# Signature checking (5.4.2):
# - Verify that r and s are in [1,n-1].
#
# Version of 2008.11.25.
#
# Revision history:
# 2005.12.31 - Initial version.
# 2008.11.25 - Change CurveFp.is_on to contains_point.
#
# Written in 2005 by Peter Pearson and placed in the public domain.
from __future__ import division
from .six import print_
from . import numbertheory
class CurveFp( object ):
"""Elliptic Curve over the field of integers modulo a prime."""
def __init__( self, p, a, b ):
"""The curve of points satisfying y^2 = x^3 + a*x + b (mod p)."""
self.__p = p
self.__a = a
self.__b = b
def p( self ):
return self.__p
def a( self ):
return self.__a
def b( self ):
return self.__b
def contains_point( self, x, y ):
"""Is the point (x,y) on this curve?"""
return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0
class Point( object ):
"""A point on an elliptic curve. Altering x and y is forbidding,
but they can be read by the x() and y() methods."""
def __init__( self, curve, x, y, order = None ):
"""curve, x, y, order; order (optional) is the order of this point."""
self.__curve = curve
self.__x = x
self.__y = y
self.__order = order
# self.curve is allowed to be None only for INFINITY:
if self.__curve: assert self.__curve.contains_point( x, y )
if order: assert self * order == INFINITY
def __eq__( self, other ):
"""Return True if the points are identical, False otherwise."""
if self.__curve == other.__curve \
and self.__x == other.__x \
and self.__y == other.__y:
return True
else:
return False
def __add__( self, other ):
"""Add one point to another point."""
# X9.62 B.3:
if other == INFINITY: return self
if self == INFINITY: return other
assert self.__curve == other.__curve
if self.__x == other.__x:
if ( self.__y + other.__y ) % self.__curve.p() == 0:
return INFINITY
else:
return self.double()
p = self.__curve.p()
l = ( ( other.__y - self.__y ) * \
numbertheory.inverse_mod( other.__x - self.__x, p ) ) % p
x3 = ( l * l - self.__x - other.__x ) % p
y3 = ( l * ( self.__x - x3 ) - self.__y ) % p
return Point( self.__curve, x3, y3 )
def __mul__( self, other ):
"""Multiply a point by an integer."""
def leftmost_bit( x ):
assert x > 0
result = 1
while result <= x: result = 2 * result
return result // 2
e = other
if self.__order: e = e % self.__order
if e == 0: return INFINITY
if self == INFINITY: return INFINITY
assert e > 0
# From X9.62 D.3.2:
e3 = 3 * e
negative_self = Point( self.__curve, self.__x, -self.__y, self.__order )
i = leftmost_bit( e3 ) // 2
result = self
# print_("Multiplying %s by %d (e3 = %d):" % ( self, other, e3 ))
while i > 1:
result = result.double()
if ( e3 & i ) != 0 and ( e & i ) == 0: result = result + self
if ( e3 & i ) == 0 and ( e & i ) != 0: result = result + negative_self
# print_(". . . i = %d, result = %s" % ( i, result ))
i = i // 2
return result
def __rmul__( self, other ):
"""Multiply a point by an integer."""
return self * other
def __str__( self ):
if self == INFINITY: return "infinity"
return "(%d,%d)" % ( self.__x, self.__y )
def double( self ):
"""Return a new point that is twice the old."""
if self == INFINITY:
return INFINITY
# X9.62 B.3:
p = self.__curve.p()
a = self.__curve.a()
l = ( ( 3 * self.__x * self.__x + a ) * \
numbertheory.inverse_mod( 2 * self.__y, p ) ) % p
x3 = ( l * l - 2 * self.__x ) % p
y3 = ( l * ( self.__x - x3 ) - self.__y ) % p
return Point( self.__curve, x3, y3 )
def x( self ):
return self.__x
def y( self ):
return self.__y
def curve( self ):
return self.__curve
def order( self ):
return self.__order
# This one point is the Point At Infinity for all purposes:
INFINITY = Point( None, None, None )
def __main__():
class FailedTest(Exception): pass
def test_add( c, x1, y1, x2, y2, x3, y3 ):
"""We expect that on curve c, (x1,y1) + (x2, y2 ) = (x3, y3)."""
p1 = Point( c, x1, y1 )
p2 = Point( c, x2, y2 )
p3 = p1 + p2
print_("%s + %s = %s" % ( p1, p2, p3 ), end=' ')
if p3.x() != x3 or p3.y() != y3:
raise FailedTest("Failure: should give (%d,%d)." % ( x3, y3 ))
else:
print_(" Good.")
def test_double( c, x1, y1, x3, y3 ):
"""We expect that on curve c, 2*(x1,y1) = (x3, y3)."""
p1 = Point( c, x1, y1 )
p3 = p1.double()
print_("%s doubled = %s" % ( p1, p3 ), end=' ')
if p3.x() != x3 or p3.y() != y3:
raise FailedTest("Failure: should give (%d,%d)." % ( x3, y3 ))
else:
print_(" Good.")
def test_double_infinity( c ):
"""We expect that on curve c, 2*INFINITY = INFINITY."""
p1 = INFINITY
p3 = p1.double()
print_("%s doubled = %s" % ( p1, p3 ), end=' ')
if p3.x() != INFINITY.x() or p3.y() != INFINITY.y():
raise FailedTest("Failure: should give (%d,%d)." % ( INFINITY.x(), INFINITY.y() ))
else:
print_(" Good.")
def test_multiply( c, x1, y1, m, x3, y3 ):
"""We expect that on curve c, m*(x1,y1) = (x3,y3)."""
p1 = Point( c, x1, y1 )
p3 = p1 * m
print_("%s * %d = %s" % ( p1, m, p3 ), end=' ')
if p3.x() != x3 or p3.y() != y3:
raise FailedTest("Failure: should give (%d,%d)." % ( x3, y3 ))
else:
print_(" Good.")
# A few tests from X9.62 B.3:
c = CurveFp( 23, 1, 1 )
test_add( c, 3, 10, 9, 7, 17, 20 )
test_double( c, 3, 10, 7, 12 )
test_add( c, 3, 10, 3, 10, 7, 12 ) # (Should just invoke double.)
test_multiply( c, 3, 10, 2, 7, 12 )
test_double_infinity(c)
# From X9.62 I.1 (p. 96):
g = Point( c, 13, 7, 7 )
check = INFINITY
for i in range( 7 + 1 ):
p = ( i % 7 ) * g
print_("%s * %d = %s, expected %s . . ." % ( g, i, p, check ), end=' ')
if p == check:
print_(" Good.")
else:
raise FailedTest("Bad.")
check = check + g
# NIST Curve P-192:
p = 6277101735386680763835789423207666416083908700390324961279
r = 6277101735386680763835789423176059013767194773182842284081
#s = 0x3045ae6fc8422f64ed579528d38120eae12196d5L
c = 0x3099d2bbbfcb2538542dcd5fb078b6ef5f3d6fe2c745de65
b = 0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1
Gx = 0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012
Gy = 0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811
c192 = CurveFp( p, -3, b )
p192 = Point( c192, Gx, Gy, r )
# Checking against some sample computations presented
# in X9.62:
d = 651056770906015076056810763456358567190100156695615665659
Q = d * p192
if Q.x() != 0x62B12D60690CDCF330BABAB6E69763B471F994DD702D16A5:
raise FailedTest("p192 * d came out wrong.")
else:
print_("p192 * d came out right.")
k = 6140507067065001063065065565667405560006161556565665656654
R = k * p192
if R.x() != 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD \
or R.y() != 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835:
raise FailedTest("k * p192 came out wrong.")
else:
print_("k * p192 came out right.")
u1 = 2563697409189434185194736134579731015366492496392189760599
u2 = 6266643813348617967186477710235785849136406323338782220568
temp = u1 * p192 + u2 * Q
if temp.x() != 0x885052380FF147B734C330C43D39B2C4A89F29B0F749FEAD \
or temp.y() != 0x9CF9FA1CBEFEFB917747A3BB29C072B9289C2547884FD835:
raise FailedTest("u1 * p192 + u2 * Q came out wrong.")
else:
print_("u1 * p192 + u2 * Q came out right.")
if __name__ == "__main__":
__main__()
|
espressif/ESP8266_RTOS_SDK
|
components/esptool_py/esptool/ecdsa/ellipticcurve.py
|
ellipticcurve.py
|
py
| 8,609 |
python
|
en
|
code
| 3,148 |
github-code
|
6
|
16053211401
|
import os
import sys
import glob
import argparse
from lsdo_viz.problem import Problem
from lsdo_viz.utils import clean, get_viz, get_args, exec_python_file
def main_viz(args=None):
if args is None:
args = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument('args_file_name', nargs='?', default='viz_args.py')
parser.add_argument('--clean_data', '-cd', nargs='?', default=None, const=True)
parser.add_argument('--clean_frames', '-cf', nargs='?', default=None, const=True)
parser.add_argument('--viz_initial', '-vi', nargs='?', default=None, const=True)
parser.add_argument('--viz_final', '-vf', nargs='?', default=None, const=True)
parser.add_argument('--viz_initial_show', '-vis', nargs='?', default=None, const=True)
parser.add_argument('--viz_final_show', '-vfs', nargs='?', default=None, const=True)
parser.add_argument('--viz_all', '-va', nargs='?', default=None, const=True)
parser.add_argument('--movie', '-m', nargs='?', default=None, const=True)
parsed_args = parser.parse_args(args)
args = get_args(parsed_args.args_file_name)
show = parsed_args.viz_initial_show or parsed_args.viz_final_show
if not show:
import matplotlib
matplotlib.use('Agg')
if parsed_args.clean_data:
clean(args.data_dir)
if parsed_args.clean_frames:
clean(args.frames_dir)
modes = []
if parsed_args.viz_initial or parsed_args.viz_initial_show:
modes.append('viz_initial')
if parsed_args.viz_final or parsed_args.viz_final_show:
modes.append('viz_final')
if parsed_args.viz_all:
modes.append('viz_all')
if parsed_args.movie:
modes.append('movie')
Problem.args = args
Problem.viz = get_viz(args.viz_file_name)
Problem.viz.args = args
Problem.viz.show = show
for mode in modes:
Problem.mode = mode
exec_python_file(args.run_file_name)
|
MAE155B-Group-3-SP20/Group3Repo
|
lsdo_viz/lsdo_viz/main_viz.py
|
main_viz.py
|
py
| 1,938 |
python
|
en
|
code
| 0 |
github-code
|
6
|
22916095420
|
#Create a gspread class and extract the data from the sheets
#requires:
# 1. Google API credentials json_key file path
# 2. scope e.g. ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
# 3. gspread_url e.g. 'https://docs.google.com/spreadsheets/d/1itaohdPiAeniCXNlntNztZ_oRvjh0HsGuJXUJWET008/edit?usp=sharing'
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd
class gspread_obj(object):
"""
Create a google spreadsheet instance to download sheet(s) and merge them
Requires spreadsheet url and Google API json key file
Examples:
>>>> gc = gspread_obj()
>>>> gc.login('home/user/google_api_key.json')
>>>> gc.get_sheets('https://docs.google.com/spreadsheets/d/1itaohdPiAeniCXNlntNztZ_oRvjh0HsGuJXUJWET008/edit?usp=sharing')
>>>> df = gc.merge_sheets()
"""
def __init__(self):
self.scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
self.client = None # gspread.Client object
self.sheets = None
def login(self, credentials_google: str):
#set Google spreadsheet credentials
credentials = ServiceAccountCredentials.from_json_keyfile_name(credentials_google, self.scope)
self.client = gspread.authorize(credentials)
def get_sheets(self, gspread_url: str):
#Get Google sheet instance
wks = self.client.open_by_url(gspread_url)
self.sheets = wks.worksheets()
def merge_sheets(self):
if self.sheets is None:
print('No sheets are found!')
df = None
elif len(self.sheets)==1:
data = self.sheets[0].get_all_values()
header = data.pop(0)
df = pd.DataFrame(data, columns=header)
elif len(self.sheets)>1:
#read all the sheets
df_list = []
for s in self.sheets:
data = s.get_all_values()
header = data.pop(0)
df = pd.DataFrame(data, columns=header)
df_list.append(df)
df = pd.concat(df_list, axis=0, join='outer', sort=False)
else:
print("self.sheets must be a list of sheet(s)!")
df = None
if df is not None:
print("Columns: ", df.columns)
print("{} Rows x {} Columns".format(df.shape[0],df.shape[1]))
return df
|
yenlow/utils
|
apis/google.py
|
google.py
|
py
| 2,442 |
python
|
en
|
code
| 1 |
github-code
|
6
|
3084393112
|
import numpy as np
import pandas as pd
import math
import json
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import optuna
def create_data(f1, f2, A1, A2, sigma=0.02):
outs = []
ts = 1000
theta1 = 1.4
theta2 = 1.0
for t in range(ts):
# if t == 500:
# theta1 = 1.4
# theta2 = -0.5
# elif t == 1500:
# theta1 = 0.7
# theta2 = 0.0
n_f1 = np.random.normal(0.0, 0.05)
n_f2 = np.random.normal(0.0, 0.05)
val = A1*math.sin(f1*t+theta1+n_f1) + A2*math.sin(f2*t+theta2+n_f2) + np.random.normal(0.0, sigma)
outs.append(val)
return np.array(outs)
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def relu(x):
if x > 0:
return x
else:
return 0.
### EKF
def predict_phase(x_vec, P_mat, J_s=np.eye(2), dw=np.array([0.01, 0.1]), Q_t=np.ones((2,2))):
# J_s: Jacobian
x_hat = x_vec + dw
P_hat = np.matmul(np.matmul(J_s,P_mat),J_s.T) + Q_t
return x_hat, P_hat
def update_phase(obs, x_hat, P_hat, x_vec, P_mat, w_vec, R_t=np.eye(2)):
y_error = obs - (np.sin(x_hat[0])+0.3*np.sin(x_hat[1]))
w_err = np.array([np.tanh(y_error*w_vec[0]), np.tanh(y_error*w_vec[1]), np.tanh(y_error*w_vec[2]), np.tanh(y_error*w_vec[3])])
alpha = sigmoid(np.dot(w_err, w_vec[4:]))
J_o = np.array([np.cos(x_hat[0]), 0.3*np.cos(x_hat[1])]) # Jacobian
S_t = np.matmul(np.matmul(J_o, P_hat), J_o.T) + R_t
K_t = np.matmul(np.matmul(P_hat, J_o.T), np.linalg.inv(S_t)) # Kalman Gain
K_t = K_t*np.array([alpha, 1.-alpha])
new_x_vec = x_vec + K_t*y_error
new_P_mat = np.matmul((np.eye(2) - np.matmul(K_t, J_o)), P_hat)
return new_x_vec, new_P_mat, y_error, alpha, K_t
ys = create_data(f1=0.01, f2=0.1, A1=1.0, A2=0.3, sigma=0.05)
# w_dict = {'w1': 0.8654948627671226, 'w2': -1.7444762795695032, 'w3': -1.256158244213108, 'w4': 2.9877172040880846, 'w5': 0.7674940690302532, 'w6': -0.5751565428986629, 'w7': -2.1525316155059886, 'w8': -1.593668210140296}
w_dict = {'w1': 0.8868339845276003, 'w2': -2.4239527390853723, 'w3': 2.5663446991064536, 'w4': -1.835679959314501, 'w5': 2.668697875044799, 'w6': -0.578802425496894, 'w7': -2.3135794565999737, 'w8': -0.9460572459969298}
w1 = w_dict['w1']
w2 = w_dict['w2']
w3 = w_dict['w3']
w4 = w_dict['w4']
w5 = w_dict['w5']
w6 = w_dict['w6']
w7 = w_dict['w7']
w8 = w_dict['w8']
W_1 = np.array([w1, w2, w3, w4, w5, w6, w7, w8])
x_vec = np.array([0.0, 0.0])
P_mat = np.eye(2)
total_err = 0.0
alphas = []
y_errors = []
preds = []
k_gains = []
ttt = 1
for _y in ys[1:]:
x_hat, P_hat = predict_phase(x_vec, P_mat)
new_x_vec, new_P_mat, y_error, _alpha, K_t = update_phase(_y, x_hat, P_hat, x_vec, P_mat, W_1)
x_vec = new_x_vec
P_mat = new_P_mat
total_err = total_err + np.sqrt(y_error*y_error)
alphas.append(_alpha)
y_errors.append(np.abs(y_error))
preds.append(np.sin(x_vec[0])+0.3*np.sin(x_vec[1]))
k_gains.append(K_t.tolist())
# print(ttt, y_error, _alpha)
ttt = ttt + 1
total_err = total_err/float(len(ys[1:]))
with open("./data/json/test_ekf_no_alpha5.json", "w") as f:
out_dict = {
"k_gain": k_gains,
# "alphas": alphas,
"y_errors": y_errors,
"ys": ys[1:].tolist(),
"preds": preds
}
json.dump(out_dict, f)
# print(alphas)
# print(y_errors)
# print(ys[1:].tolist())
# print(preds)
|
ksk-S/DynamicChangeBlindness
|
workspace_models/mcmc_model/test_ekf.py
|
test_ekf.py
|
py
| 3,468 |
python
|
en
|
code
| 0 |
github-code
|
6
|
5104206621
|
import os
import cv2
import numpy as np
import faceRecognition as fr
import HumanDetection as hd
import time
from playsound import playsound
#variabel status ruangan. 0 = empty, 1 = uknown, 2 = known
status = 0
#variabel timestamp
tsk = [0,0,0,False] #untuk durasi status known, mendeteksi ruang kosong (isempty)
tsu = [0,0,0,False] #untuk durasi status unkown
#Merupakan bagian untuk load data training dan capture video dari sumber
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
face_recognizer.read('trainingData.yml')#Load data training yang sudah tersimpan sebelumnya
name = {0 : "TestImages", 1 : "Ronalod", 2 : "Faruq", 3 : "Fadhil", 4 : "Unknown"}
#Nama Video untuk presentasi final
# known1 -> known, isempty
# coba14 -> unknown alarm
# coba 16 -> unknown alarm
# CekFadhilFaruqNaila1 -> deteksi beberapa orang sekaligus
filename = '\coba16'
hog = hd.initiate()
cap=cv2.VideoCapture('D:\Bahan Kuliah\PyCharm Projects\FaceRecog\Video'+ filename +'.mp4')
fps_read = cap.get(cv2.CAP_PROP_FPS)
print("Input Video FPS :",fps_read)
height = int( cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
print("Input Video Frame Size : ",width," x ",height)
out = cv2.VideoWriter(
'output '+ 'coba16' +'.avi',
cv2.VideoWriter_fourcc(*'MJPG'),
fps_read,
(640,480))
while (cap.isOpened()):
ret,test_img=cap.read()#capture frame dari video dan mengembalikan 2 nilai yaitu gambar dan nilai boolean dari gambar
if ret :
# Resizing Image for faster detection
resized_img = cv2.resize(test_img, (640, 480))
#resized_img = test_img
timer = cv2.getTickCount()
if status == 0 or status == 1: #apabila status sebelumnya empty atau unknown
faces_detected,gray_img=fr.faceDetection(resized_img)
#print("faces_detected:",faces_detected)
for (x,y,w,h) in faces_detected:
cv2.rectangle(resized_img,(x,y),(x+w,y+h),(0,0,255),thickness=2) #menggambar kotak untuk wajah
#cv2.imshow('face detection Tutorial ',resized_img)
for face in faces_detected:
(x,y,w,h)=face
roi_gray=gray_img[y:y+w, x:x+h]
label,confidence=face_recognizer.predict(roi_gray)#Memprediksi identitas wajah
print("confidence:",confidence)
print("label:",label)
fr.draw_rect(resized_img,face)
predicted_name=name[label]
if confidence < 80: #Jika confidence kecil dari 80 maka print identitas wajah
fr.put_text(resized_img,predicted_name,x,y)
status = 2 #ubah status jadi known
else:
predicted_name=name[4]
fr.put_text(resized_img,predicted_name,x,y)
status = 1 #ubah status jadi uknown
if status == 0 or status == 1 :
regions = hd.detect(hog, resized_img, (4,4), (4, 4), 1.2)
hd.boxes(resized_img, regions)
if len(regions) !=0 : #terdeteksi manusia
if status == 0 :
status = 1
print('Human Detected')
#update durasi
if tsu[3] == False:
tsu[0] = time.time()
tsu[3] = True
elif tsu[3] == True:
tsu[1] = time.time()
tsu[2] = tsu[1] - tsu[0]
tsk = [0, 0, 0, False]
if status == 2 :
tsu =[0,0,0,False] #reset
regions = hd.detect(hog, resized_img, (4,4), (4, 4), 1.2)
hd.boxes(resized_img, regions)
if len(regions) == 0:
print('Human Not Detected')
if tsk[3] == False:
tsk[0] = time.time()
tsk[3] = True
elif tsk[3] == True:
tsk[1] = time.time()
tsk[2] = tsk[1] - tsk[0]
else :
tsk = [0,0,0,False] #reset bila terdeteksi manusia
# showing fps
cv2.putText(resized_img, "Fps:", (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 255), 2);
fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer); cv2.putText(resized_img, str(int(fps)), (75, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2);
# ubah durasi
tsu[2] = tsu[2]*(fps/fps_read)
tsk[2] = tsk[2]*(fps/fps_read)
if status == 1: # status unknown
print("Waktu terdeteksi : ")
print(tsu, '\n')
if tsu[2] >= 10: # durasi terdeteksi melebihi 10 detik
print("alarm triggered!")
playsound("Industrial Alarm.wav")
break # keluar program
if status == 2:
print("Waktu tidak terdeteksi : ")
print(tsk, '\n')
if tsk[2] >= 2: # misal tidak terdeteksi (kosong) selama 5 detik
print("Reset Status menjadi 0")
status = 0 # ubah status jadi empty
cv2.imshow('face recognition tutorial ',resized_img)
print("Status : ",status)
out.write(resized_img.astype('uint8'))
if cv2.waitKey(1) & 0xFF == ord('q'):
# Tekan q untuk menghentikan atau tunggu hingga akhir video
break
else :
break
cap.release()
out.release()
cv2.destroyAllWindows()
print('Waktu awal terdeteksi : ', tsu[0], '\n')
print('Waktu akhir terdeteksi : ', tsu[1], '\n')
print('Durasi terdeteksi : ', tsu[2],' detik','\n')
print('Waktu awal tidak terdeteksi : ', tsk[0], '\n')
print('Waktu akhir tidak terdeteksi : ', tsk[1], '\n')
print('Durasi tidak terdeteksi : ', tsk[2],' detik','\n')
if tsu[2] >=10:
print ("Alarm Triggered!")
playsound("Industrial Alarm.wav")
print("Alarm Triggered!")
playsound("Industrial Alarm.wav")
|
AfifHM/Smart-CCTV-Using-Face-and-Human-Detection
|
FullProgram/Source Code/forVideo.py
|
forVideo.py
|
py
| 5,897 |
python
|
en
|
code
| 5 |
github-code
|
6
|
71221562748
|
'''
/**********************************************************************************
* Purpose: Write a Util Static Function to calculate monthlyPayment that reads in three
* commandline arguments P, Y, and R and calculates the monthly payments you
* would have to make over Y years to pay off a P principal loan amount at R per cent
* interest compounded monthly.
* logic :
*
* @author : Janhavi Mhatre
* @python version 3.7
* @platform : PyCharm
* @since 26-12-2018
*
***********************************************************************************/
'''
from utilities import utility
p = int(input("enter principal loan amount p: "))
y = int(input("enter years y: "))
r = int(input("enter rate r: "))
utility.monthly_pay(p, y, r)
|
JanhaviMhatre01/pythonprojects
|
monthlypayment.py
|
monthlypayment.py
|
py
| 741 |
python
|
en
|
code
| 1 |
github-code
|
6
|
32145991026
|
#
# @lc app=leetcode id=1 lang=python3
#
# [1] Two Sum
#
# @lc code=start
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, val in enumerate(nums):
rev = target - val
if rev in d:
return [d[rev], i]
else:
d[val] = i
# @lc code=end
|
rsvarma95/Leetcode
|
1.two-sum.py
|
1.two-sum.py
|
py
| 362 |
python
|
en
|
code
| 0 |
github-code
|
6
|
26159783505
|
# Bootstrap dropdown doesn't have select tag
# inspect the dropdown, find all the li under ui tag
# Loop through it and click the right li
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
# Launch the browser
service_obj = Service("C:\Drivers\chromedriver_win32\chromedriver.exe")
driver = webdriver.Chrome(service=service_obj)
driver.implicitly_wait(10)
# Open the web application
driver.get("https://www.dummyticket.com/dummy-ticket-for-visa-application/")
driver.maximize_window()
driver.find_element(By.XPATH, "//span[@id='select2-billing_country-container']").click()
countries_list = driver.find_elements(By.XPATH, "//ul[@id='select2-billing_country-results']/li")
print(len(countries_list))
for country in countries_list:
if country.text == "India":
country.click()
break
|
skk99/Selenium
|
day13/BootstrapDropdown.py
|
BootstrapDropdown.py
|
py
| 915 |
python
|
en
|
code
| 0 |
github-code
|
6
|
36273427497
|
from collections import namedtuple
import itertools
import torch
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
import torch.nn.functional as F
import data_utils
import train_utils
from models import BinaryClassifier, LSTM, CNN
import part2_train_utils
import helpers
##############################################################################
# Settings
##############################################################################
CUDA = False
##############################################################################
# Load the dataset
##############################################################################
Data = namedtuple("Data", "corpus train dev test embeddings word_to_index")
data_utils.download_ask_ubuntu_dataset()
EMBEDDINGS, WORD_TO_INDEX = data_utils.load_part2_embeddings()
ASK_UBUNTU_CORPUS = data_utils.load_corpus(WORD_TO_INDEX)
ASK_UBUNTU_TRAIN_DATA = data_utils.load_train_data()
ASK_UBUNTU_DEV_DATA, ASK_UBUNTU_TEST_DATA = data_utils.load_eval_data()
ASK_UBUNTU_DATA = Data(ASK_UBUNTU_CORPUS, ASK_UBUNTU_TRAIN_DATA,\
ASK_UBUNTU_DEV_DATA, ASK_UBUNTU_TEST_DATA,\
EMBEDDINGS, WORD_TO_INDEX)
data_utils.download_android_dataset()
ANDROID_CORPUS = data_utils.load_android_corpus(WORD_TO_INDEX)
ANDROID_DEV_DATA, ANDROID_TEST_DATA = data_utils.load_android_eval_data()
ANDROID_DATA = Data(ANDROID_CORPUS, None,\
ANDROID_DEV_DATA, ANDROID_TEST_DATA,\
EMBEDDINGS, WORD_TO_INDEX)
##############################################################################
# Train and evaluate a baseline TFIDF model
##############################################################################
TOKENIZED_ANDROID_CORPUS = data_utils.load_tokenized_android_corpus()
TOKENIZED_ANDROID_CORPUS = [
entry.title + entry.body for entry in TOKENIZED_ANDROID_CORPUS.values()
]
TFIDF_VECTORIZER = TfidfVectorizer()
TFIDF_VECTORS = TFIDF_VECTORIZER.fit_transform(TOKENIZED_ANDROID_CORPUS)
QUERY_TO_INDEX = dict(zip(ANDROID_DATA.corpus.keys(), range(len(ANDROID_DATA.corpus))))
AUC = helpers.evaluate_tfidf_auc(ANDROID_DATA.dev, TFIDF_VECTORS, QUERY_TO_INDEX)
print("AUC", AUC)
AUC = helpers.evaluate_tfidf_auc(ANDROID_DATA.test, TFIDF_VECTORS, QUERY_TO_INDEX)
print("AUC", AUC)
##############################################################################
# Train models by direct transfer and evaluate
##############################################################################
RESULTS = []
MARGINS = [0.2]
MAX_EPOCHS = 50
BATCH_SIZE = 32
FILTER_WIDTHS = [3]
POOL_METHOD = "average"
FEATURE_DIMS = [667]
DROPOUT_PS = [0.1]
NUM_HIDDEN_UNITS = [240]
LEARNING_RATES = [1E-3]
MODELS = []
LSTM_HYPERPARAMETERS = itertools.product(MARGINS, NUM_HIDDEN_UNITS, LEARNING_RATES)
for margin, num_hidden_units, learning_rate in LSTM_HYPERPARAMETERS:
model = LSTM(EMBEDDINGS, num_hidden_units, POOL_METHOD, CUDA)
criterion = helpers.MaxMarginLoss(margin)
parameters = filter(lambda p: p.requires_grad, model.parameters())
optimizer = torch.optim.Adam(parameters, lr=learning_rate)
model, mrr = train_utils.train_model(model, optimizer, criterion, ASK_UBUNTU_DATA, \
MAX_EPOCHS, BATCH_SIZE, CUDA, eval_data=ANDROID_DATA)
torch.save(model.state_dict(), "./lstm_" +
str(margin) + "_" +
str(num_hidden_units) + "_" +
str(learning_rate) + "_" +
"auc=" + str(mrr))
MODELS.append((mrr, margin, num_hidden_units, learning_rate))
##############################################################################
# Train models by adverserial domain adaptation and evaluate
##############################################################################
MAX_EPOCHS = 50
BATCH_SIZE = 32
MARGINS = [0.2]
FILTER_WIDTH = 2
POOL_METHOD = "average"
FEATURE_DIM = 240
DIS_NUM_HIDDEN_UNITS = [150, 200]
DIS_LEARNING_RATES = [-1E-3]
ENC_LEARNING_RATE = 1E-3
DIS_TRADE_OFF_RATES = [1E-7, 1E-8, 1E-9]
DIS_HYPERPARAMETERS = itertools.product(DIS_LEARNING_RATES, DIS_NUM_HIDDEN_UNITS, DIS_TRADE_OFF_RATES, MARGINS)
for dis_lr, dis_hidden_units, trade_off, margin in DIS_HYPERPARAMETERS:
enc_model = LSTM(EMBEDDINGS, FEATURE_DIM, POOL_METHOD, CUDA)
dis_model = BinaryClassifier(FEATURE_DIM, dis_hidden_units)
model, auc = part2_train_utils.train_model(
enc_model,
dis_model,
trade_off,
ASK_UBUNTU_DATA,
ANDROID_DATA,
MAX_EPOCHS,
BATCH_SIZE,
ENC_LEARNING_RATE,
dis_lr,
margin,
CUDA,
)
print("max auc", auc)
torch.save(model.state_dict(), "./lstm_" +\
str(margin) + "_" +\
str(dis_hidden_units) + "_" +\
str(trade_off) + "_" +\
"auc=" + str(auc))
|
timt51/question_retrieval
|
part2.py
|
part2.py
|
py
| 5,017 |
python
|
en
|
code
| 0 |
github-code
|
6
|
15147278540
|
from django.urls import path
from . import views
app_name = 'cis'
urlpatterns = [
path('cis/<status>/', views.CIListView.as_view(), name='ci_list'),
path('ci/create/', views.CICreateView.as_view(), name='ci_create'),
path('ci/upload/', views.ci_upload, name='ci_upload'),
path('ci/<int:pk>', views.CIDetailView.as_view(), name='ci_detail'),
path('ci/pack/send/', views.send_ci_pack, name='ci_pack_send'),
path('places/', views.manage_client_places, name='manage_client_places'),
path('place/create/', views.PlaceCreateView.as_view(), name='place_create'),
path('place/<int:pk>', views.PlaceUpdateView.as_view(), name='place_update'),
path('manufacturer/<int:pk>', views.ManufacturerDetailView.as_view(), name='manufacturer_detail'),
path('appliances/', views.ApplianceListView.as_view(), name='appliance_list'),
path('appliance/create/', views.ApplianceCreateView.as_view(), name='appliance_create'),
path('appliance/<int:pk>', views.ApplianceUpdateView.as_view(), name='appliance_update'),
]
|
DiegoVilela/internalize
|
cis/urls.py
|
urls.py
|
py
| 1,043 |
python
|
en
|
code
| 0 |
github-code
|
6
|
73652428349
|
# 给你一个下标从 0 开始的整数数组 nums 。
# 现定义两个数字的 串联 是由这两个数值串联起来形成的新数字。
# 例如,15 和 49 的串联是 1549 。
# nums 的 串联值 最初等于 0 。执行下述操作直到 nums 变为空:
# 如果 nums 中存在不止一个数字,分别选中 nums 中的第一个元素和最后一个元素,将二者串联得到的值加到 nums 的 串联值 上,然后从 nums 中删除第一个和最后一个元素。
# 如果仅存在一个元素,则将该元素的值加到 nums 的串联值上,然后删除这个元素。
# 返回执行完所有操作后 nums 的串联值。
from typing import List
class Solution:
def findTheArrayConcVal(self, nums: List[int]) -> int:
ans = 0
while(len(nums) > 0):
if len(nums) == 1:
ans += nums.pop()
else:
l = nums.pop(0)
r = nums.pop()
ans += int(str(l) + str(r))
return ans
nums = [7,52,2,4]
a = Solution()
print(a.findTheArrayConcVal(nums))
|
xxxxlc/leetcode
|
competition/单周赛/332/findTheArrayConcVal.py
|
findTheArrayConcVal.py
|
py
| 1,115 |
python
|
zh
|
code
| 0 |
github-code
|
6
|
35970918283
|
from __future__ import annotations
__all__: list[str] = []
import argparse
import subprocess
import sys
import cmn
class _LintReturnCodes(cmn.ReturnCodes):
"""Return codes that can be received from pylint."""
SUCCESS = 0
# Error code 1 means a fatal error was hit
ERROR = 2
WARNING = 4
ERROR_WARNING = 6
REFACTOR = 8
ERROR_REFACTOR = 10
WARNING_REFACTOR = 12
ERROR_WARNING_REFACTOR = 14
CONVENTION = 16
ERROR_CONVENTION = 18
WARNING_CONVENTION = 20
ERROR_WARNING_CONVENTION = 22
REFACTOR_CONVENTION = 24
ERROR_REFACTOR_CONVENTION = 26
WARNING_REFACTOR_CONVENTION = 28
ERROR_WARNING_REFACTOR_CONVENTION = 30
USAGE_ERROR = 32
COMMAND_NOT_FOUND = 200
def _run_lint(args: argparse.Namespace) -> int:
"""Runs pylint on python files in workspace.
:param args: namespace object with args to run lint with.
:return: return code from CLI.
"""
rc = _LintReturnCodes.SUCCESS
include_files = cmn.get_python_files(args.untracked_files)
cmd = [cmn.which_python(), "-m", "pylint"] + list(include_files)
try:
subprocess.run(cmd, check=True)
except FileNotFoundError as exc:
if exc.errno is cmn.WinErrorCodes.FILE_NOT_FOUND.value:
cmn.handle_missing_package_error(exc.filename)
rc = _LintReturnCodes.COMMAND_NOT_FOUND
else:
raise
except subprocess.CalledProcessError as exc:
cmn.handle_cli_error(_LintReturnCodes, exc.returncode, exc.cmd, exc)
rc = _LintReturnCodes.USAGE_ERROR
return rc
def main() -> None:
"""Main function for pylint CLI. Parses and handles CLI input."""
parser = argparse.ArgumentParser(description="Run pylint on given files.")
parser.add_argument(
"-u",
"--untracked-files",
action="store_true",
default=False,
help="run on files untracked by git",
)
args = parser.parse_args()
rc = _run_lint(args)
sys.exit(rc)
if __name__ == "__main__":
main()
|
kiransingh99/gurbani_analysis
|
tools/lint.py
|
lint.py
|
py
| 2,043 |
python
|
en
|
code
| 0 |
github-code
|
6
|
4789054179
|
# -*-coding:utf-8-*-
from __future__ import absolute_import, unicode_literals
import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
from Utils.ReadAndDecode_Continous import read_and_decode_continous
val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/continous_data/test_continous.tfrecords'
# val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/continous_data/train_continous.tfrecords'
# val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/abij_test.tfrecords'
# val_path = '/home/dmrf/GestureNuaaTeam/tensorflow_gesture_data/Gesture_data/abij_train.tfrecords'
x_val, y_val = read_and_decode_continous(val_path)
test_batch = 1
min_after_dequeue_test = test_batch * 2
num_threads = 3
test_capacity = min_after_dequeue_test + num_threads * test_batch
# 使用shuffle_batch可以随机打乱输入
test_x_batch, test_y_batch = tf.train.shuffle_batch([x_val, y_val],
batch_size=test_batch, capacity=test_capacity,
min_after_dequeue=min_after_dequeue_test)
labels_type = 6
test_count = labels_type * 100
Test_iterations = test_count / test_batch
output_graph_def = tf.GraphDef()
pb_file_path = "../Model/gesture_cnn_lstm6.pb"
pb_lstm_file_path = "../Model/gesture_lstm.pb"
with open(pb_file_path, "rb") as f:
output_graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(output_graph_def, name="")
# with open(pb_lstm_file_path, "rb") as f:
# output_graph_def.ParseFromString(f.read())
# _ = tf.import_graph_def(output_graph_def, name="")
# LABELS = ['A', 'B', 'C', 'F', 'G', 'H', 'I', 'J']
# LABELS = ['A', 'B', 'I', 'J']
label = [0, 1, 2, 3, 4, 5]
def batchtest():
re_label = np.zeros(603, dtype=np.int64)
pr_label = np.zeros(603, dtype=np.int64)
ind = 0
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
threads = tf.train.start_queue_runners(sess=sess)
input_x = sess.graph.get_tensor_by_name("input:0")
print(input_x)
fc = sess.graph.get_tensor_by_name("fullconnection1:0")
print(fc)
output_cnn = sess.graph.get_tensor_by_name("output:0")
print(output_cnn)
input_x_lstm = sess.graph.get_tensor_by_name("input_lstm:0")
print(input_x_lstm)
softmax_lstm = sess.graph.get_tensor_by_name("softmax_lstm:0")
print(softmax_lstm)
output_lstm = sess.graph.get_tensor_by_name("output_lstm:0")
print(output_lstm)
for step_test in range(Test_iterations + 1):
test_x, test_y = sess.run([test_x_batch, test_y_batch])
if test_y == 6:
continue
if test_y == 7:
continue
x_ndarry_lstm = np.zeros(shape=(test_batch, 1024), dtype=np.float32) # 定义一个长度为1024的array
# if test_y==1:
# x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})
# out= sess.run(output_cnn, feed_dict={input_x: test_x[:, :, 0:550]})
# out_lstm=sess.run(output_lstm, feed_dict={input_x_lstm: x_ndarry_lstm})
# print out,out_lstm
# tfrecords-->tensor(8,2200,2)-->4*tensor(8,550,2)-->cnn-->4*256-->lstm
# train_x[0][1][1100][0] is the flag when write tfrecord
if test_x[0][1][1100][0] == 1 * 6: # 0.5s-->need train_x[:][1][0:550][0]
x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})
elif test_x[0][1][1100][0] == 2 * 6: # 1s-->need train_x[:][1][0:1100][0]
x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})
x_ndarry_lstm[:, 256:512] = sess.run(fc, feed_dict={input_x: test_x[:, :, 550:1100]})
# x_narray_cnn[0][:] = train_x[:][:][0:550]
# x_narray_cnn[1][:] = train_x[:][:][550:1100]
else: # 2s-->need train_x[:][1][0:2200][0]
x_ndarry_lstm[:, 0:256] = sess.run(fc, feed_dict={input_x: test_x[:, :, 0:550]})
x_ndarry_lstm[:, 256:512] = sess.run(fc, feed_dict={input_x: test_x[:, :, 550:1100]})
x_ndarry_lstm[:, 512:768] = sess.run(fc, feed_dict={input_x: test_x[:, :, 1100:1650]})
x_ndarry_lstm[:, 768:1024] = sess.run(fc, feed_dict={input_x: test_x[:, :, 1650:2200]})
# x_narray_cnn[0][:] = train_x[:][:][0:550]
# x_narray_cnn[1][:] = train_x[:][:][550:1100]
# x_narray_cnn[2][:] = train_x[:][:][1100:1650]
# x_narray_cnn[3][:] = train_x[:][:][1650:2200]
# print 0
prediction_labels = sess.run(output_lstm, feed_dict={input_x_lstm: x_ndarry_lstm})
print(str(step_test))
print("real_label:", test_y)
re_label[ind] = test_y
# prediction_labels = np.argmax(out_softmax, axis=1)
pr_label[ind] = prediction_labels
ind += 1
print("predict_label:", prediction_labels)
print('')
np.savetxt('../Data/re_label_lstmtrain_addlstm6.txt', re_label)
np.savetxt('../Data/pr_label_lstmtrain_addlstm6.txt', pr_label)
if __name__ == '__main__':
# singletest_data_pc("/home/dmrf/test_gesture/JS")
# ReadDataFromTxt("/home/dmrf/下载/demodata/0_push left_1524492872166_1")
batchtest()
|
DmrfCoder/Tensorflow_gesture
|
Predict/gesture_lstm_pb_predict.py
|
gesture_lstm_pb_predict.py
|
py
| 5,528 |
python
|
en
|
code
| 0 |
github-code
|
6
|
32908608834
|
numbers = [1, 2, 5, 7, 89, 90, 10, 20]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n * n)
# list comprehension
evens = [
n * n # add value
for n in numbers # set to draw from
if n % 2 == 0 # test for inclusion
]
print(evens)
results = [
(1, 2, 70.1),
(2, 2, 80.0),
(4, 2, 20.0),
(-4, 5, 100.0),
]
make_square = lambda n : n * n
# m = max(make_square(r[2]) for r in results)
m = max(r[2] for r in results)
print(m)
# Generator expression
evens = (
n * n # add value
for n in numbers # set to draw from
if n % 2 == 0 # test for inclusion
)
for n in evens:
print(n)
|
mikeckennedy/python_workshop_demos_april_2018
|
demos/ch5_pythonic/inline.py
|
inline.py
|
py
| 650 |
python
|
en
|
code
| 1 |
github-code
|
6
|
14884570447
|
# ['基金编号', '购买成本', '基金名']
fundList = [
['160212', '3.6730', ' 国泰估值优势混合(LOF)'],
['001230', '1.2350', ' 鹏华医药科技股票']
]
# 发送基金日报的邮箱smtp服务器地址
senderIMAP = 'smtp.126.com'
# 发送基金日报的邮箱地址
senderEmailAddress = '[email protected]'
# 发送基金日报的邮箱的smtp授权码
senderAuthCode = 'SNRRQHKFKEUNNSFT'
# 邮件主题
subject = '基金日报'
# 接收基金日报的邮箱地址
receiverEmailAddress = "[email protected]"
|
VinciJoy/FundMonitor
|
config.py
|
config.py
|
py
| 533 |
python
|
en
|
code
| 4 |
github-code
|
6
|
43247812084
|
import subprocess
import os
import shutil
import pytest
TEMP_DIRECTORY = os.path.join(os.path.dirname(__file__), '..', 'tmp')
TEMP_HEADER = os.path.join(TEMP_DIRECTORY, 'header.h')
TEMP_SOURCE = os.path.join(TEMP_DIRECTORY, 'source.c')
def set_up():
os.mkdir(TEMP_DIRECTORY)
def tear_down():
shutil.rmtree(TEMP_DIRECTORY)
@pytest.fixture(autouse=True)
def run_around_tests():
set_up()
yield
tear_down()
def read_file_content(filepath: str) -> str:
with open(filepath, 'r') as file:
return file.read()
def test_integration():
# given:
resource_dir = os.path.join(os.path.dirname(__file__), 'resource')
input_path = os.path.join(resource_dir, 'example_header.h')
expected_header = os.path.join(resource_dir, 'example_mock.h')
expected_source = os.path.join(resource_dir, 'example_mock.c')
# when:
subprocess.run([
'python', '-m', 'c_mock_generator.generate_mock',
'-i', input_path,
'-oh', TEMP_HEADER,
'-oc', TEMP_SOURCE], check=True)
# then:
assert os.path.isfile(TEMP_HEADER)
assert os.path.isfile(TEMP_SOURCE)
assert read_file_content(TEMP_HEADER) == read_file_content(expected_header)
assert read_file_content(TEMP_SOURCE) == read_file_content(expected_source)
|
BjoernLange/C-Mock-Generator
|
tests/generate_mock_integration_test.py
|
generate_mock_integration_test.py
|
py
| 1,290 |
python
|
en
|
code
| 0 |
github-code
|
6
|
11315559084
|
#coding:utf-8
import sys
sys.path.insert(0, "./")
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
from flask import Flask
from flask import render_template, redirect, url_for
from flask import request, session, json
from flask import jsonify
from keywords.keywordExtract import getKeywords
from parser.analysis_doc import parser_doc, basicInfoExtract
from conflict.conflict_detect import Conflict
from retrieval.infoRetrieval import find_policy
from association.asso_analyze import Association
app = Flask(__name__)
app.config["SECRET_KEY"] = "123456"
conflict = Conflict()
asso = Association()
@app.route('/')
def hello_world():
return '欢迎来到政策关联分析系统算法后台!!!'
@app.route('/dataProcess', methods=["POST", "GET"])
def dataProcess():
'''
对输入到数据库中的政策进行数据处理,进行信息提取操作。
:return:
'''
if request.method == 'POST':
datax = request.form.get('text',"")
name = request.form.get("name", "")
if datax:
'''
添加数据处理操作
'''
try:
results = basicInfoExtract(datax, source_name=name)
return jsonify({"error_code":0, "reason":"", "data":results})
except:
return jsonify({"error_code":3, "reason":"输入数据错误,无法进行解析", "data":""})
else:
return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
else:
return jsonify({"error_code":2, "reason":"请求方式错误,应使用post请求", "data":""})
@app.route("/keywords", methods=["POST","GET"])
def keywords():
'''
关键词提取
:return:
'''
if request.method == 'POST':
datax = request.form.get('text',"")
number = int(request.form.get('number', 3))
if datax:
'''
添加数据处理操作
'''
keyword = getKeywords(datax, num= number, use_value=False)
results = {
"keywords":keyword,#关键词
}
return jsonify({"error_code":0, "reason":"", "data":results})
else:
return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
else:
return jsonify({"error_code":2, "reason":"请求方式错误,应使用post请求", "data":""})
@app.route("/dataAnalyze", methods=["POST","GET"])
def dataAnalyze():
'''
政策文本结构化解析
:return:
'''
if request.method == 'POST':
datax = request.form.get('text',"")
name = request.form.get('name', "")
if datax:
'''
添加数据处理操作
'''
try:
results = parser_doc(datax)
return jsonify({"error_code":0, "reason":"", "data":results})
except:
return jsonify({"error_code": 3, "reason": "输入数据错误,无法进行解析", "data": ""})
else:
return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
else:
return jsonify({"error_code":2, "reason":"请求方式错误,应使用post请求", "data":""})
@app.route("/conflictDetection", methods=["POST", "GET"])
def conflictDetection():
'''
政策文本冲突检测
:return:
'''
if request.method == 'POST':
# datax = request.get_data()
datax = request.form.get('policy',"")
test_policy = request.form.get('test_policy', "")
if datax and test_policy:
'''
添加数据处理操作
'''
try:
datax = json.loads(datax)
print("conflict input: %s"%(datax))
results = conflict.conflict(datax, target_sent=test_policy)
# results = {
# "result":"存在时间类型的冲突",
# "sentence":"到2020年,实现全面建设中国物联网体系平台。"
# }
return jsonify({"error_code":0, "reason":"", "data":results})
except:
return jsonify({"error_code": 3, "reason": "输入数据错误,无法进行解析", "data": ""})
else:
return jsonify({"error_code": 1, "reason": "没有输入政策数据或者是待检测文本", "data": ""})
else:
return jsonify({"error_code":2, "reason":"请求方式错误,应使用post请求", "data":""})
@app.route("/assoAnalyze", methods=["POST", "GET"])
def assoAnalyze():
'''
两个政策关联分析
:return:
'''
if request.method == 'POST':
policy1 = request.form.get('policy1', "")
policy2 = request.form.get('policy2', "")
if policy1 and policy2:
'''
添加数据处理操作
'''
try:
policy1 = json.loads(policy1)
policy2 = json.loads(policy2)
results = asso.analyzeAll(policy1, policy2)
# results = {
# "result":"对于政策A来说,政策B是起到理论指导作用",
# "policy1":{
# "1":["句子", "理论指导"],
# "2":["句子", "理论指导"],
#
# },#第一个政策每句话的分析
# "policy2":{
# "1":["句子", "理论指导"],
# "2":["句子", "理论指导"],
# }#第二个政策每句话的分析
# }
return jsonify({"error_code":0, "reason":"", "data": results})
except:
return jsonify({"error_code": 3, "reason": "输入数据错误,无法进行解析", "data": ""})
else:
return jsonify({"error_code": 1, "reason": "没有输入政策数据", "data": ""})
else:
return jsonify({"error_code":2, "reason":"请求方式错误,应使用post请求", "data":""})
@app.route("/assoSingleAnalyze", methods=["POST", "GET"])
def assoSingleAnalyze():
'''
两个政策关联分析
:return:
'''
if request.method == 'POST':
policy1 = request.form.get('policy1',"")
policy2 = request.form.get('policy2', "")
sentence = request.form.get('sentence', "")
id = request.form.get('id', None)
if policy1 and policy2 and sentence and id is not None:
try:
id = int(id)
'''
添加数据处理操作
'''
policy1 = json.loads(policy1)
policy2 = json.loads(policy2)
results = asso.assoSingleAnalyze(policy1, policy2, sentence, id)
# results = {
# "policy":{
# "1":["句子", "相似"],
# "2":["句子", "不相似"],
# }
# }
return jsonify({"error_code":0, "reason":"", "data":results})
except:
return jsonify({"error_code": 3, "reason": "输入数据错误,无法进行解析", "data": ""})
else:
return jsonify({"error_code": 1, "reason": "没有输入政策数据或者输入信息不完整", "data": ""})
else:
return jsonify({"error_code":2, "reason":"请求方式错误,应使用post请求", "data":""})
@app.route("/policyFind", methods=["POST", "GET"])
def policyFind():
'''
政策查找
:return:
'''
if request.method == 'POST':
policy1 = request.form.get('policy',"")
policy_lis = request.form.get('policy_lis', "")
number = int(request.form.get('number', 10))
if policy1 and policy_lis and number :
'''
添加数据处理操作
'''
try:
print(policy_lis)
if not isinstance(policy_lis, list):
policy_lis = policy_lis.split("#")
res = find_policy(policy1, policy_lis, int(number))
print(res)
results = {
"result":"#".join(res)#"大数据#互联网#人工智能#物联网"
}
return jsonify({"error_code":0, "reason":"", "data":results})
except:
return jsonify({"error_code": 3, "reason": "输入数据错误,无法进行解析", "data": ""})
else:
return jsonify({"error_code": 1, "reason": "没有输入政策数据或者输入信息不完整", "data": ""})
else:
return jsonify({"error_code":2, "reason":"请求方式错误,应使用post请求", "data":""})
if __name__ == '__main__':
app.debug = True
app.run(host="0.0.0.0", port = 5005, debug=True)
|
nlp520/policy_web
|
app.py
|
app.py
|
py
| 8,806 |
python
|
en
|
code
| 0 |
github-code
|
6
|
26252618051
|
import pandas as pd
import os
import sys
file = sys.argv[1]
names = pd.read_csv("classroom.csv").Name
for name in names:
os.system("git -C repositories/{} pull".format(name))
os.system("cp ../quizzes/{}.py repositories/{}".format(file, name))
os.system("git -C repositories/{} add {}.py".format(name, file))
os.system('git -C repositories/{} commit {}.py -m "Quiz"'.format(name, file))
os.system("git -C repositories/{} push".format(name))
|
wllsena/Quizzes_FGV_PL
|
broker/copy_quiz.py
|
copy_quiz.py
|
py
| 463 |
python
|
en
|
code
| 1 |
github-code
|
6
|
10786193976
|
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's account increases by the amount of the value received
def make_withdrawal(self, amount):
self.account_balance -= amount
def display_user_balance(self):
print(f"User: {self.name}, Balance: ${self.account_balance}")
def transfer_money(self, other_user, amount):
self.account_balance -= amount
other_user.account_balance += amount
justin = User("Justin","thisjustin.com")
chris = User("Christian","notsochristian.com")
brayan = User("Brayan","wtfudoin.com")
justin.make_deposit(100)
justin.make_deposit(100)
justin.make_deposit(100)
justin.make_withdrawal(130)
justin.display_user_balance()
chris.make_deposit(150)
chris.make_deposit(150)
chris.make_withdrawal(50)
chris.make_withdrawal(50)
chris.display_user_balance()
brayan.make_deposit(300)
brayan.make_withdrawal(75)
brayan.make_withdrawal(75)
brayan.make_withdrawal(75)
brayan.display_user_balance()
justin.transfer_money(brayan,200)
justin.display_user_balance()
brayan.display_user_balance()
|
imjustinluck/fundamentals
|
oop/user.py
|
user.py
|
py
| 1,280 |
python
|
en
|
code
| 0 |
github-code
|
6
|
40696675203
|
import re
from typing import NamedTuple, Optional
from magma.magmad.check import subprocess_workflow
class LscpuCommandParams(NamedTuple):
pass
class LscpuCommandResult(NamedTuple):
error: Optional[str]
core_count: Optional[int]
threads_per_core: Optional[int]
architecture: Optional[str]
model_name: Optional[str]
def get_cpu_info() -> LscpuCommandResult:
"""
Execute lscpu command via subprocess. Blocks while waiting for output.
"""
return list(
subprocess_workflow.exec_and_parse_subprocesses(
[LscpuCommandParams()],
_get_lscpu_command_args_list,
parse_lscpu_output,
),
)[0]
def _get_lscpu_command_args_list(_):
return ['lscpu']
def parse_lscpu_output(stdout, stderr, _):
"""
Parse stdout output from a lscpu command.
"""
def _create_error_result(err_msg):
return LscpuCommandResult(
error=err_msg, core_count=None,
threads_per_core=None, architecture=None,
model_name=None,
)
if stderr:
return _create_error_result(stderr)
stdout_decoded = stdout.decode()
try:
cores_per_socket = int(
re.search(
r'Core\(s\) per socket:\s*(.*)\n',
str(stdout_decoded),
).group(1),
)
num_sockets = int(
re.search(
r'Socket\(s\):\s*(.*)\n',
str(stdout_decoded),
).group(1),
)
threads_per_core = int(
re.search(
r'Thread\(s\) per core:\s*(.*)\n',
str(stdout_decoded),
).group(1),
)
architecture = re.search(
r'Architecture:\s*(.*)\n',
str(stdout_decoded),
).group(1)
model_name = re.search(
r'Model name:\s*(.*)\n',
str(stdout_decoded),
).group(1)
return LscpuCommandResult(
error=None,
core_count=cores_per_socket * num_sockets,
threads_per_core=threads_per_core,
architecture=architecture,
model_name=model_name,
)
except (AttributeError, IndexError, ValueError) as e:
return _create_error_result(
'Parsing failed: %s\n%s' % (e, stdout_decoded),
)
|
magma/magma
|
orc8r/gateway/python/magma/magmad/check/machine_check/cpu_info.py
|
cpu_info.py
|
py
| 2,341 |
python
|
en
|
code
| 1,605 |
github-code
|
6
|
43597353426
|
# Sets: unordered, mutable, no duplicates
# initialize 01
movies = {"50 shades of grey", "365", "The dictator", "Borat"}
# print(movies)
# initialize 02
web_series = set(["Suits", "Lucifer", "Dark", "Friends"])
# print(web_series)
# empty
# web_series = set()
# print(type(web_series))
# string initialize
hello_set = set("Hello")
# print(hello_set)
# insert value
web_series.add("The 100")
# web_series.add("Friend")
# print(web_series)
# delete value
# web_series.remove("Darkk")
# web_series.discard("Dark")
# clear all values
# web_series.clear()
# print(web_series)
web_series = movies.copy()
movies.add("Ready player one")
# print(web_series)
# union
gangs_of_wasseypur = {"Pankaj T", "Rajkumar R", "Nawazuddin S", "Huma Q"}
mirzapur = {"Pankaj T", "Ali Fazal", "Divyenndu", "Huma Q"}
# anurag_cast = gangs_of_wasseypur.union(mirzapur)
# print(anurag_cast)
# # intersection
# anurag_cast = gangs_of_wasseypur.intersection(mirzapur)
# print(anurag_cast)
# difference
anurag_cast = gangs_of_wasseypur.difference(mirzapur)
# print(anurag_cast)
# gangs_of_wasseypur = ["Pankaj T", "Rajkumar R", "Nawazuddin S", "Huma Q"]
# mirzapur = ["Pankaj T", "Ali Fazal", "Divyenndu", "Huma Q"]
# # anurag_cast = list()
# output = ["Rajkumar R", "Nawazuddin S", "Ali Fazal", "Divyenndu"]
# for cast in gangs_of_wasseypur:
# if cast not in mirzapur:
# anurag_cast.append(cast)
# anurag_cast = [cast for cast in gangs_of_wasseypur if cast not in mirzapur]
# print(anurag_cast)
# symmetric difference
anurag_cast = gangs_of_wasseypur.symmetric_difference(mirzapur)
# print(anurag_cast)
# update
web_series.update(gangs_of_wasseypur)
# print(web_series)
# intersection update
# mirzapur.intersection_update(gangs_of_wasseypur)
# print(mirzapur)
# difference update
# mirzapur.difference_update(gangs_of_wasseypur)
# print(mirzapur)
# symmetric difference update
# mirzapur.symmetric_difference_update(gangs_of_wasseypur)
# print(mirzapur)
# is subset
animated_movies = {"Big Hero 6", "Kung Fu Panda",
"Tangled", "Coco", "The Good Dinosaur"}
disney_movies = {"Tangled", "Coco"}
print(disney_movies.issubset(animated_movies))
# is superset
print(animated_movies.issuperset(disney_movies))
# is disjoint
print(animated_movies.isdisjoint(disney_movies))
# frozenset
numbers = frozenset({"a", "b"})
print(numbers)
|
akshitone/fy-mca-class-work
|
DivA/set.py
|
set.py
|
py
| 2,359 |
python
|
en
|
code
| 1 |
github-code
|
6
|
73510642747
|
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
mapp = defaultdict(int)
heap = []
ans = []
for word in words:
mapp[word] -= 1
for key,val in mapp.items():
heappush(heap,(val,key))
for _ in range(k):
temp = heappop(heap)
ans.append(temp[1])
return ans
|
yonaSisay/a2sv-competitive-programming
|
top-k-frequent-words.py
|
top-k-frequent-words.py
|
py
| 408 |
python
|
en
|
code
| 0 |
github-code
|
6
|
74197689149
|
import workAssyncFile
from sora.prediction import prediction
from sora.prediction.occmap import plot_occ_map as occmap
import json
import datetime
import restApi
import os
def __clearName(name):
name = "".join(x for x in name if x.isalnum() or x==' ' or x=='-' or x=='_')
name = name.replace(' ', '_')
return name
def processRequest(data, output):
outputFile = generateMap(data,output, False)
f = open (outputFile, "rb")
content = f.read()
return content
def processFile(input, output, fileName):
f = open (os.path.join(input,fileName), "r")
data = json.loads(f.read())
generateMap(data, output, True)
def generateMap(data, output, forced=False):
if 'body' in data:
return generateMapWithIternet(data, output, forced)
else:
return generateMapWithoutIternet(data, output, forced)
def generateMapWithIternet(data, output, forced=False):
body = data['body']
strDate = data['date']
strTime = data['time']
fileName = __clearName(body+" "+strDate.replace("-","")+" "+strTime.replace(":",""))
outputFile = os.path.join(output,fileName+".jpg")
if forced or not os.path.exists(outputFile):
v = (strDate+'-'+strTime).replace(":","-").split('-')
dtRef = datetime.datetime(int(v[0]), int(v[1]), int(v[2]), int(v[3]), int(v[4]), int(v[5]))
time0 = dtRef-datetime.timedelta(hours=4, minutes=0) #fuso 3
time1 = time0+datetime.timedelta(hours=2, minutes=0)
dtRef = dtRef - datetime.timedelta(hours=3, minutes=0)
pred = prediction(body=body, time_beg=time0, time_end=time1, step=10, divs=1, verbose=False)
for p in pred:
p.plot_occ_map(nameimg=fileName, path=output, fmt='jpg')
return outputFile
def generateMapWithoutIternet(data, output, forced=False):
name = data["name"]
radius = data["radius"]
coord = data["coord"]
time = data["time"]
ca = data["ca"]
pa = data["pa"]
vel = data["vel"]
dist = data["dist"]
mag = data["mag"]
longi = data["longi"]
v = time.split("T")
strDate = v[0]
if '.' in v[1]:
v[1] = v[1].split('.')[0]
strTime = v[1]
fileName = __clearName(name+" "+strDate.replace("-","")+" "+strTime.replace(":",""))
outputFile = os.path.join(output,fileName+".jpg")
if forced or not os.path.exists(outputFile):
occmap(name, radius, coord, time, ca, pa, vel, dist, mag=mag, longi=longi, dpi=50, nameimg=fileName, path=output, fmt='jpg')
return outputFile
if __name__ == '__main__':
waf = workAssyncFile.WorkAssyncFile(os.getenv('INPUT_PATH', '~/media/input'),os.getenv('OUTPUT_PATH', '~/media/output'))
waf.setProcessFile(processFile)
waf.start()
api = restApi.RespApi(port=os.getenv('PORT', 8000), cachePath=os.getenv('CACHE_PATH', '~/media/output'))
api.setProcessReponse(processRequest)
api.start()
|
linea-it/tno
|
container-SORA/src/main.py
|
main.py
|
py
| 2,969 |
python
|
en
|
code
| 1 |
github-code
|
6
|
72614657467
|
import time
h = input('Enter hex: ').lstrip('#')
RGB = tuple(int(h[i:i+2], 16) for i in (0, 2, 4))
r, g, b = RGB
Ri = (r / 255)
Gi = (g / 255)
Bi = (b / 255)
print("{:0.2f}, {:0.2f}, {:0.2f}".format(Ri, Gi, Bi))
time.sleep(10)
exit()
|
maikirakiwi/pyscripts
|
hex2imgui.py
|
hex2imgui.py
|
py
| 246 |
python
|
en
|
code
| 0 |
github-code
|
6
|
7263711725
|
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QTabWidget
from .movies_view import MoviesTab
from .games_view import GamesTab
from .music_view import MusicTab
class Window(QMainWindow):
"""Main Window."""
def __init__(self, parent=None):
"""Initializer."""
super().__init__(parent)
self.setWindowTitle("Media Library")
self.resize(720, 360)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
class MyTableWidget(QWidget):
"""Container for all the tabs."""
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
# Initialize tabs
self.tabs = QTabWidget()
self.moviesTab = MoviesTab(self)
self.gamesTab = GamesTab(self)
self.musicTab = MusicTab(self)
# Add tabs for each media type
self.tabs.addTab(self.moviesTab, "Movies")
self.tabs.addTab(self.gamesTab, "Games")
self.tabs.addTab(self.musicTab, "Music")
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
|
aisandovalm/media-library
|
media_library/views/main_view.py
|
main_view.py
|
py
| 1,186 |
python
|
en
|
code
| 0 |
github-code
|
6
|
11849550981
|
"""
Created on Thu Dec 10 22:51:52 2020
@author: yzaghir
Image Arthmeric Opeations Add -
We can add two images with the OpenCV function , cv.add()
-Resize the two images and make sur they are exactly the same size before adding
"""
# import cv library
import cv2 as cv
#import numpy as np
# read image from computer
img1 = cv.imread("images/abhi2.jpg")
img2 = cv.imread("images/flower1.jpg")
#macke sur both images are same size before adding
# pickup matrix of number from image
cropped_image1 = img1[60:200 , 50:200]
cropped_image2 = img2[60:200 , 50:200]
cv.imshow("cropped 1" , cropped_image1)
cv.imshow("cropped 2" , cropped_image2)
# adding the images
added_image = cv.add(cropped_image1 , cropped_image2)
cv.imshow("Added Image" , added_image)
# adding the images
subtracted_image = cv.subtract(cropped_image1 , cropped_image2)
cv.imshow("Subtracted Image" , subtracted_image)
|
zaghir/python
|
python-opencv/arithmetic_operations_addition_and_subtraction.py
|
arithmetic_operations_addition_and_subtraction.py
|
py
| 906 |
python
|
en
|
code
| 0 |
github-code
|
6
|
36559608646
|
import scipy as sci
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
import scipy.integrate
#Definitionen
G=6.67408e-11
m_nd=1.989e+30 #Masse der Sonne
r_nd=5.326e+12
v_nd=30000
t_nd=79.91*365*24*3600*0.51
K1=G*t_nd*m_nd/(r_nd**2*v_nd)
K2=v_nd*t_nd/r_nd
#Definition der Massen
m1=1.1 #Alpha Centauri A
m2=0.907 #Alpha Centauri B
m3=1.0 #Dritter Stern
#Definition der Anfangs-Positionen
r1=np.array([-0.5,0,0], dtype="float64")
r2=np.array([0.5,0,0], dtype="float64")
r3=np.array([0,1,0], dtype="float64")
#Definition der Anfangs-Geschwindigkeiten
v1=np.array([0.01,0.01,0], dtype="float")
v2=np.array([-0.05,0,-0.1], dtype="float64")
v3=np.array([0,-0.01,0], dtype="float64")
#Updaten der COM Formeln
r_com=(m1*r1+m2*r2+m3*r3)/(m1+m2+m3)
v_com=(m1*v1+m2*v2+m3*v3)/(m1+m2+m3)
#Bewegungsgleichungen
def ThreeBodyEquations(w,t,G,m1,m2,m3):
r1=w[:3]
r2=w[3:6]
r3=w[6:9]
v1=w[9:12]
v2=w[12:15]
v3=w[15:18]
r12=sci.linalg.norm(r2-r1)
r13=sci.linalg.norm(r3-r1)
r23=sci.linalg.norm(r3-r2)
dv1bydt=K1*m2*(r2-r1)/r12**3+K1*m3*(r3-r1)/r13**3
dv2bydt=K1*m1*(r1-r2)/r12**3+K1*m3*(r3-r2)/r23**3
dv3bydt=K1*m1*(r1-r3)/r13**3+K1*m2*(r2-r3)/r23**3
dr1bydt=K2*v1
dr2bydt=K2*v2
dr3bydt=K2*v3
r12_derivs=np.concatenate((dr1bydt,dr2bydt))
r_derivs=np.concatenate((r12_derivs,dr3bydt))
v12_derivs=np.concatenate((dv1bydt,dv2bydt))
v_derivs=np.concatenate((v12_derivs,dv3bydt))
derivs=np.concatenate((r_derivs,v_derivs))
return derivs
init_params=np.array([r1,r2,r3,v1,v2,v3])
init_params=init_params.flatten() #Erstellen eines 1D Array
time_span=np.linspace(0,20,500) #20 Perioden und 500 Punkte
#Integrieren der Funktion
three_body_sol=sci.integrate.odeint(ThreeBodyEquations,init_params,time_span,args=(G,m1,m2,m3))
r1_sol=three_body_sol[:,:3]
r2_sol=three_body_sol[:,3:6]
r3_sol=three_body_sol[:,6:9]
#Erstellen der Figur
fig=plt.figure(figsize=(15,15))
#Erstellen der Achsen
ax=fig.add_subplot(111,projection="3d")
#Ploten der Orbits
ax.plot(r1_sol[:,0],r1_sol[:,1],r1_sol[:,2],color="darkblue")
ax.plot(r2_sol[:,0],r2_sol[:,1],r2_sol[:,2],color="tab:red")
ax.plot(r3_sol[:,0],r3_sol[:,1],r3_sol[:,2],color="tab:green")
#Plotten der finalen Position der Körper
ax.scatter(r1_sol[-1,0],r1_sol[-1,1],r1_sol[-1,2],color="darkblue",marker="o",s=100,label="Alpha Centauri A")
ax.scatter(r2_sol[-1,0],r2_sol[-1,1],r2_sol[-1,2],color="tab:red",marker="o",s=100,label="Alpha Centauri B")
ax.scatter(r3_sol[-1,0],r3_sol[-1,1],r3_sol[-1,2],color="tab:green",marker="o",s=100,label="Third Star")
#Hinzufügen der Beschriftungen
ax.set_xlabel("x-Koordinate",fontsize=14)
ax.set_ylabel("y-Koordinate",fontsize=14)
ax.set_zlabel("z-Kordinate",fontsize=14)
ax.set_title("Visualisierung der Orbits von Objekten im Raum\n",fontsize=14)
ax.legend(loc="upper left",fontsize=14)
ani = animation.FuncAnimation(fig, ThreeBodyEquations, frames=1000, interval=50)
plt.show()
|
Gauner3000/Facharbeit
|
Euler_Planetenbewegung_3D.py
|
Euler_Planetenbewegung_3D.py
|
py
| 3,103 |
python
|
en
|
code
| 0 |
github-code
|
6
|
6606964316
|
import sys
from collections import deque
MOVES = [(-1, 0), (0, 1), (1, 0), (0, -1)]
input = sys.stdin.readline
def isrange(x: int, y: int) -> bool:
return 0 <= x < n and 0 <= y < n
def get_lands(x: int, y: int, island: int) -> set[tuple[int, int]]:
lands: set[tuple[int, int]] = set()
que: deque[tuple[int, int]] = deque()
que.append((x, y))
lands.add((x, y))
board[x][y] = island
while que:
x, y = que.popleft()
for movex, movey in MOVES:
nextx: int = x + movex
nexty: int = y + movey
if not isrange(nextx, nexty):
continue
if board[nextx][nexty] == 0:
continue
if (nextx, nexty) in lands:
continue
que.append((nextx, nexty))
lands.add((nextx, nexty))
board[nextx][nexty] = island
return lands
def get_bridge_length(lands: set[tuple[int, int]], island: int) -> int:
length: int = 0
que: deque[tuple[int, int]] = deque()
visited: list[list[bool]] = [[False for _ in range(n)] for _ in range(n)]
for x, y in lands:
que.append((x, y))
visited[x][y] = True
while que:
for _ in range(len(que)):
x, y = que.popleft()
for movex, movey in MOVES:
nextx: int = x + movex
nexty: int = y + movey
if not isrange(nextx, nexty):
continue
if board[nextx][nexty] == island:
continue
if visited[nextx][nexty]:
continue
if board[nextx][nexty] > 0:
return length
que.append((nextx, nexty))
visited[nextx][nexty] = True
length += 1
return -1
def solve() -> int:
island: int = 2
length: int = sys.maxsize
for x, row in enumerate(board):
for y, elem in enumerate(row):
if elem == 1:
lands = get_lands(x, y, island)
length = min(length, get_bridge_length(lands, island))
island += 1
return length
if __name__ == "__main__":
n = int(input())
board = [list(map(int, input().split())) for _ in range(n)]
print(solve())
|
JeongGod/Algo-study
|
seonghoon/week06(22.02.01~22.02.07)/b2146.py
|
b2146.py
|
py
| 2,298 |
python
|
en
|
code
| 7 |
github-code
|
6
|
25926762211
|
from random import randint
import numpy
def fill_unassigned(row):
'''
>>> a = numpy.array([1, 0, 5, 5, 0, 2])
>>> fill_unassigned(a)
>>> a
array([1, 3, 5, 5, 4, 2])
'''
usednums, c = set(row), 1
for i, x in enumerate(row):
if x != 0:
continue
while c in usednums:
c += 1
row[i] = c
usednums.add(c)
def join_sets(row, a, b):
'''
>>> a = numpy.array([1, 1, 2, 2, 3, 2])
>>> join_sets(a, 1, 2)
>>> a
array([1, 1, 1, 1, 3, 1])
'''
row[numpy.where(row == b)[0]] = a
def make_bottom_walls(row):
sets = {}
for x in row:
sets[x] = sets.get(x, 0) + 1
guarded = {k: randint(0, v - 1) for k, v in sets.items()}
bwalls = numpy.zeros(row.shape, dtype='bool')
for i, x in enumerate(row):
sets[x] -= 1
if guarded[x] == sets[x]:
continue
if randint(0, 1):
bwalls[i] = True
return bwalls
def genmaze_eller(cellcount, heightcount):
# 0 1
# +xxx+xxx+xxx+
# x | | x
# +---+---+---+ 0
# x | | x
# +xxx+xxx+xxx+
all_right_walls = numpy.zeros((cellcount - 1, heightcount), dtype=numpy.bool_)
all_bottom_walls = numpy.zeros((cellcount, heightcount - 1), dtype=numpy.bool_)
row = numpy.arange(1, cellcount + 1, dtype=numpy.int16)
rwalls = numpy.zeros((cellcount - 1,), dtype=numpy.bool_)
rwalls_req = numpy.zeros(rwalls.shape, dtype=numpy.bool_)
for y in range(heightcount):
fill_unassigned(row)
rwalls[:] = False
rwalls_req[:] = False
for x in range(cellcount - 1):
if row[x] == row[x + 1]:
rwalls_req[x] = True
continue
if randint(0, 1):
rwalls[x] = True
else:
join_sets(row, row[x], row[x + 1])
if y == heightcount - 1: # last row condition
break
all_right_walls[:, y] = rwalls_req | rwalls
bwalls = make_bottom_walls(row)
all_bottom_walls[:, y] = bwalls
row[bwalls] = 0
# walls in last row
for x in range(cellcount - 1):
if row[x + 1] != row[x]:
rwalls[x] = False
join_sets(row, row[x], row[x + 1])
all_right_walls[:, heightcount - 1] = rwalls | rwalls_req
return {
'width': cellcount,
'height': heightcount,
'rwalls': all_right_walls,
'bwalls': all_bottom_walls,
}
def debug_draw_maze(maze):
from PIL import Image, ImageDraw
WorldSize.cell = 20
w, h = maze['width'], maze['height']
img = Image.new('RGB', (w * WorldSize.cell, h * WorldSize.cell))
draw = ImageDraw.Draw(img)
draw.rectangle((0, 0, w * WorldSize.cell - 1, h * WorldSize.cell - 1), fill=(0, 0, 0))
for y in range(h):
for x in range(w - 1):
if maze['rwalls'][x, y]:
draw.line((
x * WorldSize.cell + WorldSize.cell, y * WorldSize.cell,
x * WorldSize.cell + WorldSize.cell, y * WorldSize.cell + WorldSize.cell
), fill=(255, 255, 255))
for y in range(h - 1):
for x in range(w):
if maze['bwalls'][x, y]:
draw.line((
x * WorldSize.cell, y * WorldSize.cell + WorldSize.cell,
x * WorldSize.cell + WorldSize.cell, y * WorldSize.cell + WorldSize.cell
), fill=(255, 255, 255))
img.show()
if __name__ == '__main__':
maze = genmaze_eller(30, 30)
debug_draw_maze(maze)
|
gitter-badger/tierbots
|
tierbots/worldgen/maze.py
|
maze.py
|
py
| 3,577 |
python
|
en
|
code
| 0 |
github-code
|
6
|
6635020953
|
# -*- coding:utf-8 -*-
# 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
# 路径可以从矩阵中的任意一个格子开始,
# 每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
# 如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
#
# 例如
# a b c e
# s f c s
# a d e e
# 矩阵中包含一条字符串"bcced"的路径,
# 但是矩阵中不包含"abcb"路径,
# 因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,
# 路径不能再次进入该格子。
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
flag = [False for _ in range(len(matrix))]
for i in range(rows):
for j in range(cols):
# 遍历
if self.judge(matrix, rows, cols, flag, i, j, path, 0):
return True
return False
def judge(self, matrix, rows, cols, flag, i, j, path, level):
index = i * cols + j
# 判断越界条件,递归终止条件
if i >= rows or j >= cols or i < 0 or j < 0 or \
matrix[index] != path[level] or \
flag[index] == True:
return False
if level == len(path) - 1:
return True
flag[index] = True
if (self.judge(matrix, rows, cols, flag, i + 1, j, path, level + 1) or \
self.judge(matrix, rows, cols, flag, i, j + 1, path, level + 1) or \
self.judge(matrix, rows, cols, flag, i - 1, j, path, level + 1) or \
self.judge(matrix, rows, cols, flag, i, j - 1, path, level + 1)):
return True
flag[index] = False
return False
|
rh01/gofiles
|
offer/ex25/hasPath.py
|
hasPath.py
|
py
| 1,862 |
python
|
zh
|
code
| 0 |
github-code
|
6
|
7920943241
|
"""
Neural Networks - Deep Learning
Heart Disease Predictor ( Binary Classification )
Author: Dimitrios Spanos Email: [email protected]
"""
import numpy as np
from cvxopt import matrix, solvers
# ------------
# Kernels
# ------------
def poly(x, z, d=3, coef=1, g=1):
return (g * np.dot(x, z.T) + coef) ** d
def rbf(x, z, sigma):
return np.exp(-np.linalg.norm(x-z,axis=1)**2 / (2*(sigma**2)))
def linear(x, z):
return np.matmul(x, z.T)
def sigmoid(x, z, g=1, coef=0):
return np.tanh(g * np.dot(x, z.T) + coef)
# ------------
# SVM
# ------------
class my_SVM:
def __init__(self, C, kernel='linear', sigma=1):
self.C = C
self.kernel = kernel
self.sigma = sigma
self.sv = 0
self.sv_y = 0
self.alphas = 0
self.w = 0
self.b = 0
def fit(self, X, y):
# Calculate the Kernel(xi,xj)
m, n = X.shape
K = np.zeros((m,m))
if self.kernel == 'rbf':
for i in range(m):
K[i,:] = rbf(X[i,np.newaxis], X, sigma=self.sigma)
elif self.kernel == 'poly':
for i in range(m):
K[i,:] = poly(X[i,np.newaxis], X)
elif self.kernel == 'sigmoid':
for i in range(m):
K[i,:] = sigmoid(X[i,np.newaxis], X)
elif self.kernel == 'linear':
for i in range(m):
K[i,:] = linear(X[i,np.newaxis], X)
# Solve the QP Problem
P = matrix(np.outer(y, y) * K)
q = matrix(-np.ones((m, 1)))
A = matrix(matrix(y.T), (1, m), 'd')
b = matrix(np.zeros(1))
G = matrix(np.vstack((np.eye(m)*-1, np.eye(m))))
h = matrix(np.hstack((np.zeros(m),np.ones(m)*self.C)))
solvers.options['show_progress'] = False
solution = solvers.qp(P, q, G, h, A, b)
# Get the solution's results
alphas = np.array(solution['x'])
S = (alphas > 1e-4).flatten()
self.sv = X[S]
self.sv_y = y[S]
self.w = np.dot((y.reshape(-1,1) * alphas).T, X)[0]
self.alphas = alphas[S] # get rid of alphas ~= 0
self.b = np.mean(self.sv_y - np.dot(self.sv, self.w.T))
#print("w:", self.w)
#print("b:", self.b)
def predict(self, X):
K_xi_x = 0
if self.kernel == 'rbf':
K_xi_x = rbf(self.sv, X, self.sigma)
elif self.kernel == 'poly':
K_xi_x = poly(self.sv, X)
elif self.kernel == 'sigmoid':
K_xi_x = sigmoid(self.sv, X)
elif self.kernel == 'linear':
K_xi_x = linear(self.sv, X)
sum = 0
for i in range(len(K_xi_x)):
sum +=self.alphas[i] * self.sv_y[i]* K_xi_x[i]
prod = sum + self.b
prediction = np.sign(prod)
return prediction
|
DimitriosSpanos/SVM-from-Scratch
|
SVM.py
|
SVM.py
|
py
| 2,908 |
python
|
en
|
code
| 0 |
github-code
|
6
|
25354426984
|
class Solution:
def majorityElement(self, nums: List[int]) -> int:
d={}
for i in nums:
if i in d:
d[i]+=1
else:
d[i]=1
d=sorted(d, key=d.get, reverse=True)
return(d[0])
|
nikjohn7/Coding-Challenges
|
LeetCode/May challenge/day6.py
|
day6.py
|
py
| 260 |
python
|
en
|
code
| 4 |
github-code
|
6
|
16413423811
|
from datetime import datetime, date, time
import time
from collections import OrderedDict
def parametrized_decor(parameter):
def decor(foo):
def new_foo(*args, **kwargs):
print(datetime.now())
print(f'Имя функции - {foo.__name__}')
if args is not None:
print(f'Позиционные аргументы args - {args}')
if kwargs is not None:
print(f'Именованные аргументы kwargs - {kwargs}')
result = foo(*args, **kwargs)
print('result: ', result)
print('result type: ', type(result))
return result
return new_foo
return decor
if __name__ == '__main__':
# foo(1, 2)
documents_list = [{
"type": "passport",
"number": "2207 876234",
"name": "Василий Гупкин"
}, {
"type": "invoice",
"number": "11-2",
"name": "Геннадий Покемонов"
}]
@parametrized_decor(parameter=None)
def give_name(doc_list, num):
for doc_dict in doc_list:
if num == doc_dict['number']:
print(
f"Документ под номером {num} соответствует имени {doc_dict['name']}"
)
give_name(documents_list, '11-2')
print("____" * 15)
@parametrized_decor(parameter=None)
def summator(x, y):
return x + y
three = summator(1, 2)
five = summator(2, 3)
result = summator(three, five)
|
Smelkovaalla/4.5-Decorator
|
main.py
|
main.py
|
py
| 1,414 |
python
|
en
|
code
| 0 |
github-code
|
6
|
5654287369
|
from django.shortcuts import render
from django.http import Http404, HttpResponse, JsonResponse
from django.template import loader
from catalog.models import *
from django.forms.models import model_to_dict
import random
from django.views.decorators.csrf import csrf_exempt
from django.middleware.csrf import get_token
import json
# Create your views here.
def index(request):
template = loader.get_template('template.html')
context = {}
questions_id = []
related_choices = []
ID = ""
name = ""
# get all available modules and randomly pick one
module = list(modules.objects.all().values('module_name'))
randomed = [i for i in range(len(module))]
random.shuffle(randomed)
context['module'] = module[randomed[0]]
#print(context)
#
# get related questions and pass to html template
module_id = list(modules.objects.filter(module_name=context['module']['module_name']).values("id"))[0]['id']
question = list(questions.objects.all().filter(questions_under_id=module_id))
random.shuffle(question)
context['question'] = question
#print(context)
#
#get related answers and pass to html template
#print(question)
for i in question:
questions_id.append(i.id)
#print(questions_id)
for id in questions_id:
related_choices.append(list(answers.objects.filter(answers_under_id=id)))
context['answer'] = related_choices
#print(context['answer'])
#
# get Id & scores and pass to html template
name = module[randomed[0]]["module_name"]
print(name)
Id = modules.objects.filter(module_name=name).values('id')
for each in Id:
ID = each['id']
print(ID)
Scores = scores.objects.filter(score_under_id=ID).order_by('scores').reverse()
print(Scores)
context['scores'] = Scores
return HttpResponse(template.render(context,request))
def newScore(request):
print("SUCCESS : AJAX ENTERED!")
template = loader.get_template('template.html')
context = {}
under_ID = ""
if request.method == "POST" :
# handle save logic
if request.body:
jsonLoad = json.loads(request.body)
Scores = jsonLoad['scores']
username = jsonLoad['username']
module = jsonLoad['module']
else :
return JsonResponse({"errors": ["POST object has insufficient parameters!"]})
ID = modules.objects.filter(module_name=module).values('id')
for each in ID:
under_ID = each['id']
errors = scores(scores=Scores, gameId=username, score_under_id=under_ID)
errors.save()
return HttpResponse(template.render(context,request))
|
jng27/Agile
|
psb_project/locallibrary/catalog/views.py
|
views.py
|
py
| 2,686 |
python
|
en
|
code
| 0 |
github-code
|
6
|
36606021901
|
import os
import csv
import queue
import logging
import argparse
import traceback
import itertools
import numpy as np
import tensorflow.compat.v1 as tf
from fedlearner.trainer.bridge import Bridge
from fedlearner.model.tree.tree import BoostingTreeEnsamble
from fedlearner.trainer.trainer_master_client import LocalTrainerMasterClient
from fedlearner.trainer.trainer_master_client import DataBlockInfo
'''
目前不太理解的地方:worker、verbosity、max-bins、ignore-fields
'''
def create_argument_parser():
parser = argparse.ArgumentParser(
description='FedLearner Tree Model Trainer.')
#训练角色,leader还是follower
parser.add_argument('role', type=str,
help="Role of this trainer in {'local', "
"'leader', 'follower'}")
#监听本地地址,ip+port
parser.add_argument('--local-addr', type=str,
help='Listen address of the local bridge, ' \
'in [IP]:[PORT] format')
#同伴地址,ip+port
parser.add_argument('--peer-addr', type=str,
help='Address of peer\'s bridge, ' \
'in [IP]:[PORT] format')
#分布式训练时,应用程序的id,默认空
parser.add_argument('--application-id', type=str, default=None,
help='application id on distributed ' \
'training.')
#current worker的排名,等级,默认0
parser.add_argument('--worker-rank', type=int, default=0,
help='rank of the current worker')
#总的worker数量,默认1
parser.add_argument('--num-workers', type=int, default=1,
help='total number of workers')
#mode,可以为 train,test,eval,默认为train
parser.add_argument('--mode', type=str, default='train',
help='Running mode in train, test or eval.')
#数据文件的路径
parser.add_argument('--data-path', type=str, default=None,
help='Path to data file.')
#验证数据文件的路径,仅用于test模式
parser.add_argument('--validation-data-path', type=str, default=None,
help='Path to validation data file. ' \
'Only used in train mode.')
#bool变量,默认为false,预测不需要数据
parser.add_argument('--no-data', type=bool, default=False,
help='Run prediction without data.')
#使用的文件扩展
parser.add_argument('--file-ext', type=str, default='.csv',
help='File extension to use')
#输入文件类型
parser.add_argument('--file-type', type=str, default='csv',
help='input file type: csv or tfrecord')
#加载已存储模型的路径
parser.add_argument('--load-model-path',
type=str,
default=None,
help='Path load saved models.')
#存储输出模型的位置
parser.add_argument('--export-path',
type=str,
default=None,
help='Path to save exported models.')
#保存模型的检查点
parser.add_argument('--checkpoint-path',
type=str,
default=None,
help='Path to save model checkpoints.')
#存储预测输出的路径
parser.add_argument('--output-path',
type=str,
default=None,
help='Path to save prediction output.')
#控制打印日志的数量,默认为1
parser.add_argument('--verbosity',
type=int,
default=1,
help='Controls the amount of logs to print.')
#损失函数的选择,默认为logistic
parser.add_argument('--loss-type',
default='logistic',
choices=['logistic', 'mse'],
help='What loss to use for training.')
#学习率,梯度下降中的步长,默认为0.3
parser.add_argument('--learning-rate',
type=float,
default=0.3,
help='Learning rate (shrinkage).')
#boost 迭代次数,默认为5
parser.add_argument('--max-iters',
type=int,
default=5,
help='Number of boosting iterations.')
#决策树的最大深度,默认为3
parser.add_argument('--max-depth',
type=int,
default=3,
help='Max depth of decision trees.')
#L2正则化参数,默认为1.0
parser.add_argument('--l2-regularization',
type=float,
default=1.0,
help='L2 regularization parameter.')
#最大的直方图维度
parser.add_argument('--max-bins',
type=int,
default=33,
help='Max number of histogram bins.')
#并行线程的数量,默认1
parser.add_argument('--num-parallel',
type=int,
default=1,
help='Number of parallel threads.')
#bool类型,如果被设置为true,数据第一列被认为是双方都匹配的example id
parser.add_argument('--verify-example-ids',
type=bool,
default=False,
help='If set to true, the first column of the '
'data will be treated as example ids that '
'must match between leader and follower')
#通过名字来忽略数据域,默认空字符串
parser.add_argument('--ignore-fields',
type=str,
default='',
help='Ignore data fields by name')
#分类特征的字段名称,特征的值应该为非负整数
parser.add_argument('--cat-fields',
type=str,
default='',
help='Field names of categorical features. Feature'
' values should be non-negtive integers')
#是否使用流传输,默认为否
parser.add_argument('--use-streaming',
type=bool,
default=False,
help='Whether to use streaming transmit.')
#是否发送预测评分给follower,默认为false
parser.add_argument('--send-scores-to-follower',
type=bool,
default=False,
help='Whether to send prediction scores to follower.')
#是否发送指标(metrics)给follower,默认为follower
parser.add_argument('--send-metrics-to-follower',
type=bool,
default=False,
help='Whether to send metrics to follower.')
return parser
def parse_tfrecord(record):
example = tf.train.Example()
example.ParseFromString(record)
parsed = {}
for key, value in example.features.feature.items():
kind = value.WhichOneof('kind')
if kind == 'float_list':
assert len(value.float_list.value) == 1, "Invalid tfrecord format"
parsed[key] = value.float_list.value[0]
elif kind == 'int64_list':
assert len(value.int64_list.value) == 1, "Invalid tfrecord format"
parsed[key] = value.int64_list.value[0]
elif kind == 'bytes_list':
assert len(value.bytes_list.value) == 1, "Invalid tfrecord format"
parsed[key] = value.bytes_list.value[0]
else:
raise ValueError("Invalid tfrecord format")
return parsed
def extract_field(field_names, field_name, required):
if field_name in field_names:
return []
assert not required, \
"Field %s is required but missing in data"%field_name
return None
def read_data(file_type, filename, require_example_ids,
require_labels, ignore_fields, cat_fields):
logging.debug('Reading data file from %s', filename)
if file_type == 'tfrecord':
reader = tf.io.tf_record_iterator(filename)
reader, tmp_reader = itertools.tee(reader)
first_line = parse_tfrecord(next(tmp_reader))
field_names = first_line.keys()
else:
fin = tf.io.gfile.GFile(filename, 'r')
reader = csv.DictReader(fin)
field_names = reader.fieldnames
example_ids = extract_field(
field_names, 'example_id', require_example_ids)
raw_ids = extract_field(
field_names, 'raw_id', False)
labels = extract_field(
field_names, 'label', require_labels)
ignore_fields = set(filter(bool, ignore_fields.strip().split(',')))
ignore_fields.update(['example_id', 'raw_id', 'label'])
cat_fields = set(filter(bool, cat_fields.strip().split(',')))
for name in cat_fields:
assert name in field_names, "cat_field %s missing"%name
cont_columns = list(filter(
lambda x: x not in ignore_fields and x not in cat_fields, field_names))
cont_columns.sort(key=lambda x: x[1])
cat_columns = list(filter(
lambda x: x in cat_fields and x not in cat_fields, field_names))
cat_columns.sort(key=lambda x: x[1])
features = []
cat_features = []
for line in reader:
if file_type == 'tfrecord':
line = parse_tfrecord(line)
if example_ids is not None:
example_ids.append(str(line['example_id']))
if raw_ids is not None:
raw_ids.append(str(line['raw_id']))
if labels is not None:
labels.append(float(line['label']))
features.append([float(line[i]) for i in cont_columns])
cat_features.append([int(line[i]) for i in cat_columns])
features = np.array(features, dtype=np.float)
cat_features = np.array(cat_features, dtype=np.int32)
if labels is not None:
labels = np.asarray(labels, dtype=np.float)
return features, cat_features, cont_columns, cat_columns, \
labels, example_ids, raw_ids
def read_data_dir(file_ext, file_type, path, require_example_ids,
require_labels, ignore_fields, cat_fields):
if not tf.io.gfile.isdir(path):
return read_data(
file_type, path, require_example_ids,
require_labels, ignore_fields, cat_fields)
files = []
for dirname, _, filenames in tf.io.gfile.walk(path):
for filename in filenames:
_, ext = os.path.splitext(filename)
if file_ext and ext != file_ext:
continue
subdirname = os.path.join(path, os.path.relpath(dirname, path))
files.append(os.path.join(subdirname, filename))
features = None
for fullname in files:
ifeatures, icat_features, icont_columns, icat_columns, \
ilabels, iexample_ids, iraw_ids = read_data(
file_type, fullname, require_example_ids,
require_labels, ignore_fields, cat_fields
)
if features is None:
features = ifeatures
cat_features = icat_features
cont_columns = icont_columns
cat_columns = icat_columns
labels = ilabels
example_ids = iexample_ids
raw_ids = iraw_ids
else:
assert cont_columns == icont_columns, \
"columns mismatch between files %s vs %s"%(
cont_columns, icont_columns)
assert cat_columns == icat_columns, \
"columns mismatch between files %s vs %s"%(
cat_columns, icat_columns)
features = np.concatenate((features, ifeatures), axis=0)
cat_features = np.concatenate(
(cat_features, icat_features), axis=0)
if labels is not None:
labels = np.concatenate((labels, ilabels), axis=0)
if example_ids is not None:
example_ids.extend(iexample_ids)
if raw_ids is not None:
raw_ids.extend(iraw_ids)
assert features is not None, "No data found in %s"%path
return features, cat_features, cont_columns, cat_columns, \
labels, example_ids, raw_ids
def train(args, booster):
X, cat_X, X_names, cat_X_names, y, example_ids, _ = read_data_dir(
args.file_ext, args.file_type, args.data_path, args.verify_example_ids,
args.role != 'follower', args.ignore_fields, args.cat_fields)
if args.validation_data_path:
val_X, val_cat_X, val_X_names, val_cat_X_names, val_y, \
val_example_ids, _ = \
read_data_dir(
args.file_ext, args.file_type, args.validation_data_path,
args.verify_example_ids, args.role != 'follower',
args.ignore_fields, args.cat_fields)
assert X_names == val_X_names, \
"Train data and validation data must have same features"
assert cat_X_names == val_cat_X_names, \
"Train data and validation data must have same features"
else:
val_X = val_cat_X = X_names = val_y = val_example_ids = None
if args.output_path:
tf.io.gfile.makedirs(os.path.dirname(args.output_path))
if args.checkpoint_path:
tf.io.gfile.makedirs(args.checkpoint_path)
booster.fit(
X, y,
cat_features=cat_X,
checkpoint_path=args.checkpoint_path,
example_ids=example_ids,
validation_features=val_X,
validation_cat_features=val_cat_X,
validation_labels=val_y,
validation_example_ids=val_example_ids,
output_path=args.output_path,
feature_names=X_names,
cat_feature_names=cat_X_names)
def write_predictions(filename, pred, example_ids=None, raw_ids=None):
logging.debug("Writing predictions to %s.tmp", filename)
headers = []
lines = []
if example_ids is not None:
headers.append('example_id')
lines.append(example_ids)
if raw_ids is not None:
headers.append('raw_id')
lines.append(raw_ids)
headers.append('prediction')
lines.append(pred)
lines = zip(*lines)
fout = tf.io.gfile.GFile(filename+'.tmp', 'w')
fout.write(','.join(headers) + '\n')
for line in lines:
fout.write(','.join([str(i) for i in line]) + '\n')
fout.close()
logging.debug("Renaming %s.tmp to %s", filename, filename)
tf.io.gfile.rename(filename+'.tmp', filename, overwrite=True)
def test_one_file(args, bridge, booster, data_file, output_file):
if data_file is None:
X = cat_X = X_names = cat_X_names = y = example_ids = raw_ids = None
else:
X, cat_X, X_names, cat_X_names, y, example_ids, raw_ids = \
read_data(
args.file_type, data_file, args.verify_example_ids,
False, args.ignore_fields, args.cat_fields)
pred = booster.batch_predict(
X,
example_ids=example_ids,
cat_features=cat_X,
feature_names=X_names,
cat_feature_names=cat_X_names)
if y is not None:
metrics = booster.loss.metrics(pred, y)
else:
metrics = {}
logging.info("Test metrics: %s", metrics)
if args.role == 'follower':
bridge.start(bridge.new_iter_id())
bridge.receive(bridge.current_iter_id, 'barrier')
bridge.commit()
if output_file:
tf.io.gfile.makedirs(os.path.dirname(output_file))
write_predictions(output_file, pred, example_ids, raw_ids)
if args.role == 'leader':
bridge.start(bridge.new_iter_id())
bridge.send(
bridge.current_iter_id, 'barrier', np.asarray([1]))
bridge.commit()
class DataBlockLoader(object):
def __init__(self, role, bridge, data_path, ext,
worker_rank=0, num_workers=1, output_path=None):
self._role = role
self._bridge = bridge
self._num_workers = num_workers
self._worker_rank = worker_rank
self._output_path = output_path
self._tm_role = 'follower' if role == 'leader' else 'leader'
if data_path:
files = None
if not tf.io.gfile.isdir(data_path):
files = [os.path.basename(data_path)]
data_path = os.path.dirname(data_path)
self._trainer_master = LocalTrainerMasterClient(
self._tm_role, data_path, files=files, ext=ext)
else:
self._trainer_master = None
self._count = 0
if self._role == 'leader':
self._block_queue = queue.Queue()
self._bridge.register_data_block_handler(self._data_block_handler)
self._bridge.start(self._bridge.new_iter_id())
self._bridge.send(
self._bridge.current_iter_id, 'barrier', np.asarray([1]))
self._bridge.commit()
elif self._role == 'follower':
self._bridge.start(self._bridge.new_iter_id())
self._bridge.receive(self._bridge.current_iter_id, 'barrier')
self._bridge.commit()
def _data_block_handler(self, msg):
logging.debug('DataBlock: recv "%s" at %d', msg.block_id, msg.count)
assert self._count == msg.count
if not msg.block_id:
block = None
elif self._trainer_master is not None:
block = self._trainer_master.request_data_block(msg.block_id)
return False
else:
block = DataBlockInfo(msg.block_id, None)
self._count += 1
self._block_queue.put(block)
return True
def _request_data_block(self):
while True:
for _ in range(self._worker_rank):
self._trainer_master.request_data_block()
block = self._trainer_master.request_data_block()
for _ in range(self._num_workers - self._worker_rank - 1):
self._trainer_master.request_data_block()
if block is None or self._output_path is None or \
not tf.io.gfile.exists(os.path.join(
self._output_path, block.block_id) + '.output'):
break
return block
def get_next_block(self):
if self._role == 'local':
return self._request_data_block()
if self._tm_role == 'leader':
while True:
block = self._request_data_block()
if block is not None:
if not self._bridge.load_data_block(
self._count, block.block_id):
continue
else:
self._bridge.load_data_block(self._count, '')
break
self._count += 1
else:
block = self._block_queue.get()
return block
def test(args, bridge, booster):
if not args.no_data:
assert args.data_path, "Data path must not be empty"
else:
assert not args.data_path and args.role == 'leader'
data_loader = DataBlockLoader(
args.role, bridge, args.data_path, args.file_ext,
args.worker_rank, args.num_workers, args.output_path)
while True:
data_block = data_loader.get_next_block()
if data_block is None:
break
if args.output_path:
output_file = os.path.join(
args.output_path, data_block.block_id) + '.output'
else:
output_file = None
test_one_file(
args, bridge, booster, data_block.data_path, output_file)
def run(args):
if args.verbosity == 0:
logging.basicConfig(level=logging.WARNING)
elif args.verbosity == 1:
logging.basicConfig(level=logging.INFO)
else:
logging.basicConfig(level=logging.DEBUG)
assert args.role in ['leader', 'follower', 'local'], \
"role must be leader, follower, or local"
assert args.mode in ['train', 'test', 'eval'], \
"mode must be train, test, or eval"
#follower或leader
if args.role != 'local':
bridge = Bridge(args.role, int(args.local_addr.split(':')[1]),
args.peer_addr, args.application_id, 0,
streaming_mode=args.use_streaming)
else:
bridge = None
try:
#boost
booster = BoostingTreeEnsamble(
bridge,
learning_rate=args.learning_rate,
max_iters=args.max_iters,
max_depth=args.max_depth,
l2_regularization=args.l2_regularization,
max_bins=args.max_bins,
num_parallel=args.num_parallel,
loss_type=args.loss_type,
send_scores_to_follower=args.send_scores_to_follower,
send_metrics_to_follower=args.send_metrics_to_follower)
#加载已存储的模型
if args.load_model_path:
booster.load_saved_model(args.load_model_path)
#训练不需要bridge,为什么呢
if args.mode == 'train':
train(args, booster)
#测试,评估模型需要bridge
else: # args.mode == 'test, eval'
test(args, bridge, booster)
#把模型存起来
if args.export_path:
booster.save_model(args.export_path)
except Exception as e:
logging.fatal(
'Exception raised during training: %s',
traceback.format_exc())
raise e
finally:
#结束bridge
if bridge:
bridge.terminate()
if __name__ == '__main__':
run(create_argument_parser().parse_args())
|
rain701/fedlearner-explain
|
fedlearner/fedlearner/model/tree/trainer.py
|
trainer.py
|
py
| 21,840 |
python
|
en
|
code
| 0 |
github-code
|
6
|
9419348557
|
# Time limit exceeded at sight
# range(n + 1 -i) in the second roop
# You don't need to add the third roop.
# Alternatively, you should use (k =) n - i - j
n , y= map(int, input().split())
for i in range(n + 1):
for j in range(n + 1):
for k in range(n + 1):
if i + j + k == n:
if 10000 * i + 5000 * j + 1000 * k == y:
print(i, j, k)
exit()
print(-1, -1, -1)
# Sample answer
n , y= map(int, input().split())
for i in range(n + 1):
for j in range(n + 1 - i):
if 10000 * i + 5000 * j + 1000 * (n - i - j) == y:
print(i, j, n - i - j)
exit()
print(-1, -1, -1)
|
ababa831/atcoder_beginners
|
first_trial/c_otoshidama.py
|
c_otoshidama.py
|
py
| 746 |
python
|
en
|
code
| 1 |
github-code
|
6
|
28912342142
|
import transformers
import torch.nn as nn
import config
import torch
class BERT_wmm(nn.Module):
def __init__(self, keep_tokens):
super(BERT_wmm,self).__init__()
self.bert=transformers.BertModel.from_pretrained(config.BERT_PATH)
self.fc=nn.Linear(768,768)
self.layer_normalization=nn.LayerNorm((64, 768))
# self.bert_drop=nn.Dropout(0.2)
self.out=nn.Linear(768,6932)
if keep_tokens is not None:
self.embedding = nn.Embedding(6932, 768)
weight = torch.load(config.BERT_EMBEDDING)
weight = nn.Parameter(weight['weight'][keep_tokens])
self.embedding.weight = weight
self.bert.embeddings.word_embeddings = self.embedding
print(weight.shape)
def forward(self, ids, mask, token_type_ids):
out1, _=self.bert(
ids,
attention_mask=mask,
token_type_ids=token_type_ids,
return_dict=False
)
# mean pooling
# max pooling
# concat
# bert_output=self.bert_drop(out1)
output=self.fc(out1)
layer_normalized=self.layer_normalization(output)
final_output=self.out(layer_normalized)
return final_output
|
Zibo-Zhao/Semantic-Matching
|
model.py
|
model.py
|
py
| 1,326 |
python
|
en
|
code
| 0 |
github-code
|
6
|
17940241021
|
def load_train_test(train_file, test_file):
"""
load data from train and test files out of the project
Args:
train_file: a string of train data address
test_file: a string of test data address
Returns:
train_feature: none
train_label: none
test_feature: none
test_label: none
"""
# load train data from train file
train_feature = []
train_label = []
file_read = open(train_file)
for line in file_read.readlines():
data = line.strip().split()
train_label.append(int(data[0])) # the first column is the label, data type: int
# from the second column to the end are the features, data type: float
_feature = [float(item) for item in data[1:]]
train_feature.append(_feature)
# load test data from test file
test_feature = []
test_label = []
file_read = open(test_file)
for line in file_read.readlines():
data = line.strip().split()
test_label.append(int(data[0])) # the first column is the label, data type: int
# from the second column to the end are the features, data type: float
_feature = [float(item) for item in data[1:]]
test_feature.append(_feature)
return train_feature, train_label, test_feature, test_label
|
jingmouren/antifraud
|
antifraud/feature_engineering/load_data.py
|
load_data.py
|
py
| 1,312 |
python
|
en
|
code
| 0 |
github-code
|
6
|
36008540577
|
import sqlite3
import os
import shlex
class Database():
def __init__(self, db_file):
"""Connect to the SQLite DB"""
try:
self.conn = sqlite3.connect(db_file)
self.cursor = self.conn.cursor()
except BaseException as err:
#print(str(err))
self.conn = None
self.cursor = None
def create_table(self, table_name, columns):
query = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join([f'{k} {v}' for k, v in columns.items()])})"
self.cursor.execute(query)
self.conn.commit()
def create_index(self, index_name, table_name, column_list):
#query = f"CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({column_list})"
query = f"CREATE INDEX IF NOT EXISTS idx_hash ON file_hash(filepath, filehash)"
self.cursor.execute(query)
self.conn.commit()
def delete_table(self, table_name):
query = f"DROP TABLE IF EXISTS {table_name}"
self.cursor.execute(query)
self.conn.commit()
def add_record(self, table_name, record):
query = f"INSERT INTO {table_name} ({', '.join(record.keys())}) VALUES ({', '.join(['?' for _ in record.values()])})"
#print(query)
self.cursor.execute(query, list(record.values()))
self.conn.commit()
def delete_record(self, table_name, condition):
query = f"DELETE FROM {table_name} WHERE {condition}"
self.cursor.execute(query)
self.conn.commit()
def run_query(self, query):
#print(query)
self.cursor.execute(query, args)
return self.cursor.fetchall()
def show_all_records(self, table_name):
query = f"SELECT * FROM {table_name}"
self.cursor.execute(query)
return self.cursor.fetchall()
def show_record(self, table_name, filepath):
file_path = (filepath)
#query = f"SELECT * FROM {table_name} WHERE {condition}"
#print(f"SELECT filename,filepath, filehash, timestamp FROM {table_name} WHERE filepath = '{file_path}'")
query = f'SELECT filename,filepath, filehash, timestamp FROM {table_name} WHERE filepath = "{file_path}"'
self.cursor.execute(query)
return self.cursor.fetchall()
def update_record(self, table, filepath, filehash):
"""Update the SQLite File Table"""
file_path = filepath
#print(f"file path: {file_path}")
query = f"UPDATE {table} SET filehash = '{filehash}' WHERE filepath = '{file_path}'"
self.cursor.execute(query)
return self.cursor.fetchall()
def is_rec_modifed(filepath,filehash,timestamp):
"""Check record for any changes
Returning false until function is completed"""
return False
def show_duplicate_records(self, table_name, index_name, value):
query = f"SELECT filename, filepath, filehash FROM {table_name} WHERE {index_name} = '{value}'"
self.cursor.execute(query)
return self.cursor.fetchall()
def show_all_tables(self):
query = "SELECT name FROM sqlite_master WHERE type='table'"
self.cursor.execute(query)
return self.cursor.fetchall()
def close_connection(self):
self.conn.close()
if __name__ == '__main__':
db = Database('test.db')
db.create_table('users', {'id': 'INTEGER PRIMARY KEY', 'name': 'TEXT', 'email': 'TEXT'})
db.add_record('users', {'name': 'Alice', 'email': '[email protected]'})
db.add_record('users', {'name': 'Bob', 'email': '[email protected]'})
db.add_record('users', {'name': 'Charlie', 'email': '[email protected]'})
print(db.show_all_records('users'))
print(db.show_record('users', "name='Alice'"))
db.delete_record('users', "name='Bob'")
print(db.show_all_records('users'))
db.delete_table('users')
db.close_connection()
os.remove('test.db')
|
echeadle/File_Track
|
app/sqlite_db.py
|
sqlite_db.py
|
py
| 3,901 |
python
|
en
|
code
| 0 |
github-code
|
6
|
33800228048
|
# BFS
from collections import deque
import sys
input = lambda: sys.stdin.readline()
def bfs(i, c): # 정점, 색상
q = deque([i])
visited[i] = True
color[i] = c
while q:
i = q.popleft()
for j in arr[i]:
if not visited[j]:
visited[j] = True
q.append(j)
color[j] = 3- color[i]
else:
if color[i] == color[j]:
return False
return True
if __name__ == '__main__':
k = int(input())
for _ in range(k): # 테스트 케이스
v,e = map(int, input().split())
color = [0] * (v+1)
arr = [[] for _ in range(v+1)]
for _ in range(e):
a,b = map(int, input().split())
arr[a].append(b)
arr[b].append(a)
answer = True
visited = [False] * (v+1)
for i in range(1, v+1):
if not visited[i]:
if not bfs(i, 1): # return False이면 종료
answer = False
break
print('YES' if answer else 'NO')
# DFS -> 메모리 초과
# from collections import deque
# import sys
# input = lambda: sys.stdin.readline()
# sys.setrecursionlimit(10**6)
# def dfs(i, c): # 정점, 색상
# color[i] = c
# for j in arr[i]:
# if color[j] == 0:
# if not dfs(j, 3-c):
# return False
# elif color[i] == color[j]:
# return False
# return True
# if __name__ == '__main__':
# k = int(input())
# for _ in range(k): # 테스트 케이스
# v,e = map(int, input().split())
# color = [0] * (v)
# arr = [[] for _ in range(v)]
# for _ in range(e):
# a,b = map(int, input().split())
# arr[a-1].append(b-1)
# arr[b-1].append(a-1)
# answer = True
# for i in range(0, v):
# if color[i] == 0:
# if not dfs(i, 1):
# answer = False
# print('YES' if answer else 'NO')
|
devAon/Algorithm
|
BOJ-Python/boj-1707_이분그래프.py
|
boj-1707_이분그래프.py
|
py
| 2,065 |
python
|
en
|
code
| 0 |
github-code
|
6
|
42710543766
|
'''
@ Carlos Suarez 2020
'''
import requests
import datetime
import time
import json
from cachetools import TTLCache
import ssl
import sys
class MoodleControlador():
def __init__(self,domain,token,cert):
self.domain = domain
self.token = token
self.cert = cert
#Moodle LTI
def getGrabacionesMoodleContextoLTI(self,moodle_id,tiempo):
endpoint = 'https://' + self.domain + '/contexts/?extId=' + moodle_id
bearer = "Bearer " + self.token
headers = {
"Authorization":bearer,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.get(endpoint,headers=headers,verify=self.cert)
if r.status_code == 200:
jsonInfo = json.loads(r.text)
if jsonInfo['size'] > 0:
contexto_id = jsonInfo['results'][0]['id']
return contexto_id
else:
return None
else:
print("Error Moodle ContextoLTI:" , str(r))
def grabacionesMoodleLTI(self,contexto_id):
endpoint = 'https://' + self.domain + '/recordings/?contextId=' + contexto_id
bearer = "Bearer " + self.token
headers = {
"Authorization":bearer,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.get(endpoint,headers=headers)
if r.status_code == 200:
jsonInfo = json.loads(r.text)
return jsonInfo
else:
print("Error GrabacionesLTL: " , str(r))
def get_moodleLTI_recording_data(self,recording_id):
authStr = 'Bearer ' + self.token
url = 'https://' + self.domain + '/recordings/' + recording_id + '/data'
credencial ={
'Authorization': authStr,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.get(url,headers=credencial, verify=self.cert)
if r.status_code == 200:
res = json.loads(r.text)
return res
else:
print(r)
#Moodle plugin
def moodleSesionName(self,sesionId):
endpoint = 'https://' + self.domain + '/sessions/' + sesionId
credencial = {
"Authorization":"Bearer " + self.token,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.get(endpoint,headers=credencial,verify=self.cert)
if r.status_code == 200:
res = json.loads(r.text)
return res['name']
else:
print("Error Session:", str(r))
def listaCompletaSessiones(self,criteria):
listaFiltrada = []
endpoint = 'https://' + self.domain + '/sessions'
credencial = {
"Authorization":"Bearer " + self.token,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.get(endpoint,headers=credencial,verify=self.cert)
if r.status_code == 200:
res = json.loads(r.text)
resultado = res['results']
for sesion in resultado:
if criteria in sesion['name']:
listaFiltrada.append({'id':sesion['id'], 'name':sesion['name']})
return listaFiltrada
else:
print("Error Session:", str(r))
def listaCompletaMoodleGrabaciones(self):
listaGrabaciones = []
endpoint = 'https://' + self.domain + '/recordings'
credencial = {
'Authorization': 'Bearer ' + self.token,
'Accept':'application/json'
}
r = requests.get(endpoint,headers=credencial,verify=self.cert)
if r.status_code == 200:
jsonInfo = json.loads(r.text)
resultado = jsonInfo['results']
if len(resultado) == 0:
print("No recordings found")
else:
for grabacion in resultado:
listaGrabaciones.append({'id':grabacion['id'], 'name':grabacion['name']})
print(listaGrabaciones)
else:
print("Error listaGrabación Moodle:", str(r))
def listaMoodleGrabaciones(self,sname):
endpoint = 'https://' + self.domain + '/recordings?name=' + sname
credencial = {
"Authorization":"Bearer " + self.token,
'Content-Type': 'application/json',
'Accept': 'application/json'
}
r = requests.get(endpoint,headers=credencial,verify=self.cert)
if r.status_code == 200:
res = json.loads(r.text)
idx = 0
recording_ids = []
try:
numero_grabaciones = len(res['results'])
if numero_grabaciones <= 0:
return None
while idx < numero_grabaciones:
if 'storageSize' in res['results'][idx]:
recording_ids.append({
'recording_id':res['results'][idx]['id'],
'recording_name':res['results'][idx]['name'],
'duration':res['results'][idx]['duration'],
'storageSize':res['results'][idx]['storageSize'],
'created':res['results'][idx]['created']
})
else:
recording_ids.append({
'recording_id':res['results'][idx]['id'],
'recording_name':res['results'][idx]['name'],
'duration':res['results'][idx]['duration'],
'storageSize':0,
'created':res['results'][idx]['created']
})
idx += 1
return recording_ids
except TypeError:
return None
else:
return None
|
sfc-gh-csuarez/PyCollab
|
controladores/MoodleControlador.py
|
MoodleControlador.py
|
py
| 6,010 |
python
|
en
|
code
| 15 |
github-code
|
6
|
23423087794
|
import logging
from ab.base import NavTable
from ab.base import Link, Data, Item
class Console (object):
def __init__ (self):
self._indent = 0
self._nt = NavTable()
self.logger = logging.getLogger ('ab')
self.log = lambda msg, level=logging.INFO: self.logger.info (msg)
def reset (self):
self._indent = 0
self._nt = NavTable()
def indent_more (self):
self._indent += 2
return self._indent
def indent_less (self):
self._indent -= 2
return self._indent
def indent (self):
return self._indent
# def add_nav_entry (self, **kwa):
# href = kwa.get ('href')
#
# if href:
# no = self._nt.set (href = href)
# return no
#
#
# def nav_table (self):
# if not len (self._nt):
# raise UserWarning ('empty nav table')
#
# return self._nt
#
#
# def next_target_no (self):
# self._target_no += 1
def draw (self, thing):
out = '\n'
# if type (thing) in [list, tuple]:
if type (thing) is list:
self.indent_more()
for t in thing:
out += self.draw (t)
self.indent_less()
elif isinstance (thing, Item):
out += '{indent}[{index}] {prompt} ({href})'.format (
indent = ' ' * self.indent(),
index = self._nt.set (href = thing.href),
prompt = 'Permaurl',
href = 'GET ' + thing.href,
)
out += self.draw (thing.data)
out += self.draw (thing.links)
elif isinstance (thing, Data):
out += '{indent}{prompt}: {value}'.format (
indent = ' ' * self.indent(),
prompt = thing.prompt,
value = thing.value,
)
elif isinstance (thing, Link):
out += '{indent}[{index}] {prompt} ({method} {href})'.format (
indent = ' ' * self.indent(),
index = self._nt.set (href = thing.href),
prompt = thing.prompt,
method = thing.method,
href = thing.href,
)
else:
out += '<%s>' % thing
return out
|
oftl/ab
|
ui.py
|
ui.py
|
py
| 2,324 |
python
|
en
|
code
| 0 |
github-code
|
6
|
44407906870
|
import wx
import ResizableRuneTag
'''
Created on 23/lug/2011
@author: Marco
'''
class DrawableFrame(wx.Window):
'''
Allows user to put resizable rune tags in a A4 like white frame
Configuration realized on that frame is then replicated proportionally at export time
'''
def __init__(self, parent, height, width):
wx.Window.__init__(self, parent)
self.SetSize((height, width))
self.SetMinSize((height, width))
self.SetMaxSize((height, width))
self.SetBackgroundColour(wx.Colour(255, 255, 255))
self.resizableRuneTags = []
'''
Constructor
'''
def DrawRuneTag(self, runeTagName, position, size, originalSize, info):
self.resizableRuneTags.append(ResizableRuneTag.ResizableRuneTag(self, runeTagName, size, position, originalSize, info))
def Clear(self):
for resizableRuneTag in self.resizableRuneTags:
resizableRuneTag.Destroy()
def checkSpecificPosition(self, changedRuneTag):
for tag in self.resizableRuneTags:
if changedRuneTag != tag:
radius1 = (tag.GetSize().GetHeight())/2 - 5
radius2 = (changedRuneTag.GetSize().GetHeight())/2 - 5
deltax = (tag.GetPosition().x + radius1) - (changedRuneTag.GetPosition().x + radius2)
deltay = (tag.GetPosition().y + radius1) - (changedRuneTag.GetPosition().y + radius2)
distance = (deltax*deltax + deltay*deltay)**(0.5)
radiusSum = radius1 + radius2
if distance <= radiusSum:
self.Parent.Parent.runeTagInfo.UpdateOverlap("In the output pdf file\n some slots of "+changedRuneTag.name+" RuneTag\n may laps over "+tag.name+"RuneTag")
else:
self.Parent.Parent.runeTagInfo.UpdateOverlap("")
def checkPosition(self):
size = len(self.resizableRuneTags)
for i in range(0, size):
for j in range(i+1, size):
tag1 = self.resizableRuneTags[i]
tag2 = self.resizableRuneTags[j]
radius1 = (tag1.GetSize().GetHeight())/2 - 5
radius2 = (tag2.GetSize().GetHeight())/2 - 5
deltax = (tag1.GetPosition().x + radius1) - (tag2.GetPosition().x + radius2)
deltay = (tag1.GetPosition().y + radius1) - (tag2.GetPosition().y + radius2)
distance = (deltax**2 + deltay**2)**(0.5)
radiusSum = radius1 + radius2
if distance <= radiusSum:
self.Parent.Parent.runeTagInfo.UpdateOverlap("In the output pdf file some slots of\n"+tag1.name+" RuneTag\n may laps over\n"+tag2.name+" RuneTag")
else:
self.Parent.Parent.runeTagInfo.UpdateOverlap("")
|
mziccard/RuneTagDrawer
|
DrawableFrame.py
|
DrawableFrame.py
|
py
| 2,831 |
python
|
en
|
code
| 3 |
github-code
|
6
|
10423490633
|
from __future__ import annotations
import pytest
from randovania.lib import migration_lib
def test_migrate_to_version_missing_migration() -> None:
data = {
"schema_version": 1,
}
with pytest.raises(
migration_lib.UnsupportedVersion,
match=(
"Requested a migration from something 1, but it's no longer supported. "
"You can try using an older Randovania version."
),
):
migration_lib.apply_migrations(data, [None], version_name="something")
def test_migrate_to_version_data_too_new() -> None:
data = {
"schema_version": 3,
}
with pytest.raises(
migration_lib.UnsupportedVersion,
match=(
"Found version 3, but only up to 2 is supported. This file was created using a newer Randovania version."
),
):
migration_lib.apply_migrations(data, [None])
|
randovania/randovania
|
test/lib/test_migration_lib.py
|
test_migration_lib.py
|
py
| 899 |
python
|
en
|
code
| 165 |
github-code
|
6
|
18680754942
|
import matplotlib.pyplot as plt
import numpy as np
import os
import PIL
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Sequential
import pathlib
data_dir = "./Covid(CNN)/Veriseti"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.jpeg')))
print(image_count)
'''
roses = list(data_dir.glob('roses/*'))
PIL.Image.open(str(roses[0]))
PIL.Image.open(str(roses[1]))
tulips = list(data_dir.glob('tulips/*'))
PIL.Image.open(str(tulips[0]))
PIL.Image.open(str(tulips[1]))
'''
batch_size = 32
img_height = 180
img_width = 180
#Görüntülerin% 80'ini eğitim için ve% 20'sini doğrulama için kullanalım.
train_ds = tf.keras.preprocessing.image_dataset_from_directory(
"./Veriseti",
validation_split=0.2,
subset="training",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
"./Veriseti",
validation_split=0.2,
subset="validation",
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
class_names = train_ds.class_names
print(class_names)
import matplotlib.pyplot as plt
#Verileri görselleştirin.Eğitim veri kümesindeki ilk 9 görüntü.
plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
#Bu, 180x180x3 şeklinde 32 görüntüden oluşan bir 180x180x3 (son boyut, RGB renk kanallarına atıfta bulunur)
#label_batch , şeklin bir label_batch (32,) , bunlar 32 görüntüye karşılık gelen etiketlerdir.
for image_batch, labels_batch in train_ds:
print(image_batch.shape)
print(labels_batch.shape)
break
AUTOTUNE = tf.data.experimental.AUTOTUNE
#Dataset.cache() , görüntüleri ilk dönemde diskten yüklendikten sonra bellekte tutar.
#Bu, modelinizi eğitirken veri kümesinin bir darboğaz haline gelmemesini sağlayacaktır.
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)
#Dataset.prefetch() , eğitim sırasında veri ön işleme ve model yürütme ile çakışır.
#RGB kanal değerleri [0, 255] aralığındadır. Bu bir sinir ağı için ideal değildir
#Yeniden Ölçeklendirme katmanı kullanarak değerleri [0, 1] aralığında olacak şekilde standart hale getiriyoruz.
normalization_layer = layers.experimental.preprocessing.Rescaling(1./255)
#Bu katmanı kullanmanın iki yolu vardır. Haritayı çağırarak veri kümesine uygulayabilirsiniz:
normalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))
image_batch, labels_batch = next(iter(normalized_ds))
first_image = image_batch[0]
# Notice the pixels values are now in `[0,1]`.
print(np.min(first_image), np.max(first_image))
#Veya katmanı model tanımınızın içine dahil ederek dağıtımı basitleştirebilirsiniz. Burada ikinci yaklaşımı kullanalım.
num_classes = 4
#Modeli oluşturun
model = Sequential([
layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes)
])
#Modeli derleyin
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
#Model özeti
model.summary()
#Modeli eğitin
epochs=10
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs
)
#Eğitim ve doğrulama setlerinde kayıp ve doğruluk grafikleri oluşturun.
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
#Veri büyütme
data_augmentation = keras.Sequential(
[
layers.experimental.preprocessing.RandomFlip("horizontal",
input_shape=(img_height,
img_width,
3)),
layers.experimental.preprocessing.RandomRotation(0.1),
layers.experimental.preprocessing.RandomZoom(0.1),
]
)
#Birkaç artırılmış örneğin nasıl göründüğünü, aynı görüntüye birkaç kez veri artırma uygulayarak görselleştirelim
plt.figure(figsize=(10, 10))
for images, _ in train_ds.take(1):
for i in range(9):
augmented_images = data_augmentation(images)
ax = plt.subplot(3, 3, i + 1)
plt.imshow(augmented_images[0].numpy().astype("uint8"))
plt.axis("off")
#layers.Dropout kullanarak yeni bir sinir ağı oluşturalım.
model = Sequential([
data_augmentation,
layers.experimental.preprocessing.Rescaling(1./255),
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
layers.Dropout(0.2),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dense(num_classes)
])
#Modeli derleyin ve eğitin
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.summary()
epochs = 15
history = model.fit(
train_ds,
validation_data=val_ds,
epochs=epochs
)
#Eğitim sonuçları
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
#Eğitim veya doğrulama setlerinde yer almayan bir resmi sınıflandırmak için modelimizi kullanalım.
img_path = "./Veriseti/Covid.jpeg"
img = keras.preprocessing.image.load_img(
img_path, target_size=(img_height, img_width)
)
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(
"This image most likely belongs to {} with a {:.2f} percent confidence."
.format(class_names[np.argmax(score)], 100 * np.max(score))
)
|
elifyelizcelebi/Covid-CNN
|
model.py
|
model.py
|
py
| 7,465 |
python
|
tr
|
code
| 0 |
github-code
|
6
|
44364880366
|
'''
(mdc) Programa que lê dois inteiro positivos a e b
e imprime o máximo divisor comum (mdc) de a e b.
'''
def mdc(a,b):
while b !=0:
resto = a % b
a = b
b = resto
return a
print("Informe o valor de A e B: ", end='')
a, b = map(int, input().split())
print("MDC de {} e {} = {}".format(a, b, mdc(a,b)))
|
danilosheen/topicos-especiais
|
q1.py
|
q1.py
|
py
| 342 |
python
|
pt
|
code
| 0 |
github-code
|
6
|
30478129230
|
# Reverse a Linked List in groups of given size
# Normal Reverse
def reverseList(head):
if head is None:
return -1
curr = head
temp = None
prev = None
while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
# Reverse in k groups
def solve(head, size, k):
if not head or size < k:
return head
curr = head
temp = None
prev = None
cnt = 0
while curr and cnt < k:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
cnt += 1
head.next = solve(curr, size - k, k)
return prev
def reverseKGroup(head, k):
size = 0
temp = head
while temp:
size += 1
temp = temp.next
return solve(head, size, k)
|
prabhat-gp/GFG
|
Linked List/LL Medium/5_reverse_k.py
|
5_reverse_k.py
|
py
| 828 |
python
|
en
|
code
| 0 |
github-code
|
6
|
6117949220
|
from google.cloud import bigquery
import os
import sys
import json
import argparse
import gzip
import configparser
import pandas as pd
def main():
# Load args
args = parse_args()
In_config=args.in_config
Input_study=args.in_study
Configs = configparser.ConfigParser()
Configs.read(In_config)
client = bigquery.Client()
## LOAD Job: load from GCS to BQ (table_id)
# Would it be possible to make this table temporary? Or delete itself automatically after 1 week?
Input_sumstats_path=Configs.get("config", "Input_sumstats_GCS")
Input_study_URI=Input_sumstats_path+"/"+Input_study+".parquet/*.parquet"
temp_BQ_sumstats=Configs.get("config", "Temp_BQ_sumstats")
table_id = temp_BQ_sumstats+"."+Input_study
print(table_id)
load_job_config = bigquery.LoadJobConfig(source_format=bigquery.SourceFormat.PARQUET,)
load_job = client.load_table_from_uri(
Input_study_URI, table_id, job_config=load_job_config
) # Make an API request.
load_job.result() # Waits for the job to complete.
destination_table = client.get_table(table_id) # Make an API request.
print("Loaded {} rows.".format(destination_table.num_rows))
# Query Job
table_id = Configs.get("config", "Temp_BQ_sumstats")+"."+Input_study
rsID_table = Configs.get("config", "RSID_BQ_sumstats")+"."+Input_study
query_job_config = bigquery.QueryJobConfig(destination=rsID_table)
query = """
WITH SNP_info AS (
SELECT
CONCAT(CAST(chrom AS string), CAST(pos AS string), CAST(ref AS string), CAST(alt AS string)) AS identifier,
ref,
alt,
n_total,
pval,
eaf,
beta
FROM
`{0}` )
SELECT
rs_id AS RSID, ref AS A1, alt AS A2, n_total AS N, pval AS P, eaf AS EAF, beta AS BETA
FROM
SNP_info
JOIN (
SELECT
CONCAT(CAST(chr_id AS string), CAST(position AS string), CAST(ref_allele AS string), CAST(alt_allele AS string)) AS identifier,
rs_id
FROM
`open-targets-genetics.210608.variants` ) variants
USING(identifier)
""".format(table_id)
query_job = client.query(query, job_config=query_job_config)
query_job.result()
# Extract Job
rsID_GCS_bucket=Configs.get("config", "Formatted_sumstats_GCS")
rsID_GCS_URI=rsID_GCS_bucket+"/{0}.txt.gz".format(Input_study)
extract_job_config = bigquery.ExtractJobConfig()
extract_job_config.field_delimiter = '\t'
extract_job_config.compression='GZIP'
extract_job = client.extract_table(
rsID_table,
rsID_GCS_URI,
# Location must match that of the source table.
location="EU",
job_config=extract_job_config
) # API request
extract_job.result() # Waits for job to complete.
print(
"Exported {} to {}".format(rsID_table, rsID_GCS_URI)
)
def parse_args():
''' Load command line args
'''
parser = argparse.ArgumentParser()
parser.add_argument('--in_config', metavar="<str>", type=str, required=True)
parser.add_argument('--in_study', metavar="<str>", type=str, required=True, help=("Study ID of input sumstats"))
args = parser.parse_args()
return args
if __name__ == '__main__':
main()
|
xyg123/SNP_enrich_preprocess
|
scripts/LDSC_format_single_sumstat.py
|
LDSC_format_single_sumstat.py
|
py
| 3,343 |
python
|
en
|
code
| 1 |
github-code
|
6
|
70075742268
|
# -*- encoding:utf-8 -*-
'''
@time: 2019/12/21 9:48 下午
@author: huguimin
@email: [email protected]
'''
import os
import random
import math
import torch
import argparse
import numpy as np
from util.util_data_gcn import *
from models.word2vec.ecgcn import ECGCN
from models.word2vec.ecgat import ECGAT
from models.word2vec.fssgcn import ECClassifier
from models.word2vec.aggcn import AGClassifier
# from models.ecaggcn_no_dcn import ECClassifier
from sklearn import metrics
import torch.nn as nn
import time
class Model:
def __init__(self, opt, idx):
self.opt = opt
self.embedding = load_embedding(opt.embedding_path)
self.embedding_pos = load_pos_embedding(opt.embedding_dim_pos)
self.split_size = math.ceil(opt.data_size / opt.n_split)
self.global_f1 = 0
# self.train, self.test = load_data(self.split_size, idx, opt.data_size) #意味着只能从一个角度上训练,应该换几种姿势轮着训练
if opt.dataset == 'EC':
self.train, self.test = load_percent_train(opt.per, self.split_size, idx, opt.data_size)
elif opt.dataset == 'EC_en':
self.train, self.test = load_data_en()
else:
print('DATASET NOT EXIST')
# self.train, self.test = load_data(self.split_size, idx, opt.data_size)
self.sub_model = opt.model_class(self.embedding, self.embedding_pos, self.opt).to(opt.device)
def _reset_params(self):
for p in self.sub_model.parameters():
if p.requires_grad:
if len(p.shape) > 1:
self.opt.initializer(p)
else:
stdv = 1. / math.sqrt(p.shape[0])
torch.nn.init.uniform_(p, a=-stdv, b=stdv)
def _print_args(self):
n_trainable_params, n_nontrainable_params, model_params = 0, 0, 0
for p in self.sub_model.parameters():
n_params = torch.prod(torch.tensor(p.shape)).item()
model_params += n_params
if p.requires_grad:
n_trainable_params += n_params
else:
n_nontrainable_params += n_params
print('n_trainable_params: {0}, n_nontrainable_params: {1}, model_params: {2}'.format(n_trainable_params, n_nontrainable_params, model_params))
print('> training arguments:')
for arg in vars(self.opt):
print('>>> {0}: {1}'.format(arg, getattr(self.opt, arg)))
def _train(self, criterion, optimizer):
max_test_pre = 0
max_test_rec = 0
max_test_f1 = 0
global_step = 0
continue_not_increase = 0
for epoch in range(self.opt.num_epoch):
print('>' * 100)
print('epoch: ', epoch)
n_correct, n_total = 0, 0
increase_flag = False
for train in get_train_batch_data(self.train, self.opt.batch_size, self.opt.keep_prob1, self.opt.keep_prob2):
global_step += 1
self.sub_model.train()
optimizer.zero_grad()
inputs = [train[col].to(self.opt.device) for col in self.opt.inputs_cols]
targets = train['label'].to(self.opt.device)
doc_len = train['doc_len'].to(self.opt.device)
targets = torch.argmax(targets, dim=2)
targets_flatten = torch.reshape(targets, [-1])
outputs = self.sub_model(inputs)
outputs_flatten = torch.reshape(outputs, [-1, self.opt.num_class])
loss = criterion(outputs_flatten, targets_flatten)
# loss = nn.functional.nll_loss(outputs_flatten, targets_flatten)
outputs = torch.argmax(outputs, dim=-1)
loss.backward()
optimizer.step()
if global_step % self.opt.log_step == 0:
train_acc, train_pre, train_rec, train_f1 = self._evaluate_prf_binary(targets, outputs, doc_len)
print('Train: loss:{:.4f}, train_acc: {:.4f}, train_pre:{:.4f}, train_rec:{:.4f}, train_f1: {:.4f}\n'.format(loss.item(), train_acc, train_pre, train_rec, train_f1))
test_acc, test_pre, test_rec, test_f1 = self._evaluate_acc_f1()
# if test_acc > max_test_acc:
# max_test_acc = test_acc
if test_f1 > max_test_f1:
increase_flag = True
max_test_f1 = test_f1
max_test_pre = test_pre
max_test_rec = test_rec
if self.opt.save and test_f1 > self.global_f1:
self.global_f1 = test_f1
torch.save(self.sub_model.state_dict(), 'state_dict/'+self.opt.model_name+'_'+self.opt.dataset+'_test.pkl')
print('>>> best model saved.')
print('Test: test_acc: {:.4f}, test_pre:{:.4f}, test_rec:{:.4f}, test_f1: {:.4f}'.format(test_acc, test_pre, test_rec, test_f1))
if increase_flag == False:
continue_not_increase += 1
if continue_not_increase >= 5:
print('early stop.')
break
else:
continue_not_increase = 0
return max_test_pre, max_test_rec, max_test_f1
def _evaluate_acc_f1(self):
# switch model to evaluation mode
self.sub_model.eval()
targets_all, outputs_all, doc_len_all = None, None, None
inference_time_list = []
with torch.no_grad():
for test in get_test_batch_data(self.test, self.opt.batch_size):
inputs = [test[col].to(self.opt.device) for col in self.opt.inputs_cols]
targets = test['label'].to(self.opt.device)
doc_len = test['doc_len'].to(self.opt.device)
targets = torch.argmax(targets, dim=2)#(32,75)
if self.opt.infer_time:
torch.cuda.synchronize()
start_time = time.time()
outputs = self.sub_model(inputs)
torch.cuda.synchronize()
end_time = time.time()
inference_time = end_time - start_time
inference_time_list.append(inference_time/targets.shape[0])
else:
outputs = self.sub_model(inputs)
outputs = torch.argmax(outputs, dim=2)#(32, 75)
if targets_all is None:
targets_all = targets
outputs_all = outputs
doc_len_all = doc_len
else:
targets_all = torch.cat((targets_all, targets), dim=0)
outputs_all = torch.cat((outputs_all, outputs), dim=0)
doc_len_all = torch.cat((doc_len_all, doc_len), dim=0)
test_acc, test_pre, test_rec, test_f1 = self._evaluate_prf_binary(targets_all, outputs_all, doc_len_all)
infer_time = np.mean(np.array(inference_time_list))
print('infer_time==================', str(infer_time))
return test_acc, test_pre, test_rec, test_f1
def _evaluate_prf_binary(self, targets, outputs, doc_len):
"""
:param targets: [32,75]
:param outputs: [32,75]
:return:
"""
tmp1, tmp2 = [], []
for i in range(outputs.shape[0]):
for j in range(doc_len[i]):
tmp1.append(outputs[i][j].cpu())
tmp2.append(targets[i][j].cpu())
y_pred, y_true = np.array(tmp1), np.array(tmp2)
acc = metrics.precision_score(y_true, y_pred, average='micro')
p = metrics.precision_score(y_true, y_pred, average='binary')
r = metrics.recall_score(y_true, y_pred, average='binary')
f1 = metrics.f1_score(y_true, y_pred, average='binary')
return acc, p, r, f1
def run(self, folder, repeats=1):
# Loss and Optimizer
print(('-'*50 + 'Folder{}' + '-'*50).format(folder))
criterion = nn.CrossEntropyLoss()
# criterion = nn.functional.nll_loss()
_params = filter(lambda p: p.requires_grad, self.sub_model.parameters())
optimizer = self.opt.optimizer(_params, lr=self.opt.learning_rate, weight_decay=self.opt.l2reg)
if not os.path.exists('log/'):
os.mkdir('log/')
f_out = open('log/' + self.opt.model_name + '_' + str(folder) + '_test.txt', 'a+', encoding='utf-8')
max_test_pre_avg = 0
max_test_rec_avg = 0
max_test_f1_avg = 0
for i in range(repeats):
print('repeat: ', (i + 1))
f_out.write('repeat: ' + str(i + 1))
self._reset_params()
max_test_pre, max_test_rec, max_test_f1 = self._train(criterion, optimizer)
print('max_test_acc: {0} max_test_hf1: {1}'.format(max_test_pre, max_test_f1))
f_out.write('max_test_acc: {0}, max_test_f1: {1}'.format(max_test_pre, max_test_f1))
max_test_pre_avg += max_test_pre
max_test_rec_avg += max_test_rec
max_test_f1_avg += max_test_f1
print('#' * 100)
print("max_test_acc_avg: {.4f}", max_test_pre_avg / repeats)
print('max_test_acc_rec: {.4f}', max_test_rec_avg / repeats)
print("max_test_f1_avg: {.4f}", max_test_f1_avg / repeats)
f_out.write("max_test_pre_avg: {0}, max_test_rec_avg: {1}, max_test_f1_avg: {2}".format(max_test_pre_avg / repeats, max_test_rec_avg / repeats, max_test_f1_avg / repeats))
f_out.close()
return max_test_pre_avg / repeats, max_test_rec_avg / repeats, max_test_f1_avg / repeats
if __name__ == '__main__':
# Hyper Parameters
parser = argparse.ArgumentParser()
parser.add_argument('--model_name', default='fssgcn', type=str)
parser.add_argument('--optimizer', default='adam', type=str)
parser.add_argument('--initializer', default='xavier_uniform_', type=str)
parser.add_argument('--learning_rate', default=0.001, type=float)
parser.add_argument('--input_dropout', default=0.1, type=float)
parser.add_argument('--gcn_dropout', default=0.1, type=float)
parser.add_argument('--head_dropout', default=0.1, type=float)
parser.add_argument('--keep_prob2', default=0.1, type=float)
parser.add_argument('--keep_prob1', default=0.1, type=float)
parser.add_argument('--alpha', default=0.3, type=float)
parser.add_argument('--l2reg', default=0.00001, type=float)
# parser.add_argument('--l2reg', default=0.000005, type=float)
parser.add_argument('--num_epoch', default=100, type=int)
parser.add_argument('--batch_size', default=32, type=int)
parser.add_argument('--log_step', default=5, type=int)
parser.add_argument('--embed_dim', default=200, type=int)
parser.add_argument('--embedding_dim_pos', default=100, type=int)
###中文数据集的embedding文件
parser.add_argument('--embedding_path', default='embedding.txt', type=str)
###英文数据集的embedding文件################################
# parser.add_argument('--embedding_path', default='all_embedding_en.txt', type=str)
#################################################
parser.add_argument('--pos_num',default=138, type=int)
parser.add_argument('--hidden_dim', default=100, type=int)
parser.add_argument('--num_layers', default=3, type=int)
parser.add_argument('--nheads', default=1, type=int)
parser.add_argument('--sublayer_first', default=2, type=int)
parser.add_argument('--sublayer_second', default=4, type=int)
parser.add_argument('--sublayer', default=1, type=int)
parser.add_argument('--no_rnn', default=False, type=bool)
parser.add_argument('--rnn_layer', default=1, type=int)
parser.add_argument('--rnn_hidden', default=100, type=int)
parser.add_argument('--rnn_dropout', default=0.5, type=float)
parser.add_argument('--no_pos', default=False, type=bool)
parser.add_argument('--n_split', default=10, type=int)
parser.add_argument('--per', default=1.0, type=float)
parser.add_argument('--num_class', default=2, type=int)
parser.add_argument('--save', default=True, type=bool)
parser.add_argument('--seed', default=776, type=int)
parser.add_argument('--device', default=None, type=str)
parser.add_argument('--infer_time', default=False, type=bool)
####数据集为英文数据集
# parser.add_argument('--dataset', default='EC_en', type=str)
####数据集为中文数据集
parser.add_argument('--dataset', default='EC', type=str)
opt = parser.parse_args()
model_classes = {
'ecgcn': ECGCN,
'ecgat': ECGAT,
'aggcn': AGClassifier,
'fssgcn': ECClassifier
}
input_colses = {
'ecgcn': ['content', 'sen_len', 'doc_len', 'doc_id', 'emotion_id', 'graph'],
'ecgat': ['content', 'sen_len', 'doc_len', 'doc_id', 'emotion_id', 'graph'],
'aggcn': ['content', 'sen_len', 'doc_len', 'doc_id', 'emotion_id', 'graph'],
'fssgcn': ['content', 'sen_len', 'doc_len', 'doc_id', 'emotion_id', 'graph']
}
initializers = {
'xavier_uniform_': torch.nn.init.xavier_uniform_,
'xavier_normal_': torch.nn.init.xavier_normal,
'orthogonal_': torch.nn.init.orthogonal_,
}
optimizers = {
'adadelta': torch.optim.Adadelta, # default lr=1.0
'adagrad': torch.optim.Adagrad, # default lr=0.01
'adam': torch.optim.Adam, # default lr=0.001
'adamax': torch.optim.Adamax, # default lr=0.002
'asgd': torch.optim.ASGD, # default lr=0.01
'rmsprop': torch.optim.RMSprop, # default lr=0.01
'sgd': torch.optim.SGD,
}
opt.model_class = model_classes[opt.model_name]
opt.inputs_cols = input_colses[opt.model_name]
opt.initializer = initializers[opt.initializer]
opt.optimizer = optimizers[opt.optimizer]
if opt.dataset == 'EC':
opt.max_doc_len = 75
opt.max_sen_len = 45
opt.data_size = 2105
opt.hidden_dim = 100
opt.rnn_hidden = 100
opt.embed_dim = 200
opt.embedding_path = 'embedding.txt'
else:
opt.max_doc_len = 45
opt.max_sen_len = 130
opt.data_size = 2105
opt.hidden_dim = 150
opt.rnn_hidden = 150
opt.embed_dim = 300
opt.embedding_path = 'all_embedding_en.txt'
opt.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') \
if opt.device is None else torch.device(opt.device)
if opt.seed is not None:
random.seed(opt.seed)
np.random.seed(opt.seed)
torch.manual_seed(opt.seed)
torch.cuda.manual_seed(opt.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
p, r, f1 = [], [], []
for i in range(1):
model = Model(opt, i)
###计算模型大
model._print_args()
p_t, r_t, f1_t = model.run(i)
p.append(p_t)
r.append(r_t)
f1.append(f1_t)
print("max_test_pre_avg: {:.4f}, max_test_rec_avg: {:.4f}, max_test_f1_avg: {:.4f}".format(np.mean(p), np.mean(r), np.mean(f1)))
|
LeMei/FSS-GCN
|
train.py
|
train.py
|
py
| 15,194 |
python
|
en
|
code
| 14 |
github-code
|
6
|
40467350126
|
# 1번 풀이
# import sys
# dx = [0,0,-1,1] # 우좌상하
# dy = [1,-1,0,0]
# def dfs(places, x, y,depth):
# if depth == 3: # depth 3까지 찾아봤는데 거리두기 잘 지키는 경우 True
# return True
# for i in range(4):
# nx = x + dx[i]
# ny = y + dy[i]
# if 0<= nx <5 and 0<= ny <5 and visited[nx][ny] == 0 and places[nx][ny] != 'X':
# if places[nx][ny] == 'P':
# return False
# else:
# visited[nx][ny] = 1
# if dfs(places,nx,ny,depth + 1):
# visited[nx][ny] = 0
# else:
# visited[nx][ny] = 0
# return False
# return True
# def solution(places):
# global visited
# answer = []
# for place in places:
# flag = 0
# visited = [[0] * 5 for _ in range(5)]
# for i in range(5):
# if flag == 1: # 이미 거리두기 안지키는 사람을 발견함
# break
# for j in range(5):
# if place[i][j] == 'P' and not visited[i][j]:
# visited[i][j] = 1
# if dfs(place, i, j,1):
# continue
# else: # 거리두기 안지키는게 발견
# answer.append(0)
# flag = 1
# break
# else:
# answer.append(1)
# return answer
#2번 풀이
import sys
dx = [0,0,-1,1] # 우좌상하
dy = [1,-1,0,0]
def dfs(place, x, y,depth):
global check
if depth == 3: # depth 3까지 찾아봤는데 거리두기 잘 지키는 경우 True
return
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0<= nx <5 and 0<= ny <5 and visited[nx][ny] == 0 and place[nx][ny] != 'X':
if place[nx][ny] == 'P':
check = 0
return
else:
visited[nx][ny] = 1
dfs(place,nx,ny,depth + 1)
visited[nx][ny] = 0
return
def solution(places):
global visited
global check
answer = []
for place in places:
flag = 0
check = 1 # 거리두기 잘지킴
visited = [[0] * 5 for _ in range(5)]
for i in range(5):
if flag == 1: # 이미 거리두기 안지키는 사람을 발견함
break
for j in range(5):
if place[i][j] == 'P' and not visited[i][j]:
visited[i][j] = 1
dfs(place,i,j,1)
if check:
continue
else: # 거리두기 안지키는게 발견
answer.append(0)
flag = 1
break
else:
answer.append(1)
return answer
# 3번 풀이
from collections import deque
def bfs(place):
dx = [0,0,-1,1] # 우좌상하
dy = [1,-1,0,0]
start = []
q = deque()
visited = [[0] * 5 for _ in range(5)]
for i in range(5):
for j in range(5):
if place[i][j] == 'P' and not visited[i][j]:
start.append((i,j))
for s in start:
i,j = s
visited = [[0] * 5 for _ in range(5)]
visited[i][j] = 1
q.append(s)
while q:
x, y = q.popleft()
if visited[x][y] < 3:
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < 5 and 0<= ny < 5 and place[nx][ny] != 'X' and not visited[nx][ny]:
if place[nx][ny] == 'P':
return 0
else:
visited[nx][ny] = visited[x][y] + 1
q.append((nx,ny))
return 1
def solution(places):
answer = []
for place in places:
answer.append(bfs(place))
return answer
if __name__ == '__main__':
places = [["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"],
["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"],
["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"],
["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"],
["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"]]
print(solution(places))
|
Cho-El/coding-test-practice
|
프로그래머스 문제/파이썬/level2/거리두기 확인하기.py
|
거리두기 확인하기.py
|
py
| 4,381 |
python
|
en
|
code
| 0 |
github-code
|
6
|
10424276001
|
#-*- coding: utf-8 -*-
u"""
.. moduleauthor:: Martí Congost <[email protected]>
"""
from cocktail.translations import translations
from woost.models import Extension, Configuration
translations.define("AudioExtension",
ca = u"Àudio",
es = u"Audio",
en = u"Audio"
)
translations.define("AudioExtension-plural",
ca = u"Àudio",
es = u"Audio",
en = u"Audio"
)
class AudioExtension(Extension):
def __init__(self, **values):
Extension.__init__(self, **values)
self.extension_author = u"Whads/Accent SL"
self.set("description",
u"""Reproducció de fitxers d'àudio amb recodificació automàtica a
múltiples formats.""",
"ca"
)
self.set("description",
u"""Reproducción de ficheros de audio con recodificación automática
a múltiples formatos.""",
"es"
)
self.set("description",
u"""Audio file player with transparent encoding in multiple
formats.""",
"en"
)
def _load(self):
from woost.extensions.audio import (
strings,
configuration,
audiodecoder,
audioencoder
)
# Expose the controller for serving audio files in multiple encodings
from woost.controllers.cmscontroller import CMSController
from woost.extensions.audio.audioencodingcontroller \
import AudioEncodingController
CMSController.audio = AudioEncodingController
self.install()
self.register_view_factory()
def _install(self):
self.create_default_decoders()
self.create_default_encoders()
def create_default_decoders(self):
from woost.extensions.audio.audiodecoder import AudioDecoder
config = Configuration.instance
mp3 = AudioDecoder()
mp3.mime_type = "audio/mpeg"
mp3.command = '/usr/bin/mpg321 "%s" -w -'
mp3.insert()
config.audio_decoders.append(mp3)
ogg = AudioDecoder()
ogg.mime_type = "audio/ogg"
ogg.command = '/usr/bin/oggdec -Q -o - "%s"'
ogg.insert()
config.audio_decoders.append(ogg)
flac = AudioDecoder()
flac.mime_type = "audio/flac"
flac.command = '/usr/bin/flac -dsc "%s"'
flac.insert()
config.audio_decoders.append(flac)
def create_default_encoders(self):
from woost.extensions.audio.audioencoder import AudioEncoder
config = Configuration.instance
mp3 = AudioEncoder()
mp3.identifier = "mp3-128"
mp3.mime_type = "audio/mpeg"
mp3.extension = ".mp3"
mp3.command = "/usr/bin/lame --quiet -b 128 - %s"
mp3.insert()
config.audio_encoders.append(mp3)
ogg = AudioEncoder()
ogg.identifier = "ogg-q5"
ogg.mime_type = "audio/ogg"
ogg.extension = ".ogg"
ogg.command = "/usr/bin/oggenc -q 5 - -o %s"
ogg.insert()
config.audio_encoders.append(ogg)
def register_view_factory(self):
from woost.models import Publishable
from woost.extensions.audio.audioplayer import AudioPlayer
from woost.views.viewfactory import publishable_view_factory
def audio_player(item, parameters):
if item.resource_type == "audio":
player = AudioPlayer()
player.file = item
return player
publishable_view_factory.register_first(Publishable, "audio_player", audio_player)
|
marticongost/woost
|
woost/extensions/audio/__init__.py
|
__init__.py
|
py
| 3,596 |
python
|
en
|
code
| 0 |
github-code
|
6
|
7640577991
|
test = 2+3 # 答案存在指定test物件
test # 最後一行打指定物件名稱
import random
x=[random.randint(0,100) for i in range(0,12)]
x
x0_str=str(x[0])
x0_str
x_str=[str(x[i]) for i in range(0,len(x))]
x_str
x6_logi=x[6]<50
x6_logi
x_logi=[x[i]<50 for i in range(0,len(x))]
x_logi
num_false=x_logi.count(False)
num_false
import pandas as pd
df_business=pd.read_csv("http://data.gcis.nat.gov.tw/od/file?oid=340B4FDD-880E-4287-9289-F32782F792B8")
dict_business=df_business.to_dict()
address=list(dict_business['公司所在地'].values())
num_taoyuan=["桃園市" in address[i] for i in range(0,len(address))].count(True)
num_taoyuan
capital=list(dict_business['資本額'].values())
logi_largeCapital=[capital[i]>500000 for i in range(0,len(capital))]
num_largeCapital=logi_largeCapital.count(True)
num_largeCapital
import requests
response=requests.get("https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=3")
danceInfo=response.json()
numDance=len(danceInfo)
numDance
title1=danceInfo[0]['title']
title1
local1=danceInfo[0]['showInfo'][0]['location']
local1
time1=danceInfo[0]['showInfo'][0]['time']
time1
## 解答一: 當showInfo不唯一但只考慮每個showInfo的第一個
danceInfoList=[{
'title': danceInfo[i]['title'],
'time': danceInfo[i]['showInfo'][0]['time'],
'location': danceInfo[i]['showInfo'][0]['location']
} for i in range(0,len(danceInfo))]
danceInfoList
## 解答二:
danceInfoList2=list([])
for i in range(len(danceInfo)):
title_i=danceInfo[i]['title']
for j in range(len(danceInfo[i]['showInfo'])):
time_ij=danceInfo[i]['showInfo'][j]['time']
location_ij=danceInfo[i]['showInfo'][j]['location']
danceInfoList2.append({
'title': title_i,
'time': time_ij,
'location': location_ij
})
## 解答一: 當showInfo不唯一但只考慮每個showInfo的第一個
danceInfoStr=['【{title}】將於{time}在{location}演出'.format(
title=danceInfoList[i]['title'],
time=danceInfoList[i]['time'],
location=danceInfoList[i]['location']) for i in range(0,len(danceInfoList))]
danceInfoStr
## 解答二:
danceInfoStr2=['【{title}】將於{time}在{location}演出'.format(
title=danceInfoList2[i]['title'],
time=danceInfoList2[i]['time'],
location=danceInfoList2[i]['location']) for i in range(0,len(danceInfoList2))]
danceInfoStr2
|
godgodgod11101/course_mathEcon_practice_1081
|
hw1_ans.py
|
hw1_ans.py
|
py
| 2,367 |
python
|
en
|
code
| 0 |
github-code
|
6
|
6425852046
|
# 한자리 숫자가 적힌 종이 조각이 흩어져있습니다. 흩어진 종이 조각을 붙여 소수를 몇 개 만들 수 있는지 알아내려 합니다.
# 각 종이 조각에 적힌 숫자가 적힌 문자열 numbers가 주어졌을 때,
# 종이 조각으로 만들 수 있는 소수가 몇 개인지 return 하도록 solution 함수를 완성해주세요.
# 제한사항
# numbers는 길이 1 이상 7 이하인 문자열입니다.
# numbers는 0~9까지 숫자만으로 이루어져 있습니다.
# 013은 0, 1, 3 숫자가 적힌 종이 조각이 흩어져있다는 의미입니다.
def find_prime(numbers) -> int:
from itertools import permutations
def is_prime(n: int) -> bool:
if n==2:
return True
elif n==1 or n%2==0:
return False
for i in range(3, int(n**0.5)+1, 2):
if n%i==0:
return False
return True
answer=0
primes = []
for i in range(1, len(numbers)+1):
perms = list(permutations(numbers, i))
for perm in perms:
target=''
for p in perm:
target += p
if is_prime(int(target)) and int(target) not in primes:
primes.append(int(target))
answer += 1
return answer
|
script-brew/2019_KCC_Summer_Study
|
programmers/Lv_2/MaengSanha/findPrime.py
|
findPrime.py
|
py
| 1,326 |
python
|
ko
|
code
| 0 |
github-code
|
6
|
7868827179
|
# 入力
N = int(input())
S = input()
# '(' の数 - ')' の数を depth とする
# 途中で depth が負になったら、この時点で No
depth = 0
flag = True
for i in range(N):
if S[i] == '(':
depth += 1
if S[i] == ')':
depth -= 1
if depth < 0:
flag = False
# 最後、depth = 0 ['(' と ')' の数が同じ] であるかも追加で判定する
if flag == True and depth == 0:
print("Yes")
else:
print("No")
|
E869120/math-algorithm-book
|
codes/python/Code_5_10_4.py
|
Code_5_10_4.py
|
py
| 430 |
python
|
ja
|
code
| 897 |
github-code
|
6
|
33447423792
|
#Kieren Singh Gill
#11/10/2020
#Python Fall 2020, Section 1
#GillKieren_Assign8_extra_credit.py
#import random module
import random
import sys
#cards list
cards = ['10 of Hearts', '9 of Hearts', '8 of Hearts', '7 of Hearts', '6 of Hearts', '5 of Hearts', '4 of Hearts', '3 of Hearts', '2 of Hearts', 'Ace of Hearts', 'King of Hearts', 'Queen of Hearts', 'Jack of Hearts', '10 of Diamonds', '9 of Diamonds', '8 of Diamonds', '7 of Diamonds', '6 of Diamonds', '5 of Diamonds', '4 of Diamonds', '3 of Diamonds', '2 of Diamonds', 'Ace of Diamonds', 'King of Diamonds', 'Queen of Diamonds', 'Jack of Diamonds', '10 of Clubs', '9 of Clubs', '8 of Clubs', '7 of Clubs', '6 of Clubs', '5 of Clubs', '4 of Clubs', '3 of Clubs', '2 of Clubs', 'Ace of Clubs', 'King of Clubs', 'Queen of Clubs', 'Jack of Clubs', '10 of Spades', '9 of Spades', '8 of Spades', '7 of Spades', '6 of Spades', '5 of Spades', '4 of Spades', '3 of Spades', '2 of Spades', 'Ace of Spades', 'King of Spades', 'Queen of Spades', 'Jack of Spades']
#values list
values = [10, 9, 8, 7, 6, 5, 4, 3, 2, [1,11], 10, 10, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, [1,11], 10, 10, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, [1,11], 10, 10, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, [1,11], 10, 10, 10]
#choose a random card from cards list
#store it in card1 and card2
card1 = random.choice(cards)
card2 = random.choice(cards)
#obtain the corresponding values
#store them in value1 and value2
value1 = values[cards.index(card1)]
value2 = values[cards.index(card2)]
#player's current hand
player_hand_cards = [card1, card2]
#compute possible sums of player's current hand
#if one of the values is a list value, it means it one of the cards is an Ace
#compute the possible sums depending on how many Aces are in hand
#if there are 2 Aces
if (type(value1) == list) and (type(value2) == list):
sum1 = value1[0] + value2[0]
sum2 = value1[1] + value2[0]
player_hand_total = [sum1,sum2]
#if the first card is an ace
elif (type(value1) == list):
sum1 = value1[0] + value2
sum2 = value1[1] + value2
player_hand_total = [sum1,sum2]
#if the second card is an ace
elif (type(value2) == list):
sum1 = value2[0] + value1
sum2 = value2[1] + value1
player_hand_total = [sum1,sum2]
#if there are no aces
else:
sum1 = value1 + value2
player_hand_total = [sum1]
#remove cards from deck
#remove corresponding values
del values[cards.index(card1)]
del values[cards.index(card2)]
cards.remove(card1)
cards.remove(card2)
print("================================ RESTART ================================")
print()
#let player know their cards and hand value
if len(player_hand_total) == 2:
print("Player hand:",player_hand_cards, "is worth", player_hand_total[0], "or", player_hand_total[1])
elif len(player_hand_total) == 1:
print("Player hand:", player_hand_cards, "is worth", player_hand_total[0])
print()
#if the player gets a blackjack they win
#program ends
if 21 in player_hand_total:
print("Player wins!")
sys.exit()
#ask user if they would like to hit or stand
choice = input("(h)it or (s)tand? ")
#data validation to make sure user can only progress if they enter 'h' or 's'
#create a while loop
#if user input is not 'h' or 's', reprompt them
while choice not in ['h','s']:
print("Invalid option!")
choice = input("(h)it or (s)tand? ")
#if the user chooses to hit
if choice == 'h':
card3 = random.choice(cards)
value3 = values[cards.index(card3)]
del values[cards.index(card3)]
cards.remove(card3)
player_hand_cards = [card1, card2, card3]
#if user draws an ace
if (type(value3) == list):
#if user has any more aces, this ace must be worth 1 so user doesn't bust
if (type(value1)==list) or (type(value2)==list):
value3 == 1
#add 1 to all values in the list
player_hand_total = [i + value3 for i in player_hand_total]
#if any values are above 21, remove from list
for i in player_hand_total:
if i > 21:
player_hand_total.remove(i)
#if the user doesn't have any more aces
else:
player_hand_total = [i + 11 for i in player_hand_total]
for i in range(len(player_hand_total)):
if player_hand_total[i] > 21:
player_hand_total[i] = player_hand_total[i] - 10
print("Player hand:",player_hand_cards, "is worth", player_hand_total[0], "or", player_hand_total[1])
if 21 in player_hand_total:
print("Player wins!")
sys.exit()
#unfinished***
|
kierengill/CS002-Intro-To-Programming
|
Assignment 8/GillKieren_Assign8_extra_credit.py
|
GillKieren_Assign8_extra_credit.py
|
py
| 4,617 |
python
|
en
|
code
| 0 |
github-code
|
6
|
21367959963
|
from socket import socket
from os import system
from time import sleep
s = socket()
s.bind(('localhost', 50550))
s.listen(1)
while True:
try:
conn, addr = s.accept()
conn.close()
except KeyboardInterrupt:
sleep(0.2)
system('clear')
system('git -P adog')
|
CodeTriangle/gitviz
|
watcher.py
|
watcher.py
|
py
| 298 |
python
|
en
|
code
| 0 |
github-code
|
6
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.